Now that we have created a Tui and EventHandler, we are also going to introduce the Command
pattern.
These are also typically called Actions or Messages.
Let’s define a simple impl App such that every Event from the EventHandler is mapped to an
Action from the enum.
We use handle_events(event) -> Action to take a Event and map it to a Action. We use
update(action) to take an Action and modify the state of the app.
One advantage of this approach is that we can modify handle_key_events() to use a key
configuration if we’d like, so that users can define their own map from key to action.
Another advantage of this is that the business logic of the App struct can be tested without
having to create an instance of a Tui or EventHandler, e.g.:
In the test above, we did not create an instance of the Tui or the EventHandler, and did not
call the run function, but we are still able to test the business logic of our application.
Updating the app state on Actions gets us one step closer to making our application a “state
machine”, which improves understanding and testability.
If we wanted to be purist about it, we would make our AppState immutable, and we would have an
update function like so:
In rare occasions, we may also want to choose a future action during update.
:::note In Charm’s bubbletea, this function is
called an Update. Here’s an example of what that might look like:
:::
Writing code to follow this architecture in rust (in my opinion) requires more upfront design,
mostly because you have to make your AppState struct Clone-friendly. If I were in an exploratory
or prototype stage of a TUI, I wouldn’t want to do that and would only be interested in refactoring
it this way once I got a handle on the design.
My workaround for this (as you saw earlier) is to make update a method that takes a &mut self:
You are free to reorganize the code as you see fit!
You can also add more actions as required. For example, here’s all the actions in the template: