n1kben/elm-web-components/1.0.2

NOTE: the latest version is 1.0.5

Component

Build custom elements with Elm.

The host passes values through attributes and listens for events. The component keeps its interaction state private and renders its own view. When an attribute changes, receive can send a message to update. An update can send an event back to the host.

The build tool reads the component's Input and Output types. It generates the code that reads attributes, sends events, and connects the component to the browser. See the disclosure example for a complete component.

Define a component

type Component input state msg output

The state changes, view, and events for one component.

Create one with define.

{ init : input -> ( state, Cmd msg )
, receive : input -> Maybe msg
, update : msg -> state -> ( state, Cmd msg, List output )
, view : state -> Html msg
, subscriptions : state -> Sub msg
}
-> Component input state msg output

Define a component. init receives the initial input. When an attribute changes, receive gets the new input. Return Nothing to ignore the change, or Just msg to handle it through update. Keep any input that view needs in the component's state.

The build tool reads an Input record alias and an Output union from the component module. It generates the attribute and event handling, so this definition needs neither a decoder nor an encoder.

update returns the next state, a command for component messages, and events for the host. Return an empty list when there are no events.

component =
    Component.define
        { init = init
        , receive = Just << Received
        , update = update
        , view = view
        , subscriptions = always Sub.none
        }
type alias Event =
{ name : String
, detail : Value
}

An event sent to the host. name becomes the DOM event type. detail becomes CustomEvent.detail. The event bubbles across the shadow boundary.

Browser integration

Decoder input
-> (output -> Event)
-> { inputChanged : (Value -> Msg msg) -> Sub (Msg msg)
, connectionChanged : (Bool -> Msg msg) -> Sub (Msg msg)
, outputSent : Value -> Cmd (Msg msg)
}
-> Component input state msg output
-> Program Value (Model state) (Msg msg)

Connect a component to the generated ports and codecs. The build tool calls this from a generated Elm entry point. Component modules use define.

An element keeps its Elm state when it leaves the page and returns. Its subscriptions pause while it is detached.