-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathprogram.fsx
579 lines (457 loc) · 17.3 KB
/
program.fsx
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
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
#load "runtime-scripts/Microsoft.AspNetCore.App-7.0.11.fsx"
#r "nuget: Saturn"
#r "nuget: Feliz.ViewEngine.Htmx"
#r "nuget: Unquote"
open Microsoft.AspNetCore.Builder
open Feliz.ViewEngine
open Feliz.ViewEngine.Htmx
open Giraffe
open Giraffe.EndpointRouting
open Saturn
open Saturn.Endpoint
open Microsoft.AspNetCore.Http
open Microsoft.Extensions.DependencyInjection
open Microsoft.Extensions.Logging
open Swensen.Unquote
[<AutoOpen>]
module Domain =
type Todo = {
Id: int
Text: string
Completed: bool
}
type Model = {
Todos: Todo list
}
[<AutoOpen>]
module Services =
open Microsoft.FSharp.Quotations
open FSharp.Linq.RuntimeHelpers
open Swensen.Unquote.Operators
type TodoRepository(logger: ILogger<TodoRepository>) =
let todos = new ResizeArray<Todo>()
member this.GetTodos(?filterPredicate: Expr<Todo -> bool>) =
let filter =
if filterPredicate.IsSome then
let predicate = filterPredicate.Value
let asStr = decompile predicate
logger.LogInformation($"filter: {asStr}")
predicate
else
<@ fun _ -> true @>
let lambda = LeafExpressionConverter.EvaluateQuotation filter :?> (Todo -> bool)
let res = todos |> Seq.filter(lambda) |> List.ofSeq
logger.LogInformation($"get todos, result: {res.Length}")
res
member this.GetTodo(id) =
todos |> Seq.find(fun t -> t.Id = id)
member this.AddTodo todoVal =
let newTodo = {
Id = todos.Count + 1
Text = todoVal
Completed = false
}
todos.Add(newTodo)
newTodo
member this.DeleteTodo id =
let foundTodo = todos.Find(fun t -> t.Id = id)
todos.Remove(foundTodo)
logger.LogInformation($"deleted todo, {id}")
member this.ClearAllTodos() =
todos.Clear()
logger.LogInformation($"deleted all todos")
member this.DeleteCompletedTodos() =
todos.RemoveAll(fun t -> t.Completed)
logger.LogInformation($"deleted completed todos.")
member this.UpdateTodo id todoVal =
let foundTodo = todos.Find(fun t -> t.Id = id)
let updatedTodo = { foundTodo with Text = todoVal }
todos.Add(updatedTodo)
todos.Remove(foundTodo) |> ignore
logger.LogInformation($"updated todo: {id} > {updatedTodo}")
updatedTodo
member this.ToggleTodo id =
let foundTodo = todos.Find(fun t -> t.Id = id)
let updatedTodo = { foundTodo with Completed = ( foundTodo.Completed |> not) }
todos.Add(updatedTodo)
todos.Remove(foundTodo) |> ignore
logger.LogInformation($"toggled todo: {id}")
updatedTodo
member this.ToggleAll() =
let newTodos =
todos
|> Seq.map (fun todo ->
let invertCompleted = todo.Completed |> not
{ todo with Completed = invertCompleted }
)
|> ResizeArray
todos.Clear()
todos.AddRange(newTodos)
logger.LogInformation($"toggled all todos")
todos
[<AutoOpen>]
module View =
// IMPORTANT: very useful > https://thisfunctionaltom.github.io/Html2Feliz/
let toHtml (view: ReactElement) =
view
|> Render.htmlView
|> htmlString
let listToHtml (view: ReactElement list) =
view
|> Render.htmlView
|> htmlString
let inputForm =
Html.form [
hx.indicator "todo-form"
hx.post "/todos"
hx.swap "afterbegin"
//hx.trigger "keyup[keyCode==13]"
hx.target "#todo-list"
prop.id "todo-form"
prop.children [
Html.input [
prop.id "new-todo"
prop.className "new-todo"
prop.name "title"
prop.placeholder "What needs to be done?"
prop.autoFocus true
]
]
]
let filters =
Html.ul [
prop.className "filters"
prop.children [
Html.li [
Html.a [
prop.href "#/"
hx.trigger "click"
hx.get "/todos"
hx.swap "outerHtml"
hx.target "#todo-list"
prop.text "All"
]
]
Html.li [
Html.a [
prop.href "#/active"
hx.trigger "click"
hx.get "/todos/active"
hx.swap "outerHtml"
hx.target "#todo-list"
prop.text "Active"
]
]
Html.li [
Html.a [
prop.href "#/completed"
hx.trigger "click"
hx.get "/todos/completed"
hx.swap "outerHtml"
hx.target "#todo-list"
prop.text "Completed"
]
]
]
]
let todosCount (count: int) =
Html.span [
prop.id "todos-count"
prop.text count
]
let todoListFooter =
Html.footer [
prop.className "footer"
hx.get "/todos"
hx.target "#todo-list"
prop.children [
Html.span [
prop.className "todo-count"
hx.indicator "footer"
hx.swap "outerHTML"
prop.children [
todosCount 0
]
]
filters
Html.button [
prop.className "clear-completed"
hx.confirm "Are you sure?"
hx.delete "/todos/completed"
hx.swap "innerHTML"
hx.target "#todo-list"
prop.text "Clear completed"
]
]
]
let body =
[
Html.section [
prop.className "todoapp"
prop.children [
Html.header [
prop.className "header"
prop.children [
Html.h1 "todos"
inputForm
]
]
Html.section [
prop.className "main"
prop.children [
Html.input [
prop.id "toggle-all"
prop.className "toggle-all"
prop.type' "checkbox"
hx.post "/todos/toggle-all"
hx.target "#todo-list"
]
Html.label [
prop.for' "toggle-all"
prop.text "Mark all as complete"
]
Html.ul [
prop.id "todo-list"
prop.className "todo-list"
]
]
]
todoListFooter
]
]
Html.footer [
prop.className "info"
prop.children [
Html.p "Double-click to edit a todo"
Html.p [
Html.text "Created by "
Html.a [
prop.href "https://todomvc.com"
prop.text "TodoMVC"
]
]
]
]
// Html.script [
// prop.text " htmx.on('htmx:configRequest', function (evt) { var headers = evt.detail.headers || {}; headers['X-Requested-With'] = 'XMLHttpRequest'; evt.detail.headers = headers; });"
// ]
]
let mainLayout =
Html.html [
Html.head [
Html.title "F# ♥ Htmx - TODO MVC"
Html.script [ prop.src "https://unpkg.com/[email protected]" ]
Html.meta [
prop.charset "utf-8"
]
Html.meta [
prop.name "viewport"
prop.content "width=device-width, initial-scale=1"
]
Html.title "TodoMVC"
Html.link [
prop.rel "stylesheet"
prop.href "https://unpkg.com/todomvc-common/base.css"
]
Html.link [
prop.rel "stylesheet"
prop.href "https://unpkg.com/todomvc-app-css/index.css"
]
]
Html.body body
]
|> toHtml
let editTodoText (todo: Todo) =
Html.form [
hx.post $"/todos/update/{todo.Id}"
prop.children [
Html.input [
prop.className "edit"
prop.type' "text"
prop.name "name"
prop.value todo.Text
]
]
]
(* TODO: original impl...
li(id='todo-' + todo.id,
class={completed: todo.done === true})
.view
input.toggle(hx-patch='/todos/' + todo.id,
type='checkbox',
checked=todo.done,
hx-target='#todo-' + todo.id,
hx-swap="outerHTML")
label(hx-get='/todos/edit/' + todo.id,
hx-target="#todo-" + todo.id,
hx-swap="outerHTML")
#{todo.name}
button.destroy(
hx-delete='/todos/' + todo.id,
_="on htmx:afterOnLoad remove #todo-" + todo.id )
*)
let todoLi (todo: Todo) =
Html.li [
// class={completed: todo.done === true}
if todo.Completed then
prop.className "completed"
prop.id $"todo-{todo.Id}"
hx.trigger "load"
hx.get "todos/count"
hx.target "#todos-count"
prop.children [
Html.div [
prop.className "view"
prop.children [
Html.input [
prop.className "toggle"
// prop.custom ("hx-patch", $"/todos/{todo.Id}")
hx.post $"/todos/{todo.Id}/toggle"
prop.type' "checkbox"
if todo.Completed then
prop.isChecked true
hx.target $"#todo-{todo.Id}"
hx.swap "outerHTML"
]
Html.label [
hx.get $"/todos/edit/{todo.Id}"
hx.swap "outerHTML"
hx.target $"#todo-{todo.Id}"
prop.text todo.Text
]
Html.button [
prop.className "destroy"
hx.swap "outerHTML"
hx.delete $"/todos/{todo.Id}"
hx.target $"#todo-{todo.Id}"
//hx.hyperscript $"on htmx:afterOnLoad remove #todo-{todo.Id}"
]
]
]
]
]
let currentTodos (repository : TodoRepository) =
let todos = repository.GetTodos()
if todos.Length = 0 then
[ ]
else [
for item in todos do
todoLi item
]
|> listToHtml
[<AutoOpen>]
module Controllers =
let addTodo (httpFunc: HttpFunc) (ctx: HttpContext) =
task {
let! formCollection = ctx.Request.ReadFormAsync()
let v = formCollection |> System.Text.Json.JsonSerializer.Serialize
let value = formCollection["title"] |> Seq.head
let repository = ctx.GetService<TodoRepository>()
let newTodo = repository.AddTodo(value)
let singleTodo = todoLi newTodo |> toHtml
return! singleTodo httpFunc ctx
}
let editTodo (id:int) (httpFunc: HttpFunc) (ctx: HttpContext) = task {
let repository = ctx.GetService<TodoRepository>()
let todo = repository.GetTodo id
let todoEditItem = View.editTodoText todo |> toHtml
return! todoEditItem httpFunc ctx
}
let updateTodo (id: int) (httpFunc: HttpFunc) (ctx: HttpContext) =
task {
let! formCollection = ctx.Request.ReadFormAsync()
let v = formCollection |> System.Text.Json.JsonSerializer.Serialize
let txtValue = formCollection["name"] |> Seq.head
let repository = ctx.GetService<TodoRepository>()
let updatedTodo = repository.UpdateTodo id txtValue
let updatedTodoHtml = todoLi updatedTodo |> toHtml
return! updatedTodoHtml httpFunc ctx
}
let toggle (id: int) (httpFunc: HttpFunc) (ctx: HttpContext) =
task {
let repository = ctx.GetService<TodoRepository>()
let updatedTodo = repository.ToggleTodo id
let updatedTodoHtml = todoLi updatedTodo |> toHtml
return! updatedTodoHtml httpFunc ctx
}
let toggleAll (httpFunc: HttpFunc) (ctx: HttpContext) =
task {
let repository = ctx.GetService<TodoRepository>()
repository.ToggleAll() |> ignore
let todosHtml = currentTodos repository
return! todosHtml httpFunc ctx
}
let deleteTodo (id: int) (httpFunc: HttpFunc) (ctx: HttpContext) =
task {
let repository = ctx.GetService<TodoRepository>()
repository.DeleteTodo id |> ignore
let empty = [] |> listToHtml
return! empty httpFunc ctx
}
let deleteCompletedTodos (httpFunc: HttpFunc) (ctx: HttpContext) =
task {
let repository = ctx.GetService<TodoRepository>()
repository.DeleteCompletedTodos() |> ignore
let todosHtml = currentTodos repository
return! todosHtml httpFunc ctx
}
let getTodos (httpFunc : HttpFunc) (ctx: HttpContext) =
task {
let repository = ctx.GetService<TodoRepository>()
let todosHtml = currentTodos repository
return! todosHtml httpFunc ctx
}
let getActiveTodos (httpFunc : HttpFunc) (ctx: HttpContext) =
task {
let repository = ctx.GetService<TodoRepository>()
let active = repository.GetTodos(<@ fun todo -> todo.Completed = false @>)
let activesHtml =
active
|> List.map todoLi
|> listToHtml
return! activesHtml httpFunc ctx
}
let getCompletedTodos (httpFunc : HttpFunc) (ctx: HttpContext) =
task {
let repository = ctx.GetService<TodoRepository>()
let completed = repository.GetTodos(<@ _.Completed @>)
let completedHtml =
completed
|> List.map todoLi
|> listToHtml
return! completedHtml httpFunc ctx
}
let getCount (httpFunc : HttpFunc) (ctx: HttpContext) =
task {
let repository = ctx.GetService<TodoRepository>()
let totalTodos = repository.GetTodos().Length
let resultSpan = View.todosCount totalTodos |> toHtml
return! resultSpan httpFunc ctx
}
//saturn routes
let endpoints =
router {
get "/" mainLayout
post "/todos" addTodo
get "/todos" getTodos
get "/todos/count" getCount
get "/todos/active" getActiveTodos
get "/todos/completed" getCompletedTodos
postf "/todos/%i/toggle" toggle
post "/todos/toggle-all" toggleAll
getf "/todos/edit/%i" editTodo
postf "/todos/update/%i" updateTodo
deletef "/todos/%i" deleteTodo
delete "/todos/completed" deleteCompletedTodos
}
let app =
application {
use_endpoint_router endpoints
// register repository as singleton
service_config (fun s -> s.AddSingleton<TodoRepository>(fun sp ->
let logger = sp.GetRequiredService<ILogger<TodoRepository>>()
new TodoRepository(logger)
)
)
}
run app