UI.rs
Finally we come to the last piece of the puzzle, and also the hardest part when you are just
starting out creating ratatui
TUIs --- the UI. We created a very simple UI with just one widget in
the previous tutorial, but here we’ll explore some more sophisticated layouts.
Layout basics
Our first step is to grasp how we render widgets onto the terminal.
In essence: Widgets are constructed and then drawn onto the screen using a Frame
, which is placed
within a specified Rect
.
Now, envision a scenario where we wish to divide our renderable Rect
area into three distinct
areas. For this, we can use the Layout
functionality in ratatui
.
This can be likened to partitioning a large rectangle into smaller sections.
In the example above, you can read the instructions aloud like this:
- Take the area
f.size()
(which is a rectangle), and cut it into three vertical pieces (making horizontal cuts). - The first section will be 3 lines tall
- The second section should never be smaller than one line tall, but can expand if needed.
- The final section should also be 3 lines tall
For those visual learners, I have the following graphic:
Now that we have that out of the way, let us create the TUI for our application.
The function signature
Our UI function needs two things to successfully create our UI elements. The Frame
which contains
the size of the terminal at render time (this is important, because it allows us to take resizable
terminals into account), and the application state.
Before we proceed, let’s implement a centered_rect
helper function. This code is adapted from the
popup example found in the
official repo.
This will be useful for the later subsections.