blinc_layout 0.5.0

Blinc layout engine - Flexbox layout powered by Taffy
Documentation
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
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
//! Table element builder for structured data display
//!
//! This module provides HTML-like table building helpers that use flexbox layout
//! to create structured table layouts.
//!
//! # Example
//!
//! ```ignore
//! use blinc_layout::prelude::*;
//! use blinc_core::Color;
//!
//! // Create a simple table
//! table()
//!     .w_full()
//!     .child(
//!         thead()
//!             .child(tr()
//!                 .child(th("Name"))
//!                 .child(th("Age"))
//!                 .child(th("City")))
//!     )
//!     .child(
//!         tbody()
//!             .child(tr()
//!                 .child(td("Alice"))
//!                 .child(td("30"))
//!                 .child(td("NYC")))
//!             .child(tr()
//!                 .child(td("Bob"))
//!                 .child(td("25"))
//!                 .child(td("LA")))
//!     )
//! ```
//!
//! # Table Structure
//!
//! Tables follow HTML conventions:
//! - `table()` - The outer container
//! - `thead()` - Table header section
//! - `tbody()` - Table body section
//! - `tfoot()` - Table footer section
//! - `tr()` - Table row
//! - `th(content)` - Header cell (bold, centered)
//! - `td(content)` - Data cell
//!
//! # Styling
//!
//! All table elements return `Div` and support the full fluent API:
//!
//! ```ignore
//! table()
//!     .bg(Color::from_hex(0x1a1a1a))
//!     .rounded(8.0)
//!     .child(
//!         tr()
//!             .bg(Color::from_hex(0x2a2a2a))
//!             .child(td("Styled cell").p(16.0))
//!     )
//! ```

use blinc_core::Color;
use blinc_theme::{ColorToken, ThemeState};

use crate::div::{div, Div};
use crate::text::{text, Text};

// ============================================================================
// Default Table Styling (from Theme)
// ============================================================================

/// Get header background color from theme
fn header_bg() -> Color {
    ThemeState::get().color(ColorToken::SurfaceOverlay)
}

/// Get border color from theme
fn border_color() -> Color {
    ThemeState::get().color(ColorToken::Border)
}

/// Get header text color from theme
fn header_text_color() -> Color {
    ThemeState::get().color(ColorToken::TextPrimary)
}

/// Get cell text color from theme
fn cell_text_color() -> Color {
    ThemeState::get().color(ColorToken::TextSecondary)
}

/// Get alternating row color from theme (subtle accent)
fn striped_bg() -> Color {
    ThemeState::get().color(ColorToken::AccentSubtle)
}

/// Default cell padding (in pixels)
const CELL_PADDING: f32 = 12.0;

/// Default font size
const DEFAULT_FONT_SIZE: f32 = 14.0;

// ============================================================================
// Table Container
// ============================================================================

/// Create a table container
///
/// The table is a flex-column container that holds thead, tbody, and tfoot sections.
///
/// # Example
///
/// ```ignore
/// table()
///     .w_full()
///     .rounded(8.0)
///     .bg(Color::from_hex(0x1a1a1a))
///     .child(thead().child(tr().child(th("Column"))))
///     .child(tbody().child(tr().child(td("Data"))))
/// ```
pub fn table() -> Div {
    div().flex_col().overflow_clip()
}

// ============================================================================
// Table Sections
// ============================================================================

/// Create a table header section
///
/// The thead is a flex-column container for header rows.
/// By default, it has a slightly darker background.
///
/// # Example
///
/// ```ignore
/// thead()
///     .bg(Color::from_hex(0x2a2a2a))
///     .child(tr()
///         .child(th("Name"))
///         .child(th("Value")))
/// ```
pub fn thead() -> Div {
    div().flex_col().bg(header_bg())
}

/// Create a table body section
///
/// The tbody is a flex-column container for data rows.
///
/// # Example
///
/// ```ignore
/// tbody()
///     .child(tr().child(td("Row 1")))
///     .child(tr().child(td("Row 2")))
/// ```
pub fn tbody() -> Div {
    div().flex_col()
}

/// Create a table footer section
///
/// The tfoot is a flex-column container for footer rows.
///
/// # Example
///
/// ```ignore
/// tfoot()
///     .bg(Color::from_hex(0x1a1a1a))
///     .child(tr().child(td("Total: 100")))
/// ```
pub fn tfoot() -> Div {
    div().flex_col().bg(header_bg())
}

// ============================================================================
// Table Row
// ============================================================================

/// Create a table row
///
/// A row is a flex-row container that holds cells (th or td).
/// Cells in a row will share space equally by default.
///
/// # Example
///
/// ```ignore
/// tr()
///     .child(td("Cell 1"))
///     .child(td("Cell 2"))
///     .child(td("Cell 3"))
/// ```
pub fn tr() -> Div {
    // Use a bottom separator line via a child div
    div().flex_row().w_full()
}

// ============================================================================
// Table Cells
// ============================================================================

/// A table cell wrapper that can hold any content
pub struct TableCell {
    inner: Div,
}

impl TableCell {
    fn new() -> Self {
        Self {
            inner: div()
                .flex_row()
                .items_center()
                .flex_1() // flex: 1 1 0% - grow equally with zero basis
                .padding_x_px(CELL_PADDING)
                .padding_y_px(CELL_PADDING),
        }
    }

    /// Add a child element to this cell
    pub fn child(mut self, child: impl crate::div::ElementBuilder + 'static) -> Self {
        self.inner = self.inner.child(child);
        self
    }

    /// Set cell width in pixels
    pub fn w(mut self, px: f32) -> Self {
        self.inner = self.inner.w(px).flex_shrink_0();
        self
    }

    /// Set cell to flex-grow with a specific weight
    pub fn flex_weight(mut self, weight: f32) -> Self {
        self.inner = self.inner.flex_grow();
        // Note: can't set specific flex-grow weight in current API
        // Use w() for fixed widths or flex_grow() for equal distribution
        let _ = weight; // Suppress unused warning
        self
    }

    /// Set cell to not grow (fixed width based on content)
    pub fn w_fit(mut self) -> Self {
        self.inner = self.inner.w_fit();
        self
    }

    /// Set cell padding
    pub fn p(mut self, units: f32) -> Self {
        self.inner = self.inner.p(units);
        self
    }

    /// Set cell padding in pixels
    pub fn padding_px(mut self, px: f32) -> Self {
        self.inner = self.inner.padding_x_px(px).padding_y_px(px);
        self
    }

    /// Set horizontal padding
    pub fn px(mut self, units: f32) -> Self {
        self.inner = self.inner.px(units);
        self
    }

    /// Set vertical padding
    pub fn py(mut self, units: f32) -> Self {
        self.inner = self.inner.py(units);
        self
    }

    /// Set cell background color
    pub fn bg(mut self, color: Color) -> Self {
        self.inner = self.inner.bg(color);
        self
    }

    /// Center content horizontally
    pub fn justify_center(mut self) -> Self {
        self.inner = self.inner.justify_center();
        self
    }

    /// Align content to end (right)
    pub fn justify_end(mut self) -> Self {
        self.inner = self.inner.justify_end();
        self
    }

    /// Center content vertically
    pub fn items_center(mut self) -> Self {
        self.inner = self.inner.items_center();
        self
    }

    /// Add a separator (vertical line) after this cell
    ///
    /// Creates a visual divider by adding a narrow colored div as the last child
    pub fn with_separator(self) -> Div {
        div()
            .flex_row()
            .child(self)
            .child(div().w(1.0).h_full().bg(border_color()))
    }

    /// Convert to the underlying Div (for advanced customization)
    pub fn into_div(self) -> Div {
        self.inner
    }
}

impl crate::div::ElementBuilder for TableCell {
    fn build(&self, tree: &mut crate::tree::LayoutTree) -> crate::tree::LayoutNodeId {
        self.inner.build(tree)
    }

    fn render_props(&self) -> crate::element::RenderProps {
        self.inner.render_props()
    }

    fn children_builders(&self) -> &[Box<dyn crate::div::ElementBuilder>] {
        self.inner.children_builders()
    }

    fn element_type_id(&self) -> crate::div::ElementTypeId {
        self.inner.element_type_id()
    }

    fn semantic_type_name(&self) -> Option<&'static str> {
        Some("td")
    }
}

/// Create a table header cell (th)
///
/// Header cells are bold and centered by default.
///
/// # Example
///
/// ```ignore
/// th("Column Name")
/// th("Right Aligned").justify_end()
/// ```
pub fn th(content: impl Into<String>) -> TableCell {
    let txt = text(content)
        .size(DEFAULT_FONT_SIZE)
        .color(header_text_color())
        .bold();

    TableCell::new().child(txt)
}

/// Create a table data cell (td)
///
/// Data cells contain regular text and are left-aligned by default.
///
/// # Example
///
/// ```ignore
/// td("Cell content")
/// td("123.45").justify_end()  // Right-align numbers
/// ```
pub fn td(content: impl Into<String>) -> TableCell {
    let txt = text(content)
        .size(DEFAULT_FONT_SIZE)
        .color(cell_text_color());

    TableCell::new().child(txt)
}

/// Create an empty table cell
///
/// Useful for placeholder cells or cells with custom content.
///
/// # Example
///
/// ```ignore
/// // Empty cell
/// cell()
///
/// // Cell with custom content
/// cell().child(button("Edit"))
/// ```
pub fn cell() -> TableCell {
    TableCell::new()
}

// ============================================================================
// Striped Rows Helper
// ============================================================================

/// Create a striped table row
///
/// Alternates background color based on index for zebra striping.
///
/// # Example
///
/// ```ignore
/// tbody()
///     .child(striped_tr(0).child(td("Row 0")))
///     .child(striped_tr(1).child(td("Row 1")))
///     .child(striped_tr(2).child(td("Row 2")))
/// ```
pub fn striped_tr(index: usize) -> Div {
    let bg = if index % 2 == 0 {
        Color::TRANSPARENT
    } else {
        striped_bg()
    };

    tr().bg(bg)
}

// ============================================================================
// Table Builder (Alternative API)
// ============================================================================

/// A builder for creating tables with headers and data
///
/// This provides a more declarative way to create tables from data.
///
/// # Example
///
/// ```ignore
/// TableBuilder::new()
///     .headers(&["Name", "Age", "City"])
///     .row(&["Alice", "30", "NYC"])
///     .row(&["Bob", "25", "LA"])
///     .striped(true)
///     .build()
/// ```
pub struct TableBuilder {
    headers: Vec<String>,
    rows: Vec<Vec<String>>,
    striped: bool,
    header_bg: Color,
    border_color: Color,
}

impl TableBuilder {
    /// Create a new table builder
    pub fn new() -> Self {
        Self {
            headers: Vec::new(),
            rows: Vec::new(),
            striped: false,
            header_bg: header_bg(),
            border_color: border_color(),
        }
    }

    /// Set table headers
    pub fn headers(mut self, headers: &[&str]) -> Self {
        self.headers = headers.iter().map(|s| s.to_string()).collect();
        self
    }

    /// Add a data row
    pub fn row(mut self, cells: &[&str]) -> Self {
        self.rows
            .push(cells.iter().map(|s| s.to_string()).collect());
        self
    }

    /// Enable zebra striping
    pub fn striped(mut self, enabled: bool) -> Self {
        self.striped = enabled;
        self
    }

    /// Set header background color
    pub fn header_bg(mut self, color: Color) -> Self {
        self.header_bg = color;
        self
    }

    /// Set border color
    pub fn border_color(mut self, color: Color) -> Self {
        self.border_color = color;
        self
    }

    /// Build the table
    pub fn build(self) -> Div {
        let mut tbl = table();

        // Build header
        if !self.headers.is_empty() {
            let mut header_row = tr();
            for h in &self.headers {
                header_row = header_row.child(th(h.as_str()));
            }
            tbl = tbl.child(thead().bg(self.header_bg).child(header_row));
        }

        // Build body
        if !self.rows.is_empty() {
            let mut body = tbody();
            for (i, row_data) in self.rows.iter().enumerate() {
                let mut row = if self.striped { striped_tr(i) } else { tr() };

                for cell_data in row_data {
                    row = row.child(td(cell_data.as_str()));
                }

                body = body.child(row);
            }
            tbl = tbl.child(body);
        }

        tbl
    }
}

impl Default for TableBuilder {
    fn default() -> Self {
        Self::new()
    }
}

// ============================================================================
// Convenience: Text-based cells
// ============================================================================

/// Create a header cell with custom text styling
///
/// Returns a Text element that you can further style.
/// Use `th()` if you need cell-level styling (padding, background).
pub fn th_text(content: impl Into<String>) -> Text {
    text(content)
        .size(DEFAULT_FONT_SIZE)
        .color(header_text_color())
        .bold()
}

/// Create a data cell with custom text styling
///
/// Returns a Text element that you can further style.
/// Use `td()` if you need cell-level styling (padding, background).
pub fn td_text(content: impl Into<String>) -> Text {
    text(content)
        .size(DEFAULT_FONT_SIZE)
        .color(cell_text_color())
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::div::ElementBuilder;
    use crate::tree::LayoutTree;

    fn init_theme() {
        // Initialize theme if not already done (safe to call multiple times)
        let _ = ThemeState::try_get().unwrap_or_else(|| {
            ThemeState::init_default();
            ThemeState::get()
        });
    }

    #[test]
    fn test_simple_table() {
        init_theme();
        let mut tree = LayoutTree::new();

        let tbl = table()
            .child(thead().child(tr().child(th("Header"))))
            .child(tbody().child(tr().child(td("Data"))));

        tbl.build(&mut tree);
        assert!(!tree.is_empty());
    }

    #[test]
    fn test_table_builder() {
        init_theme();
        let mut tree = LayoutTree::new();

        let tbl = TableBuilder::new()
            .headers(&["A", "B", "C"])
            .row(&["1", "2", "3"])
            .row(&["4", "5", "6"])
            .striped(true)
            .build();

        tbl.build(&mut tree);
        assert!(!tree.is_empty());
    }

    #[test]
    fn test_cell_methods() {
        init_theme();
        let mut tree = LayoutTree::new();

        let cell = td("Test")
            .w(100.0)
            .justify_end()
            .bg(Color::from_hex(0x333333));

        cell.build(&mut tree);
        assert!(!tree.is_empty());
    }
}