Skip to content

Instantly share code, notes, and snippets.

@azer azer/fake-chat.elm
Created May 21, 2018

Embed
What would you like to do?
Elm Ports Example
port module FakeChat exposing (..)
import Html exposing (Html, div, input, text, button, ul, li)
import Html.Events exposing (onClick, onInput)
import Html.Attributes exposing (type_, placeholder, value)
main =
Html.program
{ view = view
, update = update
, init = init
, subscriptions = subscriptions
}
type alias Model =
{ input : String
, messages : List String
}
type Msg
= InputChange String
| SendToJS
| NewMessage String
init : ( Model, Cmd Msg )
init =
( Model "" [], Cmd.none )
update : Msg -> Model -> ( Model, Cmd Msg )
update msg model =
case Debug.log "[elm]" msg of
InputChange newInput ->
( { model | input = newInput }, Cmd.none )
SendToJS ->
({ model | input = "" }, toJS model.input)
NewMessage incoming ->
({ model | messages = model.messages ++ [incoming] }, Cmd.none)
subscriptions : Model -> Sub Msg
subscriptions model =
toElm NewMessage
view : Model -> Html Msg
view model =
div []
[ viewMessages model.messages
, input [ type_ "text"
, placeholder "Type a message"
, onInput InputChange
, value model.input
] []
, button [ onClick SendToJS ] [ text "Send to JS" ]
]
viewMessages : List String -> Html Msg
viewMessages messages =
ul []
(List.map viewMessage messages)
viewMessage : String -> Html Msg
viewMessage message =
li []
[ text message ]
port toJS : String -> Cmd msg
port toElm : (String -> msg) -> Sub msg
<!DOCTYPE html>
<html>
<head></head>
<body>
<script type="text/javascript" src="ports.js"></script>
<script type="text/javascript">
const fakeChat = Elm.FakeChat.fullscreen()
const names = ["Alice", "Bob", "John"]
fakeChat.ports.toJS.subscribe(function (msg) {
console.log('[elm-to-js]', msg)
const name = names[Math.floor(Math.random() * names.length)]
fakeChat.ports.toElm.send(`<${name}> ${msg}`)
})
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.