use std::cell::Cell;
use std::collections::{BTreeSet, HashMap, HashSet};
use std::rc::Rc;
use std::sync::Arc;
use gpui_kit::assets::IconName;
use gpui_kit::component::tooltip::Tooltip;
use gpui_kit::component::{Icon, Sizable as _, h_flex, v_flex};
use gpui_kit::prelude::FluentBuilder as _;
use gpui_kit::{
AnyElement, App, ClickEvent, Context, EventEmitter, FontWeight, Hsla, InteractiveElement as _, IntoElement,
ListHorizontalSizingBehavior, MouseButton, MouseDownEvent, MouseMoveEvent, MouseUpEvent, ParentElement as _,
Render, SharedString, StatefulInteractiveElement as _, Styled as _, Task, TestSupportExt as _,
UniformListScrollHandle, Window, canvas, div, px, relative, uniform_list,
};
use serde::{Deserialize, Serialize};
use crate::theme::{self, color, fonts};
use crate::widgets::MenuSelect;
const MARK_W: f32 = 18.;
const TOOLBAR_H: f32 = 34.;
#[derive(Debug, Clone, PartialEq)]
pub enum Values {
Number(Vec<Option<f64>>),
Text(Vec<Option<SharedString>>),
}
impl Values {
pub fn len(&self) -> usize {
match self {
Values::Number(v) => v.len(),
Values::Text(v) => v.len(),
}
}
pub fn is_empty(&self) -> bool {
self.len() == 0
}
pub fn is_number(&self) -> bool {
matches!(self, Values::Number(_))
}
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum BarRange {
Auto,
Fixed(f64, f64),
}
#[derive(Debug, Clone, PartialEq)]
pub struct Column {
pub name: SharedString,
pub unit: Option<SharedString>,
pub values: Values,
pub bar: Option<BarRange>,
}
impl Column {
pub fn numbers(name: impl Into<SharedString>, values: Vec<Option<f64>>) -> Self {
Self { name: name.into(), unit: None, values: Values::Number(values), bar: None }
}
pub fn text(name: impl Into<SharedString>, values: Vec<Option<SharedString>>) -> Self {
Self { name: name.into(), unit: None, values: Values::Text(values), bar: None }
}
pub fn unit(mut self, unit: impl Into<SharedString>) -> Self {
self.unit = Some(unit.into());
self
}
pub fn bar(mut self) -> Self {
self.bar = Some(BarRange::Auto);
self
}
pub fn bar_range(mut self, min: f64, max: f64) -> Self {
self.bar = Some(BarRange::Fixed(min, max));
self
}
}
#[derive(Debug, Clone, PartialEq, Default)]
pub struct TableData {
pub name: SharedString,
pub columns: Vec<Column>,
}
impl TableData {
pub fn new(name: impl Into<SharedString>, columns: Vec<Column>) -> Self {
Self { name: name.into(), columns }
}
pub fn rows(&self) -> usize {
self.columns.iter().map(|c| c.values.len()).max().unwrap_or(0)
}
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(default)]
pub struct TableSpec {
pub summary: bool,
pub row_numbers: bool,
pub role_tags: bool,
pub bins: usize,
pub row_height: f32,
pub min_column_width: f32,
pub index_width: f32,
pub summary_height: f32,
pub top_values: usize,
pub many_unique: usize,
pub decimals: usize,
pub trim_zeros: bool,
pub missing_text: String,
}
impl Default for TableSpec {
fn default() -> Self {
Self {
summary: true,
row_numbers: true,
role_tags: true,
bins: 24,
row_height: 24.,
min_column_width: 140.,
index_width: 52.,
summary_height: 128.,
top_values: 3,
many_unique: 30,
decimals: 3,
trim_zeros: true,
missing_text: "—".into(),
}
}
}
impl TableSpec {
pub fn format(&self, x: Option<f64>) -> String {
match x {
None => self.missing_text.clone(),
Some(v) if !v.is_finite() => v.to_string(),
Some(v) => {
let s = format!("{v:.*}", self.decimals);
if self.trim_zeros && s.contains('.') {
s.trim_end_matches('0').trim_end_matches('.').to_string()
} else {
s
}
}
}
}
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub enum SummaryStart {
#[default]
Open,
Folded,
Off,
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub enum Selection {
#[default]
None,
Single,
Multiple,
}
#[derive(Debug, Clone, PartialEq)]
pub struct Toolbar {
pub column: usize,
pub all: SharedString,
pub noun: SharedString,
}
impl Toolbar {
pub fn new(column: usize) -> Self {
Self { column, all: "All".into(), noun: "rows".into() }
}
pub fn all(mut self, all: impl Into<SharedString>) -> Self {
self.all = all.into();
self
}
pub fn noun(mut self, noun: impl Into<SharedString>) -> Self {
self.noun = noun.into();
self
}
}
#[derive(Debug, Clone, Default, PartialEq)]
pub struct TableOptions {
pub summary: SummaryStart,
pub selection: Selection,
pub toolbar: Option<Toolbar>,
pub compact: bool,
}
impl TableOptions {
pub fn summary(mut self, start: SummaryStart) -> Self {
self.summary = start;
self
}
pub fn selection(mut self, selection: Selection) -> Self {
self.selection = selection;
self
}
pub fn toolbar(mut self, toolbar: Toolbar) -> Self {
self.toolbar = Some(toolbar);
self
}
pub fn compact(mut self, compact: bool) -> Self {
self.compact = compact;
self
}
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub enum Density {
Compact,
#[default]
Normal,
Comfortable,
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub enum Lines {
#[default]
Stripes,
Grid,
None,
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub enum HeaderStyle {
#[default]
Raised,
Plain,
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub enum BarColor {
#[default]
Row,
Accent,
}
#[derive(Debug, Clone, Copy, Default, PartialEq)]
pub struct TableStyle {
pub density: Density,
pub lines: Lines,
pub header: HeaderStyle,
pub numbers_sans: bool,
pub text_sans: bool,
pub selection: Option<Hsla>,
pub hover: Option<Hsla>,
pub bar: BarColor,
}
impl TableStyle {
pub fn row_height(&self, spec: &TableSpec) -> f32 {
match self.density {
Density::Compact => (spec.row_height - 4.).max(14.),
Density::Normal => spec.row_height,
Density::Comfortable => spec.row_height + 8.,
}
}
fn selection_color(&self) -> Hsla {
self.selection.unwrap_or_else(color::selection)
}
fn hover_color(&self) -> Hsla {
self.hover.unwrap_or_else(color::hover)
}
}
#[derive(Debug, Clone, PartialEq)]
pub enum Shape {
#[allow(missing_docs)]
Histogram { min: f64, max: f64, counts: Vec<usize> },
#[allow(missing_docs)]
Top { values: Vec<(SharedString, usize)>, other: usize, others: usize },
Distinct,
}
#[derive(Debug, Clone, PartialEq)]
pub struct ColumnSummary {
pub rows: usize,
pub missing: usize,
pub unique: usize,
pub shape: Shape,
}
pub trait Summarizer: Send + Sync {
fn histogram(&self, values: &[Option<f64>], bins: usize) -> Option<(f64, f64, Vec<usize>)> {
cpu_histogram(values, bins)
}
fn summarize(&self, data: &TableData, spec: &TableSpec) -> Vec<ColumnSummary> {
data.columns.iter().map(|c| summarize_column(self, &c.values, spec)).collect()
}
}
#[derive(Debug, Clone, Copy, Default)]
pub struct CpuSummarizer;
impl Summarizer for CpuSummarizer {}
pub fn summarize(data: &TableData, spec: &TableSpec) -> Vec<ColumnSummary> {
CpuSummarizer.summarize(data, spec)
}
pub fn cpu_histogram(values: &[Option<f64>], bins: usize) -> Option<(f64, f64, Vec<usize>)> {
let (mut min, mut max, mut any) = (f64::INFINITY, f64::NEG_INFINITY, false);
for &x in values.iter().flatten().filter(|x| x.is_finite()) {
min = min.min(x);
max = max.max(x);
any = true;
}
if !any {
return None;
}
let bins = bins.max(1);
let mut counts = vec![0; bins];
let span = if max > min { max - min } else { 1. };
for &x in values.iter().flatten().filter(|x| x.is_finite()) {
counts[((((x - min) / span) * bins as f64) as usize).min(bins - 1)] += 1;
}
Some((min, max, counts))
}
pub fn summarize_column<S: Summarizer + ?Sized>(by: &S, values: &Values, spec: &TableSpec) -> ColumnSummary {
let rows = values.len();
match values {
Values::Number(v) => {
let present = v.iter().flatten().filter(|x| x.is_finite()).count();
let unique =
v.iter().flatten().filter(|x| x.is_finite()).map(|x| x.to_bits()).collect::<HashSet<_>>().len();
let (min, max, counts) = by.histogram(v, spec.bins).unwrap_or((0., 0., Vec::new()));
ColumnSummary { rows, missing: rows - present, unique, shape: Shape::Histogram { min, max, counts } }
}
Values::Text(v) => {
let mut counts: HashMap<&str, usize> = HashMap::new();
let mut missing = 0;
for x in v {
match x {
Some(s) => *counts.entry(s.as_ref()).or_default() += 1,
None => missing += 1,
}
}
let unique = counts.len();
let shape = if unique > spec.many_unique {
Shape::Distinct
} else {
let mut all: Vec<(&str, usize)> = counts.into_iter().collect();
all.sort_by(|a, b| b.1.cmp(&a.1).then(a.0.cmp(b.0)));
let k = spec.top_values.min(all.len());
let other = all[k..].iter().map(|x| x.1).sum();
let others = all.len() - k;
Shape::Top {
values: all[..k].iter().map(|(s, n)| (SharedString::from(s.to_string()), *n)).collect(),
other,
others,
}
};
ColumnSummary { rows, missing, unique, shape }
}
}
}
pub fn sort_order(data: &TableData, col: usize, ascending: bool) -> Vec<usize> {
let n = data.rows();
let mut order: Vec<usize> = (0..n).collect();
let Some(c) = data.columns.get(col) else { return order };
let flip = |o: std::cmp::Ordering| if ascending { o } else { o.reverse() };
match &c.values {
Values::Number(v) => order.sort_by(|&a, &b| match (v.get(a).copied().flatten(), v.get(b).copied().flatten()) {
(Some(x), Some(y)) => flip(x.total_cmp(&y)),
(Some(_), None) => std::cmp::Ordering::Less,
(None, Some(_)) => std::cmp::Ordering::Greater,
(None, None) => std::cmp::Ordering::Equal,
}),
Values::Text(v) => order.sort_by(|&a, &b| match (v.get(a).cloned().flatten(), v.get(b).cloned().flatten()) {
(Some(x), Some(y)) => flip(x.cmp(&y)),
(Some(_), None) => std::cmp::Ordering::Less,
(None, Some(_)) => std::cmp::Ordering::Greater,
(None, None) => std::cmp::Ordering::Equal,
}),
}
order
}
pub fn view_order(data: &TableData, sort: Option<(usize, bool)>, only: Option<(usize, &str)>) -> Option<Vec<usize>> {
if sort.is_none() && only.is_none() {
return None;
}
let mut rows = match sort {
Some((c, up)) => sort_order(data, c, up),
None => (0..data.rows()).collect(),
};
if let Some((c, value)) = only {
match data.columns.get(c).map(|c| &c.values) {
Some(Values::Text(t)) => rows.retain(|&r| t.get(r).and_then(|x| x.as_ref()).is_some_and(|x| x == value)),
_ => rows.clear(),
}
}
Some(rows)
}
pub fn distinct_text(data: &TableData, col: usize) -> Vec<SharedString> {
match data.columns.get(col).map(|c| &c.values) {
Some(Values::Text(t)) => t.iter().flatten().cloned().collect::<BTreeSet<SharedString>>().into_iter().collect(),
_ => Vec::new(),
}
}
pub fn click_selection(
selected: &BTreeSet<usize>,
anchor: Option<usize>,
order: &[usize],
pos: usize,
mode: Selection,
shift: bool,
toggle: bool,
) -> (BTreeSet<usize>, Option<usize>) {
let Some(&row) = order.get(pos) else { return (selected.clone(), anchor) };
match mode {
Selection::None => (selected.clone(), anchor),
Selection::Single => {
if toggle && selected.contains(&row) {
(BTreeSet::new(), None)
} else {
(BTreeSet::from([row]), Some(row))
}
}
Selection::Multiple => {
if shift && let Some(from) = anchor.and_then(|a| order.iter().position(|&r| r == a)) {
let (lo, hi) = if from <= pos { (from, pos) } else { (pos, from) };
let mut out = if toggle { selected.clone() } else { BTreeSet::new() };
out.extend(order[lo..=hi].iter().copied());
(out, anchor)
} else if toggle {
let mut out = selected.clone();
if !out.remove(&row) {
out.insert(row);
}
(out, Some(row))
} else {
(BTreeSet::from([row]), Some(row))
}
}
}
}
fn bar_range(c: &Column) -> Option<(f64, f64)> {
match (c.bar?, &c.values) {
(BarRange::Fixed(lo, hi), Values::Number(_)) => Some((lo, hi)),
(BarRange::Auto, Values::Number(v)) => {
let finite = v.iter().flatten().copied().filter(|x| x.is_finite());
let (lo, hi) = finite.fold((f64::INFINITY, f64::NEG_INFINITY), |(lo, hi), x| (lo.min(x), hi.max(x)));
(lo <= hi).then(|| (lo.min(0.), hi.max(0.)))
}
_ => None,
}
}
fn bar_fraction(x: f64, (lo, hi): (f64, f64)) -> f32 {
if hi > lo { ((x - lo) / (hi - lo)).clamp(0., 1.) as f32 } else { 1. }
}
fn share(n: usize, of: usize) -> String {
if of == 0 {
return "0%".into();
}
let p = n as f64 / of as f64 * 100.;
if n > 0 && p < 1. { "<1%".into() } else { format!("{p:.0}%") }
}
#[derive(Debug, Clone, PartialEq)]
pub enum TableEvent {
Selected(Option<usize>),
RoleClicked(usize),
RowsSelected(Vec<usize>),
FilterChanged(Option<SharedString>),
}
pub struct TableView {
id: SharedString,
data: Arc<TableData>,
spec: TableSpec,
options: TableOptions,
style: TableStyle,
roles: Vec<Option<SharedString>>,
summaries: Option<Arc<Vec<ColumnSummary>>>,
order: Option<Arc<Vec<usize>>>,
order_gen: u64,
sort: Option<(usize, bool)>,
filter: Option<SharedString>,
filter_values: Vec<SharedString>,
row_colors: Arc<Vec<Option<Hsla>>>,
bar_ranges: Vec<Option<(f64, f64)>>,
selected_rows: BTreeSet<usize>,
anchor: Option<usize>,
selected: Option<usize>,
manual: HashMap<usize, f32>,
scroll: UniformListScrollHandle,
width: Rc<Cell<f32>>,
drag: Option<(usize, f32, f32)>,
summary_task: Option<Task<()>>,
sort_task: Option<Task<()>>,
summarizer: Arc<dyn Summarizer>,
}
impl EventEmitter<TableEvent> for TableView {}
impl TableView {
pub fn new(id: impl Into<SharedString>) -> Self {
Self {
id: id.into(),
data: Arc::new(TableData::default()),
spec: TableSpec::default(),
options: TableOptions::default(),
style: TableStyle::default(),
roles: Vec::new(),
summaries: None,
order: None,
order_gen: 0,
sort: None,
filter: None,
filter_values: Vec::new(),
row_colors: Arc::new(Vec::new()),
bar_ranges: Vec::new(),
selected_rows: BTreeSet::new(),
anchor: None,
selected: None,
manual: HashMap::new(),
scroll: UniformListScrollHandle::new(),
width: Rc::new(Cell::new(0.)),
drag: None,
summary_task: None,
sort_task: None,
summarizer: Arc::new(CpuSummarizer),
}
}
pub fn with_summarizer(mut self, by: Arc<dyn Summarizer>) -> Self {
self.summarizer = by;
self
}
pub fn set_summaries(&mut self, summaries: Arc<Vec<ColumnSummary>>, cx: &mut Context<Self>) {
self.summary_task = None;
self.summaries = Some(summaries);
cx.notify();
}
pub fn with_options(mut self, options: TableOptions) -> Self {
self.spec.summary = options.summary == SummaryStart::Open;
self.options = options;
self
}
pub fn with_style(mut self, style: TableStyle) -> Self {
self.style = style;
self
}
pub fn set_options(&mut self, options: TableOptions, cx: &mut Context<Self>) {
self.spec.summary = options.summary == SummaryStart::Open;
self.options = options;
self.filter = None;
self.filter_values =
self.options.toolbar.as_ref().map(|t| distinct_text(&self.data, t.column)).unwrap_or_default();
if self.summaries.is_none() && self.summary_task.is_none() {
self.resummarize(cx);
}
self.refresh_order(cx);
}
pub fn options(&self) -> &TableOptions {
&self.options
}
pub fn set_style(&mut self, style: TableStyle, cx: &mut Context<Self>) {
self.style = style;
cx.notify();
}
pub fn style(&self) -> &TableStyle {
&self.style
}
pub fn set_row_colors(&mut self, colors: Vec<Option<Hsla>>, cx: &mut Context<Self>) {
self.row_colors = Arc::new(colors);
cx.notify();
}
pub fn selected_rows(&self) -> Vec<usize> {
self.selected_rows.iter().copied().collect()
}
pub fn set_selected_rows(&mut self, rows: impl IntoIterator<Item = usize>, cx: &mut Context<Self>) {
self.selected_rows = rows.into_iter().collect();
self.anchor = self.selected_rows.first().copied();
cx.notify();
}
pub fn filter(&self) -> Option<&SharedString> {
self.filter.as_ref()
}
pub fn set_filter(&mut self, value: Option<SharedString>, cx: &mut Context<Self>) {
self.filter = value;
self.refresh_order(cx);
}
pub fn filter_values(&self) -> &[SharedString] {
&self.filter_values
}
pub fn shown_rows(&self) -> Vec<usize> {
match &self.order {
Some(o) => o.as_ref().clone(),
None => (0..self.data.rows()).collect(),
}
}
pub fn click_row(&mut self, pos: usize, shift: bool, toggle: bool, cx: &mut Context<Self>) {
if self.options.selection == Selection::None {
return;
}
let order = self.shown_rows();
let (rows, anchor) =
click_selection(&self.selected_rows, self.anchor, &order, pos, self.options.selection, shift, toggle);
self.selected_rows = rows;
self.anchor = anchor;
cx.emit(TableEvent::RowsSelected(self.selected_rows()));
cx.notify();
}
fn pick_filter(&mut self, i: usize, cx: &mut Context<Self>) {
let value = i.checked_sub(1).and_then(|k| self.filter_values.get(k).cloned());
if value != self.filter {
self.set_filter(value.clone(), cx);
cx.emit(TableEvent::FilterChanged(value));
}
}
pub fn set_data(&mut self, data: Arc<TableData>, cx: &mut Context<Self>) {
if !Arc::ptr_eq(&self.data, &data) {
self.data = data;
self.sort = None;
self.order = None;
self.selected = None;
self.selected_rows.clear();
self.anchor = None;
self.manual.clear();
self.roles.clear();
self.bar_ranges = self.data.columns.iter().map(bar_range).collect();
self.filter_values =
self.options.toolbar.as_ref().map(|t| distinct_text(&self.data, t.column)).unwrap_or_default();
if self.filter.as_ref().is_some_and(|f| !self.filter_values.contains(f)) {
self.filter = None;
}
self.resummarize(cx);
self.refresh_order(cx);
}
cx.notify();
}
pub fn data(&self) -> &Arc<TableData> {
&self.data
}
pub fn set_spec(&mut self, spec: TableSpec, cx: &mut Context<Self>) {
let again = spec.bins != self.spec.bins
|| spec.top_values != self.spec.top_values
|| spec.many_unique != self.spec.many_unique;
self.spec = spec;
if again {
self.resummarize(cx);
}
cx.notify();
}
pub fn spec(&self) -> &TableSpec {
&self.spec
}
pub fn set_roles(&mut self, roles: Vec<Option<SharedString>>, cx: &mut Context<Self>) {
self.roles = roles;
cx.notify();
}
pub fn toggle_summary(&mut self, cx: &mut Context<Self>) {
if self.options.summary != SummaryStart::Off {
self.spec.summary = !self.spec.summary;
}
cx.notify();
}
pub fn selected(&self) -> Option<usize> {
self.selected
}
pub fn select(&mut self, col: Option<usize>, cx: &mut Context<Self>) {
self.selected = col;
cx.emit(TableEvent::Selected(col));
cx.notify();
}
pub fn summaries(&self) -> Option<&Arc<Vec<ColumnSummary>>> {
self.summaries.as_ref()
}
fn resummarize(&mut self, cx: &mut Context<Self>) {
self.summaries = None;
if self.options.summary == SummaryStart::Off || self.options.compact {
self.summary_task = None;
return;
}
let (data, spec, by) = (self.data.clone(), self.spec.clone(), self.summarizer.clone());
let work = cx.background_executor().spawn(async move { by.summarize(&data, &spec) });
self.summary_task = Some(cx.spawn(async move |this, cx| {
let done = work.await;
let _ = this.update(cx, |t, cx| {
t.summaries = Some(Arc::new(done));
cx.notify();
});
}));
}
fn cycle_sort(&mut self, col: usize, cx: &mut Context<Self>) {
self.sort = match self.sort {
Some((c, true)) if c == col => Some((col, false)),
Some((c, false)) if c == col => None,
_ => Some((col, true)),
};
self.refresh_order(cx);
}
fn refresh_order(&mut self, cx: &mut Context<Self>) {
self.order_gen += 1;
let generation = self.order_gen;
let only = self.filter.clone().zip(self.options.toolbar.as_ref().map(|t| t.column));
if self.sort.is_none() && only.is_none() {
self.order = None;
self.sort_task = None;
cx.notify();
return;
}
let (data, sort) = (self.data.clone(), self.sort);
let work = cx
.background_executor()
.spawn(async move { view_order(&data, sort, only.as_ref().map(|(v, c)| (*c, v.as_ref()))) });
self.sort_task = Some(cx.spawn(async move |this, cx| {
let order = work.await;
let _ = this.update(cx, |t, cx| {
if t.order_gen == generation {
t.order = order.map(Arc::new);
cx.notify();
}
});
}));
cx.notify();
}
fn row_numbers(&self) -> bool {
self.spec.row_numbers && !self.options.compact
}
fn mark_width(&self) -> f32 {
if self.row_colors.iter().any(Option::is_some) { MARK_W } else { 0. }
}
fn widths(&self) -> Vec<f32> {
let n = self.data.columns.len();
let index = if self.row_numbers() { self.spec.index_width } else { 0. };
let lead = index + self.mark_width();
let min = if self.options.compact && n > 0 {
((self.width.get() - lead) / n as f32).clamp(24., self.spec.min_column_width)
} else {
self.spec.min_column_width
};
let base: Vec<f32> = (0..n).map(|j| self.manual.get(&j).copied().unwrap_or(min)).collect();
let free = self.width.get() - lead - base.iter().sum::<f32>();
let auto = (0..n).filter(|j| !self.manual.contains_key(j)).count();
base.iter()
.enumerate()
.map(
|(j, &w)| {
if free > 0. && auto > 0 && !self.manual.contains_key(&j) { w + free / auto as f32 } else { w }
},
)
.collect()
}
fn data_color() -> Hsla {
if theme::is_dark() { theme::data(4) } else { theme::data(0) }
}
fn header(&self, widths: &[f32], cx: &mut Context<Self>) -> impl IntoElement + use<> {
let plain = self.style.header == HeaderStyle::Plain;
let mark = self.mark_spacer(32.);
let index = self.row_numbers().then(|| {
div()
.flex_none()
.w(px(self.spec.index_width))
.h(px(32.))
.px(px(theme::SM))
.flex()
.items_center()
.justify_end()
.text_xs()
.font_family(fonts::MONO)
.text_color(color::text_muted())
.border_r_1()
.border_color(color::border())
.child("#")
});
let cells = self.data.columns.iter().enumerate().map(|(j, c)| {
let mark = if c.values.is_number() { "#" } else { "Aa" };
let sort = match self.sort {
Some((s, true)) if s == j => Some(IconName::ChevronUp),
Some((s, false)) if s == j => Some(IconName::ChevronDown),
_ => None,
};
let role = if self.spec.role_tags { self.roles.get(j).cloned().flatten() } else { None };
let tip: SharedString = format!(
"{}{} · {}{}",
c.name,
c.unit.as_ref().map(|u| format!(" ({u})")).unwrap_or_default(),
if c.values.is_number() { "numbers" } else { "text" },
role.as_ref().map(|r| format!(" · {r}")).unwrap_or_default()
)
.into();
h_flex()
.id((SharedString::from(format!("{}-head", self.id)), j))
.relative()
.flex_none()
.w(px(widths[j]))
.h(px(32.))
.px(px(theme::SM))
.gap(px(theme::XS))
.items_center()
.border_r_1()
.border_color(color::border())
.cursor_pointer()
.hover(|d| d.bg(color::hover()))
.when(self.selected == Some(j), |d| {
d.bg(color::selection()).border_t_2().border_color(color::selection_edge())
})
.tooltip(move |window, cx| Tooltip::new(tip.clone()).build(window, cx))
.on_click(cx.listener(move |this, _, _, cx| {
if this.drag.is_none() {
this.cycle_sort(j, cx)
}
}))
.child(
div()
.flex_none()
.w(px(16.))
.text_xs()
.font_family(fonts::MONO)
.font_weight(FontWeight::SEMIBOLD)
.text_color(color::text_muted())
.child(mark),
)
.child(
div()
.flex_1()
.min_w_0()
.truncate()
.text_sm()
.font_weight(if plain { FontWeight::NORMAL } else { FontWeight::SEMIBOLD })
.text_color(if plain { color::text_muted() } else { color::text() })
.child(c.name.clone()),
)
.children(c.unit.clone().map(|u| {
div().min_w_0().max_w(relative(0.4)).truncate().text_xs().text_color(color::text_muted()).child(u)
}))
.children(sort.map(|i| Icon::new(i).xsmall().text_color(color::accent_mark())))
.children(role.map(|r| {
let on = r.as_ref() != "Other";
div()
.id((SharedString::from(format!("{}-role", self.id)), j))
.flex_none()
.max_w(px(72.))
.truncate()
.px(px(theme::XS))
.rounded(px(theme::RADIUS_SM))
.border_1()
.border_color(if on { color::accent_mark() } else { color::border() })
.text_xs()
.text_color(if on { color::accent_mark() } else { color::text_muted() })
.child(r)
.on_click(cx.listener(move |_, _, _, cx| {
cx.stop_propagation();
cx.emit(TableEvent::RoleClicked(j));
}))
}))
.child(div().absolute().top_0().bottom_0().right(px(-3.)).w(px(6.)).cursor_col_resize().on_mouse_down(
MouseButton::Left,
cx.listener(move |this, e: &MouseDownEvent, _, cx| {
cx.stop_propagation();
if e.click_count >= 2 {
this.manual.remove(&j);
this.drag = None;
} else {
let w = this.widths()[j];
this.drag = Some((j, e.position.x.as_f32(), w));
}
cx.notify();
}),
))
});
h_flex().flex_none().children(index).children(mark).children(cells.collect::<Vec<_>>())
}
fn mark_spacer(&self, h: f32) -> Option<impl IntoElement + use<>> {
let w = self.mark_width();
(w > 0.).then(|| div().flex_none().w(px(w)).h(px(h)))
}
fn fold_bar(&self, cx: &mut Context<Self>) -> impl IntoElement + use<> {
let n = self.data.columns.len();
h_flex()
.id(SharedString::from(format!("{}-fold", self.id)))
.flex_none()
.w_full()
.h(px(24.))
.px(px(theme::SM))
.gap(px(theme::XS))
.items_center()
.bg(color::raised())
.border_t_1()
.border_color(color::border())
.cursor_pointer()
.text_xs()
.text_color(color::text_muted())
.hover(|d| d.text_color(color::text()))
.on_click(cx.listener(|this, _, _, cx| this.toggle_summary(cx)))
.child(Icon::new(if self.spec.summary { IconName::ChevronDown } else { IconName::ChevronRight }).xsmall())
.child(div().truncate().child(if self.spec.summary {
"SUMMARY".to_string()
} else if self.summaries.is_none() {
"SUMMARY · computing".to_string()
} else {
format!("SUMMARY · {n} columns")
}))
}
fn summary_row(&self, widths: &[f32], cx: &mut Context<Self>) -> impl IntoElement + use<> {
let h = self.spec.summary_height;
let mark = self.mark_spacer(h);
let index = self.row_numbers().then(|| {
div()
.flex_none()
.w(px(self.spec.index_width))
.h(px(h))
.border_r_1()
.border_t_1()
.border_color(color::border())
});
let sums = self.summaries.clone();
let cells = self.data.columns.iter().enumerate().map(|(j, c)| {
let body: AnyElement = match sums.as_ref().and_then(|s| s.get(j)) {
None => div().text_color(color::text_muted()).child("Computing…").into_any_element(),
Some(s) => self.summary_body(c, s).into_any_element(),
};
v_flex()
.id((SharedString::from(format!("{}-sum", self.id)), j))
.flex_none()
.w(px(widths[j]))
.h(px(h))
.p(px(theme::SM))
.gap(px(theme::XS))
.overflow_hidden()
.text_xs()
.border_r_1()
.border_t_1()
.border_color(color::border())
.cursor_pointer()
.when(self.selected == Some(j), |d| d.bg(color::selection()))
.on_click(cx.listener(move |this, _, _, cx| {
let next = if this.selected == Some(j) { None } else { Some(j) };
this.select(next, cx);
}))
.child(body)
});
h_flex().flex_none().children(index).children(mark).children(cells.collect::<Vec<_>>())
}
fn summary_body(&self, c: &Column, s: &ColumnSummary) -> impl IntoElement + use<> {
let kv = |label: &'static str, value: String, warn: bool| {
h_flex()
.w_full()
.gap(px(theme::SM))
.child(div().flex_none().max_w(relative(0.4)).truncate().text_color(color::text_muted()).child(label))
.child(
div().flex_1().min_w_0().flex().justify_end().child(
div()
.min_w_0()
.truncate()
.font_family(fonts::MONO)
.text_color(if warn { color::danger() } else { color::text() })
.child(value),
),
)
};
let head = v_flex()
.flex_none()
.gap(px(2.))
.child(kv("Missing", format!("{} · {}", s.missing, share(s.missing, s.rows)), s.missing > 0))
.child(kv("Unique", format!("{} · {}", s.unique, share(s.unique, s.rows)), false));
let data = Self::data_color();
let shape: AnyElement = match &s.shape {
Shape::Histogram { min, max, counts } => {
let top = counts.iter().copied().max().unwrap_or(0).max(1) as f32;
let unit = c.unit.as_ref().map(|u| format!(" {u}")).unwrap_or_default();
v_flex()
.flex_1()
.min_h_0()
.gap(px(2.))
.child(
h_flex()
.flex_1()
.min_h(px(16.))
.items_end()
.gap(px(1.))
.border_b_1()
.border_color(color::border())
.children(
counts.iter().map(|&n| {
div().flex_1().min_w_0().h(relative(n as f32 / top)).min_h(px(1.)).bg(data)
}),
),
)
.child(
h_flex()
.flex_none()
.justify_between()
.gap(px(theme::SM))
.font_family(fonts::MONO)
.text_color(color::text_muted())
.child(div().min_w_0().truncate().child(format!("{}{unit}", self.spec.format(Some(*min)))))
.child(div().min_w_0().truncate().child(format!("{}{unit}", self.spec.format(Some(*max))))),
)
.into_any_element()
}
Shape::Distinct => h_flex()
.flex_1()
.justify_center()
.items_center()
.gap(px(theme::XS))
.child(
div()
.font_family(fonts::MONO)
.text_base()
.font_weight(FontWeight::SEMIBOLD)
.text_color(data)
.child(s.unique.to_string()),
)
.child(div().text_color(color::text_muted()).child("distinct"))
.into_any_element(),
Shape::Top { values, other, others } => {
let most = values.first().map(|v| v.1).unwrap_or(1).max(1) as f32;
let line = |label: SharedString, n: usize, frac: f32| {
div()
.relative()
.w_full()
.h(px(16.))
.rounded(px(theme::RADIUS_SM))
.overflow_hidden()
.child(
div()
.absolute()
.top_0()
.bottom_0()
.left_0()
.w(relative(frac.clamp(0., 1.)))
.bg(data.opacity(0.22)),
)
.child(
h_flex()
.relative()
.px(px(theme::XS))
.gap(px(theme::SM))
.child(div().flex_1().min_w_0().truncate().text_color(color::text()).child(label))
.child(
div()
.flex_none()
.font_family(fonts::MONO)
.text_color(color::text_muted())
.child(share(n, s.rows)),
),
)
};
v_flex()
.flex_1()
.min_h_0()
.gap(px(2.))
.children(values.iter().map(|(v, n)| line(v.clone(), *n, *n as f32 / most)))
.when(*other > 0, |d| {
d.child(line(format!("Other ({others})").into(), *other, *other as f32 / s.rows.max(1) as f32))
})
.into_any_element()
}
};
v_flex().size_full().gap(px(theme::XS)).child(head).child(shape)
}
fn rows(&mut self, range: std::ops::Range<usize>, _: &mut Window, cx: &mut Context<Self>) -> Vec<AnyElement> {
let widths = self.widths();
let style = self.style;
let rh = style.row_height(&self.spec);
let index_w = self.row_numbers().then_some(self.spec.index_width);
let mark_w = self.mark_width();
let row_w = widths.iter().sum::<f32>() + index_w.unwrap_or(0.) + mark_w;
let data = self.data.clone();
let order = self.order.clone();
let colors = self.row_colors.clone();
let clickable = self.options.selection != Selection::None;
let grid = style.lines == Lines::Grid;
range
.map(|i| {
let r = order.as_ref().and_then(|o| o.get(i).copied()).unwrap_or(i);
let row_color = colors.get(r).copied().flatten();
let selected = self.selected_rows.contains(&r);
let cells = data.columns.iter().enumerate().map(|(j, c)| {
let (text, missing, x) = match &c.values {
Values::Number(v) => {
let x = v.get(r).copied().flatten();
(self.spec.format(x), x.is_none(), x)
}
Values::Text(v) => match v.get(r).cloned().flatten() {
Some(s) => (s.to_string(), false, None),
None => (self.spec.missing_text.clone(), true, None),
},
};
let mono = if c.values.is_number() { !style.numbers_sans } else { !style.text_sans };
let bar = self.bar_ranges.get(j).copied().flatten().zip(x).map(|(range, x)| {
let fill = match style.bar {
BarColor::Row => row_color.unwrap_or_else(color::accent),
BarColor::Accent => color::accent(),
};
div()
.absolute()
.left(px(theme::XS))
.top(px(3.))
.bottom(px(3.))
.w(relative(bar_fraction(x, range) * 0.94))
.rounded(px(theme::RADIUS_SM))
.bg(fill.opacity(0.38))
});
div()
.relative()
.flex_none()
.w(px(widths[j]))
.h_full()
.px(px(theme::SM))
.flex()
.items_center()
.when(mono, |d| d.font_family(fonts::MONO))
.when(c.values.is_number(), |d| d.justify_end())
.when(self.selected == Some(j) && !selected, |d| d.bg(color::selection()))
.when(grid, |d| d.border_r_1().border_color(color::grid()))
.children(bar)
.child(
div()
.relative()
.min_w_0()
.truncate()
.text_color(if missing { color::text_muted() } else { color::text() })
.child(text),
)
});
let hover = style.hover_color();
h_flex()
.id(SharedString::from(format!("{}-row-{i}", self.id)))
.w(px(row_w))
.flex_none()
.h(px(rh))
.text_sm()
.when(style.lines == Lines::Stripes && i % 2 == 1 && !selected, |d| {
d.bg(color::raised().opacity(0.55))
})
.when(grid, |d| d.border_b_1().border_color(color::grid()))
.when(selected, |d| d.bg(style.selection_color()))
.when(!selected, |d| d.hover(move |d| d.bg(hover)))
.when(clickable, |d| {
d.cursor_pointer().on_click(cx.listener(move |this, e: &ClickEvent, _, cx| {
let m = e.modifiers();
this.click_row(i, m.shift, m.control || m.platform, cx);
}))
})
.children(index_w.map(|w| {
div()
.flex_none()
.w(px(w))
.h_full()
.px(px(theme::SM))
.flex()
.items_center()
.justify_end()
.font_family(fonts::MONO)
.text_color(color::text_muted())
.child(div().truncate().child((r + 1).to_string()))
}))
.when(mark_w > 0., |d| {
d.child(
div()
.flex_none()
.w(px(mark_w))
.h_full()
.flex()
.items_center()
.justify_center()
.children(row_color.map(|c| div().size(px(8.)).rounded_full().bg(c))),
)
})
.children(cells.collect::<Vec<_>>())
.test_support()
.into_any_element()
})
.collect()
}
fn toolbar(&self, cx: &mut Context<Self>) -> Option<impl IntoElement + use<>> {
let bar = self.options.toolbar.as_ref()?;
let mut options: Vec<SharedString> = vec![bar.all.clone()];
options.extend(self.filter_values.iter().cloned());
let current = match &self.filter {
Some(f) => self.filter_values.iter().position(|v| v == f).map(|k| k + 1),
None => Some(0),
};
let this = cx.entity().downgrade();
let menu =
MenuSelect::new(SharedString::from(format!("{}-filter", self.id)), options, current, move |i, _, cx| {
let _ = this.update(cx, |t, cx| t.pick_filter(i, cx));
});
let shown = self.order.as_ref().map(|o| o.len()).unwrap_or_else(|| self.data.rows());
let mut counts = format!("{shown} {}", bar.noun);
if self.options.selection != Selection::None && !self.selected_rows.is_empty() {
counts.push_str(&format!(" · {} selected", self.selected_rows.len()));
}
Some(
h_flex()
.id(SharedString::from(format!("{}-toolbar", self.id)))
.flex_none()
.w_full()
.h(px(TOOLBAR_H))
.px(px(theme::SM))
.gap(px(theme::SM))
.items_center()
.bg(color::raised())
.border_b_1()
.border_color(color::border())
.child(div().w(px(168.)).flex_none().child(menu))
.child(div().flex_1())
.child(
div()
.min_w_0()
.truncate()
.text_xs()
.text_color(color::text_muted())
.child(SharedString::from(counts)),
),
)
}
}
impl Render for TableView {
fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
let widths = self.widths();
let lead = if self.row_numbers() { self.spec.index_width } else { 0. } + self.mark_width();
let total = widths.iter().sum::<f32>() + lead;
let spare = (total - self.width.get()).max(0.);
let dx = self.scroll.0.borrow().base_handle.offset().x.as_f32().clamp(-spare, 0.);
let rows = self.order.as_ref().map(|o| o.len()).unwrap_or_else(|| self.data.rows());
let toolbar = self.toolbar(cx);
let has_summary = self.options.summary != SummaryStart::Off;
let top = (!self.options.compact).then(|| {
let header = self.header(&widths, cx);
let summary = (has_summary && self.spec.summary).then(|| self.summary_row(&widths, cx));
let fold = has_summary.then(|| self.fold_bar(cx));
div()
.flex_none()
.w_full()
.overflow_hidden()
.when(self.style.header == HeaderStyle::Raised, |d| d.bg(color::raised()))
.border_b_1()
.border_color(color::border())
.child(
v_flex()
.w(px(total.max(self.width.get())))
.ml(px(dx))
.child(header)
.children(fold)
.children(summary),
)
});
let list = uniform_list(SharedString::from(format!("{}-rows", self.id)), rows, cx.processor(Self::rows))
.with_horizontal_sizing_behavior(ListHorizontalSizingBehavior::Unconstrained)
.track_scroll(&self.scroll)
.flex_1()
.min_h_0()
.w_full();
let seen = self.width.clone();
let entity = cx.entity().downgrade();
let measure = canvas(
move |bounds, _, cx| {
let w = bounds.size.width.as_f32();
if (seen.get() - w).abs() > 0.5 {
seen.set(w);
let _ = entity.update(cx, |_, cx| cx.notify());
}
},
|_, _, _, _| {},
)
.absolute()
.top_0()
.left_0()
.size_full();
v_flex()
.id(SharedString::from(format!("{}-table", self.id)))
.relative()
.size_full()
.min_h_0()
.overflow_hidden()
.bg(color::canvas())
.border_1()
.border_color(color::border())
.rounded(px(theme::RADIUS_LG))
.on_mouse_move(cx.listener(|this, e: &MouseMoveEvent, _, cx| {
if let Some((j, x0, w0)) = this.drag {
this.manual.insert(j, (w0 + e.position.x.as_f32() - x0).max(64.));
cx.notify();
}
}))
.on_mouse_up(
MouseButton::Left,
cx.listener(|this, _: &MouseUpEvent, _, cx| {
if this.drag.take().is_some() {
cx.notify();
}
}),
)
.child(measure)
.children(toolbar)
.children(top)
.child(list)
}
}
pub fn table(id: impl Into<SharedString>, data: Arc<TableData>, cx: &mut App) -> gpui_kit::Entity<TableView> {
use gpui_kit::AppContext as _;
cx.new(|cx| {
let mut t = TableView::new(id);
t.set_data(data, cx);
t
})
}
#[cfg(feature = "kitchen-table")]
impl TableData {
pub fn from_table(name: impl Into<SharedString>, table: &kitchen_table::Table) -> Self {
let columns = table
.names()
.into_iter()
.map(|n| {
let meta = table.meta(&n);
let column = if table.is_numeric(&n) {
Column::numbers(n.clone(), table.values(&n).unwrap_or_default())
} else {
let text = table.text(&n).unwrap_or_default();
Column::text(n.clone(), text.into_iter().map(|t| t.map(SharedString::from)).collect())
};
match meta.unit {
Some(u) => column.unit(u),
None => column,
}
})
.collect();
Self::new(name, columns)
}
pub fn roles_of(table: &kitchen_table::Table) -> Vec<Option<SharedString>> {
use kitchen_table::Role;
table
.names()
.iter()
.map(|n| {
Some(SharedString::from(match table.meta(n).role {
Role::Measure => "Measure",
Role::Group => "Group",
Role::Id => "Id",
Role::Other => "Other",
}))
})
.collect()
}
}
#[cfg(test)]
mod tests {
use super::*;
#[cfg(feature = "kitchen-table")]
#[test]
fn a_kitchen_table_table_becomes_plain_columns() {
use kitchen_table::{ColumnData, ColumnMeta, Role, Table};
let t = Table::from_columns(vec![
("label", ColumnData::OptText(vec![Some("good".into()), None])),
("rate", ColumnData::F64(vec![4.0, f64::NAN])),
])
.unwrap()
.with_meta("rate", ColumnMeta::role(Role::Measure).unit("Hz"))
.unwrap();
let d = TableData::from_table("units", &t);
assert_eq!(d.rows(), 2);
assert_eq!(d.columns[0].values, Values::Text(vec![Some("good".into()), None]));
assert_eq!(d.columns[1].values, Values::Number(vec![Some(4.0), None]));
assert_eq!(d.columns[1].unit.as_ref().map(|u| u.as_ref()), Some("Hz"));
assert_eq!(TableData::roles_of(&t), vec![Some("Other".into()), Some("Measure".into())]);
}
#[test]
fn view_order_sorts_and_filters_and_clicks_select() {
let t = iris_like();
assert_eq!(view_order(&t, None, None), None);
assert_eq!(view_order(&t, None, Some((1, "a"))), Some(vec![0, 2, 4]));
assert_eq!(view_order(&t, Some((0, false)), Some((1, "a"))), Some(vec![4, 0, 2]));
assert_eq!(view_order(&t, None, Some((0, "a"))), Some(vec![]));
assert_eq!(distinct_text(&t, 1), vec![SharedString::from("a"), "b".into(), "c".into()]);
assert!(distinct_text(&t, 0).is_empty());
let order = [4, 0, 2];
let none = BTreeSet::new();
let (s, a) = click_selection(&none, None, &order, 1, Selection::Single, false, false);
assert_eq!((s.iter().copied().collect::<Vec<_>>(), a), (vec![0], Some(0)));
assert!(click_selection(&s, a, &order, 1, Selection::Single, false, true).0.is_empty());
let (s, a) = click_selection(&none, None, &order, 0, Selection::Multiple, false, false);
let (s, a) = click_selection(&s, a, &order, 2, Selection::Multiple, true, false);
assert_eq!(s.iter().copied().collect::<Vec<_>>(), vec![0, 2, 4]);
let (s, a) = click_selection(&s, a, &order, 1, Selection::Multiple, false, true);
assert_eq!(s.iter().copied().collect::<Vec<_>>(), vec![2, 4]);
let (s, _) = click_selection(&s, a, &order, 1, Selection::Multiple, false, true);
assert_eq!(s.len(), 3);
assert_eq!(click_selection(&s, a, &order, 9, Selection::Multiple, false, false).0, s);
assert!(click_selection(&none, None, &order, 0, Selection::None, false, false).0.is_empty());
}
#[test]
fn bars_span_their_range_and_styles_set_row_heights() {
let c = Column::numbers("s", vec![Some(0.5), Some(1.0), None]).bar();
assert_eq!(bar_range(&c), Some((0., 1.)));
assert_eq!(bar_range(&Column::numbers("s", vec![Some(-2.), Some(-1.)]).bar()), Some((-2., 0.)));
assert_eq!(bar_range(&c.clone().bar_range(0., 2.)), Some((0., 2.)));
assert_eq!(bar_range(&Column::numbers("s", vec![None]).bar()), None);
assert_eq!(bar_range(&Column::numbers("s", vec![Some(1.)])), None);
assert_eq!(bar_fraction(0.5, (0., 1.)), 0.5);
assert_eq!(bar_fraction(3., (0., 1.)), 1.);
assert_eq!(bar_fraction(3., (3., 3.)), 1.);
let spec = TableSpec::default();
let rows = |density| TableStyle { density, ..TableStyle::default() }.row_height(&spec);
assert_eq!((rows(Density::Compact), rows(Density::Normal), rows(Density::Comfortable)), (20., 24., 32.));
assert_eq!(TableOptions::default().summary, SummaryStart::Open);
let t = Toolbar::new(2).all("All labels").noun("units");
assert_eq!((t.column, t.all.as_ref(), t.noun.as_ref()), (2, "All labels", "units"));
}
fn iris_like() -> TableData {
TableData::new(
"t",
vec![
Column::numbers("x", vec![Some(1.), Some(2.), None, Some(4.), Some(4.)]).unit("cm"),
Column::text("g", ["a", "b", "a", "c", "a"].iter().map(|s| Some(SharedString::from(*s))).collect()),
],
)
}
#[test]
fn summaries_count_missing_unique_bins_and_top_values() {
let spec = TableSpec { bins: 3, top_values: 2, ..TableSpec::default() };
let s = summarize(&iris_like(), &spec);
assert_eq!((s[0].rows, s[0].missing, s[0].unique), (5, 1, 3));
assert_eq!(s[0].shape, Shape::Histogram { min: 1., max: 4., counts: vec![1, 1, 2] });
assert_eq!((s[1].missing, s[1].unique), (0, 3));
match &s[1].shape {
Shape::Top { values, other, others } => {
assert_eq!(values[0], ("a".into(), 3));
assert_eq!((values.len(), *other, *others), (2, 1, 1));
}
other => panic!("{other:?}"),
}
struct Fixed;
impl Summarizer for Fixed {
fn histogram(&self, _: &[Option<f64>], _: usize) -> Option<(f64, f64, Vec<usize>)> {
Some((0., 9., vec![7]))
}
}
assert_eq!(
Fixed.summarize(&iris_like(), &spec)[0].shape,
Shape::Histogram { min: 0., max: 9., counts: vec![7] }
);
assert_eq!(Fixed.summarize(&iris_like(), &spec)[0].missing, 1);
let many = TableSpec { many_unique: 2, ..spec };
assert_eq!(summarize(&iris_like(), &many)[1].shape, Shape::Distinct);
}
#[test]
fn sorting_puts_missing_last_both_ways() {
let t = iris_like();
assert_eq!(sort_order(&t, 0, true), vec![0, 1, 3, 4, 2]);
assert_eq!(sort_order(&t, 0, false), vec![3, 4, 1, 0, 2]);
assert_eq!(sort_order(&t, 1, true), vec![0, 2, 4, 1, 3]);
}
#[test]
fn numbers_format_with_trimmed_zeros_and_the_spec_round_trips() {
let s = TableSpec::default();
assert_eq!(s.format(Some(1.5)), "1.5");
assert_eq!(s.format(Some(2.0)), "2");
assert_eq!(s.format(None), "—");
assert_eq!(share(1, 1000), "<1%");
let json = serde_json::to_string(&s).unwrap();
assert_eq!(serde_json::from_str::<TableSpec>(&json).unwrap(), s);
let partial: TableSpec = serde_json::from_str(r#"{"bins": 10}"#).unwrap();
assert_eq!(partial.bins, 10);
assert!(partial.summary);
}
}