-
Notifications
You must be signed in to change notification settings - Fork 0
/
main-compiled.js
380 lines (313 loc) · 15 KB
/
main-compiled.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
/**
* # Chat Module #
*
*
* ## to operate, chat module requires a HTML structure as follows: ##
*
* <form id="chatInput">
* <section>
* <label for="usrName" value="name"></label>
* <input type="text" id="usrName"/>
* </section>
* <section>
* <label for="msgId">Message ID:</label>
* <input id="msgId"/>
* </section>
* <section>
* <label for="msgBody" value="message body"></label>
* <input id="msgBody"/>
* </section>
* <button id="refresh"></button>
* <button id="post">Send</button>
* <button id="change">Edit</button>
* <button id="delete">Delete</button>
* </form>
* <section class="msgBoard"></section>
*
* ### The message board tag will be filled with the messages with the following structure: ###
*
* <article class="message">
* <h1></h1> // the name of the sender
*
* // contains: "ID:" + (id number...). the data-layout attribute should be used to hide this element.
* <p data-layout="hide"></p>
*
* <p></p> // contains the message text.
* </article>
*/
var chatModule = function () {
var btnRefresh = document.querySelector('#refresh'),
btnPost = document.querySelector('#post'),
btnDelete = document.querySelector('#delete'),
btnChange = document.querySelector('#change'),
form = document.querySelector('#chatInput'),
DONE = 4,
OK = 200,
url = 'https://hidden-headland-7200.herokuapp.com/',
msgArray; // variable will be assigned with all messages elements
// disables form default validation mechanisms.
form.onsubmit = event => {
event.preventDefault();return function validateMyForm() {
return false;
}();
};
/**
* @module - The Core module. includes the ajax function.
* @function - the ajax function
* @type {{ajax}}
* @exports - an API with an core.ajax(); method
*/
var core = function () {
/**
* AJAX Request function with callback and optional request headers.
* @param request - type of request. accepts 'GET', 'POST', 'PUT' & 'DELETE'
*
* @param url - path on the server:
* GET = https://hidden-headland-7200.herokuapp.com/
* POST = https://hidden-headland-7200.herokuapp.com/new/
* PUT = https://hidden-headland-7200.herokuapp.com/edit/<_id-number-here>
* DELETE = https://hidden-headland-7200.herokuapp.com/delete/<_id-number-here>
*
* @param callback - function to execute on readyState === 4 (DONE).
*
* @param body - the body of the request. accepts empty, null and JSON string.
* (optional)
*
* @param headers - request headers. if needed, syntax is a single string separated
* (optional) by a colon ':'. In example - <code>'Content-Type:application/json'</code>
* multiple request headers is handled with array of same syntaxed strings.
*
* @param responseType - a string of expected response types. can be left blank defaults to 'json'
* (optional)
*/
function ajax(request, url, callback, body, headers, responseType) {
// create promise on JAX Requests
var promise = new Promise(function (resolve, reject) {
var xhr = new XMLHttpRequest(),
args;
// open request
xhr.open(request, url);
// set request headers based on typeof headers.
//if headers is a string. This means that there's only one request header to set
if (typeof headers === 'string' && !!headers) {
//split strings into arguments array. always a length of 2.
args = headers.split(':');
// set headers based on the array.
xhr.setRequestHeader(args[0], args[1]);
}
// if headers is an array. This means that there's more than one request header to set
else if (headers instanceof Array) {
// loop over all setRequestHeader arguments
headers.forEach(function (el) {
if (typeof el === 'string') {
//split every arument to an aray of the two arguments required for setRequestHeader
args = el.split(":");
// evoke setRequestHeader for each of the arguments supplied.
xhr.setRequestHeader(args[0], args[1]);
}
});
}
// setting expected response type. defaults to 'json'
xhr.responseType = responseType || 'json';
xhr.onreadystatechange = function () {
// if DONE and OK
if (xhr.readyState === DONE && xhr.status === OK) {
if (xhr.response !== null) {
console.log(xhr.response.message || "no response");
}
callback(xhr, resolve); // evoke callback with xhr object as first argument.
// and the resolve function as second!
// user can evoke a .then function by the resolve
// function they add to the callback!
// if DONE but not OK
} else if (xhr.readyState === DONE && xhr.status !== OK) {
console.log('bad request');
reject('request failed'); // on failure evoke reject function to promise
}
};
// sends the request.
// if body exists or it's a null => send request with specified body
// else send request with no body
if (typeof body === 'function') {
xhr.send(body());
} else if (body !== null && body !== undefined) {
xhr.send(body);
} else {
xhr.send();
}
console.log('request ' + request + ' has been sent');
});
return promise; // send the promise down the chain
}
// returns core API
return {
ajax: ajax
};
}();
var utils = function () {
var contentJson = 'Content-Type:application/json',
datasetState = 'data-state',
selected = 'selected',
empty = 'empty response',
logFeedback = function (xhr) {
var feedback = xhr.response !== null ? xhr.response.message : empty;
console.log("message status: " + feedback);
},
getMessage = function () {
return '{"message":"' + msgBody.value + '","name":"' + usrName.value + '"}';
};
/*
* ================================================================================================================
* Message Action Utility
* ================================================================================================================
* */
// function assigns event listeners to all messages every refresh.
function messageAction() {
// assign all present messages with an event listener
for (var j = 0; j < msgArray.length; j++) {
msgArray[j].addEventListener('click', function () {
//onclick - assign the clicked element with a selected state.
// if it has one already remove the attribute.
if (this.hasAttribute(datasetState)) {
this.removeAttribute(datasetState);
} else {
//when clicked remove all selected states
for (var i = 0; i < msgArray.length; i++) {
msgArray[i].removeAttribute(datasetState);
}
// and assign the clicked element with a selected state.
this.setAttribute(datasetState, selected);
}
// insert the id value of current selected message to the msgId input field
msgId.value = this.childNodes[1].textContent.slice(4);
// if a message is currently selected - unhide edit and delete button
if (this.hasAttribute('data-state')) {
btnChange.setAttribute(datasetState, selected);
btnDelete.setAttribute(datasetState, selected);
} else {
// if it isn't hide it
btnChange.removeAttribute(datasetState);
btnDelete.removeAttribute(datasetState);
}
});
}
}
/*
*============================================= END OF MESSAGE ACTION UTIL =====================================
* */
/*
* ================================================================================================================
* Auto Scroll to bottom Util
* ================================================================================================================
* */
function scrollToBottom(msgBoard) {
msgBoard.scrollTop = msgBoard.scrollHeight;
}
/*
*==================================== END OF AUTO SCROLL TO BOTTOM UTIL ==========================================
* */
/*
* ================================================================================================================
* Refresh button callback
* ================================================================================================================
* */
// arrow function is to prevent ajax(); from firing until event dispatches
// also, an 'event' parameter is sent with the arrow function and is p-heightassed as the
// last argument to ajax(); function.
function refresh(event) {
// stop event bubbling to form
if (event) event.stopPropagation();
// return ! Promised ! AJAX request to get messages
return core.ajax('GET', url, function (xhr, resolve) {
// the json object with
// an array of object messages
var messages = xhr.response,
// string that will later be concatenated into the
// innerHTML.
string = '',
// caching the <section class="msgBoard"> tag.
msgBoard = document.querySelector('.msgBoard');
// looping over all the message objects
for (var i = 0; i < messages.length; i++) {
string += '<article class="msg"><h1>' + messages[i].name + '</h1><p data-layout="hide"> ID:' + messages[i]._id + '</p><p>' + messages[i].message + '</p></article>';
}
// assigning messages to msgBoard
msgBoard.innerHTML = string;
resolve(msgBoard); // sends the msgBoard element to the .then method
//after all messages pushed to DOM - select all in array like.
msgArray = document.querySelectorAll('.msg');
messageAction();
});
}
/*
* ================================================================================================================
* Post button event
* ================================================================================================================
* */
function post(event) {
event.stopPropagation();
return core.ajax('POST', url + 'new', function (xhr, resolve) {
logFeedback(xhr);
resolve(event);
}, getMessage(), contentJson).then(refresh);
}
/*
* ================================================================================================================
* Delete button event
* ================================================================================================================
* */
function dell(event) {
event.stopPropagation();
return core.ajax('DELETE', url + 'delete/' + msgId.value, function (xhr, resolve) {
logFeedback(xhr);
resolve(event);
}, '', contentJson).then(refresh);
}
/*
* ================================================================================================================
* Edit button event
* ================================================================================================================
* */
function change(event) {
event.stopPropagation();
return core.ajax('PUT', url + 'edit/' + msgId.value, function (xhr, resolve) {
logFeedback(xhr);
resolve(event);
}, getMessage(), contentJson).then(refresh);
}
//return utils api
return {
refresh: refresh,
send: post,
edit: change,
remove: dell,
scrollToBottom: scrollToBottom
};
}();
document.addEventListener('DOMContentLoaded', function () {
console.log('DOM fully loaded and parsed');
//initializing event listeners
btnRefresh.onclick = event => {
utils.refresh(event).then(utils.scrollToBottom);
};
btnPost.onclick = event => {
utils.send(event).then(utils.scrollToBottom);
};
btnChange.onclick = utils.edit;
btnDelete.onclick = utils.remove;
});
// fire refresh when page is fully loaded.
window.addEventListener('load', function () {
console.log('page finished loading');
// first initial firing
utils.refresh().then(utils.scrollToBottom);
// automatic 30 sec refresh.
setInterval(utils.refresh, 30000);
});
}();
/**
* =============================================================================================================
* END OF CHAT MODULE
* =============================================================================================================
*/
//# sourceMappingURL=main-compiled.js.map