This repository was archived by the owner on Nov 13, 2018. It is now read-only.
Repository navigation
Expand file tree
/
Copy pathApp.fs
More file actions
420 lines (362 loc) · 14.3 KB
/
Copy pathApp.fs
File metadata and controls
420 lines (362 loc) · 14.3 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
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
(**
- title: React-Redux TodoMVC with Fable
- tagline: Use Redux development tools with Fable
- app-style: width:800px; margin:20px auto 50px auto;
- require-paths: `'react': 'lib/react/react-with-addons', 'react-dom': 'lib/react/react-dom', 'redux': 'lib/redux/redux'`
- intro: This is a port of [React-Redux TodoMVC](https://github.com/reactjs/redux/tree/master/examples/todomvc) to show how easy
is to take advantage of the full power of [React](https://facebook.github.io/react/) and [Redux](http://redux.js.org/) in Fable apps.
You can also compare the [F# source code](https://github.com/fable-compiler/Fable/blob/master/samples/browser/react-redux/react-redux.fsx)
with the [original JS implementation](https://github.com/reactjs/redux/tree/master/examples/todomvc)
to see the advantages of Fable programming. And you can install the [Redux DevTools](http://zalmoxisus.github.io/redux-devtools-extension/)
to get the full debugging experience of modern JS development with Fable!
*)
(**
## JavaScript bindings
Fable includes [React bindings and helpers](https://www.npmjs.com/package/fable-import-react)
to make interaction with the tool more idiomatic in F#.
*)
module ReduxTodoMVC
(**
## Redux helper
Fable's support for Redux is experimental and there're no bindings available.
In order to use Redux in you Fable apps, just copy the code of the module below
and be sure to add Redux as a JS dependency.
*)
open System
open Fable.Core
open Fable.Core.JsInterop
module Redux =
open System
open Fable.Import
open Fable.Core
open Fable.Core.JsInterop
type IStore<'TState, 'TAction> =
abstract dispatch: 'TAction->unit
abstract subscribe: (unit->unit)->unit
abstract getState: unit->'TState
let private createStore_: JsFunc = import "createStore" "redux"
let createStore (reducer: 'TState->'TAction->'TState) (initState: 'TState): IStore<'TState, 'TAction> =
// Check if the action is a lifecycle event dispatched by Redux before applying the reducer
let jsReducer =
fun state action ->
match !!action?``type``: obj with
| :?string as s when s.StartsWith "@@" -> state
| _ -> reducer state action
match !!Browser.window?devToolsExtension: JsFunc with
| null -> !!createStore_.Invoke(jsReducer, initState)
| ext -> !!createStore_.Invoke(jsReducer, initState, ext.Invoke())
(**
## Domain models
Open the necessary namespaces, define our domain models (`Todo`, `TodoAction`, `TodoFilter`)
and some utilities (key codes, `classNames`).
*)
open System
open Fable.Core
open Fable.Core.JsInterop
open Fable.Import
module R = Fable.Helpers.React
open R.Props
type Todo = { Text: string; Completed: bool; Id: int }
[<Pojo>]
type TodoAction =
| AddTodo of text:string
| DeleteTodo of id:int
| EditTodo of id:int * text:string
| CompleteTodo of id:int
| CompleteAll
| ClearCompleted
type TodoFilter =
| ShowAll = 0
| ShowActive = 1
| ShowCompleted = 2
let [<Literal>] ESCAPE_KEY = 27.
let [<Literal>] ENTER_KEY = 13.
let classNames =
List.choose (fun (txt,add) -> if add then Some txt else None)
>> String.concat " "
(**
## React components
Define React components in the same way as explained in [React guide](https://facebook.github.io/react/docs/reusable-components.html#es6-classes)
but with statically checked `props` and `state` types and the DSL from the [Fable React helper](https://www.npmjs.com/package/fable-import-react).
Check the `render` method of each component and the [Fable React TodoMVC sample](https://fable-compiler.github.io/samples/react-todomvc/index.html#/) for details,
or scroll down to see how to subscribe React components to the Redux store.
*)
[<Pojo>]
type TodoTextInputProps =
{ OnSave: string->unit
; Text: string option
; Placeholder: string
; Editing: bool
; NewTodo: bool }
[<Pojo>]
type TodoTextInputState = { Text: string }
type TodoTextInput(props) =
inherit React.Component<TodoTextInputProps, TodoTextInputState>(props)
do base.setInitState({ Text = defaultArg props.Text "" })
member this.HandleSubmit(e: React.KeyboardEvent) =
if e.which = ENTER_KEY then
let text = (unbox<string> e.target?value).Trim()
this.props.OnSave(text)
if this.props.NewTodo then
this.setState({ Text = "" })
member this.HandleChange(e: React.SyntheticEvent) =
this.setState({ Text=unbox e.target?value })
member this.HandleBlur(e: React.SyntheticEvent) =
if not this.props.NewTodo then
this.props.OnSave(unbox e.target?value)
member this.render() =
R.input [
ClassName(
classNames [
"edit", this.props.Editing
"new-todo", this.props.NewTodo
])
Type "text"
OnBlur this.HandleBlur
OnChange this.HandleChange
OnKeyDown this.HandleSubmit
AutoFocus (this.state.Text.Length > 0)
Placeholder this.props.Placeholder
]
[<Pojo>]
type TodoItemProps =
{ Todo: Todo
; EditTodo: int * string -> unit
; DeleteTodo: int -> unit
; CompleteTodo: int -> unit }
[<Pojo>]
type TodoItemState = { Editing: bool }
type TodoItem(props) =
inherit React.Component<TodoItemProps, TodoItemState>(props)
do base.setInitState({ Editing = false })
member this.HandleDoubleClick(_) =
this.setState({ Editing = true })
member this.HandleSave(id, text: string) =
if text.Length = 0
then this.props.DeleteTodo(id)
else this.props.EditTodo(id, text)
this.setState({ Editing = false })
member this.render() =
let element =
if this.state.Editing
then R.com<TodoTextInput,_,_>
{ OnSave = fun (text: string) ->
this.HandleSave(this.props.Todo.Id, text)
; Editing = this.state.Editing
; Text = Some this.props.Todo.Text
; Placeholder = ""
; NewTodo = false } []
else R.div [ClassName "view"] [
R.input [
ClassName "toggle"
Type "checkbox"
Checked this.props.Todo.Completed
OnChange (fun _ ->
this.props.CompleteTodo(this.props.Todo.Id))
]
R.label [OnDoubleClick this.HandleDoubleClick]
[R.str this.props.Todo.Text]
R.div [
ClassName "destroy"
OnClick (fun _ ->
this.props.DeleteTodo(this.props.Todo.Id))
] []
]
R.li [ClassName(
classNames [
"completed", this.props.Todo.Completed
"editing", this.state.Editing])]
[element]
[<Pojo>]
type HeaderProps = { AddTodo: string->unit }
let Header (props: HeaderProps) =
R.header [ClassName "header"] [
R.h1 [] [R.str "todos"]
R.com<TodoTextInput,_,_>
{ OnSave = fun (text: string) ->
if text.Length <> 0 then
props.AddTodo text
; Placeholder = "What needs to be done?"
; NewTodo = true
; Text = None
; Editing = false } []
]
[<Pojo>]
type FooterProps =
{ ActiveCount: int
; CompletedCount: int
; Filter: TodoFilter
; OnShow: TodoFilter->unit
; OnClearCompleted: React.MouseEvent->unit }
let Footer =
let filterTitles =
dict [
TodoFilter.ShowAll, "All"
TodoFilter.ShowActive, "Active"
TodoFilter.ShowCompleted, "Completed"
]
let renderTodoCount activeCount =
R.span [ClassName "todo-count"] [
R.str(sprintf "%s item%s left"
(if activeCount > 0 then string activeCount else "No")
(if activeCount <> 1 then "s" else ""))
]
let renderFilterLink filter selectedFilter onShow =
R.a [
ClassName (classNames ["selected", filter = selectedFilter])
Style [unbox("cursor", "pointer")]
OnClick (fun _ -> onShow filter)
] [R.str filterTitles.[filter]]
let renderClearButton completedCount onClearCompleted =
if completedCount > 0
then R.button [
ClassName "clear-completed"
OnClick onClearCompleted
] [R.str "Clear completed"] |> Some
else None
fun (props: FooterProps) ->
let listItems =
[ TodoFilter.ShowAll
TodoFilter.ShowActive
TodoFilter.ShowCompleted ]
|> List.map (fun filter ->
[renderFilterLink filter props.Filter props.OnShow]
|> R.li [Key (string filter)])
R.footer [ClassName "footer"] [
renderTodoCount props.ActiveCount
R.ul [ClassName "filters"] listItems
R.opt(renderClearButton props.CompletedCount props.OnClearCompleted)
]
type [<Pojo>] MainSectionProps = { Todos: Todo[]; Dispatch: TodoAction->unit }
type [<Pojo>] MainSectionState = { Filter: TodoFilter }
type MainSection(props) =
inherit React.Component<MainSectionProps, MainSectionState>(props)
let todoFilters =
dict [
TodoFilter.ShowAll, fun _ -> true
TodoFilter.ShowActive, fun (todo: Todo) -> not todo.Completed
TodoFilter.ShowCompleted, fun todo -> todo.Completed
]
do base.setInitState({ Filter = TodoFilter.ShowAll })
member this.HandleClearCompleted() =
this.props.Dispatch(ClearCompleted)
member this.HandleShow(filter) =
this.setState({ Filter = filter })
member this.renderToggleAll(completedCount) =
if this.props.Todos.Length > 0 then
R.input [
ClassName "toggle-all"
Type "checkbox"
Checked (completedCount = this.props.Todos.Length)
OnChange (fun _ -> this.props.Dispatch(CompleteAll))
] |> Some
else None
member this.renderFooter(completedCount) =
if this.props.Todos.Length > 0
then R.fn Footer
{ ActiveCount = this.props.Todos.Length - completedCount
; CompletedCount = completedCount
; Filter = this.state.Filter
; OnShow = fun filter ->
this.HandleShow filter
; OnClearCompleted = fun _ ->
this.HandleClearCompleted() } [] |> Some
else None
member this.render() =
let filteredTodos =
this.props.Todos
|> Array.filter todoFilters.[this.state.Filter]
|> Array.toList
let completedCount =
(0, this.props.Todos) ||> Array.fold (fun count todo ->
if todo.Completed then count + 1 else count)
R.section [ClassName "main"] [
R.opt(this.renderToggleAll completedCount)
R.ul [ClassName "todo-list"]
(filteredTodos
|> List.map (fun todo ->
R.com<TodoItem,_,_>
{ Todo = todo
; EditTodo = fun (id, text) ->
this.props.Dispatch(EditTodo(id, text))
; DeleteTodo = fun id ->
this.props.Dispatch(DeleteTodo id)
; CompleteTodo = fun id ->
this.props.Dispatch(CompleteTodo id) } []))
R.opt(this.renderFooter completedCount)
]
(**
## Subscription to Redux store
The component on top of our UI hierarchy subscribes to the Redux store
and will automatically invalidate children rendering as needed. React
checks when DOM updates are actually necessary, so we don't need to worry
about the performance hit of too frequent updates.
*)
[<Pojo>]
type AppProps = { Store: Redux.IStore<Todo[], TodoAction> }
type App(p) as this =
inherit React.Component<AppProps, MainSectionProps>(p)
let getState() = { Todos=this.props.Store.getState(); Dispatch=this.props.Store.dispatch }
do base.setInitState(getState())
do this.props.Store.subscribe(getState >> this.setState)
member this.render() =
R.div [] [
R.fn Header { AddTodo = AddTodo >> this.props.Store.dispatch } []
R.com<MainSection,_,_> this.state []
]
(**
## Reducer
The reducer is a single function (which can be composed of other smaller function)
with the responsibility of updating the state in reaction to the actions
dispatched to the Redux store. F# union types and pattern matching makes
it really easy to identify and extract the data from the received actions
in a type-safe manner. The compiler will even warn us if we forget to handle
any of the possible `TodoAction` cases.
*)
let reducer (state: Todo[]) = function
| AddTodo text ->
let id =
(-1, state)
||> Array.fold(fun id todo -> max id todo.Id)
|> (+) 1
state
|> Array.append [|{Id=id; Completed=false; Text=text}|]
| DeleteTodo id ->
state
|> Array.filter(fun todo -> todo.Id <> id)
| EditTodo(id, text) ->
state
|> Array.map(fun todo ->
if todo.Id = id
then { todo with Text=text }
else todo)
| CompleteTodo id ->
state
|> Array.map(fun todo ->
if todo.Id = id
then { todo with Completed=not todo.Completed }
else todo)
| CompleteAll ->
let areAllMarked =
state |> Array.forall(fun todo -> todo.Completed)
state
|> Array.map(fun todo -> { todo with Completed=not areAllMarked})
| ClearCompleted ->
state
|> Array.filter(fun todo -> not todo.Completed)
(**
## Firing up the app
There's nothing left to do but create the Redux store with the reducer
and the initial state, pass it to our `App` component, and mount it
onto the DOM by using `ReactDom.render`. Happy coding!
*)
let start() =
let store =
{ Text="Use Fable + React + Redux"; Completed=false; Id=0}
|> Array.singleton
|> Redux.createStore reducer
ReactDom.render(
R.com<App,_,_> { Store=store } [],
Browser.document.getElementsByClassName("todoapp").[0]
) |> ignore
start()