use super::{child_id, text};
use crate::{Button, ButtonSize, ButtonVariant};
use arc_motion::{ArcPresence, arc_spring_with_options, spring::SpringOptions};
use arc_tokens::{ActiveArcTheme as _, BlockTokens, Radii, Spacing, Typography, oklab_mix};
use gpui_kit::{
App, Bounds, ElementId, IntoElement, ParentElement, Pixels, RenderOnce, Role, SharedString,
Styled, TestSupportExt as _, Window, base::StyledExt as _, canvas, div, point, prelude::*, px,
};
use std::{cell::Cell, rc::Rc};
#[derive(Clone, Debug, PartialEq)]
pub enum ComparisonValue {
Bool(bool),
Partial,
PartialWith(SharedString),
Text(SharedString),
}
impl ComparisonValue {
pub fn partial(note: impl Into<SharedString>) -> Self {
Self::PartialWith(note.into())
}
pub fn note(&self) -> Option<&SharedString> {
match self {
Self::PartialWith(note) => Some(note),
_ => None,
}
}
}
impl From<bool> for ComparisonValue {
fn from(v: bool) -> Self {
Self::Bool(v)
}
}
#[derive(Clone, Debug)]
pub struct ComparisonColumn {
pub id: SharedString,
pub name: SharedString,
pub caption: Option<SharedString>,
pub highlight: bool,
}
#[derive(Clone, Debug)]
pub struct ComparisonRow {
pub id: SharedString,
pub feature: SharedString,
pub hint: Option<SharedString>,
pub values: Vec<ComparisonValue>,
}
#[derive(Clone, Debug)]
pub struct ComparisonSection {
pub id: SharedString,
pub title: SharedString,
pub rows: Vec<ComparisonRow>,
}
type Change = Rc<dyn Fn(bool, &mut Window, &mut App)>;
type CompareChange = Rc<dyn Fn(&SharedString, &mut Window, &mut App)>;
type Action = Rc<dyn Fn(&mut Window, &mut App)>;
struct State {
differences: bool,
compare: Option<SharedString>,
done: bool,
width: Rc<Cell<f32>>,
}
#[derive(IntoElement)]
pub struct ComparisonTable {
id: ElementId,
title: SharedString,
description: Option<SharedString>,
columns: Vec<ComparisonColumn>,
sections: Vec<ComparisonSection>,
differences_only: Option<bool>,
default_differences_only: bool,
on_differences_change: Option<Change>,
max_height: Option<f32>,
compare_with: Option<SharedString>,
on_compare_change: Option<CompareChange>,
stack_below: f32,
sticky_top: f32,
cta: Option<(SharedString, Option<SharedString>, Action)>,
}
impl ComparisonTable {
pub fn new(id: impl Into<ElementId>) -> Self {
Self {
id: id.into(),
title: "How Relay compares".into(),
description: Some(
"Everything a growing team needs, without spreadsheet sprawl.".into(),
),
columns: vec![],
sections: vec![],
differences_only: None,
default_differences_only: false,
on_differences_change: None,
max_height: None,
compare_with: None,
on_compare_change: None,
stack_below: BlockTokens::STACK_BELOW,
sticky_top: 0.0,
cta: None,
}
}
pub fn title(mut self, v: impl Into<SharedString>) -> Self {
self.title = v.into();
self
}
pub fn description(mut self, v: impl Into<SharedString>) -> Self {
self.description = Some(v.into());
self
}
pub fn columns(mut self, v: impl IntoIterator<Item = ComparisonColumn>) -> Self {
self.columns = v.into_iter().collect();
self
}
pub fn sections(mut self, v: impl IntoIterator<Item = ComparisonSection>) -> Self {
self.sections = v.into_iter().collect();
self
}
pub fn differences_only(mut self, v: bool) -> Self {
self.differences_only = Some(v);
self
}
pub fn default_differences_only(mut self, v: bool) -> Self {
self.default_differences_only = v;
self
}
pub fn max_height(mut self, v: f32) -> Self {
self.max_height = Some(v.max(0.0));
self
}
pub fn stack_below(mut self, v: f32) -> Self {
self.stack_below = v.max(0.0);
self
}
pub fn sticky_top(mut self, v: f32) -> Self {
self.sticky_top = v.max(0.0);
self
}
pub fn compare_with(mut self, v: impl Into<SharedString>) -> Self {
self.compare_with = Some(v.into());
self
}
pub fn on_compare_change(
mut self,
f: impl Fn(&SharedString, &mut Window, &mut App) + 'static,
) -> Self {
self.on_compare_change = Some(Rc::new(f));
self
}
pub fn on_differences_change(
mut self,
f: impl Fn(bool, &mut Window, &mut App) + 'static,
) -> Self {
self.on_differences_change = Some(Rc::new(f));
self
}
pub fn cta(
mut self,
label: impl Into<SharedString>,
done_label: Option<SharedString>,
f: impl Fn(&mut Window, &mut App) + 'static,
) -> Self {
self.cta = Some((label.into(), done_label, Rc::new(f)));
self
}
}
fn value_text(value: &ComparisonValue) -> SharedString {
match value {
ComparisonValue::Bool(true) => "✓".into(),
ComparisonValue::Bool(false) => "—".into(),
ComparisonValue::Partial | ComparisonValue::PartialWith(_) => "◐".into(),
ComparisonValue::Text(v) => v.clone(),
}
}
fn value_label(value: &ComparisonValue) -> SharedString {
match value {
ComparisonValue::Bool(true) => "Included".into(),
ComparisonValue::Bool(false) => "Not included".into(),
ComparisonValue::Partial | ComparisonValue::PartialWith(_) => "Partial".into(),
ComparisonValue::Text(v) => v.clone(),
}
}
fn paint_mark(
rect: Bounds<Pixels>,
value: &ComparisonValue,
progress: f32,
own: bool,
colors: arc_tokens::ArcColors,
window: &mut Window,
) {
let scale = f32::from(rect.size.width) / 22.0;
if scale <= 0.0 {
return;
}
let ox = f32::from(rect.origin.x);
let oy = f32::from(rect.origin.y);
let pt = |x: f32, y: f32| point(px(ox + x * scale), px(oy + y * scale));
let p = progress.clamp(0.0, 1.0);
let mut line_color = if own {
colors.accent
} else {
colors.text_secondary
};
line_color.a *= p;
let mut ring_color = colors.border_strong;
ring_color.a *= p;
match value {
ComparisonValue::Bool(false) => {
if p > 0.01 {
let mut b = gpui_kit::PathBuilder::stroke(px(1.75 * scale));
b.move_to(pt(6.0, 11.0));
b.line_to(pt(16.0, 11.0));
if let Ok(path) = b.build() {
window.paint_path(path, line_color);
}
}
}
ComparisonValue::Partial | ComparisonValue::PartialWith(_) => {
let mut circle = gpui_kit::PathBuilder::stroke(px(1.6 * scale));
for i in 0..=40 {
let a = i as f32 / 40.0 * std::f32::consts::TAU;
let (x, y) = (11.0 + a.cos() * 9.25, 11.0 + a.sin() * 9.25);
if i == 0 {
circle.move_to(pt(x, y));
} else {
circle.line_to(pt(x, y));
}
}
circle.close();
if let Ok(path) = circle.build() {
window.paint_path(path, ring_color);
}
let mut fill = gpui_kit::PathBuilder::fill();
fill.move_to(pt(11.0, 1.75));
for i in 0..=20 {
let a = -std::f32::consts::FRAC_PI_2 + i as f32 / 20.0 * std::f32::consts::PI;
fill.line_to(pt(11.0 + a.cos() * 9.25, 11.0 + a.sin() * 9.25));
}
fill.close();
if let Ok(path) = fill.build() {
let mut c = line_color;
c.a *= 0.35;
window.paint_path(path, c);
}
}
ComparisonValue::Bool(true) | ComparisonValue::Text(_) => {
let mut circle = gpui_kit::PathBuilder::stroke(px(1.6 * scale));
for i in 0..=40 {
let a = i as f32 / 40.0 * std::f32::consts::TAU;
let (x, y) = (11.0 + a.cos() * 10.0, 11.0 + a.sin() * 10.0);
if i == 0 {
circle.move_to(pt(x, y));
} else {
circle.line_to(pt(x, y));
}
}
circle.close();
if let Ok(path) = circle.build() {
window.paint_path(path, ring_color);
}
let first = (p * 2.0).clamp(0.0, 1.0);
let second = (p * 2.0 - 1.0).clamp(0.0, 1.0);
if first > 0.0 {
let mut b = gpui_kit::PathBuilder::stroke(px(1.9 * scale));
b.move_to(pt(6.6, 11.3));
b.line_to(pt(6.6 + (9.6 - 6.6) * first, 11.3 + (14.3 - 11.3) * first));
if let Ok(path) = b.build() {
window.paint_path(path, line_color);
}
}
if second > 0.0 {
let mut b = gpui_kit::PathBuilder::stroke(px(1.9 * scale));
b.move_to(pt(9.6, 14.3));
b.line_to(pt(
9.6 + (15.5 - 9.6) * second,
14.3 + (7.9 - 14.3) * second,
));
if let Ok(path) = b.build() {
window.paint_path(path, line_color);
}
}
}
}
}
fn differs(values: &[ComparisonValue], visible: &[usize]) -> bool {
let missing = ComparisonValue::Bool(false);
let Some(first) = visible.first() else {
return false;
};
let first = values.get(*first).unwrap_or(&missing);
visible
.iter()
.skip(1)
.any(|i| values.get(*i).unwrap_or(&missing) != first)
}
impl RenderOnce for ComparisonTable {
fn render(self, w: &mut Window, cx: &mut App) -> impl IntoElement {
let colors = cx.arc_theme().colors;
let motion = cx.arc_theme().motion;
let state = w.use_keyed_state(child_id(&self.id, "state"), cx, |_, _| State {
differences: self.default_differences_only,
compare: None,
done: false,
width: Rc::new(Cell::new(BlockTokens::STACK_BELOW)),
});
let active = self.differences_only.unwrap_or(state.read(cx).differences);
let columns = self.columns;
let own = columns.iter().position(|c| c.highlight).unwrap_or(0);
let compare = self
.compare_with
.clone()
.or_else(|| state.read(cx).compare.clone());
let other = compare
.and_then(|id| {
columns
.iter()
.position(|c| c.id == id && !c.highlight && columns[own].id != id)
})
.or_else(|| (0..columns.len()).find(|i| *i != own));
let narrow = state.read(cx).width.get() < self.stack_below;
let visible: Vec<_> = (0..columns.len())
.filter(|i| !narrow || *i == own || Some(*i) == other)
.collect();
let width = state.read(cx).width.clone();
let mut root = super::surface(cx)
.id(self.id.clone())
.child(
canvas(
move |bounds, w, _| {
let next = f32::from(bounds.size.width);
if (width.get() - next).abs() > 0.5 {
width.set(next);
w.refresh();
}
},
|_, _, _, _| {},
)
.w_full()
.h(px(0.0)),
)
.child(
div()
.text_size(Typography::TEXT_XL)
.font_medium()
.child(self.title.clone()),
);
if let Some(desc) = self.description {
root = root.child(text(desc, cx));
}
let st = state.clone();
let controlled = self.differences_only.is_some();
let change = self.on_differences_change;
root = root.child(
Button::new(child_id(&self.id, "differences"))
.label("Only differences")
.selected(active)
.size(ButtonSize::Sm)
.variant(ButtonVariant::Secondary)
.on_click(move |_, w, cx| {
if !controlled {
st.update(cx, |s, _| s.differences = !active);
}
if let Some(cb) = &change {
cb(!active, w, cx);
}
w.refresh();
}),
);
if narrow {
let mut picker = div().flex().flex_wrap().gap(Spacing::S2);
for (index, column) in columns.iter().enumerate().filter(|(i, _)| *i != own) {
let st = state.clone();
let key = column.id.clone();
let cb = self.on_compare_change.clone();
let controlled = self.compare_with.is_some();
picker = picker.child(
Button::new(child_id(&self.id, format!("compare-{}", column.id)))
.label(column.name.clone())
.selected(Some(index) == other)
.size(ButtonSize::Sm)
.variant(ButtonVariant::Ghost)
.on_click(move |_, w, cx| {
if !controlled {
st.update(cx, |s, _| s.compare = Some(key.clone()));
}
if let Some(cb) = &cb {
cb(&key, w, cx);
}
w.refresh();
}),
);
}
root = root.child(picker);
}
let feature_width = if narrow {
Spacing::S24
} else {
BlockTokens::FEATURE_WIDTH
};
let band = oklab_mix(colors.accent, colors.surface, 0.06);
let mut header = div()
.id(child_id(&self.id, "head"))
.role(Role::Row)
.flex()
.gap(Spacing::S2)
.pt(px(self.sticky_top))
.border_b_1()
.border_color(colors.border)
.child(
div()
.id(child_id(&self.id, "feature-heading"))
.role(Role::ColumnHeader)
.w(feature_width)
.min_h(px(84.0))
.flex_none(),
);
for i in &visible {
let c = &columns[*i];
let own_col = *i == own;
header = header.child(
div()
.id(child_id(&self.id, format!("head-{}", c.id)))
.role(Role::ColumnHeader)
.min_w(px(0.0))
.min_h(px(84.0))
.flex_1()
.flex()
.flex_col()
.items_center()
.justify_end()
.gap(px(2.0))
.p(Spacing::S4)
.text_center()
.when(own_col, |d| {
d.bg(band).rounded_t(Radii::PANEL).rounded_b(px(0.0))
})
.child(
div()
.text_size(Typography::TEXT_BASE)
.font_medium()
.text_color(if own_col {
colors.accent_strong
} else {
colors.foreground
})
.child(c.name.clone()),
)
.when_some(c.caption.clone(), |d, v| {
d.child(
text(v, cx)
.text_size(Typography::TEXT_XS)
.text_color(colors.text_muted),
)
}),
);
}
let mut table = div()
.id(child_id(&self.id, "table"))
.role(Role::Table)
.aria_label(self.title)
.child(header);
let mut body = div()
.id(child_id(&self.id, "rows"))
.role(Role::RowGroup)
.when_some(self.max_height, |d, h| d.max_h(px(h)))
.overflow_y_scroll();
let mut count = 0;
for section in self.sections {
let any_visible = section
.rows
.iter()
.any(|r| !active || differs(&r.values, &visible));
let section_id = child_id(&self.id, section.id.clone());
let p = ArcPresence::new((section_id.clone(), "title"), any_visible)
.animate_initial(false)
.sample(w, cx);
if p.should_render() {
let mut band_row = div()
.id(child_id(§ion_id, "heading"))
.role(Role::Row)
.opacity(p.progress)
.max_h(BlockTokens::ROW_HEIGHT * p.progress)
.overflow_hidden()
.flex()
.gap(Spacing::S2)
.child(
div()
.id(child_id(§ion_id, "label"))
.role(Role::RowHeader)
.w(feature_width)
.flex_none()
.pt(Spacing::S6)
.pb(Spacing::S1)
.text_size(Typography::TEXT_XS)
.font_medium()
.text_color(colors.text_muted)
.child(section.title),
);
for i in &visible {
band_row = band_row.child(
div()
.min_w(px(0.0))
.flex_1()
.min_h(px(20.0))
.when(*i == own, |d| d.bg(band)),
);
}
body = body.child(band_row);
}
for row in section.rows {
let show = !active || differs(&row.values, &visible);
if show {
count += 1;
}
let id = child_id(&self.id, format!("row-{}", row.id));
let p = ArcPresence::new((id.clone(), "row"), show)
.animate_initial(false)
.sample(w, cx);
if !p.should_render() {
continue;
}
let mut line = div()
.id(id.clone())
.test_support()
.role(Role::Row)
.opacity(p.progress)
.max_h(BlockTokens::ROW_HEIGHT * p.progress)
.overflow_hidden()
.flex()
.gap(Spacing::S2)
.hover(move |s| {
s.bg(oklab_mix(
colors.foreground,
gpui_kit::transparent_black(),
0.025,
))
})
.child(
div()
.id(child_id(&id, "feature"))
.role(Role::RowHeader)
.w(feature_width)
.flex_none()
.min_h(px(56.0))
.flex()
.flex_col()
.justify_center()
.gap(px(2.0))
.text_size(Typography::TEXT_SM)
.font_medium()
.border_b_1()
.border_color(colors.border_subtle)
.child(row.feature)
.when_some(row.hint, |d, v| {
d.child(
text(v, cx)
.text_size(Typography::TEXT_XS)
.text_color(colors.text_muted)
.font_normal(),
)
}),
);
for i in &visible {
let missing = ComparisonValue::Bool(false);
let value = row.values.get(*i).unwrap_or(&missing);
let own_col = *i == own;
let mark = match value {
ComparisonValue::Text(_) => {
div().child(value_text(value)).into_any_element()
}
_ => {
let sample = arc_spring_with_options(
(child_id(&id, format!("mark-{}", columns[*i].id)), "draw"),
1.0,
SpringOptions::new(motion.spring.snappy).with_initial_value(0.0),
w,
cx,
);
if !sample.settled {
w.request_animation_frame();
}
let value = value.clone();
let progress = sample.value;
canvas(
|_, _, _| {},
move |rect, _, window, _| {
paint_mark(rect, &value, progress, own_col, colors, window)
},
)
.size(px(22.0))
.into_any_element()
}
};
line = line.child(
div()
.id(child_id(&id, columns[*i].id.clone()))
.role(Role::Cell)
.aria_label(value_label(value))
.min_w(px(0.0))
.min_h(px(56.0))
.flex_1()
.flex()
.items_center()
.justify_center()
.border_b_1()
.border_color(colors.border_subtle)
.when(own_col, |d| d.bg(band))
.child(
div()
.flex()
.flex_col()
.items_center()
.child(mark)
.when_some(value.note().cloned(), |d, note| {
d.child(
div()
.text_size(Typography::TEXT_XS)
.text_color(colors.text_muted)
.child(note),
)
}),
),
);
}
body = body.child(line);
}
}
let legend = div()
.id(child_id(&self.id, "legend"))
.role(Role::Cell)
.w(feature_width)
.flex_none()
.flex()
.flex_wrap()
.gap(Spacing::S2)
.text_size(Typography::TEXT_XS)
.text_color(colors.text_secondary)
.child("✓ Included")
.child("◐ Partial")
.child("— Not included");
let mut foot = div()
.id(child_id(&self.id, "foot"))
.role(Role::Row)
.flex()
.gap(Spacing::S2)
.pt(Spacing::S2)
.items_center()
.child(legend);
for i in &visible {
let own_col = *i == own;
let mut cell = div()
.id(child_id(&self.id, format!("foot-{}", columns[*i].id)))
.role(Role::Cell)
.min_w(px(0.0))
.flex_1()
.pt(Spacing::S4)
.pb(Spacing::S4)
.flex()
.items_center()
.justify_center()
.when(own_col, |d| {
d.bg(band).rounded_b(Radii::PANEL).rounded_t(px(0.0))
});
if own_col && let Some((label, done_label, action)) = self.cta.clone() {
let done = state.read(cx).done;
let st = state.clone();
let (bg, fg) = if done {
(
oklab_mix(colors.success, gpui_kit::transparent_black(), 0.14),
colors.success,
)
} else {
(colors.foreground, colors.background)
};
cell = cell.child(
div()
.id(child_id(&self.id, "cta"))
.test_support()
.role(Role::Button)
.aria_label(if done {
done_label.clone().unwrap_or_else(|| label.clone())
} else {
label.clone()
})
.cursor_pointer()
.h(px(32.0))
.px(Spacing::S4)
.flex()
.items_center()
.justify_center()
.rounded_full()
.bg(bg)
.text_color(fg)
.text_size(Typography::TEXT_SM)
.font_medium()
.active(|s| s.opacity(0.9))
.on_click({
let has_done = done_label.is_some();
move |_, w, cx| {
action(w, cx);
if has_done {
st.update(cx, |s, _| s.done = true);
}
w.refresh();
}
})
.child(if done {
done_label.clone().unwrap_or(label)
} else {
label
}),
);
}
foot = foot.child(cell);
}
table = table.child(body).child(foot);
root = root.child(table).child(
div()
.id(child_id(&self.id, "status"))
.role(Role::Status)
.child(format!(
"{count} rows · {}",
if active {
"Showing only rows that differ"
} else {
"Showing all rows"
}
)),
);
root.rounded(Radii::PANEL)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn comparison_values_are_stable() {
assert_eq!(value_text(&true.into()), "✓");
assert_eq!(value_label(&ComparisonValue::Partial), "Partial");
let noted = ComparisonValue::partial("Behind a flag");
assert_eq!(value_text(¬ed), "◐");
assert_eq!(noted.note().map(|n| n.as_ref()), Some("Behind a flag"));
}
#[test]
fn differences_use_visible_columns_and_normalize_missing_values() {
let values = [true.into(), true.into(), false.into()];
assert!(!differs(&values, &[0, 1]));
assert!(differs(&values, &[0, 2]));
assert!(!differs(&[false.into()], &[0, 3]));
assert!(!differs(&[], &[]));
}
}