TermUI.ComponentServer (TermUI v0.2.0)

View Source

GenServer that manages the lifecycle of a component.

ComponentServer wraps any component implementing TermUI behaviours, managing its lifecycle stages: init, mount, update, and unmount. It handles prop validation, timeout enforcement, and command execution.

Lifecycle Stages

  1. Init - Create initial state from props
  2. Mount - Component enters active tree, ready for events
  3. Update - Props changed, state may update
  4. Unmount - Component removed, cleanup performed

Usage

Components are typically started via ComponentSupervisor:

{:ok, pid} = ComponentSupervisor.start_component(MyButton, %{label: "OK"})

Direct usage:

{:ok, pid} = ComponentServer.start_link(MyButton, %{label: "OK"}, [])

Summary

Functions

Returns a specification to start this module under a supervisor.

Gets the lifecycle state.

Gets the current props.

Gets the current component state.

Triggers the mount lifecycle stage.

Registers a lifecycle hook.

Sends an event to the component.

Starts a component server.

Triggers the unmount lifecycle stage.

Updates the component's props.

Types

state()

@type state() :: %{
  module: module(),
  component_state: term(),
  props: map(),
  lifecycle: :initialized | :mounted | :unmounted,
  id: term(),
  hooks: %{required(atom()) => [function()]},
  recovery: :reset | :last_props | :last_state
}

Functions

child_spec(init_arg)

Returns a specification to start this module under a supervisor.

See Supervisor.

get_lifecycle(pid)

@spec get_lifecycle(pid()) :: :initialized | :mounted | :unmounted

Gets the lifecycle state.

get_props(pid)

@spec get_props(pid()) :: map()

Gets the current props.

get_state(pid)

@spec get_state(pid()) :: term()

Gets the current component state.

mount(pid)

@spec mount(pid()) :: :ok | {:error, term()}

Triggers the mount lifecycle stage.

Called when the component is added to the active component tree.

register_hook(pid, hook_type, fun)

@spec register_hook(pid(), atom(), function()) :: :ok

Registers a lifecycle hook.

Hook Types

  • :after_mount - Called after successful mount
  • :before_unmount - Called before unmount cleanup
  • :on_prop_change - Called when props change

send_event(pid, event)

@spec send_event(pid(), term()) :: :ok | {:error, term()}

Sends an event to the component.

start_link(module, props, opts \\ [])

@spec start_link(module(), map(), keyword()) :: GenServer.on_start()

Starts a component server.

Parameters

  • module - Component module
  • props - Initial properties
  • opts - Options (:id, :timeout)

unmount(pid)

@spec unmount(pid()) :: :ok

Triggers the unmount lifecycle stage.

Called when the component is removed from the tree.

update_props(pid, new_props)

@spec update_props(pid(), map()) :: :ok | {:error, term()}

Updates the component's props.

Triggers the update callback if props have changed.