AutoDropdown

This is an HTML component written in Gren. It renders and manages a dropdown for a list of items that can be selected with the mouse, or navigated with the keyboard.

Your application will hold one AutoDropdown.State and one AutoDropdown.Config for every dropdown it instantiates.

These are the rules about State and Config:

  • Always put AutoDropdown.State in your model
  • Never put AutoDropdown.Config in your model

Types

Config

type alias Config msg =
{ mouseDownMsg : String -> msg
, mouseEnterMsg : Int -> msg
, ulAttrs : Array (Attribute msg)
, liAttrs : Array (Attribute msg)
, highlightedAttrs : Array (Attribute msg)
}

The config has static information, which doesn't change during the life cycle of the AutoDropdown. This never goes into the application's Model. It's closer to your View.

State

type alias State = { isOpen : Bool, highlightedIndex : Maybe Int }

This holds AutoDropdown state which is dynamic and can change during each update cycle. It's not managed by the dropdown, but managed by the application and passed into the dropdown during 'view'. This always goes into the application's Model. The application can and should change isOpen as needed. The dropdown can change isOpen to False when the user navigates too far up (see moveUp). The application should not modify highlightedIndex; the dropdown does that.

Functions

initialState : State

Create an empty State object

view : Config msg -> State -> Array String -> Html msg

Render the HTML for the dropdown

moveDown :
Array String
-> State
-> { state : State, highlighted : Maybe String
}

The caller tells use the user is moving down, llikely due to pressing the ArrowDown key. moveDown will adjust the highlightedIndex appropriately. It returns the new State, and the Maybe highlighted item (String), in case the application needs it.

moveUp :
Array String
-> State
-> { state : State, highlighted : Maybe String
}

The caller tells use the user is moving up, likely by pressing the ArrowUp key. It returns the new State, and the Maybe highlighted item (String), in case the application needs it.

mouseEnter : Int -> Array String -> State -> State

The applications calls this to tell the dropdown that the user's mouse has entered a dropdown item while it is being displayed. This function returns the new State.