TermUI.Message (TermUI v0.2.0)

View Source

Message type conventions and helpers for component messages.

Messages are component-specific types representing meaningful actions. They carry semantic meaning—{:select_item, 3} is clearer than the raw key event that triggered it.

Message Conventions

Components define their own message types using one of these patterns:

Simple Atom Messages

:increment
:decrement
:submit
:cancel

Tuple Messages with Data

{:select_item, 3}
{:update_text, "hello"}
{:set_value, 42}

Struct Messages (for complex data)

defmodule MyComponent.Msg do
  defmodule SelectItem do
    defstruct [:index, :source]
  end
end

%MyComponent.Msg.SelectItem{index: 3, source: :keyboard}

Event to Message Conversion

Components implement event_to_msg/2 to convert events to messages:

def event_to_msg(%Event.Key{key: :enter}, _state) do
  {:msg, :submit}
end

def event_to_msg(%Event.Key{key: :up}, _state) do
  {:msg, {:move, :up}}
end

def event_to_msg(_event, _state) do
  :ignore
end

Message Routing

Messages route to the component that should handle them. The runtime delivers messages and components update their state in response.

Summary

Functions

Checks if a value is an atom message.

Matches a message against a pattern.

Returns the message type/name.

Returns the message payload.

Checks if a value is a struct message.

Checks if a value is a tuple message.

Checks if a value is a valid message.

Creates a wrapped message result from event_to_msg.

Types

t()

@type t() :: atom() | tuple() | struct()

Functions

atom?(msg)

@spec atom?(term()) :: boolean()

Checks if a value is an atom message.

match?(msg, pattern)

@spec match?(t(), atom()) :: boolean()

Matches a message against a pattern.

Examples

Message.match?(:submit, :submit)  # true
Message.match?({:select, 3}, :select)  # true
Message.match?(%Msg.SelectItem{index: 3}, Msg.SelectItem)  # true

name(msg)

@spec name(t()) :: atom()

Returns the message type/name.

For atoms, returns the atom itself. For tuples, returns the first element. For structs, returns the struct module name.

payload(msg)

@spec payload(t()) :: term()

Returns the message payload.

For atoms, returns nil. For tuples with 2 elements, returns the second element. For tuples with more elements, returns a list of remaining elements. For structs, returns the struct itself.

struct?(arg1)

@spec struct?(term()) :: boolean()

Checks if a value is a struct message.

tuple?(msg)

@spec tuple?(term()) :: boolean()

Checks if a value is a tuple message.

valid?(msg)

@spec valid?(term()) :: boolean()

Checks if a value is a valid message.

Messages can be atoms, tuples, or structs.

wrap(msg)

@spec wrap(t()) :: {:msg, t()}

Creates a wrapped message result from event_to_msg.

Returns {:msg, message} to indicate the event was converted.