Skip to content

Instantly share code, notes, and snippets.

@cessationoftime
Forked from TheSeamau5/autosuggest.elm
Last active March 24, 2017 23:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cessationoftime/61821467aa6ec58e2c041d7435ab5745 to your computer and use it in GitHub Desktop.
Save cessationoftime/61821467aa6ec58e2c041d7435ab5745 to your computer and use it in GitHub Desktop.
Autosuggest with caching in Elm
import Dict exposing (Dict)
import Html exposing (Html, div, text, input, ul, li)
import Html.Events exposing (..)
import Task exposing (Task)
import String
---------------------------
main =
Html.program
{ init = init
, view = view viewSuggestion
, update = update getSuggestions
, subscriptions = subscriptions
}
---------------------------
data : List String
data =
[ "Arizona"
, "Arkansas"
, "California"
, "Colorado"
, "Delaware"
, "Florida"
, "New York"
, "New Jersey"
, "Pennsylvania"
, "Texas" ]
attemptedSuggestions : String -> Result String (List suggestion) -> Msg suggestion
attemptedSuggestions query result =
case result of
Ok suggestions ->
AddSuggestions query suggestions
Err _ ->
NoOp
getSuggestions : String -> Task String (List String)
getSuggestions query =
if String.trim query == ""
then
Task.fail "No Query"
else
(data
|> List.filter (String.startsWith query)
|> Task.succeed)
---------------------------
type alias Model suggestion =
{ cache : Dict String (List suggestion)
, query : String
}
type Msg suggestion
= Query String
| AddSuggestions String (List suggestion)
| NoOp
init : (Model suggestion, Cmd (Msg suggestion))
init =
( { cache = Dict.empty
, query = ""
}
, Cmd.none )
subscriptions : Model suggestion -> Sub (Msg suggestion)
subscriptions model =
Sub.none
update : (String -> Task String (List suggestion))
-> Msg suggestion
-> Model suggestion
-> (Model suggestion, Cmd (Msg suggestion))
update getSuggestions msg model =
case msg of
Query query ->
let cmd =
Task.attempt (attemptedSuggestions query) (getSuggestions query)
in
( { model | query = query }
, cmd )
AddSuggestions query suggestions ->
( { model | cache = Dict.insert query suggestions model.cache }
, Cmd.none )
NoOp ->
( model
, Cmd.none )
view : (suggestion -> Html (Msg suggestion)) -> Model suggestion -> Html (Msg suggestion)
view viewSuggestion model =
let suggestions =
case Dict.get model.query model.cache of
Nothing ->
[]
Just results ->
results
in
div
[]
[ input
[ onInput Query ]
[ ]
, div
[]
( List.map viewSuggestion suggestions ) ]
viewSuggestion : String -> Html a
viewSuggestion suggestion =
div
[]
[ text suggestion ]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment