Skip to content

Instantly share code, notes, and snippets.

@amitaibu
Created October 24, 2016 20:26
Show Gist options
  • Save amitaibu/49d4911248ea56fdd545a2f50e818320 to your computer and use it in GitHub Desktop.
Save amitaibu/49d4911248ea56fdd545a2f50e818320 to your computer and use it in GitHub Desktop.
{
"version": "1.0.0",
"summary": "Examples of The Elm Architecture",
"repository": "https://github.com/elm-lang/elm-architecture-tutorial.git",
"license": "BSD3",
"source-directories": [
"nesting"
],
"exposed-modules": [],
"dependencies": {
"NoRedInk/elm-decode-pipeline": "2.0.0 <= v < 3.0.0",
"elm-lang/core": "4.0.0 <= v < 5.0.0",
"elm-lang/html": "1.0.0 <= v < 2.0.0",
"elm-lang/svg": "1.0.0 <= v < 2.0.0",
"elm-lang/websocket": "1.0.0 <= v < 2.0.0",
"evancz/elm-http": "3.0.1 <= v < 4.0.0",
"evancz/elm-markdown": "3.0.0 <= v < 4.0.0"
},
"elm-version": "0.17.0 <= v < 0.18.0"
}
module Main exposing (..)
import Html exposing (..)
import Html.App as Html
import Html.Events exposing (..)
import WebSocket
import Json.Encode
import Json.Decode
import Json.Decode.Pipeline as JD
main =
Html.program
{ init = init
, view = view
, update = update
, subscriptions = subscriptions
}
echoServer : String
echoServer =
"ws://localhost:3000/ws"
-- MODEL
type alias Model =
{ input : String
, messages : List String
}
init : ( Model, Cmd Msg )
init =
( Model "" [], Cmd.none )
-- UPDATE
type Msg
= Input String
| Send
| NewMessage String
update : Msg -> Model -> ( Model, Cmd Msg )
update msg { input, messages } =
case msg of
Input newInput ->
( Model newInput messages, Cmd.none )
Send ->
( Model "" messages, WebSocket.send echoServer input )
NewMessage str ->
case Json.Decode.decodeString decodeLesson str of
Ok val ->
let
_ =
Debug.log "OK" val
in
( Model input (("Lesson ID " ++ toString val.lessondCurrentSlide) :: messages), Cmd.none )
Err err ->
let
_ =
Debug.log "Err" err
in
Model input messages ! []
-- SUBSCRIPTIONS
subscriptions : Model -> Sub Msg
subscriptions model =
WebSocket.listen echoServer NewMessage
-- VIEW
view : Model -> Html Msg
view model =
div []
[ input [ onInput Input ] []
, button [ onClick Send ] [ text "Send" ]
, div [] (List.map viewMessage (List.reverse model.messages))
]
viewMessage : String -> Html msg
viewMessage msg =
div [] [ text msg ]
type alias Lesson =
{ lessonId : Int
, lessondCurrentSlide : Maybe Int
}
decodeLesson : Json.Decode.Decoder Lesson
decodeLesson =
JD.decode Lesson
|> JD.required "lessonId" (Json.Decode.int)
|> JD.required "lessondCurrentSlide" (JD.nullable Json.Decode.int)
encodeLesson : Lesson -> Json.Encode.Value
encodeLesson record =
let
intOrNull maybeVal =
case maybeVal of
Just val ->
Json.Encode.int val
Nothing ->
Json.Encode.null
in
Json.Encode.object
[ ( "lessonId", Json.Encode.int <| record.lessonId )
, ( "lessondCurrentSlide", intOrNull record.lessondCurrentSlide )
]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment