This repository has been archived by the owner on Feb 2, 2021. It is now read-only.
/
Attributes.purs
82 lines (72 loc) · 2.67 KB
/
Attributes.purs
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
module SDOM.Attributes
( for
, id
, name
, className
, type_
, value
, checked
, disabled
) where
import Prelude
import DOM.HTML.HTMLInputElement (setChecked, setDisabled, setValue)
import DOM.Node.Element (removeAttribute, setAttribute)
import SDOM (Attr, unsafeAttr)
import Unsafe.Coerce (unsafeCoerce)
attr :: forall context model. String -> (context -> model -> String) -> Attr context model
attr attrName f =
unsafeAttr \context e ->
{ init: \model -> setAttribute attrName (f context model) e
, update: \{ old, new } -> do
let oldValue = f context old
newValue = f context new
when (oldValue /= newValue) (setAttribute attrName newValue e)
}
for :: forall context model. (context -> model -> String) -> Attr context model
for = attr "for"
id :: forall context model. (context -> model -> String) -> Attr context model
id = attr "id"
className :: forall context model. (context -> model -> String) -> Attr context model
className = attr "class"
name :: forall context model. (context -> model -> String) -> Attr context model
name = attr "name"
type_ :: forall context model. (context -> model -> String) -> Attr context model
type_ = attr "type"
value :: forall context model. (context -> model -> String) -> Attr context model
value f =
unsafeAttr \context e ->
let update s = do
setValue s (unsafeCoerce e)
setAttribute "value" s e
in { init: \model -> update (f context model)
, update: \{ old, new } -> do
let oldValue = f context old
newValue = f context new
when (oldValue /= newValue) (update newValue)
}
checked :: forall context model. (context -> model -> Boolean) -> Attr context model
checked f =
unsafeAttr \context e ->
let update b = do
setChecked b (unsafeCoerce e)
if b then setAttribute "checked" "checked" e
else removeAttribute "checked" e
in { init: \model -> update (f context model)
, update: \{ old, new } -> do
let oldValue = f context old
newValue = f context new
when (oldValue /= newValue) (update newValue)
}
disabled :: forall context model. (context -> model -> Boolean) -> Attr context model
disabled f =
unsafeAttr \context e ->
let update b = do
setDisabled b (unsafeCoerce e)
if b then setAttribute "disabled" "disabled" e
else removeAttribute "disabled" e
in { init: \model -> update (f context model)
, update: \{ old, new } -> do
let oldValue = f context old
newValue = f context new
when (oldValue /= newValue) (update newValue)
}