mi-v1/frontend/src/Pages/POSSE.elm

170 lines
4.0 KiB
Elm

module Pages.POSSE exposing (Model, Msg, page)
import Element exposing (..)
import Element.Background as Background
import Element.Font as Font
import Element.Input as Input
import Generated.Params as Params
import Global
import Http
import Mi
import Mi.POSSE as POSSE
import Spa.Page
import Utils.Spa exposing (Page, PageContext)
page : Page Params.POSSE Model Msg model msg appMsg
page =
Spa.Page.component
{ title = always "POSSE"
, init = always init
, update = update
, subscriptions = always subscriptions
, view = always view
}
type alias Model =
{ title : String
, url : String
, body : String
, tags : String
, status : String
}
init : Params.POSSE -> ( Model, Cmd Msg, Cmd Global.Msg )
init _ =
( { title = ""
, url = ""
, body = ""
, tags = ""
, status = ""
}
, Cmd.none
, Cmd.none
)
type Msg
= UpdateTitle String
| UpdateBody String
| UpdateURL String
| UpdateTags String
| Send
| GotResponse (Result Http.Error String)
update : PageContext -> Msg -> Model -> ( Model, Cmd Msg, Cmd Global.Msg )
update { global } msg model =
case msg of
UpdateBody body ->
( { model | body = body }
, Cmd.none
, Cmd.none
)
UpdateURL url ->
( { model | url = url }
, Cmd.none
, Cmd.none
)
UpdateTags tags ->
( { model | tags = tags }
, Cmd.none
, Cmd.none
)
UpdateTitle title ->
( { model | title = title }
, Cmd.none
, Cmd.none
)
Send ->
let
post =
{ title = model.title
, body = model.body
, url = model.url
, tags = String.words model.tags
}
postJson =
POSSE.encoder post
in
( model
, Mi.request
"POST"
(Maybe.withDefault "" global.token)
"/posse/post"
(Http.jsonBody postJson)
(Http.expectString GotResponse)
, Cmd.none
)
GotResponse resp ->
case resp of
Ok _ ->
( { model | status = "Posted!" }
, Cmd.none
, Cmd.none
)
Err data ->
( { model | status = "Error when posting! " ++ Mi.errorToString data }
, Cmd.none
, Cmd.none
)
subscriptions : Model -> Sub Msg
subscriptions model =
Sub.none
view : Model -> Element Msg
view model =
let
statusMsg =
case model.status of
"" ->
none
_ ->
row [] [ text "Status", text model.status ]
makeInput : String -> (String -> Msg) -> String -> Element Msg
makeInput label msg text =
Input.spellChecked [ padding 10, Font.size 14 ]
{ label = Input.labelAbove [] (Element.text label)
, onChange = msg
, text = text
, placeholder = Nothing
}
in
column [ width fill ]
[ statusMsg
, row [ padding 10 ]
[ makeInput "Title" UpdateTitle model.title
, makeInput "URL" UpdateURL model.url
, makeInput "Tags" UpdateTags model.tags
]
, Input.multiline [ Font.size 14 ]
{ label =
Input.labelAbove
[ Input.focusedOnLoad ]
(text "Body")
, onChange = UpdateBody
, spellcheck = True
, placeholder = Nothing
, text = model.body
}
, Input.button
[]
{ onPress = Just Send
, label = text "Send"
}
]