Home

Awesome

Ashen

A framework for writing terminal applications in Swift. Based on The Elm Architecture.

As a tutorial of Ashen, let's consider an application that fetches some todo items and renders them as a list.

Example

Fully working app โ€“ย TheSheet

Old way

In a traditional controller/view pattern, views are created during initialization, and updated later as needed with your application data. Loading data from a server to load a list of views. Views are stored in instance variables and edited "in place", and the views/subviews are added/removed as events happen, so a lot of code is there to manage view state.

New way

What would this look like using Ashen or Elm or React? In these frameworks, rendering output is declarative; it is based the model, and you render all the views and their properties based on that state. Model goes in, View comes out.

func render(model: Model) -> View<Message> {
    guard
        let data = model.data
    else {
        // no data?  Show the spinner.
        return Spinner()
    }

    return Stack(.topToBottom, [
        Text("List of things"),
        ListView(dataList: data) { row in
            LabelView(text: row.title)
        }
        // ๐Ÿ‘† this view is similar to how UITableView renders cells - only
        // the rows that are visible will be rendered. rowHeight can also be
        // assigned a function, btw, to support dynamic heights.
        //
        // Also, this view is not done yet! Sorry - but it'll look something
        // like this.
    ])
}

So instead of mutating the isHidden property of views, or addSubview, we just render the views we need based on our model. SwiftUI has also adopted this model, so if you've been using it, Ashen will feel very familiar.

Commands and Messages

To fetch our data, we need to call out to the runtime to ask it to perform a background task, aka a Command, and then report the results back as a Message. Message is how your Components can tell your application about changes that might result in a change to your model. For instance, if someone types in a "name" text field you probably want to know about that so you can update the model's name property.

Sources of Messages include Views, Commands, and system event components (e.g. a KeyEvent message can be captured via the OnKeyPress component, which receives system-level events and maps those into an instance of your app's Message type).

Our application starts at the initial() method. We return our initial model and a command to run. We will return an Http command:

enum Message {
    case received(Result<(Int, Headers, Data), HttpError>)
}

func initial() -> Initial<Model, Message> {
    let url = URL(string: "http://example.com")!
    let cmd = Http.get(url) { result in
      Message.received(result)
    }

    return Initial(Model(), cmd)
}

When the Http request succeeds (or fails) the result will be turned into an instance of your application's Message type (usually an enum), and passed to the update() function that you provide.

To send multiple commands, group them with Command.list([cmd1, cmd2, ...])

Updating

In your application's update() function, you will instruct the runtime how the message affects your state. Your options are:

For convenience there are two helper "types":

Program

Here's a skeleton program template:

// This is usually an enum, but it can be any type.  Your app will respond
// to state changes by accepting a `Message` and returning a modified
// `Model`.
enum Message {
    case quit
}

// The entired state of you program will be stored here, so a struct is the
// most common type.
struct Model {
}

// Return your initial model and commands. if your app requires
// initialization from an API (i.eg. a loading spinner), use a
// `loading/loaded/error` enum to represent the initial state.  If you
// persist your application to the database you could load that here, either
// synchronously or via a `Command`.
func initial() -> Initial<Model, Message> {
    Initial(Model())
}

// Ashen will call this method with the current model, and a message that
// you use to update your model.  This will result in a screen refresh, but
// it also means that your program is very easy to test; pass a model to
// this method along with the message you want to test, and check the values
// of the model.
//
// The return value also includes a list of "commands".  Commands are
// another form of event emitters, like Components, but they talk with
// external services, either asynchronously or synchronously.
func update(model: Model, message: Message)
    -> State<Model, Message>
{
    switch message {
    case .quit:
        return .quit
    }
}

// Finally the render() method is given your model and you return
// an array of views. Why an array? I optimized for the common case: some key
// handlers, maybe some mouse events, and a "main" view.
func render(model: Model) -> [View<Message>] {
    [
        OnKeyPress(.enter, { Message.quit }),
        Frame(Spinner(), .alignment(.middleCenter)),
    ])
}

Running your Program

To run your program, pass your initial, update, view, and unmount functions to Ashen.Program and run it with ashen(program). It will return .quit or .error, depending on how the program exited.

do {
    try ashen(Program(initial, update, view))
    exit(EX_OK)
} catch {
    exit(EX_IOERR)
}

Important note: ALL Ashen programs can be aborted using ctrl+c. It is recommended that you support ctrl+\ to gracefully exit your program.

Views

View Modifiers

Views can be created in a fluent syntax (these will feel much like SwiftUI, though not nearly that level of complexity & sophistication).

Events