ratatui_widgettable/cell.rs
1use alloc::boxed::Box;
2use core::fmt;
3
4use ratatui_core::buffer::Buffer;
5use ratatui_core::layout::Rect;
6use ratatui_core::style::{Style, Styled};
7use ratatui_core::text::Text;
8use ratatui_core::widgets::Widget;
9
10/// A [`Cell`] contains the widget to be displayed in a [`Row`] of a [`Table`].
11///
12/// Unlike the `Cell` in ratatui's built-in table, which can only hold [`Text`], this `Cell` can
13/// hold any widget that can be rendered by reference (i.e. `&W` implements [`Widget`]). This
14/// includes all of the built-in ratatui widgets such as `Paragraph`, `Block`, `Gauge`, `List`,
15/// `Sparkline`, `Chart`, and even another [`Table`].
16///
17/// For widgets that can only be rendered by value, or for custom drawing logic, use
18/// [`Cell::from_fn`].
19///
20/// Note: unlike the built-in table, [`Cell::new`] takes a widget, so to create a cell from a string
21/// use [`Cell::from`] (e.g. `Cell::from("text")`) or wrap it in [`Text`] (`Cell::new(Text::from(
22/// "text"))`). Anything convertible into [`Text`] can also be passed directly to [`Row::new`].
23///
24/// You can apply a [`Style`] to the [`Cell`] using [`Cell::style`]. This will set the style for the
25/// entire area of the cell before the widget is rendered on top of it.
26///
27/// # Examples
28///
29/// ```rust
30/// use ratatui::style::Style;
31/// use ratatui::widgets::{Block, Gauge, Paragraph, Wrap};
32/// use ratatui_widgettable::Cell;
33///
34/// // Anything convertible into `Text` still works, just like the built-in table
35/// Cell::from("simple string");
36///
37/// // Any widget can be used as the content of a cell
38/// Cell::new(Paragraph::new("some long text that wraps").wrap(Wrap { trim: true }));
39/// Cell::new(Gauge::default().percent(42));
40/// Cell::new(Block::bordered().title("boxed"));
41///
42/// // Or use a closure for custom rendering
43/// Cell::from_fn(|area, buf| {
44/// buf.set_string(area.x, area.y, "custom", Style::new());
45/// });
46/// ```
47///
48/// `Cell` implements [`Styled`] which means you can use style shorthands from the [`Stylize`] trait
49/// to set the style of the cell concisely.
50///
51/// ```rust
52/// use ratatui::style::Stylize;
53/// use ratatui_widgettable::Cell;
54///
55/// Cell::from("Cell 1").red().italic();
56/// ```
57///
58/// [`Row`]: crate::Row
59/// [`Row::new`]: crate::Row::new
60/// [`Table`]: crate::Table
61/// [`Stylize`]: ratatui_core::style::Stylize
62pub struct Cell<'a> {
63 content: Box<dyn CellContent + 'a>,
64 style: Style,
65 /// The number of columns this cell will extend over
66 pub(crate) column_span: u16,
67}
68
69/// Object safe trait for anything that can render itself by reference into a cell.
70trait CellContent {
71 fn render_ref(&self, area: Rect, buf: &mut Buffer);
72}
73
74impl<W> CellContent for W
75where
76 for<'b> &'b W: Widget,
77{
78 fn render_ref(&self, area: Rect, buf: &mut Buffer) {
79 Widget::render(self, area, buf);
80 }
81}
82
83/// Wraps a closure so that it can be used as the content of a cell.
84struct FnContent<F>(F);
85
86impl<F> CellContent for FnContent<F>
87where
88 F: Fn(Rect, &mut Buffer),
89{
90 fn render_ref(&self, area: Rect, buf: &mut Buffer) {
91 (self.0)(area, buf);
92 }
93}
94
95impl<'a> Cell<'a> {
96 /// Creates a new [`Cell`] containing the given widget.
97 ///
98 /// The `widget` parameter accepts any widget which implements [`Widget`] for a reference to
99 /// itself (`&W: Widget`), which all of the built-in ratatui widgets do.
100 ///
101 /// To create a cell from a string or other [`Text`], use [`Cell::from`].
102 ///
103 /// # Examples
104 ///
105 /// ```rust
106 /// use ratatui::text::Text;
107 /// use ratatui::widgets::{Block, Paragraph};
108 /// use ratatui_widgettable::Cell;
109 ///
110 /// Cell::new(Paragraph::new("hello").block(Block::bordered()));
111 /// Cell::new(Text::from("a text"));
112 /// ```
113 pub fn new<W>(widget: W) -> Self
114 where
115 W: 'a,
116 for<'b> &'b W: Widget,
117 {
118 Self {
119 content: Box::new(widget),
120 style: Style::default(),
121 column_span: 1,
122 }
123 }
124
125 /// Creates a new [`Cell`] which renders its content using the given closure.
126 ///
127 /// The closure is called with the area of the cell and the buffer to render into. This is
128 /// useful for widgets that only implement [`Widget`] by value, stateful widgets, or custom
129 /// drawing logic.
130 ///
131 /// # Examples
132 ///
133 /// ```rust
134 /// use ratatui::widgets::{Paragraph, Widget};
135 /// use ratatui_widgettable::Cell;
136 ///
137 /// let cell = Cell::from_fn(|area, buf| {
138 /// Paragraph::new("rendered from a closure").render(area, buf);
139 /// });
140 /// ```
141 pub fn from_fn<F>(render: F) -> Self
142 where
143 F: Fn(Rect, &mut Buffer) + 'a,
144 {
145 Self {
146 content: Box::new(FnContent(render)),
147 style: Style::default(),
148 column_span: 1,
149 }
150 }
151
152 /// Set the content of the [`Cell`] to the given widget.
153 ///
154 /// This is a fluent setter method which must be chained or used as it consumes self
155 ///
156 /// # Examples
157 ///
158 /// ```rust
159 /// use ratatui::widgets::Paragraph;
160 /// use ratatui_widgettable::Cell;
161 ///
162 /// Cell::default().content(Paragraph::new("hello"));
163 /// ```
164 #[must_use = "method moves the value of self and returns the modified value"]
165 pub fn content<W>(mut self, widget: W) -> Self
166 where
167 W: 'a,
168 for<'b> &'b W: Widget,
169 {
170 self.content = Box::new(widget);
171 self
172 }
173
174 /// Set the `column_span` of this cell
175 ///
176 /// This is a fluent setter method which must be chained or used as it consumes self
177 ///
178 /// # Example
179 /// ```rust
180 /// use ratatui_widgettable::{Cell, Row};
181 /// let rows = vec![
182 /// Row::new(vec![Cell::from("12345").column_span(2)]),
183 /// Row::new(vec![Cell::from("xx"), Cell::from("yy")]),
184 /// ];
185 /// // "12345",
186 /// // "xx yy",
187 /// ```
188 #[must_use = "method moves the value of self and returns the modified value"]
189 pub const fn column_span(mut self, column_span: u16) -> Self {
190 self.column_span = column_span;
191 self
192 }
193
194 /// Set the `Style` of this cell
195 ///
196 /// `style` accepts any type that is convertible to [`Style`] (e.g. [`Style`], [`Color`], or
197 /// your own type that implements [`Into<Style>`]).
198 ///
199 /// This `Style` will override the `Style` of the [`Row`] and can be overridden by any styles
200 /// applied by the widget content.
201 ///
202 /// This is a fluent setter method which must be chained or used as it consumes self
203 ///
204 /// # Examples
205 ///
206 /// ```rust
207 /// use ratatui::style::{Style, Stylize};
208 /// use ratatui_widgettable::Cell;
209 ///
210 /// Cell::from("Cell 1").style(Style::new().red().italic());
211 /// ```
212 ///
213 /// [`Row`]: crate::Row
214 /// [`Color`]: ratatui_core::style::Color
215 #[must_use = "method moves the value of self and returns the modified value"]
216 pub fn style<S: Into<Style>>(mut self, style: S) -> Self {
217 self.style = style.into();
218 self
219 }
220}
221
222impl Cell<'_> {
223 pub(crate) fn render(&self, area: Rect, buf: &mut Buffer) {
224 // Cells of rows that don't fit in the table (e.g. because of a top margin) get an empty
225 // area which may be outside of the table. Some widgets (e.g. `&str`) write to the buffer
226 // at the position of the area even if it is empty, so these aren't rendered at all.
227 if area.is_empty() {
228 return;
229 }
230 buf.set_style(area, self.style);
231 self.content.render_ref(area, buf);
232 }
233}
234
235impl Default for Cell<'_> {
236 fn default() -> Self {
237 Self::new(Text::default())
238 }
239}
240
241impl fmt::Debug for Cell<'_> {
242 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
243 f.debug_struct("Cell")
244 .field("content", &"<widget>")
245 .field("style", &self.style)
246 .field("column_span", &self.column_span)
247 .finish()
248 }
249}
250
251impl<'a, T> From<T> for Cell<'a>
252where
253 T: Into<Text<'a>>,
254{
255 fn from(content: T) -> Self {
256 Self::new(content.into())
257 }
258}
259
260impl Styled for Cell<'_> {
261 type Item = Self;
262
263 fn style(&self) -> Style {
264 self.style
265 }
266
267 fn set_style<S: Into<Style>>(self, style: S) -> Self::Item {
268 self.style(style)
269 }
270}
271
272#[cfg(test)]
273mod tests {
274 use ratatui_core::style::{Color, Modifier, Stylize};
275 use ratatui_widgets::paragraph::Paragraph;
276
277 use super::*;
278
279 #[test]
280 fn style() {
281 let style = Style::default().red().italic();
282 let cell = Cell::default().style(style);
283 assert_eq!(cell.style, style);
284 }
285
286 #[test]
287 fn stylize() {
288 assert_eq!(
289 Cell::from("").black().on_white().bold().not_dim().style,
290 Style::default()
291 .fg(Color::Black)
292 .bg(Color::White)
293 .add_modifier(Modifier::BOLD)
294 .remove_modifier(Modifier::DIM)
295 );
296 }
297
298 #[test]
299 fn render_text() {
300 let mut buf = Buffer::empty(Rect::new(0, 0, 5, 1));
301 Cell::from("abc").render(buf.area, &mut buf);
302 assert_eq!(buf, Buffer::with_lines(["abc "]));
303 }
304
305 #[test]
306 fn render_widget() {
307 let mut buf = Buffer::empty(Rect::new(0, 0, 5, 1));
308 Cell::new(Paragraph::new("abc").right_aligned()).render(buf.area, &mut buf);
309 assert_eq!(buf, Buffer::with_lines([" abc"]));
310 }
311
312 #[test]
313 fn render_fn() {
314 let mut buf = Buffer::empty(Rect::new(0, 0, 5, 1));
315 Cell::from_fn(|area, buf| {
316 buf.set_string(area.x + 1, area.y, "x", Style::new());
317 })
318 .render(buf.area, &mut buf);
319 assert_eq!(buf, Buffer::with_lines([" x "]));
320 }
321}