rat_widget/pager/form.rs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413
//! Widget that helps with rendering a layout using GenericForm.
//!
//!
//! ```
//! # use ratatui::buffer::Buffer;
//! # use ratatui::layout::{Flex, Rect};
//! # use ratatui::text::Span;
//! # use ratatui::widgets::{Padding, Widget, StatefulWidget};
//! # use rat_focus::{FocusFlag, HasFocus};
//! # use rat_text::text_input::{TextInput, TextInputState};
//! # use rat_widget::layout::{FormLabel, FormWidget, GenericLayout, LayoutForm};
//! use rat_widget::pager::{Form, FormState};
//! #
//! # struct State {
//! # form: FormState<FocusFlag>,
//! # text1: TextInputState,
//! # text2: TextInputState,
//! # text3: TextInputState,
//! # }
//! #
//! # let mut state = State {form: Default::default(),text1: Default::default(),text2: Default::default(),text3: Default::default()};
//! # let area = Rect::default();
//! # let mut buf = Buffer::empty(Rect::default());
//! # let buf = &mut buf;
//!
//! if !state.form.valid_layout(area.as_size()) {
//! let mut form_layout = LayoutForm::new()
//! .spacing(1)
//! .flex(Flex::Legacy)
//! .line_spacing(1)
//! .min_label(10);
//!
//! form_layout.widget(
//! state.text1.focus(),
//! FormLabel::Str("Text 1"),
//! // single row
//! FormWidget::Width(22)
//! );
//! form_layout.widget(
//! state.text2.focus(),
//! FormLabel::Str("Text 2"),
//! // stretch to the form-width, preferred with 15, 1 row high.
//! FormWidget::StretchX(15, 1)
//! );
//! form_layout.widget(
//! state.text3.focus(),
//! FormLabel::Str("Text 3"),
//! // stretch to the form-width and fill vertically.
//! // preferred width is 15 3 rows high.
//! FormWidget::StretchXY(15, 3)
//! );
//!
//! // calculate the layout and set it.
//! state.form.set_layout(form_layout.paged(area.as_size(), Padding::default()));
//! }
//!
//! let mut form = Form::new()
//! .into_buffer(area, buf, &mut state.form);
//!
//! form.render(state.text1.focus(),
//! || TextInput::new(),
//! &mut state.text1
//! );
//! form.render(state.text2.focus(),
//! || TextInput::new(),
//! &mut state.text2
//! );
//! form.render(state.text3.focus(),
//! || TextInput::new(),
//! &mut state.text3
//! );
//!
//! ```
use crate::_private::NonExhaustive;
use crate::layout::GenericLayout;
use crate::pager::{Pager, PagerBuffer, PagerStyle};
use rat_reloc::RelocatableState;
use ratatui::buffer::Buffer;
use ratatui::layout::{Alignment, Rect, Size};
use ratatui::style::Style;
use ratatui::widgets::{StatefulWidget, Widget};
use std::borrow::Cow;
use std::cell::{Ref, RefCell, RefMut};
use std::hash::Hash;
use std::marker::PhantomData;
use std::rc::Rc;
/// A widget that helps with rendering a Form.
/// Uses a GenericLayout for its layout information.
/// Does no scrolling/paging whatsoever and any widgets
/// out of view are simply not rendered.
#[derive(Debug, Clone)]
pub struct Form<'a, W>
where
W: Eq + Hash + Clone,
{
pager: Pager<W>,
phantom: PhantomData<&'a ()>,
}
/// Renders directly to the frame buffer.
///
/// * It maps your widget area from layout coordinates
/// to screen coordinates before rendering.
/// * It helps with cleanup of the widget state if your
/// widget is currently invisible.
#[derive(Debug)]
pub struct FormBuffer<'a, W>
where
W: Eq + Hash + Clone,
{
pager: PagerBuffer<'a, W>,
}
/// Widget state.
#[derive(Debug, Clone)]
pub struct FormState<W>
where
W: Eq + Hash + Clone,
{
/// Page layout
/// __read+write__ renewed with each render.
pub layout: Rc<RefCell<GenericLayout<W>>>,
/// Only construct with `..Default::default()`.
pub non_exhaustive: NonExhaustive,
}
impl<W> Default for Form<'_, W>
where
W: Eq + Hash + Clone,
{
fn default() -> Self {
Self {
pager: Default::default(),
phantom: Default::default(),
}
}
}
impl<'a, W> Form<'a, W>
where
W: Eq + Hash + Clone,
{
/// New SinglePage.
pub fn new() -> Self {
Self::default()
}
/// Base style.
pub fn style(mut self, style: Style) -> Self {
self.pager = self.pager.style(style);
self
}
/// Style for text labels.
pub fn label_style(mut self, style: Style) -> Self {
self.pager = self.pager.label_style(style);
self
}
/// Alignment for text labels.
pub fn label_alignment(mut self, alignment: Alignment) -> Self {
self.pager = self.pager.label_alignment(alignment);
self
}
/// Set all styles.
pub fn styles(mut self, styles: PagerStyle) -> Self {
self.pager = self.pager.styles(styles.clone());
self
}
/// Calculate the layout page size.
pub fn layout_size(&self, area: Rect) -> Size {
area.as_size()
}
// Calculate the view area for all columns.
pub fn inner(&self, area: Rect) -> Rect {
area
}
/// Render the page navigation and create the SinglePagerBuffer
/// that will do the actual widget rendering.
pub fn into_buffer(
self,
area: Rect,
buf: &'a mut Buffer,
state: &'a mut FormState<W>,
) -> FormBuffer<'a, W> {
FormBuffer {
pager: self
.pager //
.layout(state.layout.clone())
.page(0)
.into_buffer(area, Rc::new(RefCell::new(buf))),
}
}
}
impl<'a, W> FormBuffer<'a, W>
where
W: Eq + Hash + Clone,
{
/// Is the given area visible?
pub fn is_visible(&self, widget: W) -> bool {
if let Some(idx) = self.pager.widget_idx(widget) {
self.pager.is_visible(idx)
} else {
false
}
}
/// Render all blocks for the current page.
pub fn render_block(&mut self) {
self.pager.render_block()
}
/// Render a manual label.
#[inline(always)]
pub fn render_label<FN, WW>(&mut self, widget: W, render_fn: FN) -> bool
where
FN: FnOnce(&Option<Cow<'static, str>>) -> WW,
WW: Widget,
{
let Some(idx) = self.pager.widget_idx(widget) else {
return false;
};
self.pager.render_label(idx, render_fn)
}
/// Render a stateless widget and its label, if any.
#[inline(always)]
pub fn render_widget<FN, WW>(&mut self, widget: W, render_fn: FN) -> bool
where
FN: FnOnce() -> WW,
WW: Widget,
{
let Some(idx) = self.pager.widget_idx(widget) else {
return false;
};
self.pager.render_auto_label(idx);
self.pager.render_widget(idx, render_fn)
}
/// Render an optional stateful widget and its label, if any.
#[inline(always)]
pub fn render_opt<FN, WW, SS>(&mut self, widget: W, render_fn: FN, state: &mut SS) -> bool
where
FN: FnOnce() -> Option<WW>,
WW: StatefulWidget<State = SS>,
SS: RelocatableState,
{
let Some(idx) = self.pager.widget_idx(widget) else {
return false;
};
self.pager.render_auto_label(idx);
if !self.pager.render_opt(idx, render_fn, state) {
self.hidden(state);
false
} else {
true
}
}
/// Render a stateful widget and its label, if any.
#[inline(always)]
pub fn render<FN, WW, SS>(&mut self, widget: W, render_fn: FN, state: &mut SS) -> bool
where
FN: FnOnce() -> WW,
WW: StatefulWidget<State = SS>,
SS: RelocatableState,
{
let Some(idx) = self.pager.widget_idx(widget) else {
return false;
};
self.pager.render_auto_label(idx);
if !self.pager.render(idx, render_fn, state) {
self.hidden(state);
false
} else {
true
}
}
/// Render a stateful widget and its label, if any.
/// The closure can return a second value, which will be forwarded
/// if the widget is visible.
#[inline(always)]
#[allow(clippy::question_mark)]
pub fn render2<FN, WW, SS, R>(&mut self, widget: W, render_fn: FN, state: &mut SS) -> Option<R>
where
FN: FnOnce() -> (WW, R),
WW: StatefulWidget<State = SS>,
SS: RelocatableState,
{
let Some(idx) = self.pager.widget_idx(widget) else {
return None;
};
self.pager.render_auto_label(idx);
if let Some(remainder) = self.pager.render2(idx, render_fn, state) {
Some(remainder)
} else {
self.hidden(state);
None
}
}
/// Calculate the necessary shift from view to screen.
/// This does nothing as pager always places the widgets
/// in screen coordinates.
///
/// Just to keep the api in sync with [Clipper](crate::clipper::Clipper).
pub fn shift(&self) -> (i16, i16) {
(0, 0)
}
/// Relocate the widget area to screen coordinates.
/// Returns None if the widget is not visible.
/// This clips the area to page_area.
#[allow(clippy::question_mark)]
pub fn locate_widget(&self, widget: W) -> Option<Rect> {
let Some(idx) = self.pager.widget_idx(widget) else {
return None;
};
self.pager.locate_widget(idx)
}
/// Relocate the label area to screen coordinates.
/// Returns None if the widget is not visible.
/// This clips the area to page_area.
#[allow(clippy::question_mark)]
pub fn locate_label(&self, widget: W) -> Option<Rect> {
let Some(idx) = self.pager.widget_idx(widget) else {
return None;
};
self.pager.locate_label(idx)
}
/// Relocate an area from layout coordinates to screen coordinates.
/// A result None indicates that the area is invisible.
///
/// This will clip the area to the page_area.
pub fn locate_area(&self, area: Rect) -> Option<Rect> {
self.pager.locate_area(area)
}
/// Does nothing for pager.
/// Just to keep the api in sync with [Clipper](crate::clipper::Clipper).
pub fn relocate<S>(&self, _state: &mut S)
where
S: RelocatableState,
{
}
/// Clear the areas in the widget-state.
/// This is called by render_xx whenever a widget is invisible.
pub fn hidden<S>(&self, state: &mut S)
where
S: RelocatableState,
{
state.relocate((0, 0), Rect::default())
}
/// Get access to the buffer during rendering a page.
pub fn buffer<'b>(&'b mut self) -> RefMut<'b, &'a mut Buffer> {
self.pager.buffer()
}
}
impl<W> Default for FormState<W>
where
W: Eq + Hash + Clone,
{
fn default() -> Self {
Self {
layout: Default::default(),
non_exhaustive: NonExhaustive,
}
}
}
impl<W> FormState<W>
where
W: Eq + Hash + Clone,
{
pub fn new() -> Self {
Self::default()
}
/// Layout needs to change?
pub fn valid_layout(&self, size: Size) -> bool {
let layout = self.layout.borrow();
!layout.size_changed(size) && !layout.is_empty()
}
/// Set the layout.
pub fn set_layout(&mut self, layout: GenericLayout<W>) {
self.layout = Rc::new(RefCell::new(layout));
}
/// Layout.
pub fn layout(&self) -> Ref<'_, GenericLayout<W>> {
self.layout.borrow()
}
/// Clear the layout data and reset the page/page-count.
pub fn clear(&mut self) {
self.layout.borrow_mut().clear();
}
}