-
Notifications
You must be signed in to change notification settings - Fork 22
Expand file tree
/
Copy pathTodoForm.purs
More file actions
87 lines (68 loc) · 1.78 KB
/
TodoForm.purs
File metadata and controls
87 lines (68 loc) · 1.78 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
module Example.TodoForm where
import Prelude
import Data.Maybe (Maybe(..), maybe, isNothing)
import Effect (Effect)
import React as React
import React.Hook (Hook)
import React.Hook as Hook
import React.Ref as Ref
import React.SyntheticEvent as Event
import React.DOM as DOM
import React.DOM.Props as Props
import Web.HTML.HTMLElement as HTML
import Unsafe.Coerce (unsafeCoerce)
import Example.TodoContext as TodoContext
import Example.Types (Todo(..), TodoStatus(..))
type TodoFormProps
= { todo :: Maybe Todo
, onEdit :: Todo -> Effect Unit
, onAdd :: Todo -> Effect Unit
}
todoForm :: TodoFormProps -> Hook React.ReactElement
todoForm
{ todo
, onEdit
, onAdd
} =
render <$> hook
where
hook = do
context <- Hook.useContext TodoContext.todoContext
ref <- Hook.useRef Nothing
pure { ref, context }
render
{ ref
, context:
{ backgroundColor
}
} =
DOM.form
[ Props.onSubmit onSubmit ]
[ DOM.input
[ Props._type "text"
, Props.value value
, Props.ref ref
, Props.onChange onChange
, Props.style { backgroundColor }
]
, DOM.button
[ Props._type "submit"
, Props.disabled isDisabled
]
[ DOM.text "Add" ]
]
where
value = maybe "" (\(Todo { text }) -> text) todo
isDisabled = isNothing todo
onSubmit event = do
Event.preventDefault event
maybe (pure unit) onAdd todo
domRef <- Ref.getRef ref
maybe (pure unit) (HTML.blur <<< unsafeCoerce) domRef
pure unit
onChange event = onEdit $
maybe (Todo { text, status: TodoPending })
(\(Todo todo_) -> Todo todo_ { text = text })
todo
where
text = (unsafeCoerce event).target.value