Elm: Implementing a Search box

Intro

This post is an attempt to document my understanding of how to implement a search box using the Elm programming language. The entire source code can be found on project Nikeza.

Defining the control

The following is my code for a search box:

input [ type_ "text", placeholder "name", onInput Search ] []

Note that I assigned a message (i.e. Search) to the onInput event of the textbox.

Declaring a Message Case

The Search message is defined as the following:

type Msg
    = 
    ...
    | Search String
    ...

Processing the Search Message

I implemented the Update function’s Search message as follows:

update : Msg -> Model -> ( Model, Cmd Msg )
update msg model =
    case msg of
    ...
        Search v ->
            if v == "" then
                ( { model | contributors = runtime.contributors }, Cmd.none )
            else
                let
                    onName profile =
                        profile.name
                            |> getName
                            |> toLower
                            |> contains (v |> toLower)

                    filtered =
                        runtime.contributors |> List.filter onName
                in
                    ( { model | contributors = filtered }, Cmd.none )

The above code states that if the value of the search is empty then load the general contributors. Hence, a filter does not apply for this particular case. Else, if we do have some text in our value, then use the List.filter function to evaluate if the name of the contributor contains the search text provided. We then return an updated model with filtered contributors set.

Conclusion

In conclusion, this post is an attempt to document my understanding of how to implement a search box using the Elm programming language.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: