Skip to main content

kitchen_ui/
table.rs

1//! The table every app shows data in: plain columns in (numbers or text, no data-frame library),
2//! a header, a column summary that folds down between the header and the rows, and the rows as
3//! a virtual list (only those on screen are made).
4//!
5//! - **Header**: per column a type mark (`#` numbers, `Aa` text), its name, its unit, the sort
6//!   mark and, when the app gives roles, a role tag. A click on the name sorts (ascending,
7//!   descending, off); a click on the tag is the app's ([`TableEvent::RoleClicked`]). Drag a
8//!   header's right edge to resize, double-click it to fit again.
9//! - **Summary** (folds down, giving its height back to the rows): missing and unique; numbers
10//!   draw a histogram with their minimum and maximum, text its most common values with their
11//!   share (or one count when there are many). A click selects the column
12//!   ([`TableEvent::Selected`]).
13//! - **Rows**: one line each, values in mono, numbers to the right; the header and the summary
14//!   follow the rows sideways.
15//! - **Columns fill the pane**: each starts at [`TableSpec::min_column_width`] and the spare width
16//!   is shared out among those not resized by hand.
17//! - **Text never overflows**: every cell, name and value is one line ending in "…"; a header's
18//!   full name, unit and type are in its tooltip.
19//!
20//! Summaries and sorting are computed off the UI thread ([`summarize`], [`sort_order`]: plain
21//! functions, for tests and for apps that compute them elsewhere). [`TableSpec`] is the widget's
22//! settings as JSON (the same keys as the design prototype).
23
24use std::cell::Cell;
25use std::collections::{HashMap, HashSet};
26use std::rc::Rc;
27use std::sync::Arc;
28
29use gpui_kit::assets::IconName;
30use gpui_kit::component::tooltip::Tooltip;
31use gpui_kit::component::{Icon, Sizable as _, h_flex, v_flex};
32use gpui_kit::prelude::FluentBuilder as _;
33use gpui_kit::{
34    AnyElement, App, Context, EventEmitter, FontWeight, Hsla, InteractiveElement as _, IntoElement,
35    ListHorizontalSizingBehavior, MouseButton, MouseDownEvent, MouseMoveEvent, MouseUpEvent, ParentElement as _,
36    Render, SharedString, StatefulInteractiveElement as _, Styled as _, Task, UniformListScrollHandle, Window, canvas,
37    div, px, relative, uniform_list,
38};
39use serde::{Deserialize, Serialize};
40
41use crate::theme::{self, color, fonts};
42
43/// One column's values, one per row (`None`: missing).
44#[derive(Debug, Clone, PartialEq)]
45pub enum Values {
46    /// Numbers.
47    Number(Vec<Option<f64>>),
48    /// Text.
49    Text(Vec<Option<SharedString>>),
50}
51
52impl Values {
53    /// Its rows.
54    pub fn len(&self) -> usize {
55        match self {
56            Values::Number(v) => v.len(),
57            Values::Text(v) => v.len(),
58        }
59    }
60
61    /// No rows.
62    pub fn is_empty(&self) -> bool {
63        self.len() == 0
64    }
65
66    /// Numbers, not text.
67    pub fn is_number(&self) -> bool {
68        matches!(self, Values::Number(_))
69    }
70}
71
72/// A column: its name, unit and values.
73#[derive(Debug, Clone, PartialEq)]
74pub struct Column {
75    /// Its name.
76    pub name: SharedString,
77    /// Its unit (`cm`, `µm²`), shown beside the name.
78    pub unit: Option<SharedString>,
79    /// Its values.
80    pub values: Values,
81}
82
83impl Column {
84    /// A number column.
85    pub fn numbers(name: impl Into<SharedString>, values: Vec<Option<f64>>) -> Self {
86        Self { name: name.into(), unit: None, values: Values::Number(values) }
87    }
88
89    /// A text column.
90    pub fn text(name: impl Into<SharedString>, values: Vec<Option<SharedString>>) -> Self {
91        Self { name: name.into(), unit: None, values: Values::Text(values) }
92    }
93
94    /// With its unit.
95    pub fn unit(mut self, unit: impl Into<SharedString>) -> Self {
96        self.unit = Some(unit.into());
97        self
98    }
99}
100
101/// A table: its name (shown by the app, not the widget) and its columns, all as long.
102#[derive(Debug, Clone, PartialEq, Default)]
103pub struct TableData {
104    /// Its name.
105    pub name: SharedString,
106    /// Its columns.
107    pub columns: Vec<Column>,
108}
109
110impl TableData {
111    /// A table of `columns`.
112    pub fn new(name: impl Into<SharedString>, columns: Vec<Column>) -> Self {
113        Self { name: name.into(), columns }
114    }
115
116    /// Its rows (the longest column's length).
117    pub fn rows(&self) -> usize {
118        self.columns.iter().map(|c| c.values.len()).max().unwrap_or(0)
119    }
120}
121
122/// The widget's settings; JSON with these keys (each optional: the defaults below).
123#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
124#[serde(default)]
125pub struct TableSpec {
126    /// The summary segment unfolded.
127    pub summary: bool,
128    /// Row numbers on the left (the row's place in the table, not in the sort).
129    pub row_numbers: bool,
130    /// The role tags in the header (when the app gives roles).
131    pub role_tags: bool,
132    /// Bars in a number column's histogram.
133    pub bins: usize,
134    /// A row's height (px).
135    pub row_height: f32,
136    /// The narrowest a column starts (px); spare width is shared out.
137    pub min_column_width: f32,
138    /// The row numbers' column (px).
139    pub index_width: f32,
140    /// The summary segment's height (px).
141    pub summary_height: f32,
142    /// Most common text values listed (the rest: Other).
143    pub top_values: usize,
144    /// A text column with more distinct values shows only their count.
145    pub many_unique: usize,
146    /// Decimals of numbers.
147    pub decimals: usize,
148    /// Trailing zeros dropped (`1.500` → `1.5`).
149    pub trim_zeros: bool,
150    /// What a missing value shows.
151    pub missing_text: String,
152}
153
154impl Default for TableSpec {
155    fn default() -> Self {
156        Self {
157            summary: true,
158            row_numbers: true,
159            role_tags: true,
160            bins: 24,
161            row_height: 24.,
162            min_column_width: 140.,
163            index_width: 52.,
164            summary_height: 128.,
165            top_values: 3,
166            many_unique: 30,
167            decimals: 3,
168            trim_zeros: true,
169            missing_text: "—".into(),
170        }
171    }
172}
173
174impl TableSpec {
175    /// `x` as the table shows it.
176    pub fn format(&self, x: Option<f64>) -> String {
177        match x {
178            None => self.missing_text.clone(),
179            Some(v) if !v.is_finite() => v.to_string(),
180            Some(v) => {
181                let s = format!("{v:.*}", self.decimals);
182                if self.trim_zeros && s.contains('.') {
183                    s.trim_end_matches('0').trim_end_matches('.').to_string()
184                } else {
185                    s
186                }
187            }
188        }
189    }
190}
191
192/// What a column's summary draws.
193#[derive(Debug, Clone, PartialEq)]
194pub enum Shape {
195    /// Numbers: counts in equal bins from `min` to `max` (empty: no values).
196    #[allow(missing_docs)]
197    Histogram { min: f64, max: f64, counts: Vec<usize> },
198    /// Text with few values: the most common with their counts; `other` rows hold `others` more.
199    #[allow(missing_docs)]
200    Top { values: Vec<(SharedString, usize)>, other: usize, others: usize },
201    /// Text with many values: only their count is shown (the summary's `unique`).
202    Distinct,
203}
204
205/// A column's summary.
206#[derive(Debug, Clone, PartialEq)]
207pub struct ColumnSummary {
208    /// Rows in the column.
209    pub rows: usize,
210    /// Missing values (and non-finite numbers).
211    pub missing: usize,
212    /// Distinct values.
213    pub unique: usize,
214    /// What it draws.
215    pub shape: Shape,
216}
217
218/// Where a table's summaries are computed: on the CPU here by default ([`CpuSummarizer`]), or
219/// by a backend the app plugs in ([`TableView::with_summarizer`]): a GPU histogram through
220/// kitchen-compute, a data-frame library, a server that already holds the table. A backend may
221/// replace only [`Summarizer::histogram`] (the costly part for numbers) or the whole
222/// [`Summarizer::summarize`]. Called off the UI thread.
223pub trait Summarizer: Send + Sync {
224    /// The minimum, the maximum and the counts in `bins` equal bins of a number column's finite
225    /// values (`None` when it has none).
226    fn histogram(&self, values: &[Option<f64>], bins: usize) -> Option<(f64, f64, Vec<usize>)> {
227        cpu_histogram(values, bins)
228    }
229
230    /// Every column's summary.
231    fn summarize(&self, data: &TableData, spec: &TableSpec) -> Vec<ColumnSummary> {
232        data.columns.iter().map(|c| summarize_column(self, &c.values, spec)).collect()
233    }
234}
235
236/// Summaries on the CPU, in this thread.
237#[derive(Debug, Clone, Copy, Default)]
238pub struct CpuSummarizer;
239
240impl Summarizer for CpuSummarizer {}
241
242/// Every column's summary on the CPU (blocking: run it off the UI thread for a large table).
243pub fn summarize(data: &TableData, spec: &TableSpec) -> Vec<ColumnSummary> {
244    CpuSummarizer.summarize(data, spec)
245}
246
247/// The CPU histogram [`Summarizer::histogram`] defaults to.
248pub fn cpu_histogram(values: &[Option<f64>], bins: usize) -> Option<(f64, f64, Vec<usize>)> {
249    let (mut min, mut max, mut any) = (f64::INFINITY, f64::NEG_INFINITY, false);
250    for &x in values.iter().flatten().filter(|x| x.is_finite()) {
251        min = min.min(x);
252        max = max.max(x);
253        any = true;
254    }
255    if !any {
256        return None;
257    }
258    let bins = bins.max(1);
259    let mut counts = vec![0; bins];
260    let span = if max > min { max - min } else { 1. };
261    for &x in values.iter().flatten().filter(|x| x.is_finite()) {
262        counts[((((x - min) / span) * bins as f64) as usize).min(bins - 1)] += 1;
263    }
264    Some((min, max, counts))
265}
266
267/// A column's summary, its histogram from `by`.
268pub fn summarize_column<S: Summarizer + ?Sized>(by: &S, values: &Values, spec: &TableSpec) -> ColumnSummary {
269    let rows = values.len();
270    match values {
271        Values::Number(v) => {
272            let present = v.iter().flatten().filter(|x| x.is_finite()).count();
273            let unique =
274                v.iter().flatten().filter(|x| x.is_finite()).map(|x| x.to_bits()).collect::<HashSet<_>>().len();
275            let (min, max, counts) = by.histogram(v, spec.bins).unwrap_or((0., 0., Vec::new()));
276            ColumnSummary { rows, missing: rows - present, unique, shape: Shape::Histogram { min, max, counts } }
277        }
278        Values::Text(v) => {
279            let mut counts: HashMap<&str, usize> = HashMap::new();
280            let mut missing = 0;
281            for x in v {
282                match x {
283                    Some(s) => *counts.entry(s.as_ref()).or_default() += 1,
284                    None => missing += 1,
285                }
286            }
287            let unique = counts.len();
288            let shape = if unique > spec.many_unique {
289                Shape::Distinct
290            } else {
291                let mut all: Vec<(&str, usize)> = counts.into_iter().collect();
292                all.sort_by(|a, b| b.1.cmp(&a.1).then(a.0.cmp(b.0)));
293                let k = spec.top_values.min(all.len());
294                let other = all[k..].iter().map(|x| x.1).sum();
295                let others = all.len() - k;
296                Shape::Top {
297                    values: all[..k].iter().map(|(s, n)| (SharedString::from(s.to_string()), *n)).collect(),
298                    other,
299                    others,
300                }
301            };
302            ColumnSummary { rows, missing, unique, shape }
303        }
304    }
305}
306
307/// The rows in order of column `col` (missing values last, ties in table order).
308pub fn sort_order(data: &TableData, col: usize, ascending: bool) -> Vec<usize> {
309    let n = data.rows();
310    let mut order: Vec<usize> = (0..n).collect();
311    let Some(c) = data.columns.get(col) else { return order };
312    let flip = |o: std::cmp::Ordering| if ascending { o } else { o.reverse() };
313    match &c.values {
314        Values::Number(v) => order.sort_by(|&a, &b| match (v.get(a).copied().flatten(), v.get(b).copied().flatten()) {
315            (Some(x), Some(y)) => flip(x.total_cmp(&y)),
316            (Some(_), None) => std::cmp::Ordering::Less,
317            (None, Some(_)) => std::cmp::Ordering::Greater,
318            (None, None) => std::cmp::Ordering::Equal,
319        }),
320        Values::Text(v) => order.sort_by(|&a, &b| match (v.get(a).cloned().flatten(), v.get(b).cloned().flatten()) {
321            (Some(x), Some(y)) => flip(x.cmp(&y)),
322            (Some(_), None) => std::cmp::Ordering::Less,
323            (None, Some(_)) => std::cmp::Ordering::Greater,
324            (None, None) => std::cmp::Ordering::Equal,
325        }),
326    }
327    order
328}
329
330/// Share of `n` in `of`, as the summary writes it.
331fn share(n: usize, of: usize) -> String {
332    if of == 0 {
333        return "0%".into();
334    }
335    let p = n as f64 / of as f64 * 100.;
336    if n > 0 && p < 1. { "<1%".into() } else { format!("{p:.0}%") }
337}
338
339/// What the table tells the app.
340#[derive(Debug, Clone, PartialEq)]
341pub enum TableEvent {
342    /// A column was selected (its summary clicked), or the selection cleared.
343    Selected(Option<usize>),
344    /// A column's role tag was clicked: the app changes the role ([`TableView::set_roles`]).
345    RoleClicked(usize),
346}
347
348/// The table view.
349pub struct TableView {
350    id: SharedString,
351    data: Arc<TableData>,
352    spec: TableSpec,
353    roles: Vec<Option<SharedString>>,
354    summaries: Option<Arc<Vec<ColumnSummary>>>,
355    order: Option<Arc<Vec<usize>>>,
356    sort: Option<(usize, bool)>,
357    selected: Option<usize>,
358    manual: HashMap<usize, f32>,
359    scroll: UniformListScrollHandle,
360    width: Rc<Cell<f32>>,
361    drag: Option<(usize, f32, f32)>,
362    summary_task: Option<Task<()>>,
363    sort_task: Option<Task<()>>,
364    summarizer: Arc<dyn Summarizer>,
365}
366
367impl EventEmitter<TableEvent> for TableView {}
368
369impl TableView {
370    /// An empty table; `id` keeps its elements apart from another table's in the same window.
371    pub fn new(id: impl Into<SharedString>) -> Self {
372        Self {
373            id: id.into(),
374            data: Arc::new(TableData::default()),
375            spec: TableSpec::default(),
376            roles: Vec::new(),
377            summaries: None,
378            order: None,
379            sort: None,
380            selected: None,
381            manual: HashMap::new(),
382            scroll: UniformListScrollHandle::new(),
383            width: Rc::new(Cell::new(0.)),
384            drag: None,
385            summary_task: None,
386            sort_task: None,
387            summarizer: Arc::new(CpuSummarizer),
388        }
389    }
390
391    /// Computes the summaries with `by` (a backend) instead of the CPU.
392    pub fn with_summarizer(mut self, by: Arc<dyn Summarizer>) -> Self {
393        self.summarizer = by;
394        self
395    }
396
397    /// Summaries computed elsewhere (a server's answer, a cache), in column order: shown as they
398    /// are, nothing computed here until the data or the bins change.
399    pub fn set_summaries(&mut self, summaries: Arc<Vec<ColumnSummary>>, cx: &mut Context<Self>) {
400        self.summary_task = None;
401        self.summaries = Some(summaries);
402        cx.notify();
403    }
404
405    /// Shows `data` (its summaries computed off the UI thread); sort, selection and widths reset.
406    pub fn set_data(&mut self, data: Arc<TableData>, cx: &mut Context<Self>) {
407        if !Arc::ptr_eq(&self.data, &data) {
408            self.data = data;
409            self.sort = None;
410            self.order = None;
411            self.selected = None;
412            self.manual.clear();
413            self.roles.clear();
414            self.resummarize(cx);
415        }
416        cx.notify();
417    }
418
419    /// The table shown.
420    pub fn data(&self) -> &Arc<TableData> {
421        &self.data
422    }
423
424    /// The settings (a change of bins or of the text limits computes the summaries again).
425    pub fn set_spec(&mut self, spec: TableSpec, cx: &mut Context<Self>) {
426        let again = spec.bins != self.spec.bins
427            || spec.top_values != self.spec.top_values
428            || spec.many_unique != self.spec.many_unique;
429        self.spec = spec;
430        if again {
431            self.resummarize(cx);
432        }
433        cx.notify();
434    }
435
436    /// The settings.
437    pub fn spec(&self) -> &TableSpec {
438        &self.spec
439    }
440
441    /// Each column's role tag, in column order (`None`: no tag).
442    pub fn set_roles(&mut self, roles: Vec<Option<SharedString>>, cx: &mut Context<Self>) {
443        self.roles = roles;
444        cx.notify();
445    }
446
447    /// Folds or unfolds the summary.
448    pub fn toggle_summary(&mut self, cx: &mut Context<Self>) {
449        self.spec.summary = !self.spec.summary;
450        cx.notify();
451    }
452
453    /// The selected column.
454    pub fn selected(&self) -> Option<usize> {
455        self.selected
456    }
457
458    /// Selects column `col` (or none), as a click on its summary does.
459    pub fn select(&mut self, col: Option<usize>, cx: &mut Context<Self>) {
460        self.selected = col;
461        cx.emit(TableEvent::Selected(col));
462        cx.notify();
463    }
464
465    /// The summaries, once computed.
466    pub fn summaries(&self) -> Option<&Arc<Vec<ColumnSummary>>> {
467        self.summaries.as_ref()
468    }
469
470    fn resummarize(&mut self, cx: &mut Context<Self>) {
471        self.summaries = None;
472        let (data, spec, by) = (self.data.clone(), self.spec.clone(), self.summarizer.clone());
473        let work = cx.background_executor().spawn(async move { by.summarize(&data, &spec) });
474        self.summary_task = Some(cx.spawn(async move |this, cx| {
475            let done = work.await;
476            let _ = this.update(cx, |t, cx| {
477                t.summaries = Some(Arc::new(done));
478                cx.notify();
479            });
480        }));
481    }
482
483    /// Sorts by `col` (ascending, then descending, then off), off the UI thread.
484    fn cycle_sort(&mut self, col: usize, cx: &mut Context<Self>) {
485        self.sort = match self.sort {
486            Some((c, true)) if c == col => Some((col, false)),
487            Some((c, false)) if c == col => None,
488            _ => Some((col, true)),
489        };
490        let Some((col, up)) = self.sort else {
491            self.order = None;
492            self.sort_task = None;
493            cx.notify();
494            return;
495        };
496        let data = self.data.clone();
497        let work = cx.background_executor().spawn(async move { sort_order(&data, col, up) });
498        self.sort_task = Some(cx.spawn(async move |this, cx| {
499            let order = work.await;
500            let _ = this.update(cx, |t, cx| {
501                if t.sort == Some((col, up)) {
502                    t.order = Some(Arc::new(order));
503                    cx.notify();
504                }
505            });
506        }));
507        cx.notify();
508    }
509
510    /// Column widths: the minimum (or the hand-set width), the spare width of the pane shared out.
511    fn widths(&self) -> Vec<f32> {
512        let n = self.data.columns.len();
513        let base: Vec<f32> =
514            (0..n).map(|j| self.manual.get(&j).copied().unwrap_or(self.spec.min_column_width)).collect();
515        let index = if self.spec.row_numbers { self.spec.index_width } else { 0. };
516        let free = self.width.get() - index - base.iter().sum::<f32>();
517        let auto = (0..n).filter(|j| !self.manual.contains_key(j)).count();
518        base.iter()
519            .enumerate()
520            .map(
521                |(j, &w)| {
522                    if free > 0. && auto > 0 && !self.manual.contains_key(&j) { w + free / auto as f32 } else { w }
523                },
524            )
525            .collect()
526    }
527
528    fn data_color() -> Hsla {
529        if theme::is_dark() { theme::data(4) } else { theme::data(0) }
530    }
531
532    fn header(&self, widths: &[f32], cx: &mut Context<Self>) -> impl IntoElement + use<> {
533        let index = self.spec.row_numbers.then(|| {
534            div()
535                .flex_none()
536                .w(px(self.spec.index_width))
537                .h(px(32.))
538                .px(px(theme::SM))
539                .flex()
540                .items_center()
541                .justify_end()
542                .text_xs()
543                .font_family(fonts::MONO)
544                .text_color(color::text_muted())
545                .border_r_1()
546                .border_color(color::border())
547                .child("#")
548        });
549        let cells = self.data.columns.iter().enumerate().map(|(j, c)| {
550            let mark = if c.values.is_number() { "#" } else { "Aa" };
551            let sort = match self.sort {
552                Some((s, true)) if s == j => Some(IconName::ChevronUp),
553                Some((s, false)) if s == j => Some(IconName::ChevronDown),
554                _ => None,
555            };
556            let role = if self.spec.role_tags { self.roles.get(j).cloned().flatten() } else { None };
557            let tip: SharedString = format!(
558                "{}{} · {}{}",
559                c.name,
560                c.unit.as_ref().map(|u| format!(" ({u})")).unwrap_or_default(),
561                if c.values.is_number() { "numbers" } else { "text" },
562                role.as_ref().map(|r| format!(" · {r}")).unwrap_or_default()
563            )
564            .into();
565            h_flex()
566                .id((SharedString::from(format!("{}-head", self.id)), j))
567                .relative()
568                .flex_none()
569                .w(px(widths[j]))
570                .h(px(32.))
571                .px(px(theme::SM))
572                .gap(px(theme::XS))
573                .items_center()
574                .border_r_1()
575                .border_color(color::border())
576                .cursor_pointer()
577                .hover(|d| d.bg(color::hover()))
578                .when(self.selected == Some(j), |d| {
579                    d.bg(color::selection()).border_t_2().border_color(color::selection_edge())
580                })
581                .tooltip(move |window, cx| Tooltip::new(tip.clone()).build(window, cx))
582                .on_click(cx.listener(move |this, _, _, cx| {
583                    if this.drag.is_none() {
584                        this.cycle_sort(j, cx)
585                    }
586                }))
587                .child(
588                    div()
589                        .flex_none()
590                        .w(px(16.))
591                        .text_xs()
592                        .font_family(fonts::MONO)
593                        .font_weight(FontWeight::SEMIBOLD)
594                        .text_color(color::text_muted())
595                        .child(mark),
596                )
597                .child(
598                    div()
599                        .flex_1()
600                        .min_w_0()
601                        .truncate()
602                        .text_sm()
603                        .font_weight(FontWeight::SEMIBOLD)
604                        .text_color(color::text())
605                        .child(c.name.clone()),
606                )
607                .children(c.unit.clone().map(|u| {
608                    div().min_w_0().max_w(relative(0.4)).truncate().text_xs().text_color(color::text_muted()).child(u)
609                }))
610                .children(sort.map(|i| Icon::new(i).xsmall().text_color(color::accent_mark())))
611                .children(role.map(|r| {
612                    let on = r.as_ref() != "Other";
613                    div()
614                        .id((SharedString::from(format!("{}-role", self.id)), j))
615                        .flex_none()
616                        .max_w(px(72.))
617                        .truncate()
618                        .px(px(theme::XS))
619                        .rounded(px(theme::RADIUS_SM))
620                        .border_1()
621                        .border_color(if on { color::accent_mark() } else { color::border() })
622                        .text_xs()
623                        .text_color(if on { color::accent_mark() } else { color::text_muted() })
624                        .child(r)
625                        .on_click(cx.listener(move |_, _, _, cx| {
626                            cx.stop_propagation();
627                            cx.emit(TableEvent::RoleClicked(j));
628                        }))
629                }))
630                .child(div().absolute().top_0().bottom_0().right(px(-3.)).w(px(6.)).cursor_col_resize().on_mouse_down(
631                    MouseButton::Left,
632                    cx.listener(move |this, e: &MouseDownEvent, _, cx| {
633                        cx.stop_propagation();
634                        if e.click_count >= 2 {
635                            this.manual.remove(&j);
636                            this.drag = None;
637                        } else {
638                            let w = this.widths()[j];
639                            this.drag = Some((j, e.position.x.as_f32(), w));
640                        }
641                        cx.notify();
642                    }),
643                ))
644        });
645        h_flex().flex_none().children(index).children(cells.collect::<Vec<_>>())
646    }
647
648    fn fold_bar(&self, cx: &mut Context<Self>) -> impl IntoElement + use<> {
649        let n = self.data.columns.len();
650        h_flex()
651            .id(SharedString::from(format!("{}-fold", self.id)))
652            .flex_none()
653            .w_full()
654            .h(px(24.))
655            .px(px(theme::SM))
656            .gap(px(theme::XS))
657            .items_center()
658            .bg(color::raised())
659            .border_t_1()
660            .border_color(color::border())
661            .cursor_pointer()
662            .text_xs()
663            .text_color(color::text_muted())
664            .hover(|d| d.text_color(color::text()))
665            .on_click(cx.listener(|this, _, _, cx| this.toggle_summary(cx)))
666            .child(Icon::new(if self.spec.summary { IconName::ChevronDown } else { IconName::ChevronRight }).xsmall())
667            .child(div().truncate().child(if self.spec.summary {
668                "SUMMARY".to_string()
669            } else if self.summaries.is_none() {
670                "SUMMARY · computing".to_string()
671            } else {
672                format!("SUMMARY · {n} columns")
673            }))
674    }
675
676    fn summary_row(&self, widths: &[f32], cx: &mut Context<Self>) -> impl IntoElement + use<> {
677        let h = self.spec.summary_height;
678        let index = self.spec.row_numbers.then(|| {
679            div()
680                .flex_none()
681                .w(px(self.spec.index_width))
682                .h(px(h))
683                .border_r_1()
684                .border_t_1()
685                .border_color(color::border())
686        });
687        let sums = self.summaries.clone();
688        let cells = self.data.columns.iter().enumerate().map(|(j, c)| {
689            let body: AnyElement = match sums.as_ref().and_then(|s| s.get(j)) {
690                None => div().text_color(color::text_muted()).child("Computing…").into_any_element(),
691                Some(s) => self.summary_body(c, s).into_any_element(),
692            };
693            v_flex()
694                .id((SharedString::from(format!("{}-sum", self.id)), j))
695                .flex_none()
696                .w(px(widths[j]))
697                .h(px(h))
698                .p(px(theme::SM))
699                .gap(px(theme::XS))
700                .overflow_hidden()
701                .text_xs()
702                .border_r_1()
703                .border_t_1()
704                .border_color(color::border())
705                .cursor_pointer()
706                .when(self.selected == Some(j), |d| d.bg(color::selection()))
707                .on_click(cx.listener(move |this, _, _, cx| {
708                    let next = if this.selected == Some(j) { None } else { Some(j) };
709                    this.select(next, cx);
710                }))
711                .child(body)
712        });
713        h_flex().flex_none().children(index).children(cells.collect::<Vec<_>>())
714    }
715
716    fn summary_body(&self, c: &Column, s: &ColumnSummary) -> impl IntoElement + use<> {
717        let kv = |label: &'static str, value: String, warn: bool| {
718            h_flex()
719                .w_full()
720                .gap(px(theme::SM))
721                .child(div().flex_none().max_w(relative(0.4)).truncate().text_color(color::text_muted()).child(label))
722                .child(
723                    div().flex_1().min_w_0().flex().justify_end().child(
724                        div()
725                            .min_w_0()
726                            .truncate()
727                            .font_family(fonts::MONO)
728                            .text_color(if warn { color::danger() } else { color::text() })
729                            .child(value),
730                    ),
731                )
732        };
733        let head = v_flex()
734            .flex_none()
735            .gap(px(2.))
736            .child(kv("Missing", format!("{} · {}", s.missing, share(s.missing, s.rows)), s.missing > 0))
737            .child(kv("Unique", format!("{} · {}", s.unique, share(s.unique, s.rows)), false));
738        let data = Self::data_color();
739        let shape: AnyElement = match &s.shape {
740            Shape::Histogram { min, max, counts } => {
741                let top = counts.iter().copied().max().unwrap_or(0).max(1) as f32;
742                let unit = c.unit.as_ref().map(|u| format!(" {u}")).unwrap_or_default();
743                v_flex()
744                    .flex_1()
745                    .min_h_0()
746                    .gap(px(2.))
747                    .child(
748                        h_flex()
749                            .flex_1()
750                            .min_h(px(16.))
751                            .items_end()
752                            .gap(px(1.))
753                            .border_b_1()
754                            .border_color(color::border())
755                            .children(
756                                counts.iter().map(|&n| {
757                                    div().flex_1().min_w_0().h(relative(n as f32 / top)).min_h(px(1.)).bg(data)
758                                }),
759                            ),
760                    )
761                    .child(
762                        h_flex()
763                            .flex_none()
764                            .justify_between()
765                            .gap(px(theme::SM))
766                            .font_family(fonts::MONO)
767                            .text_color(color::text_muted())
768                            .child(div().min_w_0().truncate().child(format!("{}{unit}", self.spec.format(Some(*min)))))
769                            .child(div().min_w_0().truncate().child(format!("{}{unit}", self.spec.format(Some(*max))))),
770                    )
771                    .into_any_element()
772            }
773            Shape::Distinct => h_flex()
774                .flex_1()
775                .justify_center()
776                .items_center()
777                .gap(px(theme::XS))
778                .child(
779                    div()
780                        .font_family(fonts::MONO)
781                        .text_base()
782                        .font_weight(FontWeight::SEMIBOLD)
783                        .text_color(data)
784                        .child(s.unique.to_string()),
785                )
786                .child(div().text_color(color::text_muted()).child("distinct"))
787                .into_any_element(),
788            Shape::Top { values, other, others } => {
789                let most = values.first().map(|v| v.1).unwrap_or(1).max(1) as f32;
790                let line = |label: SharedString, n: usize, frac: f32| {
791                    div()
792                        .relative()
793                        .w_full()
794                        .h(px(16.))
795                        .rounded(px(theme::RADIUS_SM))
796                        .overflow_hidden()
797                        .child(
798                            div()
799                                .absolute()
800                                .top_0()
801                                .bottom_0()
802                                .left_0()
803                                .w(relative(frac.clamp(0., 1.)))
804                                .bg(data.opacity(0.22)),
805                        )
806                        .child(
807                            h_flex()
808                                .relative()
809                                .px(px(theme::XS))
810                                .gap(px(theme::SM))
811                                .child(div().flex_1().min_w_0().truncate().text_color(color::text()).child(label))
812                                .child(
813                                    div()
814                                        .flex_none()
815                                        .font_family(fonts::MONO)
816                                        .text_color(color::text_muted())
817                                        .child(share(n, s.rows)),
818                                ),
819                        )
820                };
821                v_flex()
822                    .flex_1()
823                    .min_h_0()
824                    .gap(px(2.))
825                    .children(values.iter().map(|(v, n)| line(v.clone(), *n, *n as f32 / most)))
826                    .when(*other > 0, |d| {
827                        d.child(line(format!("Other ({others})").into(), *other, *other as f32 / s.rows.max(1) as f32))
828                    })
829                    .into_any_element()
830            }
831        };
832        v_flex().size_full().gap(px(theme::XS)).child(head).child(shape)
833    }
834
835    fn rows(&mut self, range: std::ops::Range<usize>, _: &mut Window, _: &mut Context<Self>) -> Vec<AnyElement> {
836        let widths = self.widths();
837        let rh = self.spec.row_height;
838        let index_w = self.spec.row_numbers.then_some(self.spec.index_width);
839        let row_w = widths.iter().sum::<f32>() + index_w.unwrap_or(0.);
840        let data = self.data.clone();
841        let order = self.order.clone();
842        range
843            .map(|i| {
844                let r = order.as_ref().and_then(|o| o.get(i).copied()).unwrap_or(i);
845                let cells = data.columns.iter().enumerate().map(|(j, c)| {
846                    let (text, missing) = match &c.values {
847                        Values::Number(v) => {
848                            let x = v.get(r).copied().flatten();
849                            (self.spec.format(x), x.is_none())
850                        }
851                        Values::Text(v) => match v.get(r).cloned().flatten() {
852                            Some(s) => (s.to_string(), false),
853                            None => (self.spec.missing_text.clone(), true),
854                        },
855                    };
856                    div()
857                        .flex_none()
858                        .w(px(widths[j]))
859                        .h_full()
860                        .px(px(theme::SM))
861                        .flex()
862                        .items_center()
863                        .when(c.values.is_number(), |d| d.justify_end())
864                        .when(self.selected == Some(j), |d| d.bg(color::selection()))
865                        .child(
866                            div()
867                                .min_w_0()
868                                .truncate()
869                                .text_color(if missing { color::text_muted() } else { color::text() })
870                                .child(text),
871                        )
872                });
873                h_flex()
874                    .id(("kitchen-table-row", i))
875                    .w(px(row_w))
876                    .flex_none()
877                    .h(px(rh))
878                    .font_family(fonts::MONO)
879                    .text_sm()
880                    .when(i % 2 == 1, |d| d.bg(color::raised().opacity(0.55)))
881                    .hover(|d| d.bg(color::hover()))
882                    .children(index_w.map(|w| {
883                        div()
884                            .flex_none()
885                            .w(px(w))
886                            .h_full()
887                            .px(px(theme::SM))
888                            .flex()
889                            .items_center()
890                            .justify_end()
891                            .text_color(color::text_muted())
892                            .child(div().truncate().child((r + 1).to_string()))
893                    }))
894                    .children(cells.collect::<Vec<_>>())
895                    .into_any_element()
896            })
897            .collect()
898    }
899}
900
901impl Render for TableView {
902    fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
903        let widths = self.widths();
904        let total = widths.iter().sum::<f32>() + if self.spec.row_numbers { self.spec.index_width } else { 0. };
905        // The header follows the rows sideways, only as far as the rows themselves can go
906        let spare = (total - self.width.get()).max(0.);
907        let dx = self.scroll.0.borrow().base_handle.offset().x.as_f32().clamp(-spare, 0.);
908        let rows = self.order.as_ref().map(|o| o.len()).unwrap_or_else(|| self.data.rows());
909        let header = self.header(&widths, cx);
910        let summary = self.spec.summary.then(|| self.summary_row(&widths, cx));
911        let fold = self.fold_bar(cx);
912        let list = uniform_list(SharedString::from(format!("{}-rows", self.id)), rows, cx.processor(Self::rows))
913            .with_horizontal_sizing_behavior(ListHorizontalSizingBehavior::Unconstrained)
914            .track_scroll(&self.scroll)
915            .flex_1()
916            .min_h_0()
917            .w_full();
918        // The pane's width, measured as it is laid out: columns fill it
919        let seen = self.width.clone();
920        let entity = cx.entity().downgrade();
921        let measure = canvas(
922            move |bounds, _, cx| {
923                let w = bounds.size.width.as_f32();
924                if (seen.get() - w).abs() > 0.5 {
925                    seen.set(w);
926                    let _ = entity.update(cx, |_, cx| cx.notify());
927                }
928            },
929            |_, _, _, _| {},
930        )
931        .absolute()
932        .top_0()
933        .left_0()
934        .size_full();
935        v_flex()
936            .id(SharedString::from(format!("{}-table", self.id)))
937            .relative()
938            .size_full()
939            .min_h_0()
940            .overflow_hidden()
941            .bg(color::canvas())
942            .border_1()
943            .border_color(color::border())
944            .rounded(px(theme::RADIUS_LG))
945            .on_mouse_move(cx.listener(|this, e: &MouseMoveEvent, _, cx| {
946                if let Some((j, x0, w0)) = this.drag {
947                    this.manual.insert(j, (w0 + e.position.x.as_f32() - x0).max(64.));
948                    cx.notify();
949                }
950            }))
951            .on_mouse_up(
952                MouseButton::Left,
953                cx.listener(|this, _: &MouseUpEvent, _, cx| {
954                    if this.drag.take().is_some() {
955                        cx.notify();
956                    }
957                }),
958            )
959            .child(measure)
960            .child(
961                div()
962                    .flex_none()
963                    .w_full()
964                    .overflow_hidden()
965                    .bg(color::raised())
966                    .border_b_1()
967                    .border_color(color::border())
968                    .child(
969                        v_flex()
970                            .w(px(total.max(self.width.get())))
971                            .ml(px(dx))
972                            .child(header)
973                            .child(fold)
974                            .children(summary),
975                    ),
976            )
977            .child(list)
978    }
979}
980
981/// The view's own entity, made for `data` (convenience for apps).
982pub fn table(id: impl Into<SharedString>, data: Arc<TableData>, cx: &mut App) -> gpui_kit::Entity<TableView> {
983    use gpui_kit::AppContext as _;
984    cx.new(|cx| {
985        let mut t = TableView::new(id);
986        t.set_data(data, cx);
987        t
988    })
989}
990
991#[cfg(test)]
992mod tests {
993    use super::*;
994
995    fn iris_like() -> TableData {
996        TableData::new(
997            "t",
998            vec![
999                Column::numbers("x", vec![Some(1.), Some(2.), None, Some(4.), Some(4.)]).unit("cm"),
1000                Column::text("g", ["a", "b", "a", "c", "a"].iter().map(|s| Some(SharedString::from(*s))).collect()),
1001            ],
1002        )
1003    }
1004
1005    #[test]
1006    fn summaries_count_missing_unique_bins_and_top_values() {
1007        let spec = TableSpec { bins: 3, top_values: 2, ..TableSpec::default() };
1008        let s = summarize(&iris_like(), &spec);
1009        assert_eq!((s[0].rows, s[0].missing, s[0].unique), (5, 1, 3));
1010        assert_eq!(s[0].shape, Shape::Histogram { min: 1., max: 4., counts: vec![1, 1, 2] });
1011        assert_eq!((s[1].missing, s[1].unique), (0, 3));
1012        match &s[1].shape {
1013            Shape::Top { values, other, others } => {
1014                assert_eq!(values[0], ("a".into(), 3));
1015                assert_eq!((values.len(), *other, *others), (2, 1, 1));
1016            }
1017            other => panic!("{other:?}"),
1018        }
1019        // A backend that replaces only the histogram
1020        struct Fixed;
1021        impl Summarizer for Fixed {
1022            fn histogram(&self, _: &[Option<f64>], _: usize) -> Option<(f64, f64, Vec<usize>)> {
1023                Some((0., 9., vec![7]))
1024            }
1025        }
1026        assert_eq!(
1027            Fixed.summarize(&iris_like(), &spec)[0].shape,
1028            Shape::Histogram { min: 0., max: 9., counts: vec![7] }
1029        );
1030        assert_eq!(Fixed.summarize(&iris_like(), &spec)[0].missing, 1);
1031        let many = TableSpec { many_unique: 2, ..spec };
1032        assert_eq!(summarize(&iris_like(), &many)[1].shape, Shape::Distinct);
1033    }
1034
1035    #[test]
1036    fn sorting_puts_missing_last_both_ways() {
1037        let t = iris_like();
1038        assert_eq!(sort_order(&t, 0, true), vec![0, 1, 3, 4, 2]);
1039        assert_eq!(sort_order(&t, 0, false), vec![3, 4, 1, 0, 2]);
1040        assert_eq!(sort_order(&t, 1, true), vec![0, 2, 4, 1, 3]);
1041    }
1042
1043    #[test]
1044    fn numbers_format_with_trimmed_zeros_and_the_spec_round_trips() {
1045        let s = TableSpec::default();
1046        assert_eq!(s.format(Some(1.5)), "1.5");
1047        assert_eq!(s.format(Some(2.0)), "2");
1048        assert_eq!(s.format(None), "—");
1049        assert_eq!(share(1, 1000), "<1%");
1050        let json = serde_json::to_string(&s).unwrap();
1051        assert_eq!(serde_json::from_str::<TableSpec>(&json).unwrap(), s);
1052        let partial: TableSpec = serde_json::from_str(r#"{"bins": 10}"#).unwrap();
1053        assert_eq!(partial.bins, 10);
1054        assert!(partial.summary);
1055    }
1056}