-
Notifications
You must be signed in to change notification settings - Fork 1
/
app.js
409 lines (341 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
;(function() {
'use strict'
//
// Variables
//
// Save the localStorage ID to a variable for easier configuration later
const storageID = 'todosRouting'
// Placeholders
let app, field
//
// Methods
//
/**
* Get the URL parameters
* source: https://css-tricks.com/snippets/javascript/get-url-variables/
* @param {String} url The URL
* @return {Object} The URL parameters
*/
const getParams = function(url) {
const params = {}
const parser = document.createElement('a')
parser.href = url ? url : window.location.href
const query = parser.search.substring(1)
const vars = query.split('&')
if (vars.length < 1 || vars[0].length < 1) return params
for (let i = 0; i < vars.length; i++) {
const pair = vars[i].split('=')
params[decodeURIComponent(pair[0])] = decodeURIComponent(pair[1])
}
return params
}
/**
* Create todo lists view
*/
const createLists = function() {
app = new Reef('#app', {
data: {},
template: function({ lists }) {
// Create the form
const form = `<h1>My Lists</h1>
<form id="add-lists">
<label for="new-list">Create a list</label>
<input type="text" id="new-list" autofocus>
<button>Create List</button>
</form>`
// If there are no lists, ask the user to create one
if (lists.length < 1) {
return (
form +
"<p>You don't have any lists yet. Create one using the form above.</p>"
)
}
// Generate markup for list items
return (
form +
'<ol class="lists">' +
lists
.map((list, index) => {
const todoHTML = `<li>
<a href="?list=${index}">${list.name} (${list.todos.length})</a>
<button data-delete-list="${index}" aria-label="Delete ${list.name}">🗑</button>
</li>`
return todoHTML
})
.join('') +
'</ol>'
)
}
})
}
/**
* Create todo items view
*/
const createTodos = function() {
app = new Reef('#app', {
data: {},
template: function({ lists, current }) {
// Create a link back to the lists view
const link =
'<a href="' +
window.location.href.replace('?list=' + current, '') +
'">← Back to Lists</a>'
// Get the current list
const list = lists[current]
// If the list doesn't exist, show a message and link back to all lists
if (!list) {
return link + '<h1>This list could not be found, sorry!</h1>'
}
// Create the form
const form =
link +
'<h1>' +
list.name +
'</h1>' +
'<form id="add-todos">' +
'<label for="new-todo">What do you want to do?</label>' +
'<input type="text" id="new-todo" autofocus>' +
'<button>Add Todo</button>' +
'</form>'
// If there are no todos, ask the user to add some
if (list.todos.length < 1) {
return (
form +
"<p>You don't have any todos yet. Add some using the form above.</p>"
)
}
// Generate markup for todo items
return (
form +
'<ul class="todos">' +
list.todos
.map((todo, index) => {
const todoHTML = `<li ${
todo.completed ? 'class="todo-completed"' : ''
}>
<label for="todo-${index}">
<input type="checkbox" id="todo-${index}" data-todo="${index}"
${todo.completed ? 'checked=checked' : ''}>${
todo.item
}<button data-delete-todo="${index}" aria-label="Delete ${
todo.item
}">🗑</button></label></li>`
return todoHTML
})
.join('') +
'</ul>'
)
}
})
}
/**
* Clear the field and return focus
*/
const focusField = function() {
field.value = ''
field.focus()
}
/**
* Check whether an element is already on the list
*/
const checkDuplicated = element =>
element.name === field.value || element.item === field.value
/**
* Add a new todo item to the app
* @param {Event} event The Event object
*/
const addTodo = function(event) {
// Only run for #add-todos form
if (event.target.id !== 'add-todos') return
// Stop the form from reloading the page
event.preventDefault()
// If the #new-todo input has no value, do nothing
if (field.value.length < 1) return
// Get a copy of the data and then get lists and current with destructuring
const { lists, current } = app.getData()
// Get the current list
const list = lists[current]
if (!list) return
// Check for duplicates
if (list.todos.some(checkDuplicated)) {
alert(`Oops! ${field.value} is already added to the list!`)
return focusField()
}
// Update data object
list.todos.push({
item: field.value,
completed: false
})
// Render fresh UI
app.setData({ lists: lists })
// Clear the field and return focus
focusField()
}
/**
* Add a new list to the app
* @param {Event} event The Event object
*/
const addList = function(event) {
// Only run for #add-lists form
if (event.target.id !== 'add-lists') return
// Stop the form from reloading the page
event.preventDefault()
// If the #new-list input has no value, do nothing
if (field.value.length < 1) return
// Get a copy of the lists from data with destructuring
const { lists } = app.getData()
// Check for duplicates
if (lists.some(checkDuplicated)) {
alert(`Oops! ${field.value} is already added to the list!`)
return focusField()
}
// Add the new list
lists.push({
name: field.value,
todos: []
})
// Render fresh UI
app.setData({ lists: lists })
// Clear the field and return focus
focusField()
}
/**
* Handle form submit events
* @param {Event} event The Event object
*/
const submitHandler = function(event) {
addList(event)
addTodo(event)
}
/**
* Mark todo item as complete
* @param {Event} event The event object
*/
const completeTodo = function(event) {
// Only run on todo items
const todo = event.target.getAttribute('data-todo')
if (!todo) return
// Get a copy of the data and then get lists and current with destructuring
const { lists, current } = app.getData()
// Get the current list
const list = lists[current]
if (!list || !list.todos[todo]) return
// Update the todo state
list.todos[todo].completed = event.target.checked
// Render a fresh UI
app.setData({ lists: lists })
}
/**
* Delete a todo item from the list
* @param {Event} event The event object
*/
const deleteTodo = function(event) {
// Only run on delete button clicks
const todo = event.target.getAttribute('data-delete-todo')
if (!todo) return
// Get a copy of the data and then get lists and current with destructuring
const { lists, current } = app.getData()
// Get the current list
const list = lists[current]
if (!list || !list.todos[todo]) return
// Confirm with the user before deleting
if (
!window.confirm(
'Are you sure you want to delete this todo item? This cannot be undone.'
)
)
return
// Remove the item from the todo state
list.todos.splice(todo, 1)
// Render a fresh UI
app.setData({ lists: lists })
}
/**
* Delete a list
* @param {Event} event The event object
*/
const deleteList = function(event) {
// Only run on delete button clicks
const list = event.target.getAttribute('data-delete-list')
if (!list) return
// Get a copy of the data and then get lists with destructuring
const { lists } = app.getData()
if (!lists[list]) return
// Confirm with the user before deleting
if (
!window.confirm(
`Are you sure you want to delete "${lists[list].name}"? All todo items associated with this list will also be deleted. This cannot be undone.`
)
)
return
// Remove the item from the todo state
lists.splice(list, 1)
// Render a fresh UI
app.setData({ lists: lists })
}
/**
* Handle click events
* @param {Event} event The Event object
*/
const clickHandler = function(event) {
// Mark todo item as complete
completeTodo(event)
// Delete todo item
deleteTodo(event)
// Delete list
deleteList(event)
}
/**
* Save todo items to localStorage
*/
const saveTodos = function() {
localStorage.setItem(storageID, JSON.stringify(app.getData()))
}
/**
* Load todos into state on page load
* @param {String} list The current list index
*/
const loadTodos = function(list) {
// Check for saved data in localStorage
const saved = localStorage.getItem(storageID)
const data = saved
? JSON.parse(saved)
: {
lists: []
}
data.current = list ? parseInt(list, 10) : null
// Update the state and run an initial render
app.setData(data)
}
/**
* Setup the UI
*/
const setup = function() {
// Get the list ID from the URL if there is one
const list = getParams().list
// If there's a list ID, create the todos view
// Otherwise, create the lists view
if (list) {
createTodos()
} else {
createLists()
}
// Render the initial UI
loadTodos(list)
// Define the field variable
// This will match against EITHER #new-list OR #new-todo, whichever it finds first
// This prevents me from having to conditionally set my selector
field = document.querySelector('#new-list, #new-todo')
}
//
// Inits & Event Listeners
//
// Setup the app view
setup()
// Listen for form submit events
document.addEventListener('submit', submitHandler, false)
// Listen for click events
document.addEventListener('click', clickHandler, false)
// On render events, save todo items
document.addEventListener('render', saveTodos, false)
})()