-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.js
550 lines (411 loc) · 15 KB
/
app.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
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
import { SavedPostsDatabase } from "./javascript/saving.js";
import { convertToPercent, countCharacters, generateDate, getDate, getTime, isSmallScreenSize, isValidCharacterCount, typeWriter } from "./javascript/utils.js"
import { classify, modelStatus } from "./javascript/classifier.js"
import { SAVED_POSTS_LS_KEY } from "./javascript/constants.js";
export const globalState = {
prevInput: '',
input: '',
output: '',
isLoading: false,
wordCount: 0,
lastSavedPost: {}
}
const inputField = document.getElementById("input-text");
const submitButton = document.getElementById("analyze-btn");
const clearButton = document.getElementById("clear-btn");
const exampleSelector = document.getElementById("sample-hate-speech");
const wordCountDisplay = document.getElementById("word-count");
const labelsSection = document.getElementById("label-section");
const labelsContainer = document.getElementById("labels-container");
const outputContainer = document.getElementById("output-container");
const outputSection = document.getElementById("output-section");
const inputDisplayContainer = document.getElementById("input-display-container");
const inputDisplay = document.getElementById("input-display");
const inputDisplayText = document.getElementById("input-display-text");
const inputDisplayDate = document.getElementById("input-display-date");
const tweetTime = document.getElementById("tweet-time");
const tweetDate = document.getElementById("tweet-date");
const outputDisplay = document.getElementById("output-display");
const modelStatusDisplay = document.getElementById("model-status");
const saveBtn = document.getElementById("save-btn");
const exportButtons = document.querySelectorAll(".export-btn");
const savedPostsSection = document.getElementById("saved-post-section");
const savedPostsContainer = document.getElementById("saved-posts");
const savedPostsCounter = document.getElementById("saved-posts-counter");
const dropdownButtons = document.querySelectorAll('.btn-dropdown');
const dropdownMenus = document.querySelectorAll('.dropdown');
const deleteAllButton = document.getElementById('sp-btn-delete');
// Initialize Database
const DATABASE = new SavedPostsDatabase(SAVED_POSTS_LS_KEY,
{
containerElement: savedPostsContainer,
counterElement: savedPostsCounter,
}
)
export function debug(...args) {
// console.log(...args);
}
function debugGlobalState() {
// console.group('Global State Debug:');
// console.log(`Global Input: ${globalState.input}`);
// console.log(`Field Input: ${inputField.value}`);
// console.log(`Global Word Count: ${globalState.wordCount}`);
// console.log(`Field Word Count: ${getWordCountFromInputField()}`);
// console.log(`Global Output:`, globalState.output);
// console.log(`Global IsLoading:`, globalState.isLoading);
// console.groupEnd();
}
const setGlobalInput = (text) => {
globalState.input = text;
}
/**
* Should be used to set the last submitted input to the classifier
* @param {string} prevInput
*/
const setGlobalPrevInput = (prevInput) => {
globalState.prevInput = prevInput;
}
const setGlobalWordCount = (number) => {
globalState.wordCount = number;
}
const setGlobalOutput = (array) => {
globalState.output = array;
}
const setGlobalIsLoading = (bool) => {
globalState.isLoading = bool;
}
const setGlobalLastSavedPost = (savedPost) => {
globalState.lastSavedPost = savedPost;
}
// initialize global states
const initializeGlobalState = () => {
setGlobalInput(inputField.value)
setGlobalWordCount(getWordCountFromInputField());
}
document.addEventListener("DOMContentLoaded", function () {
initializeGlobalState();
debug('globalState.input: ', globalState.input)
debug('globalState.wordCount: ', globalState.wordCount)
updateWordCountDisplay(globalState.wordCount)
updateSubmitButtonState()
inputField.oninput = (e) => {
debug(e.target.value)
debug(getWordCountFromInputField())
handleInputChange()
updateSubmitButtonState()
}
exportButtons.forEach(button => {
button.onclick = () => {
const filetype = button.getAttribute('data-filetype');
console.log('exporting as', filetype)
DATABASE.downloadReport({ filetype, filename: '' })
}
})
// Get content of localstorage
DATABASE.initializeSavedPosts()
updateSavedPostContainer();
// Initialize delete event listeners
deleteAllButton.onclick = () => {
if (!confirm(`Are you sure you want to delete all saved posts?\nThis action cannot be undone.`)) return;
try {
DATABASE.deleteAllPosts();
updateSavedPostContainer();
} catch (e) {
console.error('Error: ', e)
}
}
dropdownButtons.forEach(button => {
button.onclick = (e) => {
e.stopPropagation();
console.log('dropdown-btn clicked')
// TODO: refactor to allow moving dropdown position
const dropdownMenu = button.nextElementSibling;
const isClosed = !dropdownMenu.classList.contains('active');
closeAllDropdowns();
if (isClosed) {
dropdownMenu.classList.add('active');
} else {
dropdownMenu.classList.remove('active');
}
}
})
window.onclick = (e) => {
closeAllDropdowns();
}
const closeAllDropdowns = () => {
dropdownMenus.forEach(dropdown => {
dropdown.classList.remove('active');
});
}
});
/**
* Sync UI and global state for word count
*/
const updateWordCount = () => {
setGlobalWordCount(getWordCountFromInputField());
updateWordCountDisplay(getWordCountFromInputField())
}
const updateInput = () => {
setGlobalInput(inputField.value);
}
const handleInputChange = () => {
// TEST: should check if previous input == current output
updateInput()
updateWordCount()
updateSubmitButtonState()
}
/**
* Counts and returns the number of words from value of inputField
* @returns {number} word count of inputField
*/
const getWordCountFromInputField = () => {
const wordCount = countCharacters(inputField.value)
return wordCount;
}
/**
* Displays a given number in the word counter UI.
* Will turn red if word count is between 3 and 280 inclusive.
* @param {number} count
*/
const updateWordCountDisplay = (count) => {
wordCountDisplay.textContent = count;
if (!isValidCharacterCount(count)) {
wordCountDisplay.style.color = "red";
} else {
wordCountDisplay.style.color = "#3A36E4";
}
}
/**
* Takes the value of the model status and display it in the UI.
* @param {string} status
*/
const updateModelStatus = (status) => {
if (modelStatusDisplay.textContent === "👍 Classifier is up and running") return
if (status === "loading") {
modelStatusDisplay.innerHTML = `<span class="loading-spinner"> </span>Loading classifier (will load only once)`;
} else if (status === "ready") {
modelStatusDisplay.textContent = "👍 Classifier is up and running";
} else if (status === "error") {
modelStatusDisplay.textContent = "Error loading classifier";
} else {
modelStatusDisplay.textContent = "-";
}
}
const setInputFieldValue = (text) => {
inputField.value = text;
}
const updateSubmitButtonState = () => {
// console.group("updateSubmitButtonState: ")
// console.log("wordcount: ", wordCount)
// console.log("prevInput: ", prevInput)
// console.groupEnd()
// Disable the submit button if input is invalid or data is being fetched
submitButton.disabled = !isValidCharacterCount(globalState.wordCount) || globalState.isLoading || globalState.prevInput === inputField.value;
};
const displayDateToInputDisplay = () => {
const newDate = generateDate();
const time = getTime(newDate);
const date = getDate(newDate);
tweetTime.textContent = time;
tweetDate.textContent = date;
inputDisplayDate.style.display = "flex";
}
/**
* Takes a string and displays it to the input display in output UI.
* @param {string | {label: string, score: number}[]} output an array of labels and scores sorted by descending scores
*/
const updateInputDisplay = (inputText) => {
inputDisplay.classList.remove("fade-in")
inputDisplay.classList.add("fade-in")
inputDisplayContainer.style.display = "grid"
// inputDisplayText.textContent = inputText
typeWriter(inputDisplayText, inputText);
displayDateToInputDisplay();
}
/**
* Takes a string and displays it to the output UI.
* Otherwise takes the output array from the classifier and displays it to the output UI.
* @param {string | {label: string, score: number}[]} output an array of labels and scores sorted by descending scores
*/
const updateOutputDisplay = (output) => {
/**
* @sample_output
*
* [{ label: Race, score: 0.9196538 },
* { label: Gender, score: 0.8739012 },
* { label: Race, score: 0.4322910 },
* { label: Religion, score: 0.2021788 },
* { label: Others, score: 0.00218272 },
* { label: Age, score: 0.00019923 }]
*/
if (Array.isArray(output)) {
let outputText = "";
output.forEach(label => {
let text = label.label;
let score = label.score;
outputText += `<p>${text} - ${(score * 100).toFixed(2)}%</p>`;
});
outputDisplay.innerHTML = outputText;
} else {
outputDisplay.innerHTML = output;
}
}
const updateLoadingDisplay = (isLoading) => {
if (isLoading) {
labelsContainer.classList.add("fade-out");
labelsContainer.innerHTML = `
<div class="analyze_container">
<img src="assets/mlthsc.png" class="logo-spin">
<p class="">Analyzing</p>
</div>
`;
labelsContainer.classList.remove("fade-out");
}
}
export const updateLabelsContainer = (outputs) => {
let htmlContent = "";
for (let output of outputs) {
const probability = convertToPercent(output.score);
const labelClass = `label-${output.label.toLowerCase()}`;
const labelPercentClass = `label-percent-${output.label.toLowerCase()}`;
htmlContent += `
<div class="label-container fade-in">
<div class="label ${labelClass} border-none" style="--target-width: ${probability}%; animation: loadProgressBar 2s forwards;">
<span class="label-percent ${labelPercentClass}">${probability}%</span> ${output.label}
</div>
</div>`;
}
labelsContainer.innerHTML = htmlContent;
}
const updateOutputContainer = () => {
const DELAY = 1000 // in miliseconds
// debug('loadingDisplay: ', loadingDisplay)
// Fake loading for 1 second
setTimeout(() => {
updateLoadingDisplay(false)
updateLabelsContainer(globalState.output)
if (isSmallScreenSize()) {
labelsSection.scrollIntoView({ behavior: "smooth" });
}
}, DELAY)
}
clearButton.onclick = (e) => {
// TEST: should remove content inside inputField
// TEST: should reset the exampleOptions to default
// TEST: should reset word count
// inputField.scrollIntoView({ behavior: "smooth" });
inputField.value = "";
updateInput()
exampleSelector.selectedIndex = 0;
updateWordCount()
updateSubmitButtonState()
debugGlobalState()
}
/**
* Takes the input from the global state and updates the UI accordingly
*/
const handleSubmitInput = async () => {
const wordCount = globalState.wordCount;
if (!isValidCharacterCount(wordCount)) {
return
}
// TEST: should get output from the classifier if successful
// TEST: should display output to the UI
// 1. Disable button
// 2. update model status
try {
setGlobalIsLoading(true)
updateSubmitButtonState()
updateModelStatus(modelStatus)
updateLoadingDisplay(true)
const output = await classify(globalState.input)
outputSection.scrollIntoView({ behavior: "smooth" });
updateModelStatus("ready")
setGlobalPrevInput(globalState.input);
setGlobalOutput(output);
updateInputDisplay(globalState.prevInput)
updateSubmitButtonState()
setGlobalIsLoading(false)
updateOutputContainer()
} catch (error) {
console.log("Error: ", error)
}
debugGlobalState()
debug(globalState.output)
}
submitButton.onclick = async (e) => {
// TEST: should get value of inputField
// TEST: should check if word count is enough
// TEST: should disable submitButton when loading
handleSubmitInput();
}
exampleSelector.oninput = () => {
// TEST: should change value of inputField
// TEST: should reset word count
setInputFieldValue(exampleSelector.value)
handleInputChange()
debugGlobalState()
}
/** TODO
* @TODO set title attribute to analyzeBtn on hover when same prevInput and input
* @TODO date and time to post
* @TODO save results to local storage
* @TODO retrieve from local storage and display to UI
* @TODO filter results
* @TODO pagination
* @TODO count and graph results
* @TODO export as csv
* @TODO dark mode
* @TODO guide below as an article
* @TODO description for the labels with icons/emoji (take from github readme)
*/
/** FEATURES
* @FEAT input text
* @FEAT hate speech examples
* @FEAT word counter
* @FEAT clear input field
* @FEAT post like display
* @FEAT hate speech categories display
*/
const updateSavedPostContainer = () => {
DATABASE.renderPostsContainer()
DATABASE.renderCount()
addDeleteEventListeners();
}
const handleSavePost = () => {
// clicking saveBtn should save current post to localstorage
// clikcing saveBtn should update the savedPosts container
// clikcing saveBtn should not save input when
const savedPost = SavedPostsDatabase.createSavedPost(globalState.prevInput, globalState.output)
try {
// if (savedPost.input === globalState.lastSavedPost.input) {
// throw new Error('prev input and current input are the same')
// }
DATABASE.addPost(savedPost)
updateSavedPostContainer();
setGlobalLastSavedPost(savedPost)
savedPostsSection.scrollIntoView({ behavior: "smooth" });
} catch (error) {
console.error("Error: ", error)
}
}
const addDeleteEventListeners = () => {
const deleteButtons = document.querySelectorAll('.delete-btn');
deleteButtons.forEach(button => {
button.onclick = (e) => {
const postId = button.getAttribute('data-id');
const postText = button.getAttribute('data-text');
console.log(`deleting ${postId}`);
if (!confirm(`Are you sure you want to delete Post ID:${postId}?\nThis action cannot be undone.\n\n"""\n${postText}\n\n"""`)) return;
try {
DATABASE.deletePostById(postId);
updateSavedPostContainer();
} catch (e) {
console.error('Error: ', e)
}
};
});
}
saveBtn.onclick = () => {
handleSavePost()
}