Skip to main content

ctl_layout/
column.rs

1//! One column of a table.
2
3use ctl_text::{Overflow, Text};
4
5use crate::align::Align;
6
7/// A column of a table: its header, what it does with a cell wider than it
8/// gets, and which edge its cells sit against.
9///
10/// The overflow applies to the header as well as to the cells.
11#[derive(Clone, Debug)]
12pub struct Column {
13    pub(crate) header: Option<Text>,
14    pub(crate) overflow: Overflow,
15    pub(crate) align: Align,
16}
17
18impl Column {
19    /// A column headed by `header`. A `&str` or a `String` is in the default
20    /// style, and a [`Text`] keeps its own styles.
21    #[must_use]
22    pub fn new(header: impl Into<Text>) -> Self {
23        Self::headed(Some(header.into()))
24    }
25
26    /// A column with no header. A table draws a header row only when at least
27    /// one of its columns has a header. Then this column's header cell is
28    /// empty.
29    #[must_use]
30    pub fn untitled() -> Self {
31        Self::headed(None)
32    }
33
34    fn headed(header: Option<Text>) -> Self {
35        Self {
36            header,
37            overflow: Overflow::default(),
38            align: Align::default(),
39        }
40    }
41
42    /// Sets what the column does with a cell wider than it gets: keep words
43    /// whole, fold them, or cut the line with an ellipsis. The default is
44    /// [`Overflow::KeepWords`].
45    #[must_use]
46    pub fn overflow(mut self, overflow: Overflow) -> Self {
47        self.overflow = overflow;
48        self
49    }
50
51    /// Aligns every cell of the column to the right, header included, so
52    /// numbers line up on their last digit. This is [`align`](Self::align)
53    /// with [`Align::Right`].
54    #[must_use]
55    pub fn numeric(self) -> Self {
56        self.align(Align::Right)
57    }
58
59    /// Aligns every cell of the column, header included, against the edge
60    /// that `align` selects. The default is [`Align::Left`].
61    #[must_use]
62    pub fn align(mut self, align: Align) -> Self {
63        self.align = align;
64        self
65    }
66}