Skip to content
This repository has been archived by the owner on Oct 4, 2019. It is now read-only.

Commit

Permalink
commented code. Added length check to update message script
Browse files Browse the repository at this point in the history
  • Loading branch information
ConnorJamesLow committed Feb 16, 2019
1 parent 6f37961 commit 5201293
Showing 1 changed file with 136 additions and 19 deletions.
155 changes: 136 additions & 19 deletions client/Messaging.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
function initApp() {
Utils = {

// get a cookie from the document.cookie string
getCookie: (name) => {
const key = `${name}=`;
const decodedCookie = decodeURIComponent(document.cookie);
Expand All @@ -15,6 +17,8 @@ function initApp() {
}
return false;
},

// add a new cookie to document.cookie
setCookie: (name, value, daysTillExpiration) => {
const d = new Date();
d.setTime(d.getTime() + (daysTillExpiration * 24 * 60 * 60 * 1000));
Expand All @@ -27,12 +31,22 @@ function initApp() {
// API_URL: location.href.indexOf('localhost') > 0
// ? 'http://localhost:8080/AnotherCloudApp/messaging'
// : 'https://gcucloud.herokuapp.com/messaging',

// the base url for the API
API_URL: 'https://gcucloud.herokuapp.com/messaging',

// the number of messages to retrieve at once.
LOAD_SIZE: 10,
},
state: {
offset: 0,
topIndex: 0,

// the index of the oldest retrieved message
lowIndex: 0,

// the index of the newest retrieved message
highIndex: 0,

// the name of the user
name: (() => {

// try to get the name from a cookie
Expand All @@ -49,7 +63,7 @@ function initApp() {
},
requests: {
getNewMessages: () => {
const options = App.helpers.getOptions('GET', `get-new-messages?index=${App.state.topIndex}`);
const options = App.helpers.getOptions('GET', `get-new-messages?index=${App.state.highIndex}`);
return $.ajax(options);
},
getMessageRange: (index, count) => {
Expand All @@ -58,22 +72,30 @@ function initApp() {
},
sendMessage: (message) => {
const options = App.helpers.getOptions('POST', 'sendmessage');

// add data to options
options.data = JSON.stringify({
'messagebody': message,
'creationdate': moment(new Date()).format('Y-MM-DD hh:mm:ss'),
'sender': App.state.name
});

// specify the body format
options.processData = false;
options.headers["Content-Type"] = 'application/json';
console.log(options);
return $.ajax(options);
},
updateMessage: (message, id) => {
const options = App.helpers.getOptions('PUT', 'updatemessage');

// add data for update
options.data = JSON.stringify({
'id': id,
'messagebody': message
});

// specify body format
options.processData = false;
options.headers["Content-Type"] = 'application/json';
return $.ajax(options);
Expand All @@ -84,6 +106,8 @@ function initApp() {
}
},
helpers: {

// returns a base ajax options object
getOptions(method, uri) {
return {
async: true,
Expand All @@ -98,95 +122,159 @@ function initApp() {
},
actions: {
init: () => {

// add the first ten messages to the chat.
App.actions.loadMessages();

// change the chat header to use the user's nickname
App.dom.updateName();

// bind the enter key (13) to the send button.
App.elements.input.keyup((ev) => {
if (ev.which === 13) {
App.actions.sendMessage();
}
});

// listen for new messages.
App.state.listener = setInterval(App.actions.loadRecent, 1500);
},
loadRecent: () => {

// send a request for the messages.
const promise = App.requests.getNewMessages();
promise.done(response => {

// if messages are returned, add them to the chat box.
if (response.length > 0) {

// get the latest id
const recent = response[response.length - 1].id;
console.log('recent:', recent, 'top index:', App.state.topIndex);
if (recent > App.state.topIndex) {
App.state.topIndex = recent;
console.log('recent:', recent, 'top index:', App.state.highIndex);
if (recent > App.state.highIndex) {

// update the app state
App.state.highIndex = recent;

// append the new messages
App.dom.appendMessagesToChat(response);
}
}
});
},
loadMessages: () => {
const promise = App.requests.getMessageRange(App.state.offset, App.constants.LOAD_SIZE);

// request a range of messages preceeding the current index of the oldest retrieved message
const promise = App.requests.getMessageRange(App.state.lowIndex, App.constants.LOAD_SIZE);
promise.done(response => {

// if results were returned add them to the page.
if (response.length > 0) {
if (App.state.topIndex === 0) {
App.state.topIndex = response[0].id;
console.log(App.state.topIndex);
if (App.state.highIndex === 0) {

// if this is the first call, set the initial highest index
App.state.highIndex = response[0].id;
console.log(App.state.highIndex);
}
App.dom.prependMessagesToChat(response);
} else {

// assume there are no older messages and disable the button.
App.dom.disableLoader();
}
});
},
sendMessage: () => {

// get the message from the messaging input
const message = App.elements.input.val();

// make sure the message is not empty or just spaces.
if (message.trim().length > 0) {

// do a POST request with the message
App.requests.sendMessage(message).done(() => {
// App.dom.appendMessagesToChat([{
// messagebody: message,
// sender: App.state.name
// }]);

// clear the message box.
App.dom.clearMessageBox();
});
}
},
updateMessage: (id) => {

// get the message from the update input
const message = $('#update-input').val();
App.requests.updateMessage(message, id).done(() => {
App.dom.destoryEditor();
$(`#payload-${id}`).html(message);
});

// make sure the message is not empty or just spaces.
if (message.trim().length > 0) {

// do a POST request with the message
App.requests.updateMessage(message, id).done(() => {

// close the editor
App.dom.destoryEditor();

// update the message on screen.
$(`#payload-${id}`).html(message);
});
}
},
deleteMessage: (id) => {

// function to run once the user responds to our sweet alert.
const confirmDelete = function (result) {

// if the user confirmed the action, delete the message.
if (result.value) {
App.requests.deleteMessage(id).done(() => {
$(`#message-${id}`).remove();
});
}
else {

// else, report the cancelation.
swal('Deletion canceled!', '', 'info');
}
};

// options for the sweet alert.
swalO = {
title: 'Confirm',
text: 'Are you sure you want to delete this message?',
type: 'warning',
showCancelButton: true,
};

// create the sweet alert.
swal(swalO).then(confirmDelete);
},
setName: () => {

// get the nickname from the input.
const name = $('#name-input').val();

// set the name to a cookie
Utils.setCookie('nickname', name, 14);

// update the app state
App.state.name = name;

// destroy the editor
App.dom.destoryEditor();
}
},
dom: {

// adds a list of messages to the top of the chat stack
prependMessagesToChat: (data) => {
data.forEach((message) => {
const html = App.templates.message(message.sender, message.messagebody, message.id, message.creationdate);
App.elements.messages.prepend(html);
App.state.offset = message.id;
App.state.lowIndex = message.id;
});
},

// adds a list of messages to the bottom of the chat stack
appendMessagesToChat: (data) => {
console.log(data);
data.forEach((message) => {
Expand All @@ -195,31 +283,46 @@ function initApp() {
});
App.dom.scrollToBottom();
},

// Empty the messaging input.
clearMessageBox: () => {
App.elements.input.val('');
},

// reveal the update message editor
showEditor: (id) => {
const message = $(`#message-${id}`);
const text = message.data('message');
$('body').prepend(App.templates.messageEditor(id, text));
},

// remove any overlays and editors.
destoryEditor: () => {
$('#overlay').addClass('d-none');
$('#overlay').removeClass('d-flex');
$('#overlay').html('');
},

// grey out the load message button and disable it's functionality
disableLoader: () => {
App.elements.loader.addClass('app-disabled');
App.elements.loader.html('No more messages');
App.elements.loader.attr('onclick', '');
},

// update the chat title
updateName: () => {
App.elements.name.html(App.state.name);
},

// scroll to the bottom of the chat.
scrollToBottom: () => {
App.elements.card.scrollTop(App.elements.card[0].scrollHeight);
}
},
templates: {

// a new message in the chat
message: (name, message, id, creationdate) => {
const isUser = name === App.state.name;
return `
Expand All @@ -246,6 +349,8 @@ function initApp() {
</div>
</div>`;
},

// the nickname editor
nickname: () => {
return `
<div class="align-items-center h-100 justify-content-around position-absolute w-100 app-overlay d-none" id="overlay">
Expand All @@ -263,6 +368,8 @@ function initApp() {
</div>
</div>`;
},

// the udpate message editor
messageEditor: (id, message) => {
return `
<div class="align-items-center h-100 justify-content-around position-absolute w-100 app-overlay d-flex" id="overlay">
Expand All @@ -287,10 +394,20 @@ function initApp() {
}
},
elements: {

// the messaging input
input: $('#message-input'),

// the message box with current messages
messages: $('#message-board'),

// the user's name on the chat title.
name: $('#display-name'),

// the "Load new messages" button
loader: $('#load-messages'),

// the entire chat module.
card: $('.card-body')
}
}
Expand Down

0 comments on commit 5201293

Please sign in to comment.