Advertisement
Guest User

Untitled

a guest
Apr 12th, 2023
38
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. port module PortTest exposing (..)
  2.  
  3. import Browser
  4. import Html exposing (..)
  5. import Html.Attributes exposing (..)
  6. import Html.Events exposing (..)
  7. import Json.Decode exposing (Decoder,decodeString, map4, field, int, string)
  8. import Json.Encode
  9.  
  10.  
  11.  
  12. -- MAIN
  13.  
  14.  
  15. main : Program () Model Msg
  16. main =
  17.   Browser.element
  18.     { init = init
  19.     , view = view
  20.     , update = update
  21.     , subscriptions = subscriptions
  22.     }
  23.  
  24.  
  25.  
  26.  
  27. -- PORTS
  28.  
  29.  
  30. port sendMessage : Json.Encode.Value -> Cmd msg
  31. port messageReceiver : (Json.Encode.Value -> msg) -> Sub msg
  32.  
  33.  
  34.  
  35. -- MODEL
  36.  
  37.  
  38. type alias Model =
  39.   { draft : String
  40.   , messages : List Quote
  41.   }
  42.  
  43. type alias Quote =
  44.   { quote : String
  45.   , source : String
  46.   , author : String
  47.   , year : Int
  48.   }
  49.  
  50.  
  51. init : () -> ( Model, Cmd Msg )
  52. init flags =
  53.   ( { draft = "", messages = [] }
  54.   , Cmd.none
  55.   )
  56.  
  57.  
  58.  
  59. -- UPDATE
  60.  
  61.  
  62. type Msg = Recv Quote
  63.  
  64.  
  65. -- Use the `sendMessage` port when someone presses ENTER or clicks
  66. -- the "Send" button. Check out index.html to see the corresponding
  67. -- JS where this is piped into a WebSocket.
  68. --
  69. update : Msg -> Model -> ( Model, Cmd Msg )
  70. update msg model =
  71.   case msg of
  72.     Recv message ->
  73.       ( { model | messages = model.messages ++ [ message] }
  74.       , Cmd.none
  75.       )
  76.  
  77.  
  78. -- SUBSCRIPTIONS
  79.  
  80. -- Subscribe to the `messageReceiver` port to hear about messages coming in
  81. -- from JS. Check out the index.html file to see how this is hooked up to a
  82. -- WebSocket.
  83. --
  84. subscriptions : Model -> Sub Msg
  85. subscriptions model = messageReceiver quoteDecoder
  86.  
  87.  
  88.  
  89. -- VIEW
  90.  
  91.  
  92. view : Model -> Html Msg
  93. view model =
  94. --  Debug.log "my model" model
  95.   div []
  96.     [ h1 [] [ text "Websocket json test" ]
  97.     , ul []
  98.         (List.map (\msg -> li [] [ text msg.quote ]) model.messages)
  99.     ]
  100.  
  101.  
  102.  
  103.  
  104. quoteDecoder : Json.Decode.Decoder msg
  105. quoteDecoder  =
  106.   map4 Quote
  107.     (field "quote" string)
  108.     (field "source" string)
  109.     (field "author" string)
  110.     (field "year" int)
  111.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement