-
Notifications
You must be signed in to change notification settings - Fork 33
/
index.html
306 lines (277 loc) · 8.78 KB
/
index.html
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
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<title>Serverless Todo with Vue and AWS Lambda</title>
<link rel="stylesheet" href="https://unpkg.com/todomvc-app-css@2.4.1/index.css" type="text/css" />
<script src="https://unpkg.com/vue@3"></script>
</head>
<body>
<!--
A fully spec-compliant TodoMVC implementation
https://todomvc.com/
-->
<script type="module">
const { createApp } = Vue
// This should be changed based on authenticated user
const STORAGE_KEY = 'vue-serverless-todo'
let apiBaseUrl = '{{API_BASE_URL}}';
function uuidv4(a) {
return a ? (a ^ crypto.getRandomValues(new Uint8Array(8))[0] % 16 >> a/4 ).toString(16) :
([1e7] + -1e3 + -4e3 + -8e3 + -1e11).replace(/[018]/g, uuidv4)
}
// AWS Cloud9 development
if (apiBaseUrl.indexOf('API_BASE_URL') !== -1) {
apiBaseUrl = location.protocol + '//' + location.hostname;
}
const filters = {
all: (todos) => todos,
active: (todos) => todos.filter((todo) => !todo.completed),
completed: (todos) => todos.filter((todo) => todo.completed)
}
createApp({
// app initial state
data: () => ({
todos: [], // JSON.parse(localStorage.getItem(STORAGE_KEY) || '[]'),
editedTodo: null,
visibility: 'all',
fetchedInitialData: false,
todosUrl: null,
todosId: null
}),
// watch todos change for localStorage persistence
watch: {
todos: {
handler(todos) {
const randomId = this.getRandomTodoId();
localStorage.setItem(STORAGE_KEY + '-' + randomId, JSON.stringify(todos))
if (this.fetchedInitialData) {
this.callApi('PUT', { body: todos, path: '/todos/' + randomId })
}
},
deep: true
}
},
mounted() {
this.init();
},
computed: {
filteredTodos() {
return filters[this.visibility](this.todos)
},
remaining() {
return filters.active(this.todos).length
}
},
// methods that implement data logic.
// note there's no DOM manipulation here at all.
methods: {
init(id) {
if (! this.isLoggedIn()) {
let loginUrl = (window.location.protocol + '//' + window.location.hostname + window.location.pathname).replace('/index.html', '/login.html');
if (window.location.pathname === '/') {
loginUrl = window.location.protocol + '//' + window.location.hostname + window.location.pathname + 'login.html';
}
window.location = loginUrl;
return
}
const randomId = id || this.getRandomTodoId()
localStorage.setItem('random-id', randomId)
console.log('randomId => ' + randomId)
window.history.replaceState(null, null, '?' + randomId + location.hash)
this.todosUrl = location.protocol + '//' + location.hostname + location.pathname + '?' + randomId
this.todosId = randomId
window.addEventListener('hashchange', this.onHashChange)
fetch(apiBaseUrl + '/todos/' + randomId, {
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer ' + window.localStorage.getItem('auth_token')
}
}).then( response => {
if (response.status >= 400) {
window.location = 'login.html' // relative path
window.localStorage.setItem('logged_in', false);
window.localStorage.removeItem('auth_token');
return;
}
response.json().then( items => {
console.log(items)
this.todos = items
this.fetchedInitialData = true;
this.onHashChange()
})
});
},
toggleAll(e) {
this.todos.forEach((todo) => (todo.completed = e.target.checked))
},
getRandomTodoId() {
return window.location.search.replace('?', '') ||
localStorage.getItem('random-id') ||
uuidv4().split('-')[4];
},
callApi(method, params) {
const fetchParam = {
method: method || 'GET',
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer ' + window.localStorage.getItem('auth_token')
}
}
const methodsWithBody = ['POST', 'PUT'];
if (methodsWithBody.indexOf(method) !== -1) {
fetchParam['body'] = JSON.stringify(params.body)
}
const urlPath = params.path || '';
fetch(apiBaseUrl + urlPath, fetchParam)
.then(response => {
if (response.status >= 400) {
window.location = 'login.html' // relative path
window.localStorage.setItem('logged_in', false);
window.localStorage.removeItem('auth_token');
return;
}
})
.catch(err => console.log(`ERR: Can not ${method} todo. Message: ` + err.toString()))
},
isLoggedIn() {
return JSON.parse(localStorage.getItem('logged_in')) === true;
},
addTodo(e) {
const value = e.target.value.trim()
if (!value) {
return
}
const newItem = {
id: Date.now(),
title: value,
completed: false
};
this.todos.push(newItem)
e.target.value = ''
},
removeTodo(todo) {
this.todos.splice(this.todos.indexOf(todo), 1)
},
editTodo(todo) {
this.beforeEditCache = todo.title
this.editedTodo = todo
},
doneEdit(todo) {
if (!this.editedTodo) {
return
}
this.editedTodo = null
todo.title = todo.title.trim()
if (!todo.title) {
this.removeTodo(todo)
}
},
cancelEdit(todo) {
this.editedTodo = null
todo.title = this.beforeEditCache
},
removeCompleted() {
this.todos = filters.active(this.todos)
},
createNewTodoId(e) {
this.todos = [];
localStorage.removeItem('random-id')
history.replaceState(null, null, location.pathname)
this.init(e.target.value.trim())
e.target.value = ''
document.querySelector('.new-todo').focus()
},
onHashChange() {
var visibility = window.location.hash.replace(/#\/?/, '')
if (filters[visibility]) {
this.visibility = visibility
} else {
window.location.hash = ''
this.visibility = 'all'
}
}
}
}).mount('#app')
</script>
<div id="app">
<section class="todoapp">
<header class="header">
<h1>todos</h1>
<input
class="new-todo"
autofocus
placeholder="What needs to be done?"
@keyup.enter="addTodo"
>
</header>
<section class="main" v-show="todos.length">
<input
id="toggle-all"
class="toggle-all"
type="checkbox"
:checked="remaining === 0"
@change="toggleAll"
>
<label for="toggle-all">Mark all as complete</label>
<ul class="todo-list">
<li
v-for="todo in filteredTodos"
class="todo"
:key="todo.id"
:class="{ completed: todo.completed, editing: todo === editedTodo }"
>
<div class="view">
<input class="toggle" type="checkbox" v-model="todo.completed">
<label @dblclick="editTodo(todo)">{{ todo.title }}</label>
<button class="destroy" @click="removeTodo(todo)"></button>
</div>
<input
v-if="todo === editedTodo"
class="edit"
type="text"
v-model="todo.title"
@vnode-mounted="({ el }) => el.focus()"
@blur="doneEdit(todo)"
@keyup.enter="doneEdit(todo)"
@keyup.escape="cancelEdit(todo)"
>
</li>
</ul>
</section>
<footer class="footer" v-show="todos.length">
<span class="todo-count">
<strong>{{ remaining }}</strong>
<span>{{ remaining === 1 ? ' item' : ' items' }} left</span>
</span>
<ul class="filters">
<li>
<a href="#/all" :class="{ selected: visibility === 'all' }">All</a>
</li>
<li>
<a href="#/active" :class="{ selected: visibility === 'active' }">Active</a>
</li>
<li>
<a href="#/completed" :class="{ selected: visibility === 'completed' }">Completed</a>
</li>
</ul>
<button class="clear-completed" @click="removeCompleted" v-show="todos.length > remaining">
Clear completed
</button>
</footer>
</section>
<section class="main">
<h3>Create or update todos</h3>
<input
class="new-todo"
placeholder="Enter todos id (empty for random)"
@keyup.enter="createNewTodoId"
>
<p>Current todos ({{ todosId }}) URL: <br><a :href="todosUrl">{{ todosUrl}}</a></p>
<!-- BEGIN - Remove this line
<p><a href="login.html?logout">Logout</a></p>
END - Remove this line -->
</section>
</div>
</body>
</html>