-
Notifications
You must be signed in to change notification settings - Fork 22
Expand file tree
/
Copy pathExample.purs
More file actions
75 lines (58 loc) · 1.71 KB
/
Example.purs
File metadata and controls
75 lines (58 loc) · 1.71 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
module Example where
import Prelude
import Data.Array (snoc, modifyAt, elemIndex)
import Data.Maybe (Maybe(..), fromMaybe)
import Data.Tuple (Tuple(..))
import React as React
import React.Hook (Hook)
import React.Hook as Hook
import Example.TodoList (todoList)
import Example.Types (Todo(..), TodoStatus(..))
data Action
= Add Todo
| Edit Todo
| Done Todo
| Clear Todo
example :: { } -> Hook React.ReactElement
example _ =
React.createHookLeafElement todoList <$> hook
where
hook = do
Tuple state dispatch <- Hook.useReducer reducer initialState
let
inputs = Just [ Hook.hookInput dispatch ]
onAdd <- Hook.useCallback (Hook.dispatch dispatch <<< Add) inputs
onEdit <- Hook.useCallback (Hook.dispatch dispatch <<< Edit) inputs
onDone <- Hook.useCallback (Hook.dispatch dispatch <<< Done) inputs
onClear <- Hook.useCallback (Hook.dispatch dispatch <<< Clear) inputs
pure { todo: state.todo
, todos: state.todos
, onAdd
, onEdit
, onDone
, onClear
}
where
initialState =
{ todo: Nothing
, todos: [ ]
}
reducer state =
case _ of
Add todo -> state
{ todo = Nothing
, todos = snoc state.todos todo
}
Edit todo -> state
{ todo = Just todo
}
Done todo -> state
{ todos = setStatus todo TodoDone
}
Clear todo -> state
{ todos = setStatus todo TodoCleared
}
where
setStatus todo status = fromMaybe state.todos $ do
i <- elemIndex todo state.todos
modifyAt i (\(Todo a) -> Todo a { status = status }) state.todos