Skip to content

Instantly share code, notes, and snippets.

@dlight
Created July 18, 2017 12:08
Show Gist options
  • Save dlight/6baa1e9eac3f3792d59e0b596cb44cd3 to your computer and use it in GitHub Desktop.
Save dlight/6baa1e9eac3f3792d59e0b596cb44cd3 to your computer and use it in GitHub Desktop.
module Hello exposing (..)
import Html exposing (Html, program, li, ul, div, text, button, input)
import Html.Events exposing (onClick, onInput)
import Html.Events.Extra exposing (onEnter)
import RemoteData exposing (WebData)
import Http
type alias Model =
{ query : String
, results : List (WebData String)
}
init : (Model, Cmd Msg)
init = ({ query = "", results = [] }, Cmd.none)
type Msg
= SearchBox String
| Search
| OnFetch Int (WebData String)
view : Model -> Html Msg
view { results } =
div []
[ searchbar
, listResults results
]
searchbar : Html Msg
searchbar = div []
[ input [onInput SearchBox, onEnter Search] []
, button [onClick Search] [text "Search"]
]
listResults : List (WebData String) -> Html Msg
listResults searchResults =
ul []
(List.map (\s -> li [] [showResult s]) searchResults)
showResult : WebData String -> Html Msg
showResult msg =
case msg of
RemoteData.NotAsked ->
text "notasked?"
RemoteData.Loading ->
text "Loading..."
RemoteData.Success result ->
text result
RemoteData.Failure error ->
text (toString error)
fetchUrl : String
fetchUrl = "http://localhost:5000/search/"
fetchQuery : Int -> String -> Cmd Msg
fetchQuery pos query =
Http.getString (fetchUrl ++ query) |> RemoteData.sendRequest
|> Cmd.map (OnFetch pos)
update : Msg -> Model -> (Model, Cmd Msg)
update msg model =
case msg of
SearchBox newQuery ->
({ model | query = newQuery }, Cmd.none)
Search ->
let newResults = RemoteData.Loading :: model.results in
({ model | results = newResults },
fetchQuery (List.length newResults) model.query)
OnFetch pos result ->
let f l i el =
if l-i == pos then
result
else
el
newResults = List.indexedMap (f (List.length model.results)) model.results in
({ model | results = newResults }, Cmd.none)
main : Program Never Model Msg
main =
program
{ init = init
, view = view
, update = update
, subscriptions = always Sub.none
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment