-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.js
353 lines (321 loc) · 9.18 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
/* global Vue, Vuex, axios, track */
/* eslint-disable no-console */
/* eslint-disable-next-line */
const uri = window.location.search.substring(1)
const params = new URLSearchParams(uri)
const appStartDelay = parseFloat(params.get('appStartDelay') || '0')
function appStart() {
Vue.use(Vuex)
function randomId() {
return Math.random().toString().substr(2, 10)
}
/**
* When adding new todo items, we can force the delay by using
* the URL query parameter `addTodoDelay=<ms>`.
*/
let addTodoDelay = 0
const store = new Vuex.Store({
state: {
loading: false,
todos: [],
newTodo: '',
delay: 0
},
getters: {
newTodo: state => state.newTodo,
todos: state => state.todos,
loading: state => state.loading
},
mutations: {
SET_DELAY(state, delay) {
state.delay = delay
},
SET_RENDER_DELAY(state, ms) {
state.renderDelay = ms
},
SET_LOADING(state, flag) {
state.loading = flag
if (flag === false) {
// an easy way for the application to signal
// that it is done loading
document.body.classList.add('loaded')
}
},
SET_TODOS(state, todos) {
state.todos = todos
// expose the todos via the global "window" object
// but only if we are running Cypress tests
if (window.Cypress) {
window.todos = todos
}
},
SET_NEW_TODO(state, todo) {
state.newTodo = todo
},
ADD_TODO(state, todoObject) {
state.todos.push(todoObject)
},
REMOVE_TODO(state, todo) {
let todos = state.todos
todos.splice(todos.indexOf(todo), 1)
},
CLEAR_NEW_TODO(state) {
state.newTodo = ''
}
},
actions: {
setDelay({ commit }, delay) {
commit('SET_DELAY', delay)
},
setRenderDelay({ commit }, ms) {
commit('SET_RENDER_DELAY', ms)
},
loadTodos({ commit, state }) {
console.log('loadTodos start, delay is %d', state.delay)
setTimeout(() => {
commit('SET_LOADING', true)
axios
.get('/todos')
.then(r => r.data)
.then(todos => {
setTimeout(() => {
commit('SET_TODOS', todos)
}, state.renderDelay)
})
.catch(e => {
console.error('could not load todos')
console.error(e.message)
console.error(e.response.data)
})
.finally(() => {
setTimeout(() => {
commit('SET_LOADING', false)
}, state.renderDelay)
})
}, state.delay)
},
/**
* Sets text for the future todo
*
* @param {any} { commit }
* @param {string} todo Message
*/
setNewTodo({ commit }, todo) {
commit('SET_NEW_TODO', todo)
},
addTodo({ commit, state }) {
if (!state.newTodo) {
// do not add empty todos
return
}
const todo = {
title: state.newTodo,
completed: false,
id: randomId()
}
// artificial delay in the application
// for test "flaky test - can pass or not depending on the app's speed"
// in cypress/integration/08-retry-ability/answer.js
// increase the timeout delay to make the test fail
// 50ms should be good
setTimeout(() => {
track('todo.add', todo.title)
axios.post('/todos', todo).then(() => {
commit('ADD_TODO', todo)
})
}, addTodoDelay)
},
addEntireTodo({ commit }, todoFields) {
const todo = {
...todoFields,
id: randomId()
}
axios.post('/todos', todo).then(() => {
commit('ADD_TODO', todo)
})
},
removeTodo({ commit }, todo) {
track('todo.remove', todo.title)
axios.delete(`/todos/${todo.id}`).then(() => {
console.log('removed todo', todo.id, 'from the server')
commit('REMOVE_TODO', todo)
})
},
async copyTodos({ state }) {
const markdown =
state.todos
.map(todo => {
const mark = todo.completed ? 'x' : ' '
return `- [${mark}] ${todo.title}`
})
.join('\n') + '\n'
await navigator.clipboard.writeText(markdown)
},
async removeCompleted({ commit, state }) {
const remainingTodos = state.todos.filter(todo => !todo.completed)
const completedTodos = state.todos.filter(todo => todo.completed)
for (const todo of completedTodos) {
await axios.delete(`/todos/${todo.id}`)
}
commit('SET_TODOS', remainingTodos)
},
async sortTodos({ commit, state }) {
const sortedTodos = state.todos.sort((a, b) => a.title.localeCompare(b.title))
await axios.post('/reset', { todos: sortedTodos })
commit('SET_TODOS', sortedTodos)
},
clearNewTodo({ commit }) {
commit('CLEAR_NEW_TODO')
},
// example promise-returning action
addTodoAfterDelay({ commit }, { milliseconds, title }) {
return new Promise(resolve => {
setTimeout(() => {
const todo = {
title,
completed: false,
id: randomId()
}
commit('ADD_TODO', todo)
resolve()
}, milliseconds)
})
}
}
})
// a few helper utilities
const filters = {
all: function (todos) {
return todos
},
active: function (todos) {
return todos.filter(function (todo) {
return !todo.completed
})
},
completed: function (todos) {
return todos.filter(function (todo) {
return todo.completed
})
}
}
// app Vue instance
const app = new Vue({
store,
data: {
file: null,
visibility: 'all'
},
el: '.todoapp',
created() {
const delay = parseFloat(params.get('delay') || '0')
const renderDelay = parseFloat(params.get('renderDelay') || '0')
addTodoDelay = parseFloat(params.get('addTodoDelay') || '0')
this.$store.dispatch('setRenderDelay', renderDelay).then(() => {
this.$store.dispatch('setDelay', delay).then(() => {
this.$store.dispatch('loadTodos')
})
})
// how would you test the periodic loading of todos?
setInterval(() => {
this.$store.dispatch('loadTodos')
}, 60000)
},
// computed properties
// https://vuejs.org/guide/computed.html
computed: {
loading() {
return this.$store.getters.loading
},
newTodo() {
return this.$store.getters.newTodo
},
todos() {
return this.$store.getters.todos
},
filteredTodos() {
return filters[this.visibility](this.$store.getters.todos)
},
remaining() {
return this.$store.getters.todos.filter(todo => !todo.completed).length
}
},
// methods that implement data logic.
// note there's no DOM manipulation here at all.
methods: {
pluralize: function (word, count) {
return word + (count === 1 ? '' : 's')
},
setNewTodo(e) {
this.$store.dispatch('setNewTodo', e.target.value)
},
addTodo(e) {
if (typeof e === 'string') {
this.$store.dispatch('setNewTodo', e)
this.$store.dispatch('addTodo')
this.$store.dispatch('clearNewTodo')
return
}
// do not allow adding empty todos
if (!e.target.value.trim()) {
throw new Error('Cannot add a blank todo')
}
e.target.value = ''
this.$store.dispatch('addTodo')
this.$store.dispatch('clearNewTodo')
},
removeTodo(todo) {
this.$store.dispatch('removeTodo', todo)
},
// utility method for create a todo with title and completed state
addEntireTodo(title, completed = false) {
this.$store.dispatch('addEntireTodo', {
title,
completed
})
},
removeCompleted() {
this.$store.dispatch('removeCompleted')
},
copyTodos() {
this.$store.dispatch('copyTodos')
},
sortTodos() {
this.$store.dispatch('sortTodos')
},
slowlySortTodos() {
const delay = Math.random() * 1000 + 1000
setTimeout(() => {
this.$store.dispatch('sortTodos')
}, delay)
}
}
})
// use the Router from the vendor/director.js library
;(function (app, Router) {
'use strict'
let router = new Router()
;['all', 'active', 'completed'].forEach(function (visibility) {
router.on(visibility, function () {
app.visibility = visibility
})
})
router.configure({
notfound: function () {
window.location.hash = ''
app.visibility = 'all'
}
})
router.init()
})(app, Router)
// if you want to expose "app" globally only
// during end-to-end tests you can guard it using "window.Cypress" flag
// if (window.Cypress) {
window.app = app
// }
}
if (appStartDelay > 0) {
setTimeout(appStart, appStartDelay)
} else {
appStart()
}