-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.js
478 lines (363 loc) · 9.3 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
// ==================
// Helper Functions
// ==================
const onDocumentReady = (fn) => {
const hasDOMLoaded = (document.attachEvent ?
document.readyState === "complete" :
document.readyState !== "loading"
);
if (hasDOMLoaded) {
fn();
} else {
document.addEventListener('DOMContentLoaded', fn);
}
};
const delegateEvent = (element, eventName, selector, handler) => {
element.addEventListener(eventName, (event) => {
if (event.target && event.target.matches(selector)) {
handler(event);
}
});
};
// =======================
// Data-Relative Classes
// =======================
const { LocalStorageDataBase, Task } = (() => {
// LocalStorage interaction class
// --------------------------------
class LocalStorageDataBase {
constructor(namespace) {
this.namespace = namespace;
}
loadData() {
return JSON.parse(localStorage.getItem(this.namespace));
}
saveData(data) {
localStorage.setItem(this.namespace, JSON.stringify(data));
}
}
// Task Data Class
// -----------------
let TaskIdCounter = 0;
const getNextTaskId = () => TaskIdCounter++;
class Task {
constructor(text, isDone) {
this.text = text;
this.id = getNextTaskId();
this.isDone = !!isDone;
}
static parse({ text, isDone }) {
return new Task(text, isDone);
}
}
// "export"
return {
LocalStorageDataBase,
Task,
};
})();
// ===========================
// Task List Interface (API)
// ===========================
const taskListInterface = (() => {
const dataBase = new LocalStorageDataBase('simpleDB');
const storedData = dataBase.loadData();
const taskList = storedData ? storedData.map(Task.parse) : [];
const isValidId = (taskId) => (
typeof taskId === 'string' ||
typeof taskId === 'number'
);
// GET Method
const getData = (taskId) => {
if (typeof taskId === 'undefined') {
return taskList;
}
// 400 Error
if (!isValidId(taskId)) {
throw new TypeError('Invalid task ID');
}
const foundTask = taskList.find((task) => task.id == taskId);
// 404 Error
if (!foundTask) {
throw new ReferenceError('Task not found');
}
return foundTask;
};
// POST Method
const addItem = (data) => {
const task = (data instanceof Task) ? data : Task.parse(data);
taskList.push(task);
dataBase.saveData(taskList);
};
// PUT Method
const updateItem = (taskId, data) => {
// 400 Error
if (!isValidId(taskId)) {
throw new TypeError('Invalid task ID');
}
const taskIndex = taskList.findIndex((task) => task.id == taskId);
// 404 Error
if (taskIndex === -1) {
throw new ReferenceError('Task not found');
}
const targetTask = taskList[taskIndex];
// TODO: Add validation for "protected" attributes like ID
Object.keys(targetTask).forEach((key) => {
if (
typeof data[key] === 'undefined' ||
data[key] === targetTask[key]
) {
return;
}
targetTask[key] = data[key];
});
dataBase.saveData(taskList);
};
// DELETE Method
const deleteItem = (taskId) => {
// 400 Error
if (!isValidId(taskId)) {
throw new TypeError('Invalid task ID');
}
const taskIndex = taskList.findIndex((task) => task.id == taskId);
// 404 Error
if (taskIndex === -1) {
throw new ReferenceError('Task not found');
}
taskList.splice(taskIndex, 1);
dataBase.saveData(taskList);
};
return {
get: getData,
add: addItem,
update: updateItem,
delete: deleteItem,
}
})();
// ======================
// DOM-Relative Classes
// ======================
const { SimpleForm, SimpleList } = (() => {
// Simple Form
// -------------
class SimpleForm {
constructor(selector) {
if (typeof selector !== 'string' || selector === '') {
throw new TypeError(`'${selector}' is not a valid selector.`);
}
this._selector = selector;
this.DOM = {
form: null,
input: null,
};
this.classes = {
validityChecked: 'was-validated'
};
}
init() {
this.updateElementReferences();
this.addEventListeners();
}
updateElementReferences() {
const formElement = document.querySelector(this._selector);
if (!formElement) {
throw new ReferenceError('Form element not found');
}
this.DOM.form = formElement;
const inputElement = this.DOM.form.querySelector('[name=task-text]');
if (!inputElement) {
throw new ReferenceError('Input element not found');
}
this.DOM.input = inputElement;
}
addEventListeners() {
this.DOM.form.addEventListener('submit', (event) => {
event.preventDefault();
event.stopPropagation();
this.validate();
});
}
validate() {
this.DOM.form.classList.add(this.classes.validityChecked);
if (!this.DOM.form.checkValidity()) {
return;
}
this.submit(this.DOM.input.value);
}
submit(data) {
this.DOM.form.dispatchEvent(
new CustomEvent('validSubmit', {
detail: { formData: data }
})
);
this.reset();
}
reset() {
this.DOM.form.classList.remove(this.classes.validityChecked);
this.DOM.form.reset();
}
}
const simpleTemplateRender = (template, context) => {
const isValidValue = (value) => (
typeof value !== 'undefined' &&
value !== null
);
return template.replace(
/{{([^]*?)}}/g,
(originalString, key) => (isValidValue(context[key]) ? context[key] : originalString)
);
};
// Simple List
// -------------
class SimpleList {
constructor(selector) {
if (typeof selector !== 'string' || selector === '') {
throw new TypeError(`'${selector}' is not a valid selector.`);
}
this._selector = selector;
this.DOM = {
list: null,
};
}
init() {
this.updateElementReferences();
}
updateElementReferences() {
const listElement = document.querySelector(this._selector);
if (!listElement) {
throw new ReferenceError('List element not found');
}
this.DOM.list = listElement;
}
add(template, context) {
const renderedHTML = simpleTemplateRender(template, context);
this.DOM.list.innerHTML += renderedHTML;
this.DOM.list.dispatchEvent(
new CustomEvent('itemAdded', {
detail: {
itemId: context.id,
renderedHTML,
}
})
);
}
remove(itemId) {
const targetItem = this.DOM.list.querySelector(`[data-id="${itemId}"]`);
if (!targetItem) {
throw new ReferenceError(`No elements with data-id="${itemId}".`);
}
this.DOM.list.removeChild(targetItem);
this.DOM.list.dispatchEvent(
new CustomEvent('itemRemoved', {
detail: { itemId }
})
);
}
}
// "export"
return {
SimpleForm,
SimpleList,
};
})();
// =============
// Application
// =============
class SimpleTodo {
constructor () {
// Create DOM interacting instances
this.taskForm = new SimpleForm('[data-is=task-form]');
this.taskList = new SimpleList('[data-is=task-list]');
this.templates = {
task: null,
};
}
init() {
this.taskForm.init();
this.taskList.init();
this.getTemplates();
const storedData = taskListInterface.get();
// Add stored tasks
if (!!storedData) {
storedData.forEach((task) => {
this.taskList.add(
this.templates.task,
this.getTaskContext(task),
);
});
}
this.addEventListeners();
}
getTemplates() {
const taskTemplate = document.getElementById('task-template');
if (!taskTemplate) {
throw new ReferenceError('Task template element was not found');
}
this.templates.task = taskTemplate.innerHTML;
}
getTaskContext(task) {
return {
text: task.text,
id: task.id,
isDoneClass: task.isDone ? 'task-complete' : '',
};
}
addEventListeners() {
this.taskForm.DOM.form.addEventListener('validSubmit', (event) => {
if (!(event instanceof Event)) {
throw new TypeError('This function must be bound to an EventListener');
}
this.addTask(new Task(event.detail.formData, false));
});
delegateEvent(this.taskList.DOM.list, 'click', '[data-action=remove]', (event) => {
if (!(event instanceof Event)) {
throw new TypeError('This function must be bound to an EventListener');
}
event.preventDefault();
event.stopPropagation();
this.removeTask(event.target.parentNode.getAttribute('data-id'));
});
delegateEvent(this.taskList.DOM.list, 'click', '.task', (event) => {
if (!(event instanceof Event)) {
throw new TypeError('This function must be bound to an EventListener');
}
event.preventDefault();
event.stopPropagation();
const targetElement = event.target;
const taskId = targetElement.getAttribute('data-id');
const wasDone = targetElement.classList.contains('task-complete');
this.updateTaskCompletion(taskId, !wasDone);
});
}
addTask(newTask) {
// API -> POST
taskListInterface.add(newTask);
// Update DOM
this.taskList.add(
this.templates.task,
this.getTaskContext(newTask)
);
}
removeTask(taskId) {
// API -> DELETE
taskListInterface.delete(taskId);
// Update DOM
this.taskList.remove(taskId);
}
updateTaskCompletion(taskId, isDone) {
// API -> PUT
taskListInterface.update(taskId, { isDone });
// Update DOM
const targetElement = this.taskList.DOM.list.querySelector(`[data-id="${taskId}"]`);
if (!targetElement) {
throw new ReferenceError(`No elements with data-id="${taskId}".`);
}
targetElement.classList[isDone ? 'add' : 'remove']('task-complete');
}
}
// Create singleton instance
const simpleTodo = new SimpleTodo();
// Init application when DOM has loaded
onDocumentReady(() => {
simpleTodo.init();
});