Skip to content

UI.rs

最後に、パズルの最後のピースと、 ratatui tuisの作成を始めたばかりの最も難しい部分にもなります。以前のチュートリアルでは、1つのウィジェットしかない非常にシンプルなUIを作成しましたが、ここでは、より洗練されたレイアウトを調べます。

レイアウトの基本

最初のステップは、ウィジェットをターミナルにレンダリングする方法を把握することです。

本質的に、ウィジェットが構築され、 Frame を使用して画面に描画されます。 Rect 内に配置されます。

次に、レンダリング可能な Rect 領域を3つの異なる領域に分割したいシナリオを想定しています。このために、 ratatuiLayout 機能を使用できます。

let chunks = Layout::default()
.direction(Direction::Vertical)
.constraints([
Constraint::Length(3),
Constraint::Min(1),
Constraint::Length(3),
])
.split(frame.area());

これは、大きな長方形をより小さなセクションに分割することに例えることができます。

上記の例では、次のような指示を声に出して読むことができます。

1.領域を f.size() (長方形です) を取り、3つの垂直ピース (水平カットを作成) にカットします。2。最初のセクションは3行3になります。3行目。2番目のセクションは、1行よりも小さくなることはありませんが、必要に応じて拡張できます。4.最後のセクションは高さ3行でなければなりません

それらの視覚学習者のために、私は次のグラフィックを持っています:

Top segment always remains 3 lines Bottom segment is consistently 3 lines Constraint::Length 3 Middle segment maintains a minimum height of 1 line, but can expand if additional space is present. Constraint::Length > 1 Constraint::Length 3

邪魔にならないので、アプリケーション用のTUIを作成しましょう。

関数の署名

UI 関数が UI 要素を正常に作成するには、2 つの要素が必要です。レンダリング時のターミナルのサイズを含む「フレーム」(サイズ変更可能なターミナルを考慮に入れることができるため、これは重要です) とアプリケーションの状態です。

pub fn ui(frame: &mut Frame, app: &App) {

先に進む前に、centered_rect ヘルパー関数を実装しましょう。このコードは、ポップアップの例 から改変したものです。

/// helper function to create a centered rect using up certain percentage of the available rect `r`
fn centered_rect(percent_x: u16, percent_y: u16, r: Rect) -> Rect {
// Cut the given rectangle into three vertical pieces
let popup_layout = Layout::default()
.direction(Direction::Vertical)
.constraints([
Constraint::Percentage((100 - percent_y) / 2),
Constraint::Percentage(percent_y),
Constraint::Percentage((100 - percent_y) / 2),
])
.split(r);
// Then cut the middle vertical piece into three width-wise pieces
Layout::default()
.direction(Direction::Horizontal)
.constraints([
Constraint::Percentage((100 - percent_x) / 2),
Constraint::Percentage(percent_x),
Constraint::Percentage((100 - percent_x) / 2),
])
.split(popup_layout[1])[1] // Return the middle chunk
}

これは、後のサブセクションに役立ちます。