-
Notifications
You must be signed in to change notification settings - Fork 1
/
main.go
433 lines (354 loc) · 10.8 KB
/
main.go
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
package main
import (
"crypto/rand"
"encoding/base64"
"encoding/json"
"fmt"
"net/http"
"os"
"strconv"
"strings"
"time"
"todomvc/go-templ-htmx-_hyperscript/tpl"
"github.com/a-h/templ"
)
var idCounter uint64
type Todo struct {
Id uint64 `json:"id"`
title string
Done bool `json:"done"`
editing bool
}
type todos []Todo
type Filter struct {
url string
name string
selected bool
}
// enum
type Action int
// group action related constants in one type
const (
Create Action = 0
Toggle Action = 1
Edit Action = 2
Update Action = 3
Delete Action = 4
)
var filters = []Filter{
{url: "#/", name: "All", selected: true},
{url: "#/active", name: "Active", selected: false},
{url: "#/completed", name: "Completed", selected: false},
}
func (t *todos) crudOps(action Action, todo Todo) Todo {
index := -1
if action != Create {
for i, r := range *t {
if r.Id == todo.Id {
index = i
break
}
}
}
switch action {
case Create:
*t = append(*t, todo)
return todo
case Toggle:
(*t)[index].Done = todo.Done
case Update:
title := strings.Trim(todo.title, " ")
if len(title) != 0 {
(*t)[index].title = title
(*t)[index].editing = false
} else {
// remove if title is empty
*t = append((*t)[:index], (*t)[index+1:]...)
return Todo{}
}
case Delete:
*t = append((*t)[:index], (*t)[index+1:]...)
default:
// edit should do nothing only return todo from store
}
if index != -1 && action != Delete {
return (*t)[index]
}
return Todo{}
}
// main is the entry point of the application.
func main() {
t := &todos{}
// Register the routes.
http.Handle("/set-hash", http.HandlerFunc(setHash))
http.Handle("/learn.json", http.HandlerFunc(learnHandler))
http.Handle("/update-count", http.HandlerFunc(t.updateCount))
http.Handle("/toggle-all", http.HandlerFunc(t.toggleAllHandler))
http.Handle("/completed", http.HandlerFunc(t.clearCompleted))
http.Handle("/footer", http.HandlerFunc(t.footerHandler))
http.Handle("/", http.HandlerFunc(t.pageHandler))
http.Handle("/add-todo", http.HandlerFunc(t.addTodoHandler))
http.Handle("/toggle-todo", http.HandlerFunc(t.toggleTodo))
http.Handle("/edit-todo", http.HandlerFunc(t.editTodoHandler))
http.Handle("/update-todo", http.HandlerFunc(t.updateTodo))
http.Handle("/remove-todo", http.HandlerFunc(t.removeTodo))
http.Handle("/toggle-main", http.HandlerFunc(t.toggleMainHandler))
http.Handle("/toggle-footer", http.HandlerFunc(t.toggleFooterHandler))
http.Handle("/todo-list", http.HandlerFunc(t.todoListHandler))
http.Handle("/todo-json", http.HandlerFunc(t.getJSON))
http.Handle("/swap-json", http.HandlerFunc(t.swapJSON))
http.Handle("/todo-item", http.HandlerFunc(t.todoItemHandler))
// this is used to serve axe-core for the todomvc test
dir := "./cypress-example-todomvc/node_modules"
// serve *._hs file
http.Handle("/hs/", http.StripPrefix("/hs/", http.FileServer(http.Dir("./hs"))))
// use the http.Handle to register the file server handler for a specific route
http.Handle("/node_modules/", http.StripPrefix("/node_modules/", http.FileServer(http.Dir(dir))))
// start the server.
addr := os.Getenv("LISTEN_ADDRESS")
if addr == "" {
addr = "localhost:8888"
}
fmt.Printf("Listening on %s\n", addr)
// Start the HTTP server
if err := http.ListenAndServe(addr, nil); err != nil {
fmt.Printf("Error: %s\n", err)
}
}
// countNotDone returns the count of todos that are not done
func countNotDone(todos []Todo) int {
count := 0
for _, todo := range todos {
if !todo.Done {
count++
}
}
return count
}
func defChecked(todos []Todo) bool {
// count the number of uncompleted tasks
uncompletedCount := countNotDone(todos)
// determine the defaultChecked value
defaultChecked := false
if uncompletedCount == 0 && len(todos) > 0 {
defaultChecked = true
}
return defaultChecked
}
// has completeTask checks if there is any completed task in the Todos slice
func hasCompleteTask(todos []Todo) bool {
for _, todo := range todos {
if todo.Done {
return true
}
}
return false
}
// templRenderer sets the common headers and renders the given component.
func templRenderer(w http.ResponseWriter, r *http.Request, component templ.Component) {
w.Header().Set("Content-Type", "text/html; charset=utf-8")
component.Render(r.Context(), w)
}
// byteRenderer writes the given value as a response with the Content-Type header set to text/html; charset=utf-8.
func byteRenderer[V string](w http.ResponseWriter, r *http.Request, value V) {
w.Header().Set("Content-Type", "text/html; charset=utf-8")
w.Write([]byte(value))
}
func learnHandler(w http.ResponseWriter, r *http.Request) {
// set the Content-Type header to indicate JSON
w.Header().Set("Content-Type", "application/json")
// create an empty JSON object and write it to the response
emptyJSON := map[string]interface{}{} // an empty JSON object
json.NewEncoder(w).Encode(emptyJSON)
}
// this for acquiring todos as json where client can fetch todo to render when route change
// its pretty much as the same how react do DOM diffing instead we do it on server and send
// the needed rendered HTML as client check which one is missing
func (t *todos) getJSON(w http.ResponseWriter, r *http.Request) {
// set the Content-Type header to indicate JSON
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(*t)
}
// swap json state if toggle is click
func (t *todos) swapJSON(w http.ResponseWriter, r *http.Request) {
all, err := strconv.ParseBool(r.FormValue("all"))
if err != nil {
fmt.Println("Error:", err)
return
}
for _, todo := range *t {
id := todo.Id
if all {
t.crudOps(Toggle, Todo{id, "", true, false})
} else {
t.crudOps(Toggle, Todo{id, "", false, false})
}
}
byteRenderer(w, r, "")
}
func selectedFilter(filters []Filter) string {
for _, filter := range filters {
if filter.selected {
return filter.name
}
}
return "All"
}
func setHash(w http.ResponseWriter, r *http.Request) {
name := r.FormValue("name")
if len(name) == 0 {
name = "All"
}
// loop through filters and update the selected field
for i := range filters {
if filters[i].name == name {
filters[i].selected = true
} else {
filters[i].selected = false
}
}
byteRenderer(w, r, "")
}
func generateRandomString(length int) (string, error) {
bytes := make([]byte, length)
_, err := rand.Read(bytes)
if err != nil {
return "", err
}
return base64.URLEncoding.EncodeToString(bytes), nil
}
func (t *todos) footerHandler(w http.ResponseWriter, r *http.Request) {
templRenderer(w, r, footer(*t, filters, hasCompleteTask(*t)))
}
func (t *todos) pageHandler(w http.ResponseWriter, r *http.Request) {
_, err := r.Cookie("sessionId")
if err == http.ErrNoCookie {
// fmt.Println("Error:", err)
newCookieValue, err := generateRandomString(32)
if err != nil {
http.Error(w, "Internal Server Error", http.StatusInternalServerError)
return
}
newCookie := http.Cookie{
Name: "sessionId",
Value: newCookieValue,
Expires: time.Now().Add(time.Second * 6000),
HttpOnly: true,
}
http.SetCookie(w, &newCookie)
// start with new todo data when session is reset
*t = make([]Todo, 0)
idCounter = 0
}
templRenderer(w, r, Page(*t, filters, defChecked(*t), hasCompleteTask(*t), selectedFilter(filters)))
}
func (t *todos) todoListHandler(w http.ResponseWriter, r *http.Request) {
templRenderer(w, r, todoList(*t, selectedFilter(filters)))
}
// toggle section main
func (t *todos) toggleMainHandler(w http.ResponseWriter, r *http.Request) {
templRenderer(w, r, toggleMain(*t, defChecked(*t)))
}
// toggle footer footer
func (t *todos) toggleFooterHandler(w http.ResponseWriter, r *http.Request) {
templRenderer(w, r, footer(*t, filters, hasCompleteTask(*t)))
}
func (t *todos) addTodoHandler(w http.ResponseWriter, r *http.Request) {
title := strings.Trim(r.FormValue("title"), " ")
// ignore adding if title is empty
if len(title) == 0 {
byteRenderer(w, r, "")
return
}
idCounter++
id := idCounter
todo := t.crudOps(Create, Todo{id, title, false, false})
if len(*t) == 1 {
templRenderer(w, r, todoList(*t, selectedFilter(filters)))
} else {
templRenderer(w, r, todoItem(todo, selectedFilter(filters)))
}
}
func (t *todos) todoItemHandler(w http.ResponseWriter, r *http.Request) {
id, err := strconv.ParseUint(r.FormValue("id"), 0, 32)
if err != nil {
fmt.Println("Error:", err)
return
}
todo := t.crudOps(Edit, Todo{id, "", false, false})
templRenderer(w, r, todoItem(todo, selectedFilter(filters)))
}
func (t *todos) clearCompleted(w http.ResponseWriter, r *http.Request) {
// determine render "none" or "block" based on incomplete tasks
hasCompleted := hasCompleteTask(*t)
if hasCompleted {
templRenderer(w, r, tpl.ClearCompleted(hasCompleteTask(*t)))
} else {
byteRenderer(w, r, "")
}
}
func (t *todos) updateCount(w http.ResponseWriter, r *http.Request) {
uncompletedCount := countNotDone(*t)
plural := ""
if uncompletedCount != 1 {
plural = "s"
}
byteRenderer(w, r, fmt.Sprintf("<strong>%d</strong> item%s left", uncompletedCount, plural))
}
func (t *todos) toggleAllHandler(w http.ResponseWriter, r *http.Request) {
// count the number of uncompleted tasks
checked := defChecked(*t)
// render the template or send the value to the client as needed
byteRenderer(w, r, strconv.FormatBool(checked))
}
func (t *todos) toggleTodo(w http.ResponseWriter, r *http.Request) {
id, err := strconv.ParseUint(r.FormValue("id"), 0, 32)
if err != nil {
fmt.Println("Error:", err)
return
}
done, err := strconv.ParseBool(r.FormValue("done"))
if err != nil {
fmt.Println("Error:", err)
return
}
todo := t.crudOps(Toggle, Todo{id, "", !done, false})
templRenderer(w, r, todoItem(todo, selectedFilter(filters)))
}
func (t *todos) editTodoHandler(w http.ResponseWriter, r *http.Request) {
id, err := strconv.ParseUint(r.FormValue("id"), 0, 32)
if err != nil {
fmt.Println("Error:", err)
return
}
// the trick is to only target the input element,
// since there's bunch _hyperscript scope events happening here
// we don't want to swap and loose the selectors.
// we also don't want to do any crud operations
// since editing only client side changes
todo := t.crudOps(Edit, Todo{id, "", false, false})
templRenderer(w, r, editTodo(Todo{id, todo.title, todo.Done, true}))
}
func (t *todos) updateTodo(w http.ResponseWriter, r *http.Request) {
id, err := strconv.ParseUint(r.FormValue("id"), 0, 32)
if err != nil {
fmt.Println("Error:", err)
return
}
title := r.FormValue("title")
todo := t.crudOps(Update, Todo{id, title, false, false})
if len(todo.title) == 0 {
byteRenderer(w, r, "")
return
}
templRenderer(w, r, todoItem(todo, selectedFilter(filters)))
}
func (t *todos) removeTodo(w http.ResponseWriter, r *http.Request) {
id, err := strconv.ParseUint(r.FormValue("id"), 0, 32)
if err != nil {
fmt.Println("Error:", err)
return
}
t.crudOps(Delete, Todo{id, "", false, false})
byteRenderer(w, r, "")
}