Repository navigation
Expand file tree
/
Copy pathclient_finished_course.html
More file actions
364 lines (334 loc) · 11.7 KB
/
Copy pathclient_finished_course.html
File metadata and controls
364 lines (334 loc) · 11.7 KB
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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Awesome Shopping App</title>
<link
rel="stylesheet"
href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css"
/>
<style>
.strikethrough {
text-decoration: line-through;
opacity: 0.55;
}
.clickable {
cursor: pointer;
}
[v-cloak] {
display: none;
}
</style>
<script type="importmap">
{
"imports": {
"vue": "https://cdn.jsdelivr.net/npm/vue@3/dist/vue.esm-browser.prod.js"
}
}
</script>
</head>
<body class="bg-body-tertiary">
<div id="app" v-cloak>
<div class="container py-4" style="max-width: 720px">
<header class="d-flex align-items-center justify-content-between mb-4">
<h1 class="h4 m-0">🛒 Awesome Shopping App</h1>
<button
v-if="isAuthenticated"
class="btn btn-sm btn-outline-secondary"
@click="logout"
>
Log out
</button>
</header>
<!-- Any API/network error surfaces here. -->
<div v-if="errorMessage" class="alert alert-danger" role="alert">
{{ errorMessage }}
</div>
<!-- ===================== LOGIN ===================== -->
<form
v-if="!isAuthenticated"
class="card card-body shadow-sm"
@submit.prevent="login"
>
<p class="text-body-secondary">
Sign in with your Django account to view your shopping lists.
</p>
<div class="mb-3">
<label class="form-label" for="username">Username</label>
<input
id="username"
v-model="credentials.username"
type="text"
class="form-control"
autocomplete="username"
required
/>
</div>
<div class="mb-3">
<label class="form-label" for="password">Password</label>
<input
id="password"
v-model="credentials.password"
type="password"
class="form-control"
autocomplete="current-password"
required
/>
</div>
<button class="btn btn-primary" type="submit" :disabled="loading">
<span
v-if="loading"
class="spinner-border spinner-border-sm me-1"
aria-hidden="true"
></span>
Sign in
</button>
</form>
<!-- ===================== APP ===================== -->
<template v-else>
<div v-if="loadingLists" class="text-center text-body-secondary py-5">
<span class="spinner-border" aria-hidden="true"></span>
</div>
<p v-else-if="lists.length === 0" class="text-body-secondary">
You have no shopping lists yet.
</p>
<template v-else>
<ul class="nav nav-tabs">
<li v-for="list in lists" :key="list.id" class="nav-item">
<button
class="nav-link"
type="button"
:class="{ active: list.id === activeListId }"
@click="selectList(list.id)"
>
{{ list.name }}
</button>
</li>
</ul>
<div class="border border-top-0 rounded-bottom p-3 bg-body">
<div
v-if="loadingItems"
class="text-center text-body-secondary py-4"
>
<span class="spinner-border" aria-hidden="true"></span>
</div>
<template v-else>
<ul class="list-group mb-3">
<li
v-for="item in activeItems"
:key="item.id"
class="clickable list-group-item d-flex align-items-center"
:class="{ strikethrough: item.purchased }"
@click="toggleItem(item)"
>
<input
class="form-check-input me-2"
type="checkbox"
:checked="item.purchased"
@click.prevent
/>
{{ item.name }}
</li>
<li
v-if="activeItems.length === 0"
class="list-group-item text-body-secondary"
>
This list is empty.
</li>
</ul>
<form @submit.prevent="addItem">
<input
v-model="newItemName"
type="text"
class="form-control"
placeholder="Add a new item and press Enter"
/>
</form>
</template>
</div>
</template>
</template>
</div>
</div>
<script type="module">
import { createApp, ref, reactive, computed, watch } from "vue";
// Point this at wherever your Django dev server is running.
const API_BASE = "http://127.0.0.1:8000";
const TOKEN_KEY = "shopping_app_token";
createApp({
setup() {
const token = ref(localStorage.getItem(TOKEN_KEY));
const credentials = reactive({ username: "", password: "" });
const lists = ref([]);
const activeListId = ref(null);
const itemsByList = reactive({});
const newItemName = ref("");
const loading = ref(false); // login request
const loadingLists = ref(false);
const loadingItems = ref(false);
const errorMessage = ref("");
const isAuthenticated = computed(() => Boolean(token.value));
const activeItems = computed(
() => itemsByList[activeListId.value] ?? []
);
async function api(path, options = {}) {
const headers = { ...options.headers };
if (options.body) headers["Content-Type"] = "application/json";
if (token.value) headers["Authorization"] = `Token ${token.value}`;
const response = await fetch(`${API_BASE}${path}`, {
...options,
headers,
});
if (response.status === 401) {
logout();
throw new Error("Your session has expired. Please sign in again.");
}
if (!response.ok) {
const detail = await response.json().catch(() => null);
throw new Error(extractError(detail) || `Request failed (${response.status})`);
}
// 204 No Content (e.g. DELETE) has no body to parse.
return response.status === 204 ? null : response.json();
}
function extractError(detail) {
if (!detail) return "";
if (typeof detail === "string") return detail;
// DRF errors look like {"field": ["msg"]} or {"detail": "msg"}.
const first = Object.values(detail).flat()[0];
return typeof first === "string" ? first : "";
}
/** Follow DRF's pagination `next` links to collect every result. */
async function fetchAllPages(path) {
const results = [];
let next = path;
while (next) {
const page = await api(next);
results.push(...page.results);
next = page.next ? page.next.replace(API_BASE, "") : null;
}
return results;
}
async function login() {
loading.value = true;
errorMessage.value = "";
try {
const data = await api("/api-token-auth/", {
method: "POST",
body: JSON.stringify({ ...credentials }),
});
token.value = data.token;
localStorage.setItem(TOKEN_KEY, data.token);
credentials.password = "";
await loadLists();
} catch (error) {
errorMessage.value =
"Login failed. Please check your username and password.";
} finally {
loading.value = false;
}
}
function logout() {
token.value = null;
localStorage.removeItem(TOKEN_KEY);
lists.value = [];
activeListId.value = null;
for (const key of Object.keys(itemsByList)) delete itemsByList[key];
}
async function loadLists() {
loadingLists.value = true;
errorMessage.value = "";
try {
lists.value = await fetchAllPages("/api/shopping-lists/");
if (lists.value.length) selectList(lists.value[0].id);
} catch (error) {
errorMessage.value = error.message;
} finally {
loadingLists.value = false;
}
}
async function selectList(listId) {
activeListId.value = listId;
newItemName.value = "";
if (itemsByList[listId]) return; // already cached
loadingItems.value = true;
errorMessage.value = "";
try {
itemsByList[listId] = sortItems(
await fetchAllPages(`/api/shopping-lists/${listId}/shopping-items/`)
);
} catch (error) {
errorMessage.value = error.message;
} finally {
loadingItems.value = false;
}
}
async function addItem() {
const name = newItemName.value.trim();
if (!name) return;
errorMessage.value = "";
try {
const created = await api(
`/api/shopping-lists/${activeListId.value}/shopping-items/`,
{
method: "POST",
body: JSON.stringify({ name, purchased: false }),
}
);
itemsByList[activeListId.value] = sortItems([
...activeItems.value,
created,
]);
newItemName.value = "";
} catch (error) {
errorMessage.value = error.message;
}
}
async function toggleItem(item) {
errorMessage.value = "";
try {
const updated = await api(
`/api/shopping-lists/${item.shopping_list}/shopping-items/${item.id}/`,
{
method: "PATCH",
body: JSON.stringify({ purchased: !item.purchased }),
}
);
const items = itemsByList[item.shopping_list];
const index = items.findIndex((i) => i.id === item.id);
items[index] = updated;
itemsByList[item.shopping_list] = sortItems(items);
} catch (error) {
errorMessage.value = error.message;
}
}
function sortItems(items) {
return [...items].sort(
(a, b) =>
Number(a.purchased) - Number(b.purchased) ||
a.name.localeCompare(b.name)
);
}
if (token.value) loadLists();
return {
credentials,
lists,
activeListId,
newItemName,
loading,
loadingLists,
loadingItems,
errorMessage,
isAuthenticated,
activeItems,
login,
logout,
selectList,
addItem,
toggleItem,
};
},
}).mount("#app");
</script>
</body>
</html>