Skip to main content

comfy_table/
inline_table.rs

1//! Inline table support for embedding nested tables beneath rows of a parent table.
2//!
3//! An [`InlineTable`] acts as a nested table rendered directly below a specific row in the outer [`Table`].
4//! It automatically inherits the parent table's border styles and column separators,
5//! while maintaining its own column structure, headers, rows, and constraints.
6//!
7//! Because `InlineTable` implements [`Deref`] and [`DerefMut`] targeting [`Table`], you can use
8//! all familiar table configuration methods ([`Table::set_header`], [`Table::add_row`], etc.) directly
9//! on an `InlineTable`.
10//!
11//! # Best Practice: Inside-Out Composition
12//!
13//! When working with inline tables—especially when creating multi-level nested tables—the
14//! recommended approach is to define tables **inside-out** (bottom-up):
15//!
16//! 1. Define and populate the innermost [`InlineTable`] instances with their columns, headers, and rows.
17//! 2. Combine them into higher-level inline tables or sections using [`Table::add_inline_table`].
18//! 3. Finally, assemble the outer [`Table`], adding rows and attaching the prepared inline tables.
19//!
20//! This modular pattern keeps table logic clean, prevents scope confusion, and ensures clear data flow.
21//!
22//! # Example
23//!
24//! ```
25//! use comfy_table::{InlineTable, Table};
26//!
27//! // 1. Define the innermost nested table first
28//! let mut inner_table = InlineTable::new();
29//! inner_table
30//!     .set_header(vec!["Component", "Latency", "Status"])
31//!     .add_row(vec!["Cache Tier", "0.4 ms", "Healthy"])
32//!     .add_row(vec!["Storage Tier", "2.1 ms", "Healthy"]);
33//!
34//! // 2. Define the intermediate section and attach the inner table
35//! let mut service_section = InlineTable::new();
36//! service_section
37//!     .set_header(vec!["Service", "Region"])
38//!     .add_row(vec!["Authentication API", "eu-central-1"])
39//!     .add_inline_table(inner_table);
40//!
41//! // 3. Assemble the outer table
42//! let mut outer = Table::new();
43//! outer
44//!     .set_header(vec!["Cluster", "Environment"])
45//!     .add_row(vec!["Production-Core", "Live"])
46//!     .add_inline_table(service_section)
47//!     .add_row(vec!["Staging-Core", "Idle"]);
48//!
49//! println!("{outer}");
50//! ```
51
52use std::ops::{Deref, DerefMut};
53
54use crate::{
55    Table,
56    utils::{
57        arrangement::arrange_content,
58        formatting::content_format::{BuildInlineTableItem, BuildTableItem, format_content},
59    },
60};
61
62/// A nested table designed to be embedded inline directly below a row within a parent [`Table`].
63///
64/// `InlineTable` wraps an inner [`Table`] and tracks its placement relative to the rows of the
65/// parent table. It implements [`Deref`] and [`DerefMut`] targeting [`Table`], allowing full access
66/// to all table configuration methods (such as [`Table::set_header`], [`Table::add_row`],
67/// [`Table::set_constraints`], etc.).
68///
69/// When added to a parent table via [`Table::add_inline_table`], it is rendered below the most recently
70/// added row and inherits the outer table's styling for consistent appearance.
71///
72/// # Best Practice: Inside-Out Construction
73///
74/// It is recommended to construct tables **inside-out** (bottom-up):
75/// 1. Define and populate the innermost [`InlineTable`] instances first.
76/// 2. Nest them into intermediate inline tables via [`Table::add_inline_table`].
77/// 3. Finally, assemble the outer [`Table`].
78///
79/// # Example
80///
81/// ```
82/// use comfy_table::{InlineTable, Table};
83///
84/// let mut inline = InlineTable::new();
85/// inline.set_header(vec!["Sub", "Entry"]);
86/// inline.add_row(vec!["Nested", "Value"]);
87///
88/// let mut table = Table::new();
89/// table.add_row(vec!["Main", "Row"]);
90/// table.add_inline_table(inline);
91/// ```
92#[derive(Debug, Clone)]
93pub struct InlineTable {
94    pub(crate) index_row_above: Option<usize>,
95    pub table: Table,
96}
97
98struct InlineTableFromArgs {
99    index_row_above: Option<usize>,
100    table: Table,
101}
102
103impl From<InlineTableFromArgs> for InlineTable {
104    fn from(args: InlineTableFromArgs) -> Self {
105        let mut core = args.table;
106        core.columns = Vec::new();
107        core.header = None;
108        core.rows = Vec::new();
109        core.inline_tables = Vec::new();
110        Self {
111            index_row_above: args.index_row_above,
112            table: core,
113        }
114    }
115}
116
117impl Deref for InlineTable {
118    type Target = Table;
119    fn deref(&self) -> &Self::Target {
120        &self.table
121    }
122}
123
124impl DerefMut for InlineTable {
125    fn deref_mut(&mut self) -> &mut Self::Target {
126        &mut self.table
127    }
128}
129
130impl Default for InlineTable {
131    fn default() -> Self {
132        Self::new()
133    }
134}
135
136impl InlineTable {
137    /// Create a new, empty [`InlineTable`].
138    ///
139    /// By default, the table has no headers, rows, or predefined row association.
140    ///
141    /// ```
142    /// use comfy_table::InlineTable;
143    ///
144    /// let inline = InlineTable::new();
145    /// assert!(inline.is_empty());
146    /// ```
147    pub fn new() -> Self {
148        Self {
149            table: Table::new(),
150            index_row_above: None,
151        }
152    }
153
154    fn new_from_table(table: Table, index_row_above: Option<usize>) -> Self {
155        Self::from(InlineTableFromArgs {
156            table,
157            index_row_above,
158        })
159    }
160
161    /// Set the 0-based index of the parent table row directly above this inline table.
162    ///
163    /// When using [`Table::add_inline_table`], this index is automatically populated based on
164    /// the most recently added row. You can manually adjust this index if you need custom
165    /// row positioning, or pass `None` to display the inline table above the first row.
166    pub fn set_row_above_index(&mut self, index: Option<usize>) {
167        self.index_row_above = index;
168    }
169
170    /// Formats the inline table into table items using the styles and arrangement of the parent table.
171    ///
172    /// This reapplies the outer table's styling (such as border and separator characters) to ensure
173    /// visual consistency across the entire table output.
174    pub fn build_inline_table(
175        &self,
176        outer_table: &Table,
177        index_row_above: Option<usize>,
178    ) -> BuildTableItem {
179        let mut inline_table = Self::new_from_table(outer_table.clone(), index_row_above);
180        inline_table.table.columns = self.columns.clone();
181        inline_table.table.header = self.header.clone();
182        inline_table.table.rows = self.rows.clone();
183        inline_table.table.inline_tables = self.inline_tables.clone();
184        let display_info = arrange_content(&inline_table);
185        BuildTableItem::Inline(BuildInlineTableItem {
186            items: format_content(&inline_table.table, &display_info),
187            table: self.clone(),
188        })
189    }
190}