Skip to content

Instantly share code, notes, and snippets.

@cfleschhut cfleschhut/CommentBox.elm
Last active Mar 25, 2019

Embed
What would you like to do?
module CommentBox exposing (main)
import Browser
import Html exposing (..)
import Html.Attributes exposing (..)
import Html.Events exposing (..)
main : Program () Model Msg
main =
Browser.sandbox
{ init = initialModel
, view = view
, update = update
}
-- MODEL
type alias Comment =
{ name : String
, description : String
}
type alias Model =
{ newCommentText : String
, newCommentUser : String
, comments : List Comment
}
initialModel : Model
initialModel =
{ newCommentText = ""
, newCommentUser = ""
, comments =
[ { name = "User A", description = "Hi!" }
, { name = "User B", description = "Hello world!" }
]
}
-- UPDATE
type Msg
= AddComment
| ChangeNewCommentUser String
| ChangeNewCommentText String
update : Msg -> Model -> Model
update msg model =
case msg of
AddComment ->
let
comment =
{ name = "User " ++ model.newCommentUser
, description = model.newCommentText
}
in
{ model
| comments = comment :: model.comments
, newCommentUser = ""
, newCommentText = ""
}
ChangeNewCommentUser username ->
{ model | newCommentUser = username }
ChangeNewCommentText description ->
{ model | newCommentText = description }
-- VIEW
author : String -> Comment -> String
author currentUser { name } =
if currentUser == name then
name ++ " (You)"
else
name
commentView : Comment -> Html Msg
commentView comment =
div [ class "comment" ]
[ text (author "User A" comment)
, text ""
, text comment.description
]
commentList : Model -> Html Msg
commentList model =
div [ class "comment-list" ]
(List.map commentView model.comments)
inputUsername : Model -> Html Msg
inputUsername model =
div []
[ label [] [ text "User:" ]
, input
[ class "comment-input-user"
, type_ "text"
, value model.newCommentUser
, onInput ChangeNewCommentUser
]
[]
]
inputComment : Model -> Html Msg
inputComment model =
div []
[ label [] [ text "Comment:" ]
, textarea
[ class "comment-input-text"
, onInput ChangeNewCommentText
, value model.newCommentText
, rows 4
]
[]
]
inputButton : Html Msg
inputButton =
div []
[ button
[ class "comment-button-add"
, onClick AddComment
]
[ text "Add Comment" ]
]
view : Model -> Html Msg
view model =
div [ class "comment-box" ]
[ commentList model
, div [ class "comment-input" ]
[ inputUsername model
, inputComment model
, inputButton
]
]
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.