skip to content
==> tests/table.c <==
1/* A table as ratatui draws one: a header, Length and Fill columns with spacing, the highlight
2 * symbol's column appearing with a selection, and scrolling to keep the selection visible. */
3#include "mesh/check.h"
4#include "tui/table.h"
5
6#include <string.h>
7
8static const char *row(const tui_buffer *b, uint16_t y) {
9    static char out[512];
10    size_t n = 0;
11    for (uint16_t x = 0; x < b->area.width; x++) {
12        const char *s = tui_cell_symbol(tui_buffer_cell_c(b, x, y));
13        size_t k = strlen(s);
14        memcpy(out + n, s, k);
15        n += k;
16    }
17    out[n] = 0;
18    return out;
19}
20
21static tui_table_row mk(tui_arena *a, const char *x, const char *y) {
22    tui_table_row r = tui_table_row_new();
23    tui_table_row_push(a, &r, tui_table_cell_text(tui_text_from_str(a, x)));
24    tui_table_row_push(a, &r, tui_table_cell_text(tui_text_from_str(a, y)));
25    return r;
26}
27
28int main(void) {
29    tui_arena a = {0};
30    tui_buffer b;
31    tui_buffer_init(&b, (tui_rect){0, 0, 12, 3});
32    tui_table_row rows[4] = {mk(&a, "a", "one"), mk(&a, "b", "two"), mk(&a, "c", "three"), mk(&a, "d", "four")};
33    tui_table_row head = mk(&a, "k", "value");
34    tui_constraint w[2] = {TUI_LENGTH(3), TUI_FILL(1)};
35    tui_table t = tui_table_new(rows, 4, w, 2);
36    t.header = &head;
37    tui_table_render(&a, &t, b.area, &b, NULL);
38    CHECK_S(row(&b, 0), "k   value   ");
39    CHECK_S(row(&b, 1), "a   one     ");
40    CHECK_S(row(&b, 2), "b   two     ");
41    /* Select the last row: a highlight column, and the rows scroll. */
42    tui_buffer_clear(&b, b.area);
43    t.highlight_symbol = tui_text_from_str(&a, ">");
44    t.row_highlight_style = tui_style_bold(tui_style_new());
45    tui_table_state st = {.has_selected = true, .selected = 3};
46    tui_table_render(&a, &t, b.area, &b, &st);
47    CHECK_S(row(&b, 0), " k   value  ");
48    CHECK_S(row(&b, 1), " c   three  ");
49    CHECK_S(row(&b, 2), ">d   four   ");
50    CHECK_U(st.offset, 2);
51    CHECK_U(tui_buffer_cell(&b, 5, 2)->mod, TUI_BOLD);
52    tui_buffer_free(&b);
53    tui_arena_free(&a);
54    tui_layout_cache_clear();
55    return mesh_check_done();
56}