ublx 0.1.5

TUI to index once, enrich with metadata, and browse a flat snapshot in a 3-pane layout with multiple modes.
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
//! Ratatui [`Table`] widgets for [`super::sections`] (metadata, writing, sheet-style JSON).
//!
//! Windowed row slicing and column width balancing live here; see [`super::draw`] for painting.
//! File-viewer grids (CSV / Markdown) use **comfy-table** in [`crate::render::viewers::pretty_tables`].

use ratatui::layout::Constraint;
use ratatui::text::Line;
use ratatui::widgets::{Cell, Row, Table};
use rayon::prelude::*;

use crate::config::PARALLEL;
use crate::layout::style;
use crate::modules::viewer_search;
use crate::ui::UI_STRINGS;
use crate::utils::truncate_middle;

use super::{
    format,
    sections::{ContentsSection, KvSection, SingleColumnListSection},
};

const COLUMN_SPACING: usize = 1;
const KEY_WIDTH_FALLBACK: usize = 4;
const KEY_WIDTH_MIN: usize = 35;
const VALUE_WIDTH_MIN: usize = 10;

/// When a table has more than this many columns, we balance widths to fill the pane; otherwise we use natural (compact) widths so few-column tables (e.g. sheet stats) don’t look over-spaced.
const SIZE_OPTIMIZATION_COLUMN_THRESHOLD: usize = 3;

/// Global byte offsets for KV cells when find ranges are synced to [`super::sections::searchable_text_from_json`].
pub struct KvFindSync<'a> {
    pub line_starts: &'a [usize],
    pub ranges: &'a [(usize, usize)],
    pub current: usize,
    /// Line index in haystack of the first data row in the full (unwindowed) section.
    pub first_data_line_idx: usize,
    /// Row offset into that section for the visible window (`skip` in draw).
    pub row_skip: usize,
}

/// Shared find/highlight rendering settings for table builders.
#[derive(Clone, Copy)]
pub struct TableFindRenderCtx<'a> {
    pub needle: Option<&'a str>,
    pub current_line_idx: Option<usize>,
    pub first_data_line_idx: usize,
    pub metadata_mode: bool,
}

/// Visible row window and styling offset for virtualized table builders.
#[derive(Clone, Copy)]
pub struct TableWindow {
    pub row_offset: usize,
    pub start: usize,
    pub end: usize,
}

/// Shared column spacing and base text style for KV / Contents / single-column tables.
#[inline]
fn table_with_chrome(t: Table<'static>) -> Table<'static> {
    t.column_spacing(COLUMN_SPACING as u16)
        .style(style::text_style())
}

/// Owned cell text so [`Table`] rows are `'static` (find highlights are already owned [`Line`]s).
#[inline]
fn cell_for_str(
    s: &str,
    find_needle: Option<&str>,
    current_match_row: bool,
    metadata_mode: bool,
) -> Cell<'static> {
    if viewer_search::option_needle_nonempty(find_needle) {
        if current_match_row && metadata_mode {
            Cell::from(viewer_search::highlight_cell_line_with_style(
                s,
                find_needle.unwrap(),
                style::viewer_find_match_current_metadata_contrast(),
                true,
            ))
        } else if metadata_mode {
            Cell::from(viewer_search::highlight_cell_line_ascii_insensitive(
                s,
                find_needle.unwrap(),
            ))
        } else {
            Cell::from(viewer_search::highlight_cell_line(s, find_needle.unwrap()))
        }
    } else {
        Cell::from(Line::from(s.to_string()))
    }
}

/// Compute column widths (in characters) from natural widths and available width.
/// Natural width per column is typically max(header len, max cell len in column).
/// If total natural fits, use natural (capped by available); otherwise scale down
/// proportionally. Distribute any remainder so sum equals available. Each column gets at least 1.
#[must_use]
pub fn balanced_column_widths(
    natural: &[usize],
    available_width: usize,
    spacing: usize,
) -> Vec<u16> {
    let n = natural.len().max(1);
    let gaps = (n - 1) * spacing;
    let available = available_width.saturating_sub(gaps);
    if available == 0 {
        return natural.iter().map(|_| 1u16).collect();
    }
    let total: usize = natural.iter().sum();
    if total == 0 {
        let w = (available / n).min(u16::MAX as usize) as u16;
        return (0..natural.len()).map(|_| w.max(1)).collect();
    }
    let mut widths: Vec<u16> = natural
        .iter()
        .map(|&nat| {
            let w = (nat * available) / total;
            (w.min(u16::MAX as usize).max(1)) as u16
        })
        .collect();
    let mut remainder = available.saturating_sub(widths.iter().map(|&w| w as usize).sum::<usize>());
    for w in &mut widths {
        if remainder == 0 {
            break;
        }
        *w = (*w as usize + 1).min(u16::MAX as usize) as u16;
        remainder -= 1;
    }
    widths
}

#[must_use]
pub fn entry_cell(
    obj: &serde_json::Map<String, serde_json::Value>,
    key: &str,
    max_array_inline: usize,
) -> String {
    obj.get(key).map_or_else(
        || "—".to_string(),
        |v| format::format_value(v, key, max_array_inline),
    )
}

/// Build key/value table for one section.
///
/// `table_width_chars` is the full table width in terminal columns (e.g. [`Rect::width`]); value cells
/// are truncated with [`truncate_middle`] when there is no active find (needle / KV sync), so long
/// strings match the visible value column.
#[must_use]
pub fn section_to_table(
    section: &KvSection,
    row_offset: usize,
    find_needle: Option<&str>,
    find_kv: Option<&KvFindSync<'_>>,
    metadata_mode: bool,
    table_width_chars: u16,
) -> Table<'static> {
    let header = Row::new(vec![
        UI_STRINGS.tables.header_key,
        UI_STRINGS.tables.header_value,
    ])
    .style(style::table_header_style())
    .bottom_margin(0);
    let key_w = section
        .rows
        .iter()
        .map(|(k, _)| k.chars().count())
        .max()
        .unwrap_or(KEY_WIDTH_FALLBACK)
        .min(KEY_WIDTH_MIN) as u16;
    let value_max_chars = (table_width_chars as usize)
        .saturating_sub(key_w as usize)
        .saturating_sub(COLUMN_SPACING)
        .max(8);
    let truncate_value = find_kv.is_none() && !viewer_search::option_needle_nonempty(find_needle);
    let data_rows: Vec<Row> = section
        .rows
        .iter()
        .enumerate()
        .map(|(i, (k, v))| {
            let v_display = if truncate_value && v.chars().count() > value_max_chars {
                truncate_middle(v, value_max_chars)
            } else {
                v.clone()
            };
            let (key_cell, value_cell) = if let Some(f) = find_kv {
                let li = f.first_data_line_idx + f.row_skip + i;
                let key_off = f.line_starts.get(li).copied().unwrap_or(0);
                let value_off = key_off.saturating_add(k.len()).saturating_add(1);
                let base_style = style::text_style();
                let match_style = style::viewer_find_match_table_cell();
                let current_style = if metadata_mode {
                    style::viewer_find_match_current_metadata_contrast()
                } else {
                    style::viewer_find_match_current_table_cell()
                };
                let key_cell = Cell::from(viewer_search::highlight_line_with_find_styles(
                    k.as_str(),
                    key_off,
                    f.ranges,
                    f.current,
                    base_style,
                    match_style,
                    current_style,
                ));
                let value_cell = Cell::from(viewer_search::highlight_line_with_find_styles(
                    v.as_str(),
                    value_off,
                    f.ranges,
                    f.current,
                    base_style,
                    match_style,
                    current_style,
                ));
                (key_cell, value_cell)
            } else {
                let key_cell = cell_for_str(k.as_str(), find_needle, false, false);
                let value_cell = if viewer_search::option_needle_nonempty(find_needle) {
                    cell_for_str(v_display.as_str(), find_needle, false, false)
                } else {
                    match format::value_cell_style(v_display.as_str()) {
                        Some(st) => Cell::from(Line::from(v_display).style(st)),
                        None => Cell::from(Line::from(v_display)),
                    }
                };
                (key_cell, value_cell)
            };
            Row::new(vec![key_cell, value_cell]).style(style::table_row_style(row_offset + i))
        })
        .collect();
    table_with_chrome(
        Table::new(
            data_rows,
            [
                Constraint::Length(key_w),
                Constraint::Min(VALUE_WIDTH_MIN as u16),
            ],
        )
        .header(header),
    )
}

/// Build one display row; string values are truncated to fit column width (chars).
fn contents_row(
    obj: &serde_json::Map<String, serde_json::Value>,
    column_keys: &[String],
    column_widths: &[u16],
    max_array_inline: usize,
) -> Vec<String> {
    column_keys
        .iter()
        .enumerate()
        .map(|(j, k)| {
            let cell = entry_cell(obj, k, max_array_inline);
            let max_chars = column_widths.get(j).copied().unwrap_or(0) as usize;
            let len = cell.chars().count();
            if max_chars > 0 && len > max_chars {
                truncate_middle(&cell, max_chars)
            } else {
                cell
            }
        })
        .collect()
}

/// Max per-column character widths from `entries` into `natural` (in place).
fn accumulate_natural_widths_from_entries<'a>(
    natural: &mut [usize],
    entries: impl Iterator<Item = &'a serde_json::Value>,
    keys: &[String],
    max_array_inline: usize,
) {
    for v in entries {
        let Some(obj) = v.as_object() else {
            continue;
        };
        for (j, k) in keys.iter().enumerate() {
            let len = entry_cell(obj, k, max_array_inline).chars().count();
            if let Some(nat) = natural.get_mut(j) {
                *nat = (*nat).max(len);
            }
        }
    }
}

/// Merge parallel chunk naturals into `acc` (per-column max).
fn merge_max_natural_widths(acc: &mut [usize], chunk: &[usize]) {
    for (j, &cn) in chunk.iter().enumerate() {
        if let Some(nat_j) = acc.get_mut(j) {
            *nat_j = (*nat_j).max(cn);
        }
    }
}

/// Natural width (chars) per column: max of header length and max cell length in visible window.
/// Column names (headers) are always included so they are never squeezed.
/// Uses parallel iteration when visible row count exceeds [`PARALLEL.contents_natural_widths`].
#[must_use]
pub fn contents_natural_widths(
    section: &ContentsSection,
    start: usize,
    end: usize,
    max_array_inline: usize,
) -> Vec<usize> {
    let keys = &section.column_keys;
    let cols = &section.columns;
    if keys.is_empty() {
        return vec![];
    }
    let header_natural: Vec<usize> = cols.iter().map(|s| s.chars().count()).collect();
    let entries_window = end.saturating_sub(start);
    if entries_window < PARALLEL.contents_natural_widths {
        let mut natural = header_natural;
        accumulate_natural_widths_from_entries(
            &mut natural,
            section.entries.iter().skip(start).take(entries_window),
            keys,
            max_array_inline,
        );
        natural
    } else {
        let slice = &section.entries[start..end];
        let chunk_size = (entries_window / 4).max(1);
        let chunk_naturals: Vec<Vec<usize>> = slice
            .par_chunks(chunk_size)
            .map(|chunk| {
                let mut nat = header_natural.clone();
                accumulate_natural_widths_from_entries(
                    &mut nat,
                    chunk.iter(),
                    keys,
                    max_array_inline,
                );
                nat
            })
            .collect();
        let mut natural = header_natural;
        for chunk_nat in chunk_naturals {
            merge_max_natural_widths(&mut natural, &chunk_nat);
        }
        natural
    }
}

/// Minimum width per column (header length) so column names are never truncated.
fn contents_header_widths(section: &ContentsSection) -> Vec<u16> {
    section
        .columns
        .iter()
        .map(|s| s.chars().count().min(u16::MAX as usize) as u16)
        .collect()
}

/// Build multi-column table for a Contents section, only for entry indices [start, end) (for virtualization).
/// Column widths are derived from content (header + visible rows), balanced against `table_width`.
#[must_use]
pub fn contents_to_table_window(
    section: &ContentsSection,
    window: TableWindow,
    table_width: u16,
    max_array_inline: usize,
    find: TableFindRenderCtx<'_>,
) -> Table<'static> {
    let natural = contents_natural_widths(section, window.start, window.end, max_array_inline);
    let header_widths = contents_header_widths(section);
    let ncols = section.column_keys.len();
    let use_size_optimization = ncols > SIZE_OPTIMIZATION_COLUMN_THRESHOLD;

    let mut column_widths = if natural.is_empty() {
        let available =
            (table_width as usize).saturating_sub((ncols.saturating_sub(1)) * COLUMN_SPACING);
        let w = (available / ncols.max(1)).min(u16::MAX as usize) as u16;
        (0..ncols).map(|_| w.max(1)).collect::<Vec<u16>>()
    } else if use_size_optimization {
        balanced_column_widths(&natural, table_width as usize, COLUMN_SPACING)
    } else {
        let gaps = (ncols.saturating_sub(1)) * COLUMN_SPACING;
        let natural_with_header: Vec<usize> = natural
            .iter()
            .zip(header_widths.iter())
            .map(|(n, &hw)| (*n).max(hw as usize))
            .collect();
        let total_compact = natural_with_header.iter().sum::<usize>() + gaps;
        if total_compact <= table_width as usize {
            natural_with_header
                .into_iter()
                .map(|w| w.min(u16::MAX as usize) as u16)
                .collect()
        } else {
            balanced_column_widths(&natural_with_header, table_width as usize, COLUMN_SPACING)
        }
    };
    for (j, &min_w) in header_widths.iter().enumerate() {
        if let Some(w) = column_widths.get_mut(j) {
            *w = (*w).max(min_w);
        }
    }
    let constraints: Vec<Constraint> = column_widths
        .iter()
        .map(|&w| Constraint::Length(w))
        .collect();

    let header = Row::new(
        section
            .columns
            .iter()
            .map(|s| cell_for_str(s.as_str(), find.needle, false, false))
            .collect::<Vec<_>>(),
    )
    .style(style::table_header_style())
    .bottom_margin(0);
    let data_rows: Vec<Row> = section
        .entries
        .iter()
        .enumerate()
        .skip(window.start)
        .take(window.end.saturating_sub(window.start))
        .filter_map(|(_i, v)| v.as_object())
        .enumerate()
        .map(|(idx, obj)| {
            let global_row_idx = window.start + idx;
            let row_is_current = find
                .current_line_idx
                .is_some_and(|li| li == find.first_data_line_idx.saturating_add(global_row_idx));
            let row_strs =
                contents_row(obj, &section.column_keys, &column_widths, max_array_inline);
            Row::new(
                row_strs
                    .into_iter()
                    .map(|c| cell_for_str(&c, find.needle, row_is_current, find.metadata_mode))
                    .collect::<Vec<_>>(),
            )
            .style(style::table_row_style(
                window.row_offset + window.start + idx,
            ))
        })
        .collect();
    table_with_chrome(Table::new(data_rows, constraints).header(header))
}

/// Build a single-column table with no header (e.g. `common_pivots` list). Only rows [start, end) are included.
#[must_use]
pub fn single_column_list_to_table(
    section: &SingleColumnListSection,
    window: TableWindow,
    find: TableFindRenderCtx<'_>,
) -> Table<'static> {
    let data_rows: Vec<Row> = section
        .values
        .iter()
        .skip(window.start)
        .take(window.end.saturating_sub(window.start))
        .enumerate()
        .map(|(idx, s)| {
            let global_row_idx = window.start + idx;
            let row_is_current = find
                .current_line_idx
                .is_some_and(|li| li == find.first_data_line_idx.saturating_add(global_row_idx));
            Row::new(vec![cell_for_str(
                s.as_str(),
                find.needle,
                row_is_current,
                find.metadata_mode,
            )])
            .style(style::table_row_style(
                window.row_offset + window.start + idx,
            ))
        })
        .collect();
    table_with_chrome(Table::new(data_rows, [Constraint::Min(0)]))
}