1use std::cell::Cell;
45use std::collections::{BTreeSet, HashMap, HashSet};
46use std::rc::Rc;
47use std::sync::Arc;
48
49use gpui_kit::assets::IconName;
50use gpui_kit::component::tooltip::Tooltip;
51use gpui_kit::component::{Icon, Sizable as _, h_flex, v_flex};
52use gpui_kit::prelude::FluentBuilder as _;
53use gpui_kit::{
54 AnyElement, App, ClickEvent, Context, EventEmitter, FontWeight, Hsla, InteractiveElement as _, IntoElement,
55 ListHorizontalSizingBehavior, MouseButton, MouseDownEvent, MouseMoveEvent, MouseUpEvent, ParentElement as _,
56 Render, SharedString, StatefulInteractiveElement as _, Styled as _, Task, TestSupportExt as _,
57 UniformListScrollHandle, Window, canvas, div, px, relative, uniform_list,
58};
59use serde::{Deserialize, Serialize};
60
61use crate::theme::{self, color, fonts};
62use crate::widgets::MenuSelect;
63
64const MARK_W: f32 = 18.;
66const TOOLBAR_H: f32 = 34.;
68
69#[derive(Debug, Clone, PartialEq)]
71pub enum Values {
72 Number(Vec<Option<f64>>),
74 Text(Vec<Option<SharedString>>),
76}
77
78impl Values {
79 pub fn len(&self) -> usize {
81 match self {
82 Values::Number(v) => v.len(),
83 Values::Text(v) => v.len(),
84 }
85 }
86
87 pub fn is_empty(&self) -> bool {
89 self.len() == 0
90 }
91
92 pub fn is_number(&self) -> bool {
94 matches!(self, Values::Number(_))
95 }
96}
97
98#[derive(Debug, Clone, Copy, PartialEq)]
100pub enum BarRange {
101 Auto,
103 Fixed(f64, f64),
105}
106
107#[derive(Debug, Clone, PartialEq)]
109pub struct Column {
110 pub name: SharedString,
112 pub unit: Option<SharedString>,
114 pub values: Values,
116 pub bar: Option<BarRange>,
118}
119
120impl Column {
121 pub fn numbers(name: impl Into<SharedString>, values: Vec<Option<f64>>) -> Self {
123 Self { name: name.into(), unit: None, values: Values::Number(values), bar: None }
124 }
125
126 pub fn text(name: impl Into<SharedString>, values: Vec<Option<SharedString>>) -> Self {
128 Self { name: name.into(), unit: None, values: Values::Text(values), bar: None }
129 }
130
131 pub fn unit(mut self, unit: impl Into<SharedString>) -> Self {
133 self.unit = Some(unit.into());
134 self
135 }
136
137 pub fn bar(mut self) -> Self {
139 self.bar = Some(BarRange::Auto);
140 self
141 }
142
143 pub fn bar_range(mut self, min: f64, max: f64) -> Self {
145 self.bar = Some(BarRange::Fixed(min, max));
146 self
147 }
148}
149
150#[derive(Debug, Clone, PartialEq, Default)]
152pub struct TableData {
153 pub name: SharedString,
155 pub columns: Vec<Column>,
157}
158
159impl TableData {
160 pub fn new(name: impl Into<SharedString>, columns: Vec<Column>) -> Self {
162 Self { name: name.into(), columns }
163 }
164
165 pub fn rows(&self) -> usize {
167 self.columns.iter().map(|c| c.values.len()).max().unwrap_or(0)
168 }
169}
170
171#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
173#[serde(default)]
174pub struct TableSpec {
175 pub summary: bool,
177 pub row_numbers: bool,
179 pub role_tags: bool,
181 pub bins: usize,
183 pub row_height: f32,
185 pub min_column_width: f32,
187 pub index_width: f32,
189 pub summary_height: f32,
191 pub top_values: usize,
193 pub many_unique: usize,
195 pub decimals: usize,
197 pub trim_zeros: bool,
199 pub missing_text: String,
201}
202
203impl Default for TableSpec {
204 fn default() -> Self {
205 Self {
206 summary: true,
207 row_numbers: true,
208 role_tags: true,
209 bins: 24,
210 row_height: 24.,
211 min_column_width: 140.,
212 index_width: 52.,
213 summary_height: 128.,
214 top_values: 3,
215 many_unique: 30,
216 decimals: 3,
217 trim_zeros: true,
218 missing_text: "—".into(),
219 }
220 }
221}
222
223impl TableSpec {
224 pub fn format(&self, x: Option<f64>) -> String {
226 match x {
227 None => self.missing_text.clone(),
228 Some(v) if !v.is_finite() => v.to_string(),
229 Some(v) => {
230 let s = format!("{v:.*}", self.decimals);
231 if self.trim_zeros && s.contains('.') {
232 s.trim_end_matches('0').trim_end_matches('.').to_string()
233 } else {
234 s
235 }
236 }
237 }
238 }
239}
240
241#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
243pub enum SummaryStart {
244 #[default]
246 Open,
247 Folded,
249 Off,
251}
252
253#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
255pub enum Selection {
256 #[default]
258 None,
259 Single,
261 Multiple,
263}
264
265#[derive(Debug, Clone, PartialEq)]
267pub struct Toolbar {
268 pub column: usize,
270 pub all: SharedString,
272 pub noun: SharedString,
274}
275
276impl Toolbar {
277 pub fn new(column: usize) -> Self {
279 Self { column, all: "All".into(), noun: "rows".into() }
280 }
281
282 pub fn all(mut self, all: impl Into<SharedString>) -> Self {
284 self.all = all.into();
285 self
286 }
287
288 pub fn noun(mut self, noun: impl Into<SharedString>) -> Self {
290 self.noun = noun.into();
291 self
292 }
293}
294
295#[derive(Debug, Clone, Default, PartialEq)]
298pub struct TableOptions {
299 pub summary: SummaryStart,
301 pub selection: Selection,
303 pub toolbar: Option<Toolbar>,
305 pub compact: bool,
307}
308
309impl TableOptions {
310 pub fn summary(mut self, start: SummaryStart) -> Self {
312 self.summary = start;
313 self
314 }
315
316 pub fn selection(mut self, selection: Selection) -> Self {
318 self.selection = selection;
319 self
320 }
321
322 pub fn toolbar(mut self, toolbar: Toolbar) -> Self {
324 self.toolbar = Some(toolbar);
325 self
326 }
327
328 pub fn compact(mut self, compact: bool) -> Self {
330 self.compact = compact;
331 self
332 }
333}
334
335#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
337pub enum Density {
338 Compact,
340 #[default]
342 Normal,
343 Comfortable,
345}
346
347#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
349pub enum Lines {
350 #[default]
352 Stripes,
353 Grid,
355 None,
357}
358
359#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
361pub enum HeaderStyle {
362 #[default]
364 Raised,
365 Plain,
367}
368
369#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
371pub enum BarColor {
372 #[default]
374 Row,
375 Accent,
377}
378
379#[derive(Debug, Clone, Copy, Default, PartialEq)]
382pub struct TableStyle {
383 pub density: Density,
385 pub lines: Lines,
387 pub header: HeaderStyle,
389 pub numbers_sans: bool,
391 pub text_sans: bool,
393 pub selection: Option<Hsla>,
395 pub hover: Option<Hsla>,
397 pub bar: BarColor,
399}
400
401impl TableStyle {
402 pub fn row_height(&self, spec: &TableSpec) -> f32 {
404 match self.density {
405 Density::Compact => (spec.row_height - 4.).max(14.),
406 Density::Normal => spec.row_height,
407 Density::Comfortable => spec.row_height + 8.,
408 }
409 }
410
411 fn selection_color(&self) -> Hsla {
412 self.selection.unwrap_or_else(color::selection)
413 }
414
415 fn hover_color(&self) -> Hsla {
416 self.hover.unwrap_or_else(color::hover)
417 }
418}
419
420#[derive(Debug, Clone, PartialEq)]
422pub enum Shape {
423 #[allow(missing_docs)]
425 Histogram { min: f64, max: f64, counts: Vec<usize> },
426 #[allow(missing_docs)]
428 Top { values: Vec<(SharedString, usize)>, other: usize, others: usize },
429 Distinct,
431}
432
433#[derive(Debug, Clone, PartialEq)]
435pub struct ColumnSummary {
436 pub rows: usize,
438 pub missing: usize,
440 pub unique: usize,
442 pub shape: Shape,
444}
445
446pub trait Summarizer: Send + Sync {
452 fn histogram(&self, values: &[Option<f64>], bins: usize) -> Option<(f64, f64, Vec<usize>)> {
455 cpu_histogram(values, bins)
456 }
457
458 fn summarize(&self, data: &TableData, spec: &TableSpec) -> Vec<ColumnSummary> {
460 data.columns.iter().map(|c| summarize_column(self, &c.values, spec)).collect()
461 }
462}
463
464#[derive(Debug, Clone, Copy, Default)]
466pub struct CpuSummarizer;
467
468impl Summarizer for CpuSummarizer {}
469
470pub fn summarize(data: &TableData, spec: &TableSpec) -> Vec<ColumnSummary> {
472 CpuSummarizer.summarize(data, spec)
473}
474
475pub fn cpu_histogram(values: &[Option<f64>], bins: usize) -> Option<(f64, f64, Vec<usize>)> {
477 let (mut min, mut max, mut any) = (f64::INFINITY, f64::NEG_INFINITY, false);
478 for &x in values.iter().flatten().filter(|x| x.is_finite()) {
479 min = min.min(x);
480 max = max.max(x);
481 any = true;
482 }
483 if !any {
484 return None;
485 }
486 let bins = bins.max(1);
487 let mut counts = vec![0; bins];
488 let span = if max > min { max - min } else { 1. };
489 for &x in values.iter().flatten().filter(|x| x.is_finite()) {
490 counts[((((x - min) / span) * bins as f64) as usize).min(bins - 1)] += 1;
491 }
492 Some((min, max, counts))
493}
494
495pub fn summarize_column<S: Summarizer + ?Sized>(by: &S, values: &Values, spec: &TableSpec) -> ColumnSummary {
497 let rows = values.len();
498 match values {
499 Values::Number(v) => {
500 let present = v.iter().flatten().filter(|x| x.is_finite()).count();
501 let unique =
502 v.iter().flatten().filter(|x| x.is_finite()).map(|x| x.to_bits()).collect::<HashSet<_>>().len();
503 let (min, max, counts) = by.histogram(v, spec.bins).unwrap_or((0., 0., Vec::new()));
504 ColumnSummary { rows, missing: rows - present, unique, shape: Shape::Histogram { min, max, counts } }
505 }
506 Values::Text(v) => {
507 let mut counts: HashMap<&str, usize> = HashMap::new();
508 let mut missing = 0;
509 for x in v {
510 match x {
511 Some(s) => *counts.entry(s.as_ref()).or_default() += 1,
512 None => missing += 1,
513 }
514 }
515 let unique = counts.len();
516 let shape = if unique > spec.many_unique {
517 Shape::Distinct
518 } else {
519 let mut all: Vec<(&str, usize)> = counts.into_iter().collect();
520 all.sort_by(|a, b| b.1.cmp(&a.1).then(a.0.cmp(b.0)));
521 let k = spec.top_values.min(all.len());
522 let other = all[k..].iter().map(|x| x.1).sum();
523 let others = all.len() - k;
524 Shape::Top {
525 values: all[..k].iter().map(|(s, n)| (SharedString::from(s.to_string()), *n)).collect(),
526 other,
527 others,
528 }
529 };
530 ColumnSummary { rows, missing, unique, shape }
531 }
532 }
533}
534
535pub fn sort_order(data: &TableData, col: usize, ascending: bool) -> Vec<usize> {
537 let n = data.rows();
538 let mut order: Vec<usize> = (0..n).collect();
539 let Some(c) = data.columns.get(col) else { return order };
540 let flip = |o: std::cmp::Ordering| if ascending { o } else { o.reverse() };
541 match &c.values {
542 Values::Number(v) => order.sort_by(|&a, &b| match (v.get(a).copied().flatten(), v.get(b).copied().flatten()) {
543 (Some(x), Some(y)) => flip(x.total_cmp(&y)),
544 (Some(_), None) => std::cmp::Ordering::Less,
545 (None, Some(_)) => std::cmp::Ordering::Greater,
546 (None, None) => std::cmp::Ordering::Equal,
547 }),
548 Values::Text(v) => order.sort_by(|&a, &b| match (v.get(a).cloned().flatten(), v.get(b).cloned().flatten()) {
549 (Some(x), Some(y)) => flip(x.cmp(&y)),
550 (Some(_), None) => std::cmp::Ordering::Less,
551 (None, Some(_)) => std::cmp::Ordering::Greater,
552 (None, None) => std::cmp::Ordering::Equal,
553 }),
554 }
555 order
556}
557
558pub fn view_order(data: &TableData, sort: Option<(usize, bool)>, only: Option<(usize, &str)>) -> Option<Vec<usize>> {
562 if sort.is_none() && only.is_none() {
563 return None;
564 }
565 let mut rows = match sort {
566 Some((c, up)) => sort_order(data, c, up),
567 None => (0..data.rows()).collect(),
568 };
569 if let Some((c, value)) = only {
570 match data.columns.get(c).map(|c| &c.values) {
571 Some(Values::Text(t)) => rows.retain(|&r| t.get(r).and_then(|x| x.as_ref()).is_some_and(|x| x == value)),
572 _ => rows.clear(),
573 }
574 }
575 Some(rows)
576}
577
578pub fn distinct_text(data: &TableData, col: usize) -> Vec<SharedString> {
580 match data.columns.get(col).map(|c| &c.values) {
581 Some(Values::Text(t)) => t.iter().flatten().cloned().collect::<BTreeSet<SharedString>>().into_iter().collect(),
582 _ => Vec::new(),
583 }
584}
585
586pub fn click_selection(
590 selected: &BTreeSet<usize>,
591 anchor: Option<usize>,
592 order: &[usize],
593 pos: usize,
594 mode: Selection,
595 shift: bool,
596 toggle: bool,
597) -> (BTreeSet<usize>, Option<usize>) {
598 let Some(&row) = order.get(pos) else { return (selected.clone(), anchor) };
599 match mode {
600 Selection::None => (selected.clone(), anchor),
601 Selection::Single => {
602 if toggle && selected.contains(&row) {
603 (BTreeSet::new(), None)
604 } else {
605 (BTreeSet::from([row]), Some(row))
606 }
607 }
608 Selection::Multiple => {
609 if shift && let Some(from) = anchor.and_then(|a| order.iter().position(|&r| r == a)) {
610 let (lo, hi) = if from <= pos { (from, pos) } else { (pos, from) };
611 let mut out = if toggle { selected.clone() } else { BTreeSet::new() };
612 out.extend(order[lo..=hi].iter().copied());
613 (out, anchor)
614 } else if toggle {
615 let mut out = selected.clone();
616 if !out.remove(&row) {
617 out.insert(row);
618 }
619 (out, Some(row))
620 } else {
621 (BTreeSet::from([row]), Some(row))
622 }
623 }
624 }
625}
626
627fn bar_range(c: &Column) -> Option<(f64, f64)> {
629 match (c.bar?, &c.values) {
630 (BarRange::Fixed(lo, hi), Values::Number(_)) => Some((lo, hi)),
631 (BarRange::Auto, Values::Number(v)) => {
632 let finite = v.iter().flatten().copied().filter(|x| x.is_finite());
633 let (lo, hi) = finite.fold((f64::INFINITY, f64::NEG_INFINITY), |(lo, hi), x| (lo.min(x), hi.max(x)));
634 (lo <= hi).then(|| (lo.min(0.), hi.max(0.)))
636 }
637 _ => None,
638 }
639}
640
641fn bar_fraction(x: f64, (lo, hi): (f64, f64)) -> f32 {
643 if hi > lo { ((x - lo) / (hi - lo)).clamp(0., 1.) as f32 } else { 1. }
644}
645
646fn share(n: usize, of: usize) -> String {
648 if of == 0 {
649 return "0%".into();
650 }
651 let p = n as f64 / of as f64 * 100.;
652 if n > 0 && p < 1. { "<1%".into() } else { format!("{p:.0}%") }
653}
654
655#[derive(Debug, Clone, PartialEq)]
657pub enum TableEvent {
658 Selected(Option<usize>),
660 RoleClicked(usize),
662 RowsSelected(Vec<usize>),
664 FilterChanged(Option<SharedString>),
666}
667
668pub struct TableView {
670 id: SharedString,
671 data: Arc<TableData>,
672 spec: TableSpec,
673 options: TableOptions,
674 style: TableStyle,
675 roles: Vec<Option<SharedString>>,
676 summaries: Option<Arc<Vec<ColumnSummary>>>,
677 order: Option<Arc<Vec<usize>>>,
678 order_gen: u64,
679 sort: Option<(usize, bool)>,
680 filter: Option<SharedString>,
681 filter_values: Vec<SharedString>,
682 row_colors: Arc<Vec<Option<Hsla>>>,
683 bar_ranges: Vec<Option<(f64, f64)>>,
684 selected_rows: BTreeSet<usize>,
685 anchor: Option<usize>,
686 selected: Option<usize>,
687 manual: HashMap<usize, f32>,
688 scroll: UniformListScrollHandle,
689 width: Rc<Cell<f32>>,
690 drag: Option<(usize, f32, f32)>,
691 summary_task: Option<Task<()>>,
692 sort_task: Option<Task<()>>,
693 summarizer: Arc<dyn Summarizer>,
694}
695
696impl EventEmitter<TableEvent> for TableView {}
697
698impl TableView {
699 pub fn new(id: impl Into<SharedString>) -> Self {
701 Self {
702 id: id.into(),
703 data: Arc::new(TableData::default()),
704 spec: TableSpec::default(),
705 options: TableOptions::default(),
706 style: TableStyle::default(),
707 roles: Vec::new(),
708 summaries: None,
709 order: None,
710 order_gen: 0,
711 sort: None,
712 filter: None,
713 filter_values: Vec::new(),
714 row_colors: Arc::new(Vec::new()),
715 bar_ranges: Vec::new(),
716 selected_rows: BTreeSet::new(),
717 anchor: None,
718 selected: None,
719 manual: HashMap::new(),
720 scroll: UniformListScrollHandle::new(),
721 width: Rc::new(Cell::new(0.)),
722 drag: None,
723 summary_task: None,
724 sort_task: None,
725 summarizer: Arc::new(CpuSummarizer),
726 }
727 }
728
729 pub fn with_summarizer(mut self, by: Arc<dyn Summarizer>) -> Self {
731 self.summarizer = by;
732 self
733 }
734
735 pub fn set_summaries(&mut self, summaries: Arc<Vec<ColumnSummary>>, cx: &mut Context<Self>) {
738 self.summary_task = None;
739 self.summaries = Some(summaries);
740 cx.notify();
741 }
742
743 pub fn with_options(mut self, options: TableOptions) -> Self {
745 self.spec.summary = options.summary == SummaryStart::Open;
746 self.options = options;
747 self
748 }
749
750 pub fn with_style(mut self, style: TableStyle) -> Self {
752 self.style = style;
753 self
754 }
755
756 pub fn set_options(&mut self, options: TableOptions, cx: &mut Context<Self>) {
758 self.spec.summary = options.summary == SummaryStart::Open;
759 self.options = options;
760 self.filter = None;
761 self.filter_values =
762 self.options.toolbar.as_ref().map(|t| distinct_text(&self.data, t.column)).unwrap_or_default();
763 if self.summaries.is_none() && self.summary_task.is_none() {
765 self.resummarize(cx);
766 }
767 self.refresh_order(cx);
768 }
769
770 pub fn options(&self) -> &TableOptions {
772 &self.options
773 }
774
775 pub fn set_style(&mut self, style: TableStyle, cx: &mut Context<Self>) {
777 self.style = style;
778 cx.notify();
779 }
780
781 pub fn style(&self) -> &TableStyle {
783 &self.style
784 }
785
786 pub fn set_row_colors(&mut self, colors: Vec<Option<Hsla>>, cx: &mut Context<Self>) {
788 self.row_colors = Arc::new(colors);
789 cx.notify();
790 }
791
792 pub fn selected_rows(&self) -> Vec<usize> {
794 self.selected_rows.iter().copied().collect()
795 }
796
797 pub fn set_selected_rows(&mut self, rows: impl IntoIterator<Item = usize>, cx: &mut Context<Self>) {
799 self.selected_rows = rows.into_iter().collect();
800 self.anchor = self.selected_rows.first().copied();
801 cx.notify();
802 }
803
804 pub fn filter(&self) -> Option<&SharedString> {
806 self.filter.as_ref()
807 }
808
809 pub fn set_filter(&mut self, value: Option<SharedString>, cx: &mut Context<Self>) {
812 self.filter = value;
813 self.refresh_order(cx);
814 }
815
816 pub fn filter_values(&self) -> &[SharedString] {
818 &self.filter_values
819 }
820
821 pub fn shown_rows(&self) -> Vec<usize> {
823 match &self.order {
824 Some(o) => o.as_ref().clone(),
825 None => (0..self.data.rows()).collect(),
826 }
827 }
828
829 pub fn click_row(&mut self, pos: usize, shift: bool, toggle: bool, cx: &mut Context<Self>) {
832 if self.options.selection == Selection::None {
833 return;
834 }
835 let order = self.shown_rows();
836 let (rows, anchor) =
837 click_selection(&self.selected_rows, self.anchor, &order, pos, self.options.selection, shift, toggle);
838 self.selected_rows = rows;
839 self.anchor = anchor;
840 cx.emit(TableEvent::RowsSelected(self.selected_rows()));
841 cx.notify();
842 }
843
844 fn pick_filter(&mut self, i: usize, cx: &mut Context<Self>) {
845 let value = i.checked_sub(1).and_then(|k| self.filter_values.get(k).cloned());
846 if value != self.filter {
847 self.set_filter(value.clone(), cx);
848 cx.emit(TableEvent::FilterChanged(value));
849 }
850 }
851
852 pub fn set_data(&mut self, data: Arc<TableData>, cx: &mut Context<Self>) {
855 if !Arc::ptr_eq(&self.data, &data) {
856 self.data = data;
857 self.sort = None;
858 self.order = None;
859 self.selected = None;
860 self.selected_rows.clear();
861 self.anchor = None;
862 self.manual.clear();
863 self.roles.clear();
864 self.bar_ranges = self.data.columns.iter().map(bar_range).collect();
865 self.filter_values =
866 self.options.toolbar.as_ref().map(|t| distinct_text(&self.data, t.column)).unwrap_or_default();
867 if self.filter.as_ref().is_some_and(|f| !self.filter_values.contains(f)) {
868 self.filter = None;
869 }
870 self.resummarize(cx);
871 self.refresh_order(cx);
872 }
873 cx.notify();
874 }
875
876 pub fn data(&self) -> &Arc<TableData> {
878 &self.data
879 }
880
881 pub fn set_spec(&mut self, spec: TableSpec, cx: &mut Context<Self>) {
883 let again = spec.bins != self.spec.bins
884 || spec.top_values != self.spec.top_values
885 || spec.many_unique != self.spec.many_unique;
886 self.spec = spec;
887 if again {
888 self.resummarize(cx);
889 }
890 cx.notify();
891 }
892
893 pub fn spec(&self) -> &TableSpec {
895 &self.spec
896 }
897
898 pub fn set_roles(&mut self, roles: Vec<Option<SharedString>>, cx: &mut Context<Self>) {
900 self.roles = roles;
901 cx.notify();
902 }
903
904 pub fn toggle_summary(&mut self, cx: &mut Context<Self>) {
906 if self.options.summary != SummaryStart::Off {
907 self.spec.summary = !self.spec.summary;
908 }
909 cx.notify();
910 }
911
912 pub fn selected(&self) -> Option<usize> {
914 self.selected
915 }
916
917 pub fn select(&mut self, col: Option<usize>, cx: &mut Context<Self>) {
919 self.selected = col;
920 cx.emit(TableEvent::Selected(col));
921 cx.notify();
922 }
923
924 pub fn summaries(&self) -> Option<&Arc<Vec<ColumnSummary>>> {
926 self.summaries.as_ref()
927 }
928
929 fn resummarize(&mut self, cx: &mut Context<Self>) {
930 self.summaries = None;
931 if self.options.summary == SummaryStart::Off || self.options.compact {
932 self.summary_task = None;
933 return;
934 }
935 let (data, spec, by) = (self.data.clone(), self.spec.clone(), self.summarizer.clone());
936 let work = cx.background_executor().spawn(async move { by.summarize(&data, &spec) });
937 self.summary_task = Some(cx.spawn(async move |this, cx| {
938 let done = work.await;
939 let _ = this.update(cx, |t, cx| {
940 t.summaries = Some(Arc::new(done));
941 cx.notify();
942 });
943 }));
944 }
945
946 fn cycle_sort(&mut self, col: usize, cx: &mut Context<Self>) {
948 self.sort = match self.sort {
949 Some((c, true)) if c == col => Some((col, false)),
950 Some((c, false)) if c == col => None,
951 _ => Some((col, true)),
952 };
953 self.refresh_order(cx);
954 }
955
956 fn refresh_order(&mut self, cx: &mut Context<Self>) {
958 self.order_gen += 1;
959 let generation = self.order_gen;
960 let only = self.filter.clone().zip(self.options.toolbar.as_ref().map(|t| t.column));
961 if self.sort.is_none() && only.is_none() {
962 self.order = None;
963 self.sort_task = None;
964 cx.notify();
965 return;
966 }
967 let (data, sort) = (self.data.clone(), self.sort);
968 let work = cx
969 .background_executor()
970 .spawn(async move { view_order(&data, sort, only.as_ref().map(|(v, c)| (*c, v.as_ref()))) });
971 self.sort_task = Some(cx.spawn(async move |this, cx| {
972 let order = work.await;
973 let _ = this.update(cx, |t, cx| {
974 if t.order_gen == generation {
975 t.order = order.map(Arc::new);
976 cx.notify();
977 }
978 });
979 }));
980 cx.notify();
981 }
982
983 fn row_numbers(&self) -> bool {
985 self.spec.row_numbers && !self.options.compact
986 }
987
988 fn mark_width(&self) -> f32 {
990 if self.row_colors.iter().any(Option::is_some) { MARK_W } else { 0. }
991 }
992
993 fn widths(&self) -> Vec<f32> {
996 let n = self.data.columns.len();
997 let index = if self.row_numbers() { self.spec.index_width } else { 0. };
998 let lead = index + self.mark_width();
999 let min = if self.options.compact && n > 0 {
1000 ((self.width.get() - lead) / n as f32).clamp(24., self.spec.min_column_width)
1001 } else {
1002 self.spec.min_column_width
1003 };
1004 let base: Vec<f32> = (0..n).map(|j| self.manual.get(&j).copied().unwrap_or(min)).collect();
1005 let free = self.width.get() - lead - base.iter().sum::<f32>();
1006 let auto = (0..n).filter(|j| !self.manual.contains_key(j)).count();
1007 base.iter()
1008 .enumerate()
1009 .map(
1010 |(j, &w)| {
1011 if free > 0. && auto > 0 && !self.manual.contains_key(&j) { w + free / auto as f32 } else { w }
1012 },
1013 )
1014 .collect()
1015 }
1016
1017 fn data_color() -> Hsla {
1018 if theme::is_dark() { theme::data(4) } else { theme::data(0) }
1019 }
1020
1021 fn header(&self, widths: &[f32], cx: &mut Context<Self>) -> impl IntoElement + use<> {
1022 let plain = self.style.header == HeaderStyle::Plain;
1023 let mark = self.mark_spacer(32.);
1024 let index = self.row_numbers().then(|| {
1025 div()
1026 .flex_none()
1027 .w(px(self.spec.index_width))
1028 .h(px(32.))
1029 .px(px(theme::SM))
1030 .flex()
1031 .items_center()
1032 .justify_end()
1033 .text_xs()
1034 .font_family(fonts::MONO)
1035 .text_color(color::text_muted())
1036 .border_r_1()
1037 .border_color(color::border())
1038 .child("#")
1039 });
1040 let cells = self.data.columns.iter().enumerate().map(|(j, c)| {
1041 let mark = if c.values.is_number() { "#" } else { "Aa" };
1042 let sort = match self.sort {
1043 Some((s, true)) if s == j => Some(IconName::ChevronUp),
1044 Some((s, false)) if s == j => Some(IconName::ChevronDown),
1045 _ => None,
1046 };
1047 let role = if self.spec.role_tags { self.roles.get(j).cloned().flatten() } else { None };
1048 let tip: SharedString = format!(
1049 "{}{} · {}{}",
1050 c.name,
1051 c.unit.as_ref().map(|u| format!(" ({u})")).unwrap_or_default(),
1052 if c.values.is_number() { "numbers" } else { "text" },
1053 role.as_ref().map(|r| format!(" · {r}")).unwrap_or_default()
1054 )
1055 .into();
1056 h_flex()
1057 .id((SharedString::from(format!("{}-head", self.id)), j))
1058 .relative()
1059 .flex_none()
1060 .w(px(widths[j]))
1061 .h(px(32.))
1062 .px(px(theme::SM))
1063 .gap(px(theme::XS))
1064 .items_center()
1065 .border_r_1()
1066 .border_color(color::border())
1067 .cursor_pointer()
1068 .hover(|d| d.bg(color::hover()))
1069 .when(self.selected == Some(j), |d| {
1070 d.bg(color::selection()).border_t_2().border_color(color::selection_edge())
1071 })
1072 .tooltip(move |window, cx| Tooltip::new(tip.clone()).build(window, cx))
1073 .on_click(cx.listener(move |this, _, _, cx| {
1074 if this.drag.is_none() {
1075 this.cycle_sort(j, cx)
1076 }
1077 }))
1078 .child(
1079 div()
1080 .flex_none()
1081 .w(px(16.))
1082 .text_xs()
1083 .font_family(fonts::MONO)
1084 .font_weight(FontWeight::SEMIBOLD)
1085 .text_color(color::text_muted())
1086 .child(mark),
1087 )
1088 .child(
1089 div()
1090 .flex_1()
1091 .min_w_0()
1092 .truncate()
1093 .text_sm()
1094 .font_weight(if plain { FontWeight::NORMAL } else { FontWeight::SEMIBOLD })
1095 .text_color(if plain { color::text_muted() } else { color::text() })
1096 .child(c.name.clone()),
1097 )
1098 .children(c.unit.clone().map(|u| {
1099 div().min_w_0().max_w(relative(0.4)).truncate().text_xs().text_color(color::text_muted()).child(u)
1100 }))
1101 .children(sort.map(|i| Icon::new(i).xsmall().text_color(color::accent_mark())))
1102 .children(role.map(|r| {
1103 let on = r.as_ref() != "Other";
1104 div()
1105 .id((SharedString::from(format!("{}-role", self.id)), j))
1106 .flex_none()
1107 .max_w(px(72.))
1108 .truncate()
1109 .px(px(theme::XS))
1110 .rounded(px(theme::RADIUS_SM))
1111 .border_1()
1112 .border_color(if on { color::accent_mark() } else { color::border() })
1113 .text_xs()
1114 .text_color(if on { color::accent_mark() } else { color::text_muted() })
1115 .child(r)
1116 .on_click(cx.listener(move |_, _, _, cx| {
1117 cx.stop_propagation();
1118 cx.emit(TableEvent::RoleClicked(j));
1119 }))
1120 }))
1121 .child(div().absolute().top_0().bottom_0().right(px(-3.)).w(px(6.)).cursor_col_resize().on_mouse_down(
1122 MouseButton::Left,
1123 cx.listener(move |this, e: &MouseDownEvent, _, cx| {
1124 cx.stop_propagation();
1125 if e.click_count >= 2 {
1126 this.manual.remove(&j);
1127 this.drag = None;
1128 } else {
1129 let w = this.widths()[j];
1130 this.drag = Some((j, e.position.x.as_f32(), w));
1131 }
1132 cx.notify();
1133 }),
1134 ))
1135 });
1136 h_flex().flex_none().children(index).children(mark).children(cells.collect::<Vec<_>>())
1137 }
1138
1139 fn mark_spacer(&self, h: f32) -> Option<impl IntoElement + use<>> {
1141 let w = self.mark_width();
1142 (w > 0.).then(|| div().flex_none().w(px(w)).h(px(h)))
1143 }
1144
1145 fn fold_bar(&self, cx: &mut Context<Self>) -> impl IntoElement + use<> {
1146 let n = self.data.columns.len();
1147 h_flex()
1148 .id(SharedString::from(format!("{}-fold", self.id)))
1149 .flex_none()
1150 .w_full()
1151 .h(px(24.))
1152 .px(px(theme::SM))
1153 .gap(px(theme::XS))
1154 .items_center()
1155 .bg(color::raised())
1156 .border_t_1()
1157 .border_color(color::border())
1158 .cursor_pointer()
1159 .text_xs()
1160 .text_color(color::text_muted())
1161 .hover(|d| d.text_color(color::text()))
1162 .on_click(cx.listener(|this, _, _, cx| this.toggle_summary(cx)))
1163 .child(Icon::new(if self.spec.summary { IconName::ChevronDown } else { IconName::ChevronRight }).xsmall())
1164 .child(div().truncate().child(if self.spec.summary {
1165 "SUMMARY".to_string()
1166 } else if self.summaries.is_none() {
1167 "SUMMARY · computing".to_string()
1168 } else {
1169 format!("SUMMARY · {n} columns")
1170 }))
1171 }
1172
1173 fn summary_row(&self, widths: &[f32], cx: &mut Context<Self>) -> impl IntoElement + use<> {
1174 let h = self.spec.summary_height;
1175 let mark = self.mark_spacer(h);
1176 let index = self.row_numbers().then(|| {
1177 div()
1178 .flex_none()
1179 .w(px(self.spec.index_width))
1180 .h(px(h))
1181 .border_r_1()
1182 .border_t_1()
1183 .border_color(color::border())
1184 });
1185 let sums = self.summaries.clone();
1186 let cells = self.data.columns.iter().enumerate().map(|(j, c)| {
1187 let body: AnyElement = match sums.as_ref().and_then(|s| s.get(j)) {
1188 None => div().text_color(color::text_muted()).child("Computing…").into_any_element(),
1189 Some(s) => self.summary_body(c, s).into_any_element(),
1190 };
1191 v_flex()
1192 .id((SharedString::from(format!("{}-sum", self.id)), j))
1193 .flex_none()
1194 .w(px(widths[j]))
1195 .h(px(h))
1196 .p(px(theme::SM))
1197 .gap(px(theme::XS))
1198 .overflow_hidden()
1199 .text_xs()
1200 .border_r_1()
1201 .border_t_1()
1202 .border_color(color::border())
1203 .cursor_pointer()
1204 .when(self.selected == Some(j), |d| d.bg(color::selection()))
1205 .on_click(cx.listener(move |this, _, _, cx| {
1206 let next = if this.selected == Some(j) { None } else { Some(j) };
1207 this.select(next, cx);
1208 }))
1209 .child(body)
1210 });
1211 h_flex().flex_none().children(index).children(mark).children(cells.collect::<Vec<_>>())
1212 }
1213
1214 fn summary_body(&self, c: &Column, s: &ColumnSummary) -> impl IntoElement + use<> {
1215 let kv = |label: &'static str, value: String, warn: bool| {
1216 h_flex()
1217 .w_full()
1218 .gap(px(theme::SM))
1219 .child(div().flex_none().max_w(relative(0.4)).truncate().text_color(color::text_muted()).child(label))
1220 .child(
1221 div().flex_1().min_w_0().flex().justify_end().child(
1222 div()
1223 .min_w_0()
1224 .truncate()
1225 .font_family(fonts::MONO)
1226 .text_color(if warn { color::danger() } else { color::text() })
1227 .child(value),
1228 ),
1229 )
1230 };
1231 let head = v_flex()
1232 .flex_none()
1233 .gap(px(2.))
1234 .child(kv("Missing", format!("{} · {}", s.missing, share(s.missing, s.rows)), s.missing > 0))
1235 .child(kv("Unique", format!("{} · {}", s.unique, share(s.unique, s.rows)), false));
1236 let data = Self::data_color();
1237 let shape: AnyElement = match &s.shape {
1238 Shape::Histogram { min, max, counts } => {
1239 let top = counts.iter().copied().max().unwrap_or(0).max(1) as f32;
1240 let unit = c.unit.as_ref().map(|u| format!(" {u}")).unwrap_or_default();
1241 v_flex()
1242 .flex_1()
1243 .min_h_0()
1244 .gap(px(2.))
1245 .child(
1246 h_flex()
1247 .flex_1()
1248 .min_h(px(16.))
1249 .items_end()
1250 .gap(px(1.))
1251 .border_b_1()
1252 .border_color(color::border())
1253 .children(
1254 counts.iter().map(|&n| {
1255 div().flex_1().min_w_0().h(relative(n as f32 / top)).min_h(px(1.)).bg(data)
1256 }),
1257 ),
1258 )
1259 .child(
1260 h_flex()
1261 .flex_none()
1262 .justify_between()
1263 .gap(px(theme::SM))
1264 .font_family(fonts::MONO)
1265 .text_color(color::text_muted())
1266 .child(div().min_w_0().truncate().child(format!("{}{unit}", self.spec.format(Some(*min)))))
1267 .child(div().min_w_0().truncate().child(format!("{}{unit}", self.spec.format(Some(*max))))),
1268 )
1269 .into_any_element()
1270 }
1271 Shape::Distinct => h_flex()
1272 .flex_1()
1273 .justify_center()
1274 .items_center()
1275 .gap(px(theme::XS))
1276 .child(
1277 div()
1278 .font_family(fonts::MONO)
1279 .text_base()
1280 .font_weight(FontWeight::SEMIBOLD)
1281 .text_color(data)
1282 .child(s.unique.to_string()),
1283 )
1284 .child(div().text_color(color::text_muted()).child("distinct"))
1285 .into_any_element(),
1286 Shape::Top { values, other, others } => {
1287 let most = values.first().map(|v| v.1).unwrap_or(1).max(1) as f32;
1288 let line = |label: SharedString, n: usize, frac: f32| {
1289 div()
1290 .relative()
1291 .w_full()
1292 .h(px(16.))
1293 .rounded(px(theme::RADIUS_SM))
1294 .overflow_hidden()
1295 .child(
1296 div()
1297 .absolute()
1298 .top_0()
1299 .bottom_0()
1300 .left_0()
1301 .w(relative(frac.clamp(0., 1.)))
1302 .bg(data.opacity(0.22)),
1303 )
1304 .child(
1305 h_flex()
1306 .relative()
1307 .px(px(theme::XS))
1308 .gap(px(theme::SM))
1309 .child(div().flex_1().min_w_0().truncate().text_color(color::text()).child(label))
1310 .child(
1311 div()
1312 .flex_none()
1313 .font_family(fonts::MONO)
1314 .text_color(color::text_muted())
1315 .child(share(n, s.rows)),
1316 ),
1317 )
1318 };
1319 v_flex()
1320 .flex_1()
1321 .min_h_0()
1322 .gap(px(2.))
1323 .children(values.iter().map(|(v, n)| line(v.clone(), *n, *n as f32 / most)))
1324 .when(*other > 0, |d| {
1325 d.child(line(format!("Other ({others})").into(), *other, *other as f32 / s.rows.max(1) as f32))
1326 })
1327 .into_any_element()
1328 }
1329 };
1330 v_flex().size_full().gap(px(theme::XS)).child(head).child(shape)
1331 }
1332
1333 fn rows(&mut self, range: std::ops::Range<usize>, _: &mut Window, cx: &mut Context<Self>) -> Vec<AnyElement> {
1334 let widths = self.widths();
1335 let style = self.style;
1336 let rh = style.row_height(&self.spec);
1337 let index_w = self.row_numbers().then_some(self.spec.index_width);
1338 let mark_w = self.mark_width();
1339 let row_w = widths.iter().sum::<f32>() + index_w.unwrap_or(0.) + mark_w;
1340 let data = self.data.clone();
1341 let order = self.order.clone();
1342 let colors = self.row_colors.clone();
1343 let clickable = self.options.selection != Selection::None;
1344 let grid = style.lines == Lines::Grid;
1345 range
1346 .map(|i| {
1347 let r = order.as_ref().and_then(|o| o.get(i).copied()).unwrap_or(i);
1348 let row_color = colors.get(r).copied().flatten();
1349 let selected = self.selected_rows.contains(&r);
1350 let cells = data.columns.iter().enumerate().map(|(j, c)| {
1351 let (text, missing, x) = match &c.values {
1352 Values::Number(v) => {
1353 let x = v.get(r).copied().flatten();
1354 (self.spec.format(x), x.is_none(), x)
1355 }
1356 Values::Text(v) => match v.get(r).cloned().flatten() {
1357 Some(s) => (s.to_string(), false, None),
1358 None => (self.spec.missing_text.clone(), true, None),
1359 },
1360 };
1361 let mono = if c.values.is_number() { !style.numbers_sans } else { !style.text_sans };
1362 let bar = self.bar_ranges.get(j).copied().flatten().zip(x).map(|(range, x)| {
1363 let fill = match style.bar {
1364 BarColor::Row => row_color.unwrap_or_else(color::accent),
1365 BarColor::Accent => color::accent(),
1366 };
1367 div()
1368 .absolute()
1369 .left(px(theme::XS))
1370 .top(px(3.))
1371 .bottom(px(3.))
1372 .w(relative(bar_fraction(x, range) * 0.94))
1373 .rounded(px(theme::RADIUS_SM))
1374 .bg(fill.opacity(0.38))
1375 });
1376 div()
1377 .relative()
1378 .flex_none()
1379 .w(px(widths[j]))
1380 .h_full()
1381 .px(px(theme::SM))
1382 .flex()
1383 .items_center()
1384 .when(mono, |d| d.font_family(fonts::MONO))
1385 .when(c.values.is_number(), |d| d.justify_end())
1386 .when(self.selected == Some(j) && !selected, |d| d.bg(color::selection()))
1387 .when(grid, |d| d.border_r_1().border_color(color::grid()))
1388 .children(bar)
1389 .child(
1390 div()
1391 .relative()
1392 .min_w_0()
1393 .truncate()
1394 .text_color(if missing { color::text_muted() } else { color::text() })
1395 .child(text),
1396 )
1397 });
1398 let hover = style.hover_color();
1399 h_flex()
1400 .id(SharedString::from(format!("{}-row-{i}", self.id)))
1401 .w(px(row_w))
1402 .flex_none()
1403 .h(px(rh))
1404 .text_sm()
1405 .when(style.lines == Lines::Stripes && i % 2 == 1 && !selected, |d| {
1406 d.bg(color::raised().opacity(0.55))
1407 })
1408 .when(grid, |d| d.border_b_1().border_color(color::grid()))
1409 .when(selected, |d| d.bg(style.selection_color()))
1410 .when(!selected, |d| d.hover(move |d| d.bg(hover)))
1411 .when(clickable, |d| {
1412 d.cursor_pointer().on_click(cx.listener(move |this, e: &ClickEvent, _, cx| {
1413 let m = e.modifiers();
1414 this.click_row(i, m.shift, m.control || m.platform, cx);
1415 }))
1416 })
1417 .children(index_w.map(|w| {
1418 div()
1419 .flex_none()
1420 .w(px(w))
1421 .h_full()
1422 .px(px(theme::SM))
1423 .flex()
1424 .items_center()
1425 .justify_end()
1426 .font_family(fonts::MONO)
1427 .text_color(color::text_muted())
1428 .child(div().truncate().child((r + 1).to_string()))
1429 }))
1430 .when(mark_w > 0., |d| {
1431 d.child(
1432 div()
1433 .flex_none()
1434 .w(px(mark_w))
1435 .h_full()
1436 .flex()
1437 .items_center()
1438 .justify_center()
1439 .children(row_color.map(|c| div().size(px(8.)).rounded_full().bg(c))),
1440 )
1441 })
1442 .children(cells.collect::<Vec<_>>())
1443 .test_support()
1444 .into_any_element()
1445 })
1446 .collect()
1447 }
1448
1449 fn toolbar(&self, cx: &mut Context<Self>) -> Option<impl IntoElement + use<>> {
1451 let bar = self.options.toolbar.as_ref()?;
1452 let mut options: Vec<SharedString> = vec![bar.all.clone()];
1453 options.extend(self.filter_values.iter().cloned());
1454 let current = match &self.filter {
1455 Some(f) => self.filter_values.iter().position(|v| v == f).map(|k| k + 1),
1456 None => Some(0),
1457 };
1458 let this = cx.entity().downgrade();
1459 let menu =
1460 MenuSelect::new(SharedString::from(format!("{}-filter", self.id)), options, current, move |i, _, cx| {
1461 let _ = this.update(cx, |t, cx| t.pick_filter(i, cx));
1462 });
1463 let shown = self.order.as_ref().map(|o| o.len()).unwrap_or_else(|| self.data.rows());
1464 let mut counts = format!("{shown} {}", bar.noun);
1465 if self.options.selection != Selection::None && !self.selected_rows.is_empty() {
1466 counts.push_str(&format!(" · {} selected", self.selected_rows.len()));
1467 }
1468 Some(
1469 h_flex()
1470 .id(SharedString::from(format!("{}-toolbar", self.id)))
1471 .flex_none()
1472 .w_full()
1473 .h(px(TOOLBAR_H))
1474 .px(px(theme::SM))
1475 .gap(px(theme::SM))
1476 .items_center()
1477 .bg(color::raised())
1478 .border_b_1()
1479 .border_color(color::border())
1480 .child(div().w(px(168.)).flex_none().child(menu))
1481 .child(div().flex_1())
1482 .child(
1483 div()
1484 .min_w_0()
1485 .truncate()
1486 .text_xs()
1487 .text_color(color::text_muted())
1488 .child(SharedString::from(counts)),
1489 ),
1490 )
1491 }
1492}
1493
1494impl Render for TableView {
1495 fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
1496 let widths = self.widths();
1497 let lead = if self.row_numbers() { self.spec.index_width } else { 0. } + self.mark_width();
1498 let total = widths.iter().sum::<f32>() + lead;
1499 let spare = (total - self.width.get()).max(0.);
1501 let dx = self.scroll.0.borrow().base_handle.offset().x.as_f32().clamp(-spare, 0.);
1502 let rows = self.order.as_ref().map(|o| o.len()).unwrap_or_else(|| self.data.rows());
1503 let toolbar = self.toolbar(cx);
1504 let has_summary = self.options.summary != SummaryStart::Off;
1505 let top = (!self.options.compact).then(|| {
1506 let header = self.header(&widths, cx);
1507 let summary = (has_summary && self.spec.summary).then(|| self.summary_row(&widths, cx));
1508 let fold = has_summary.then(|| self.fold_bar(cx));
1509 div()
1510 .flex_none()
1511 .w_full()
1512 .overflow_hidden()
1513 .when(self.style.header == HeaderStyle::Raised, |d| d.bg(color::raised()))
1514 .border_b_1()
1515 .border_color(color::border())
1516 .child(
1517 v_flex()
1518 .w(px(total.max(self.width.get())))
1519 .ml(px(dx))
1520 .child(header)
1521 .children(fold)
1522 .children(summary),
1523 )
1524 });
1525 let list = uniform_list(SharedString::from(format!("{}-rows", self.id)), rows, cx.processor(Self::rows))
1526 .with_horizontal_sizing_behavior(ListHorizontalSizingBehavior::Unconstrained)
1527 .track_scroll(&self.scroll)
1528 .flex_1()
1529 .min_h_0()
1530 .w_full();
1531 let seen = self.width.clone();
1533 let entity = cx.entity().downgrade();
1534 let measure = canvas(
1535 move |bounds, _, cx| {
1536 let w = bounds.size.width.as_f32();
1537 if (seen.get() - w).abs() > 0.5 {
1538 seen.set(w);
1539 let _ = entity.update(cx, |_, cx| cx.notify());
1540 }
1541 },
1542 |_, _, _, _| {},
1543 )
1544 .absolute()
1545 .top_0()
1546 .left_0()
1547 .size_full();
1548 v_flex()
1549 .id(SharedString::from(format!("{}-table", self.id)))
1550 .relative()
1551 .size_full()
1552 .min_h_0()
1553 .overflow_hidden()
1554 .bg(color::canvas())
1555 .border_1()
1556 .border_color(color::border())
1557 .rounded(px(theme::RADIUS_LG))
1558 .on_mouse_move(cx.listener(|this, e: &MouseMoveEvent, _, cx| {
1559 if let Some((j, x0, w0)) = this.drag {
1560 this.manual.insert(j, (w0 + e.position.x.as_f32() - x0).max(64.));
1561 cx.notify();
1562 }
1563 }))
1564 .on_mouse_up(
1565 MouseButton::Left,
1566 cx.listener(|this, _: &MouseUpEvent, _, cx| {
1567 if this.drag.take().is_some() {
1568 cx.notify();
1569 }
1570 }),
1571 )
1572 .child(measure)
1573 .children(toolbar)
1574 .children(top)
1575 .child(list)
1576 }
1577}
1578
1579pub fn table(id: impl Into<SharedString>, data: Arc<TableData>, cx: &mut App) -> gpui_kit::Entity<TableView> {
1581 use gpui_kit::AppContext as _;
1582 cx.new(|cx| {
1583 let mut t = TableView::new(id);
1584 t.set_data(data, cx);
1585 t
1586 })
1587}
1588
1589#[cfg(feature = "kitchen-table")]
1593impl TableData {
1594 pub fn from_table(name: impl Into<SharedString>, table: &kitchen_table::Table) -> Self {
1596 let columns = table
1597 .names()
1598 .into_iter()
1599 .map(|n| {
1600 let meta = table.meta(&n);
1601 let column = if table.is_numeric(&n) {
1602 Column::numbers(n.clone(), table.values(&n).unwrap_or_default())
1603 } else {
1604 let text = table.text(&n).unwrap_or_default();
1605 Column::text(n.clone(), text.into_iter().map(|t| t.map(SharedString::from)).collect())
1606 };
1607 match meta.unit {
1608 Some(u) => column.unit(u),
1609 None => column,
1610 }
1611 })
1612 .collect();
1613 Self::new(name, columns)
1614 }
1615
1616 pub fn roles_of(table: &kitchen_table::Table) -> Vec<Option<SharedString>> {
1618 use kitchen_table::Role;
1619 table
1620 .names()
1621 .iter()
1622 .map(|n| {
1623 Some(SharedString::from(match table.meta(n).role {
1624 Role::Measure => "Measure",
1625 Role::Group => "Group",
1626 Role::Id => "Id",
1627 Role::Other => "Other",
1628 }))
1629 })
1630 .collect()
1631 }
1632}
1633
1634#[cfg(test)]
1635mod tests {
1636 use super::*;
1637
1638 #[cfg(feature = "kitchen-table")]
1639 #[test]
1640 fn a_kitchen_table_table_becomes_plain_columns() {
1641 use kitchen_table::{ColumnData, ColumnMeta, Role, Table};
1642 let t = Table::from_columns(vec![
1643 ("label", ColumnData::OptText(vec![Some("good".into()), None])),
1644 ("rate", ColumnData::F64(vec![4.0, f64::NAN])),
1645 ])
1646 .unwrap()
1647 .with_meta("rate", ColumnMeta::role(Role::Measure).unit("Hz"))
1648 .unwrap();
1649 let d = TableData::from_table("units", &t);
1650 assert_eq!(d.rows(), 2);
1651 assert_eq!(d.columns[0].values, Values::Text(vec![Some("good".into()), None]));
1652 assert_eq!(d.columns[1].values, Values::Number(vec![Some(4.0), None]));
1653 assert_eq!(d.columns[1].unit.as_ref().map(|u| u.as_ref()), Some("Hz"));
1654 assert_eq!(TableData::roles_of(&t), vec![Some("Other".into()), Some("Measure".into())]);
1655 }
1656
1657 #[test]
1658 fn view_order_sorts_and_filters_and_clicks_select() {
1659 let t = iris_like();
1660 assert_eq!(view_order(&t, None, None), None);
1661 assert_eq!(view_order(&t, None, Some((1, "a"))), Some(vec![0, 2, 4]));
1662 assert_eq!(view_order(&t, Some((0, false)), Some((1, "a"))), Some(vec![4, 0, 2]));
1663 assert_eq!(view_order(&t, None, Some((0, "a"))), Some(vec![]));
1664 assert_eq!(distinct_text(&t, 1), vec![SharedString::from("a"), "b".into(), "c".into()]);
1665 assert!(distinct_text(&t, 0).is_empty());
1666 let order = [4, 0, 2];
1667 let none = BTreeSet::new();
1668 let (s, a) = click_selection(&none, None, &order, 1, Selection::Single, false, false);
1670 assert_eq!((s.iter().copied().collect::<Vec<_>>(), a), (vec![0], Some(0)));
1671 assert!(click_selection(&s, a, &order, 1, Selection::Single, false, true).0.is_empty());
1672 let (s, a) = click_selection(&none, None, &order, 0, Selection::Multiple, false, false);
1674 let (s, a) = click_selection(&s, a, &order, 2, Selection::Multiple, true, false);
1675 assert_eq!(s.iter().copied().collect::<Vec<_>>(), vec![0, 2, 4]);
1676 let (s, a) = click_selection(&s, a, &order, 1, Selection::Multiple, false, true);
1678 assert_eq!(s.iter().copied().collect::<Vec<_>>(), vec![2, 4]);
1679 let (s, _) = click_selection(&s, a, &order, 1, Selection::Multiple, false, true);
1680 assert_eq!(s.len(), 3);
1681 assert_eq!(click_selection(&s, a, &order, 9, Selection::Multiple, false, false).0, s);
1682 assert!(click_selection(&none, None, &order, 0, Selection::None, false, false).0.is_empty());
1683 }
1684
1685 #[test]
1686 fn bars_span_their_range_and_styles_set_row_heights() {
1687 let c = Column::numbers("s", vec![Some(0.5), Some(1.0), None]).bar();
1688 assert_eq!(bar_range(&c), Some((0., 1.)));
1689 assert_eq!(bar_range(&Column::numbers("s", vec![Some(-2.), Some(-1.)]).bar()), Some((-2., 0.)));
1690 assert_eq!(bar_range(&c.clone().bar_range(0., 2.)), Some((0., 2.)));
1691 assert_eq!(bar_range(&Column::numbers("s", vec![None]).bar()), None);
1692 assert_eq!(bar_range(&Column::numbers("s", vec![Some(1.)])), None);
1693 assert_eq!(bar_fraction(0.5, (0., 1.)), 0.5);
1694 assert_eq!(bar_fraction(3., (0., 1.)), 1.);
1695 assert_eq!(bar_fraction(3., (3., 3.)), 1.);
1696 let spec = TableSpec::default();
1697 let rows = |density| TableStyle { density, ..TableStyle::default() }.row_height(&spec);
1698 assert_eq!((rows(Density::Compact), rows(Density::Normal), rows(Density::Comfortable)), (20., 24., 32.));
1699 assert_eq!(TableOptions::default().summary, SummaryStart::Open);
1700 let t = Toolbar::new(2).all("All labels").noun("units");
1701 assert_eq!((t.column, t.all.as_ref(), t.noun.as_ref()), (2, "All labels", "units"));
1702 }
1703
1704 fn iris_like() -> TableData {
1705 TableData::new(
1706 "t",
1707 vec![
1708 Column::numbers("x", vec![Some(1.), Some(2.), None, Some(4.), Some(4.)]).unit("cm"),
1709 Column::text("g", ["a", "b", "a", "c", "a"].iter().map(|s| Some(SharedString::from(*s))).collect()),
1710 ],
1711 )
1712 }
1713
1714 #[test]
1715 fn summaries_count_missing_unique_bins_and_top_values() {
1716 let spec = TableSpec { bins: 3, top_values: 2, ..TableSpec::default() };
1717 let s = summarize(&iris_like(), &spec);
1718 assert_eq!((s[0].rows, s[0].missing, s[0].unique), (5, 1, 3));
1719 assert_eq!(s[0].shape, Shape::Histogram { min: 1., max: 4., counts: vec![1, 1, 2] });
1720 assert_eq!((s[1].missing, s[1].unique), (0, 3));
1721 match &s[1].shape {
1722 Shape::Top { values, other, others } => {
1723 assert_eq!(values[0], ("a".into(), 3));
1724 assert_eq!((values.len(), *other, *others), (2, 1, 1));
1725 }
1726 other => panic!("{other:?}"),
1727 }
1728 struct Fixed;
1730 impl Summarizer for Fixed {
1731 fn histogram(&self, _: &[Option<f64>], _: usize) -> Option<(f64, f64, Vec<usize>)> {
1732 Some((0., 9., vec![7]))
1733 }
1734 }
1735 assert_eq!(
1736 Fixed.summarize(&iris_like(), &spec)[0].shape,
1737 Shape::Histogram { min: 0., max: 9., counts: vec![7] }
1738 );
1739 assert_eq!(Fixed.summarize(&iris_like(), &spec)[0].missing, 1);
1740 let many = TableSpec { many_unique: 2, ..spec };
1741 assert_eq!(summarize(&iris_like(), &many)[1].shape, Shape::Distinct);
1742 }
1743
1744 #[test]
1745 fn sorting_puts_missing_last_both_ways() {
1746 let t = iris_like();
1747 assert_eq!(sort_order(&t, 0, true), vec![0, 1, 3, 4, 2]);
1748 assert_eq!(sort_order(&t, 0, false), vec![3, 4, 1, 0, 2]);
1749 assert_eq!(sort_order(&t, 1, true), vec![0, 2, 4, 1, 3]);
1750 }
1751
1752 #[test]
1753 fn numbers_format_with_trimmed_zeros_and_the_spec_round_trips() {
1754 let s = TableSpec::default();
1755 assert_eq!(s.format(Some(1.5)), "1.5");
1756 assert_eq!(s.format(Some(2.0)), "2");
1757 assert_eq!(s.format(None), "—");
1758 assert_eq!(share(1, 1000), "<1%");
1759 let json = serde_json::to_string(&s).unwrap();
1760 assert_eq!(serde_json::from_str::<TableSpec>(&json).unwrap(), s);
1761 let partial: TableSpec = serde_json::from_str(r#"{"bins": 10}"#).unwrap();
1762 assert_eq!(partial.bins, 10);
1763 assert!(partial.summary);
1764 }
1765}