-
Notifications
You must be signed in to change notification settings - Fork 0
/
App.elm
120 lines (88 loc) · 2.46 KB
/
App.elm
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
port module PusherApp exposing (..)
import Html exposing (..)
import Html.App as App
import Task exposing (Task)
import Http
import Html.Attributes exposing (..)
import Html.Events exposing (onClick, onInput)
import Json.Decode as JSDecode
import Json.Encode as JSEncode
type alias Model =
{ messages : List String
, field : String
}
type Msg
= NoOp
| NewMessage String
| SendMessage
| UpdateField String
main =
App.program
{ init = init
, view = view
, update = update
, subscriptions = subscriptions
}
initialModel =
{ messages = [ "Hello World" ], field = "" }
init : ( Model, Cmd Msg )
init =
( initialModel, Cmd.none )
port newMessage : (String -> msg) -> Sub msg
subscriptions : Model -> Sub Msg
subscriptions model =
newMessage NewMessage
jsonBody : String -> String
jsonBody str =
JSEncode.encode 0
(JSEncode.object [ ( "text", JSEncode.string str ) ])
httpPostMessage : String -> Task Http.Error String
httpPostMessage str =
Http.fromJson JSDecode.string
<| Http.send Http.defaultSettings
{ verb = "POST"
, headers =
[ ( "Content-Type", "application/json" )
, ( "Accept", "application/json" )
]
, url = "http://localhost:4567/messages"
, body = Http.string (jsonBody str)
}
postJson : String -> Cmd Msg
postJson str =
Task.perform (always NoOp) (always NoOp) (httpPostMessage str)
update : Msg -> Model -> ( Model, Cmd Msg )
update action model =
case action of
NewMessage string ->
( { model | messages = string :: model.messages }
, Cmd.none
)
UpdateField string ->
( { model | field = string }, Cmd.none )
NoOp ->
( model, Cmd.none )
SendMessage ->
( { model | field = "" }, postJson model.field )
makeListItem : String -> Html Msg
makeListItem message =
li [] [ text message ]
makeUserForm : String -> Html Msg
makeUserForm field =
div []
[ input
[ placeholder "Your chat message here"
, onInput UpdateField
, value field
]
[]
, button [ onClick SendMessage ]
[ text "Send" ]
]
view : Model -> Html Msg
view model =
div []
[ makeUserForm model.field
, ul []
(List.map makeListItem model.messages)
]