This repository has been archived by the owner on Aug 13, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
TodoMvc.hx
366 lines (333 loc) · 9.67 KB
/
TodoMvc.hx
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
package todomvc;
// This example was taken directly from Elm's TodoMVC example,
// to show how Blok can be similar to the Elm architecture.
//
// https://github.com/evancz/elm-todomvc/blob/master/src/Main.elm
import haxe.Json;
import haxe.ds.ReadOnlyArray;
using StringTools;
using Lambda;
using Blok;
class TodoMvc {
static function main() {
Platform.mount(
js.Browser.document.getElementById('root'),
Root.node({ model: Model.load() })
);
}
}
// `Record` is a simple way to create immutable objects.
//
// Instead of being able to mutate fields, you use a macro-generated
// `record.with({ ... })` method to create a copy of the object
// with updated fields.
//
// This is useful if you're using `@lazy` Components (more on that
// later) or trying to be Elmish.
class Entry implements Record {
@constant var id:Int; // @constant vars are always copied and never change.
@prop var description:String;
@prop var completed:Bool;
@prop var editing:Bool;
}
enum abstract Visibility(String) to String {
var All;
var Completed;
var Active;
}
// A `State` is like a mix of the Model and Updates in the Elm architecture.
//
// Think of each `@update` method as a message in elm.
@service(fallback = Model.load())
class Model implements State {
static inline final BLOK_TODO_MODEL = 'blok-todo-model';
public static function load():Model {
var stored = js.Browser.window.localStorage.getItem(BLOK_TODO_MODEL);
var model = if (stored == null)
new Model({
uid: 0,
visibility: All,
entries: []
})
else {
var raw = Json.parse(stored);
var entries = (Reflect.field(raw, 'entries'):Array<Dynamic>).map(e -> {
new Entry(cast e);
});
Reflect.setField(raw, 'entries', entries);
new Model(cast raw);
}
model.getObservable().observe(save);
return model;
}
static function save(model:Model) {
js.Browser.window.localStorage.setItem(BLOK_TODO_MODEL, Json.stringify({
uid: model.uid,
visibility: model.visibility,
entries: model.entries
}));
}
@prop var entries:ReadOnlyArray<Entry>;
@prop var field:String = '';
@prop var uid:Int;
@prop var visibility:Visibility;
@memo
public function getVisibleEntries() {
var out = entries.filter(entry -> switch visibility {
case Completed: entry.completed;
case Active: !entry.completed;
case All: true;
});
out.reverse();
return out;
}
@update
public function add() {
if (field.trim().length == 0) return null;
return {
field: '',
uid: uid + 1,
entries: entries.concat([
new Entry({
id: uid,
description: field,
editing: false,
completed: false
})
])
};
}
@update
public function updateField(value:String) {
return { field: value };
}
@update
public function editingEntry(id:Int, isEditing:Bool) {
if (!entries.exists(e -> e.id == id)) return null;
return {
entries: entries.map(e -> if (e.id == id) e.with({ editing: isEditing }) else e)
};
}
@update
public function updateEntry(id:Int, description:String) {
if (!entries.exists(e -> e.id == id)) return null;
return {
entries: entries.map(e -> if (e.id == id) e.with({ description: description }) else e)
};
}
@update
public function deleteEntry(id:Int) {
if (!entries.exists(e -> e.id == id)) return null;
return {
entries: entries.filter(e -> e.id != id)
};
}
@update
public function deleteCompleted() {
return {
entries: entries.filter(e -> !e.completed)
};
}
@update
public function check(id:Int, isCompleted:Bool) {
if (!entries.exists(e -> e.id == id)) return null;
return {
entries: entries.map(e -> if (e.id == id) e.with({ completed: isCompleted }) else e)
};
}
@update
public function checkAll(isCompleted:Bool) {
return {
entries: entries.map(e -> e.with({ completed: isCompleted }))
};
}
@update
public function changeVisibility(visibility:Visibility) {
return { visibility: visibility };
}
}
class Root extends Component {
@prop var model:Model;
public function render() {
return Html.div({ className: 'todomvc-wrapper' },
Html.section({ className: 'todoapp' },
Provider.provide(model, context -> Html.fragment(
ViewInput.node({ task: Model.from(context).field }),
ViewEntries.node({}),
ViewControls.node({})
))
)
);
}
}
// Components marked with `@lazy` will only update if their
// `@prop`s have changed (only `task` in this case).
@lazy
class ViewInput extends Component {
@prop var task:String;
var ref:js.html.InputElement;
public function render() {
return Html.header({ className: 'header' },
Context.use(context -> Html.fragment(
Html.h1({}, Html.text('todos')),
Html.input({
ref: el -> ref = cast el,
className: 'new-todo',
placeholder: 'What needs doing?',
autofocus: true,
value: task,
oninput: e -> {
Model.from(context).updateField(ref.value);
},
onkeydown: e -> {
var ev:js.html.KeyboardEvent = cast e;
if (ev.key == 'Enter') {
ref.value = '';
Model.from(context).add();
}
}
})
)
)
);
}
}
class ViewEntries extends Component {
public function render() {
return Model.use(model -> {
var allCompleted = model.entries.filter(e -> !e.completed).length == 0;
Html.section({
className: 'main',
style: if (model.entries.length == 0) 'visibility: hidden' else null
},
Html.input({
className: 'toggle-all',
id: 'toggle-all',
type: Checkbox,
name: 'toggle-all',
checked: allCompleted,
onclick: _ -> model.checkAll(!allCompleted)
}),
Html.label({ htmlFor: 'toggle-all' },
Html.text('Mark all as complete')
),
Html.ul({ className: 'todo-list' },
...[ for (entry in model.getVisibleEntries())
// Note the second argument here -- this is the component's
// key, which ensures we maintain the correct order for our
// components.
ViewEntry.node({ entry: entry }, entry.id)
]
)
);
});
}
}
class ViewEntry extends Component {
@prop var entry:Entry;
@use var model:Model; // @use is a shortcut for `Model.from(context)`.
var ref:js.html.InputElement;
// Methods with `@effect` meta will run after _every_ render.
//
// Other available hooks are `@init` (runs once when the
// Component is constructed) and `@dispose` (runs once when
// the Component is removed).
@effect
public function maybeFocus() {
if (entry.editing) ref.focus();
}
public function render() {
return Html.li({
key: entry.id,
className: [
if (entry.completed) 'completed' else null,
if (entry.editing) 'editing' else null
].filter(c -> c != null).join(' ')
},
Html.div({ className: 'view' },
Html.input({
className: 'toggle',
type: Checkbox,
checked: entry.completed,
onclick: _ -> model.check(entry.id, !entry.completed)
}),
Html.label({
ondblclick: _ -> model.editingEntry(entry.id, true)
}, Html.text(entry.description)),
Html.button({
className: 'destroy',
onclick: _ -> model.deleteEntry(entry.id)
})
),
Html.input({
ref: e -> ref = cast e,
className: 'edit',
value: entry.description,
name: 'title',
id: 'todo-${entry.id}',
oninput: _ -> model.updateEntry(entry.id, ref.value),
onblur: _ -> model.editingEntry(entry.id, false),
onkeydown: e -> {
var ev:js.html.KeyboardEvent = cast e;
if (ev.key == 'Enter') {
model.editingEntry(entry.id, false);
}
}
})
);
}
}
class ViewControls extends Component {
public function render() {
return Model.use(model -> {
var entriesCompleted = model.entries.filter(e -> e.completed).length;
var entriesLeft = model.entries.length - entriesCompleted;
return Html.footer(
{
className: 'footer',
style: if (model.entries.length == 0) 'display: none' else null
},
Html.span({ className: 'todo-count' },
Html.strong({},
Html.text(switch entriesLeft {
case 1: '${entriesLeft} item left';
default: '${entriesLeft} items left';
})
)
),
Html.ul({ className: 'filters' },
visibilityControl('#/', All, model.visibility, model),
visibilityControl('#/active', Active, model.visibility, model),
visibilityControl('#/completed', Completed, model.visibility, model)
),
Html.button(
{
className: 'clear-completed',
style: if (entriesCompleted == 0) 'visibility: hidden' else null,
onclick: _ -> model.deleteCompleted()
},
Html.text('Clear completed (${entriesCompleted})')
)
);
});
}
inline function visibilityControl(
url:String,
visibility:Visibility,
actualVisibility:Visibility,
model:Model
) {
return Html.li(
{
onclick: _ -> model.changeVisibility(visibility)
},
Html.a(
{
href: url,
className: if (visibility == actualVisibility) 'selected' else null
},
Html.text(visibility)
)
);
}
}