This repository was archived by the owner on Nov 24, 2023. It is now read-only.
-
-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathTodoMvcApp.scala
194 lines (154 loc) · 6.4 KB
/
TodoMvcApp.scala
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
package todomvc
import com.raquo.laminar.api.L.{*, given}
import org.scalajs.dom.KeyCode
// Laminar is a simple, expressive, and safe UI library for Scala.js
// https://github.com/raquo/Laminar
// Everything we need is in this one file. TodoMvcApp.render() is called from App.scala
object TodoMvcApp {
// This implementation is very loosely based on Outwatch TodoMVC, for comparison see
// https://github.com/clovellytech/outwatch-examples/tree/master/todomvc/src/main/scala/todomvc
// Models
case class TodoItem(id: Int, text: String, completed: Boolean)
sealed abstract class Filter(val name: String, val passes: TodoItem => Boolean)
object ShowAll extends Filter("All", _ => true)
object ShowActive extends Filter("Active", !_.completed)
object ShowCompleted extends Filter("Completed", _.completed)
val filters: List[Filter] = ShowAll :: ShowActive :: ShowCompleted :: Nil
sealed trait Command
case class Create(itemText: String) extends Command
case class UpdateText(itemId: Int, text: String) extends Command
case class UpdateCompleted(itemId: Int, completed: Boolean) extends Command
case class Delete(itemId: Int) extends Command
case object DeleteCompleted extends Command
// State
// Var-s are reactive state variables suitable for both local state and redux-like global stores.
// Laminar uses my library Airstream as its reactive layer https://github.com/raquo/Airstream
private val itemsVar = Var(List[TodoItem]())
private val filterVar = Var[Filter](ShowAll)
private var lastId = 1 // just for auto-incrementing IDs
private val commandObserver = Observer[Command] {
case Create(itemText) =>
lastId += 1
if (filterVar.now() == ShowCompleted) filterVar.set(ShowAll)
itemsVar.update(_ :+ TodoItem(id = lastId, text = itemText, completed = false))
case UpdateText(itemId, text) =>
itemsVar.update(_.map(item => if (item.id == itemId) item.copy(text = text) else item))
case UpdateCompleted(itemId, completed) =>
itemsVar.update(_.map(item => if (item.id == itemId) item.copy(completed = completed) else item))
case Delete(itemId) =>
itemsVar.update(_.filterNot(_.id == itemId))
case DeleteCompleted =>
itemsVar.update(_.filterNot(_.completed))
}
// Rendering
// This is what we expose to the public – a single div element: not a stream, not some virtual DOM representation.
// You can get the real JS DOM element it manages using its .ref property – that reference does not change over time.
def apply(): HtmlElement = {
div(
cls("todoapp"),
div(
cls("header"),
h1("todos"),
renderNewTodoInput,
),
div(
hideIfNoItems,
cls("main"),
ul(
cls("todo-list"),
children <-- itemsVar.signal.combineWith(filterVar.signal).mapN(_ filter _.passes).split(_.id)(renderTodoItem)
)
),
renderStatusBar
)
}
private def renderNewTodoInput =
input(
cls("new-todo"),
placeholder("What needs to be done?"),
onMountFocus,
inContext { thisNode =>
// Note: mapTo below accepts parameter by-name, evaluating it on every enter key press
onEnterPress.mapToValue.filter(_.nonEmpty) -->
commandObserver.contramap[String] { text =>
thisNode.ref.value = "" // clear input
Create(itemText = text)
}
}
)
// Render a single item. Note that the result is a single element: not a stream, not some virtual DOM representation.
private def renderTodoItem(itemId: Int, initialTodo: TodoItem, $item: Signal[TodoItem]): HtmlElement = {
val isEditingVar = Var(false) // Example of local state
val updateTextObserver = commandObserver.contramap[UpdateText] { updateCommand =>
isEditingVar.set(false)
updateCommand
}
li(
cls <-- $item.map(item => Map("completed" -> item.completed)),
onDblClick.filter(_ => !isEditingVar.now()).mapTo(true) --> isEditingVar.writer,
children <-- isEditingVar.signal.map[List[HtmlElement]] {
case true =>
renderTextUpdateInput(itemId, $item, updateTextObserver) :: Nil
case false =>
List(
renderCheckboxInput(itemId, $item),
label(child.text <-- $item.map(_.text)),
button(cls("destroy"), onClick.mapTo(Delete(itemId)) --> commandObserver)
)
}
)
}
// Note that we pass reactive variables: `$item` for reading, `updateTextObserver` for writing
private def renderTextUpdateInput(itemId: Int, $item: Signal[TodoItem], updateTextObserver: Observer[UpdateText]) =
input(
cls("edit"),
defaultValue <-- $item.map(_.text),
onMountFocus,
onEnterPress.mapToValue.map(UpdateText(itemId, _)) --> updateTextObserver,
onBlur.mapToValue.map(UpdateText(itemId, _)) --> updateTextObserver
)
private def renderCheckboxInput(itemId: Int, $item: Signal[TodoItem]) =
input(
cls("toggle"),
typ("checkbox"),
checked <-- $item.map(_.completed),
onInput.mapToChecked.map(checked => UpdateCompleted(itemId, completed = checked)) --> commandObserver
)
private def renderStatusBar =
footerTag(
hideIfNoItems,
cls("footer"),
span(
cls("todo-count"),
child.text <-- itemsVar.signal
.map(_.count(!_.completed))
.map(pluralize(_, "item left", "items left")),
),
ul(
cls("filters"),
filters.map(filter => li(renderFilterButton(filter)))
),
child.maybe <-- itemsVar.signal.map { items =>
if (items.exists(ShowCompleted.passes)) Some(
button(
cls("clear-completed"),
"Clear completed",
onClick.map(_ => DeleteCompleted) --> commandObserver
)
) else None
}
)
private def renderFilterButton(filter: Filter) =
a(
cls <-- filterVar.signal.map(selectedFilter => Map("selected" -> (selectedFilter == filter))),
onClick.preventDefault.mapTo(filter) --> filterVar.writer,
filter.name
)
// Every little thing in Laminar can be abstracted away
private def hideIfNoItems: Mod[HtmlElement] =
display <-- itemsVar.signal.map(items => if (items.nonEmpty) "" else "none")
// Helpers
private def pluralize(num: Int, singular: String, plural: String): String =
s"$num ${if (num == 1) singular else plural}"
private val onEnterPress = onKeyPress.filter(_.keyCode == KeyCode.Enter)
}