Tuix.App behaviour (tuix v0.1.0)

Copy Markdown View Source

The behaviour for Tuix applications, modeled after Phoenix LiveView.

An app holds its state in assigns, reacts to events and messages, and declaratively describes its UI in render/1. Tuix re-renders after every callback and writes only the changed terminal cells.

Example

defmodule Counter do
  use Tuix.App

  @impl true
  def mount(_opts, app), do: {:ok, assign(app, count: 0)}

  @impl true
  def handle_event(%Tuix.Event.Key{key: "+"}, app),
    do: {:noreply, update(app, :count, &(&1 + 1))}

  def handle_event(%Tuix.Event.Key{key: "q"}, app),
    do: {:stop, :normal, app}

  def handle_event(_event, app), do: {:noreply, app}

  @impl true
  def render(assigns) do
    box border: :rounded, padding: 1 do
      text("Count: #{assigns.count}", fg: :green)
    end
  end
end

Tuix.run(Counter)

Because the runtime is a regular process, any Elixir message — timer ticks, Task results, PubSub broadcasts — can drive the UI through handle_info/2.

Summary

Callbacks

Handles keyboard and resize events.

Handles arbitrary Elixir messages sent to the runtime process.

Initializes state. Receives the options passed to Tuix.run/2.

Returns the element tree for the current assigns.

Functions

Assigns a key/value pair (or many, from a keyword list or map) into the app.

Updates an existing assign with a function.

Types

t()

@type t() :: %Tuix.App{assigns: map(), module: module(), private: map()}

Callbacks

handle_event(event, app)

(optional)
@callback handle_event(event :: Tuix.Event.t(), app :: t()) ::
  {:noreply, t()} | {:stop, reason :: term(), t()}

Handles keyboard and resize events.

handle_info(message, app)

(optional)
@callback handle_info(message :: term(), app :: t()) ::
  {:noreply, t()} | {:stop, reason :: term(), t()}

Handles arbitrary Elixir messages sent to the runtime process.

mount(opts, app)

(optional)
@callback mount(opts :: keyword(), app :: t()) :: {:ok, t()}

Initializes state. Receives the options passed to Tuix.run/2.

render(assigns)

@callback render(assigns :: map()) :: Tuix.Element.t()

Returns the element tree for the current assigns.

Functions

assign(app, key_values)

assign(app, key, value)

Assigns a key/value pair (or many, from a keyword list or map) into the app.

update(app, key, fun)

Updates an existing assign with a function.