1use super::{child_id, text};
5use crate::{Button, ButtonSize, ButtonVariant};
6use arc_motion::{ArcPresence, arc_spring_with_options, spring::SpringOptions};
7use arc_tokens::{ActiveArcTheme as _, BlockTokens, Radii, Spacing, Typography, oklab_mix};
8use gpui_kit::{
9 App, Bounds, ElementId, IntoElement, ParentElement, Pixels, RenderOnce, Role, SharedString,
10 Styled, TestSupportExt as _, Window, base::StyledExt as _, canvas, div, point, prelude::*, px,
11};
12use std::{cell::Cell, rc::Rc};
13
14#[derive(Clone, Debug, PartialEq)]
15pub enum ComparisonValue {
16 Bool(bool),
17 Partial,
18 PartialWith(SharedString),
20 Text(SharedString),
21}
22impl ComparisonValue {
23 pub fn partial(note: impl Into<SharedString>) -> Self {
24 Self::PartialWith(note.into())
25 }
26 pub fn note(&self) -> Option<&SharedString> {
27 match self {
28 Self::PartialWith(note) => Some(note),
29 _ => None,
30 }
31 }
32}
33impl From<bool> for ComparisonValue {
34 fn from(v: bool) -> Self {
35 Self::Bool(v)
36 }
37}
38#[derive(Clone, Debug)]
39pub struct ComparisonColumn {
40 pub id: SharedString,
41 pub name: SharedString,
42 pub caption: Option<SharedString>,
43 pub highlight: bool,
44}
45#[derive(Clone, Debug)]
46pub struct ComparisonRow {
47 pub id: SharedString,
48 pub feature: SharedString,
49 pub hint: Option<SharedString>,
50 pub values: Vec<ComparisonValue>,
51}
52#[derive(Clone, Debug)]
53pub struct ComparisonSection {
54 pub id: SharedString,
55 pub title: SharedString,
56 pub rows: Vec<ComparisonRow>,
57}
58type Change = Rc<dyn Fn(bool, &mut Window, &mut App)>;
59type CompareChange = Rc<dyn Fn(&SharedString, &mut Window, &mut App)>;
60type Action = Rc<dyn Fn(&mut Window, &mut App)>;
61struct State {
62 differences: bool,
63 compare: Option<SharedString>,
64 done: bool,
65 width: Rc<Cell<f32>>,
66}
67#[derive(IntoElement)]
68pub struct ComparisonTable {
69 id: ElementId,
70 title: SharedString,
71 description: Option<SharedString>,
72 columns: Vec<ComparisonColumn>,
73 sections: Vec<ComparisonSection>,
74 differences_only: Option<bool>,
75 default_differences_only: bool,
76 on_differences_change: Option<Change>,
77 max_height: Option<f32>,
78 compare_with: Option<SharedString>,
79 on_compare_change: Option<CompareChange>,
80 stack_below: f32,
81 sticky_top: f32,
82 cta: Option<(SharedString, Option<SharedString>, Action)>,
83}
84impl ComparisonTable {
85 pub fn new(id: impl Into<ElementId>) -> Self {
86 Self {
87 id: id.into(),
88 title: "How Relay compares".into(),
89 description: Some(
90 "Everything a growing team needs, without spreadsheet sprawl.".into(),
91 ),
92 columns: vec![],
93 sections: vec![],
94 differences_only: None,
95 default_differences_only: false,
96 on_differences_change: None,
97 max_height: None,
98 compare_with: None,
99 on_compare_change: None,
100 stack_below: BlockTokens::STACK_BELOW,
101 sticky_top: 0.0,
102 cta: None,
103 }
104 }
105 pub fn title(mut self, v: impl Into<SharedString>) -> Self {
106 self.title = v.into();
107 self
108 }
109 pub fn description(mut self, v: impl Into<SharedString>) -> Self {
110 self.description = Some(v.into());
111 self
112 }
113 pub fn columns(mut self, v: impl IntoIterator<Item = ComparisonColumn>) -> Self {
114 self.columns = v.into_iter().collect();
115 self
116 }
117 pub fn sections(mut self, v: impl IntoIterator<Item = ComparisonSection>) -> Self {
118 self.sections = v.into_iter().collect();
119 self
120 }
121 pub fn differences_only(mut self, v: bool) -> Self {
122 self.differences_only = Some(v);
123 self
124 }
125 pub fn default_differences_only(mut self, v: bool) -> Self {
126 self.default_differences_only = v;
127 self
128 }
129 pub fn max_height(mut self, v: f32) -> Self {
130 self.max_height = Some(v.max(0.0));
131 self
132 }
133 pub fn stack_below(mut self, v: f32) -> Self {
134 self.stack_below = v.max(0.0);
135 self
136 }
137 pub fn sticky_top(mut self, v: f32) -> Self {
139 self.sticky_top = v.max(0.0);
140 self
141 }
142 pub fn compare_with(mut self, v: impl Into<SharedString>) -> Self {
143 self.compare_with = Some(v.into());
144 self
145 }
146 pub fn on_compare_change(
147 mut self,
148 f: impl Fn(&SharedString, &mut Window, &mut App) + 'static,
149 ) -> Self {
150 self.on_compare_change = Some(Rc::new(f));
151 self
152 }
153 pub fn on_differences_change(
154 mut self,
155 f: impl Fn(bool, &mut Window, &mut App) + 'static,
156 ) -> Self {
157 self.on_differences_change = Some(Rc::new(f));
158 self
159 }
160 pub fn cta(
162 mut self,
163 label: impl Into<SharedString>,
164 done_label: Option<SharedString>,
165 f: impl Fn(&mut Window, &mut App) + 'static,
166 ) -> Self {
167 self.cta = Some((label.into(), done_label, Rc::new(f)));
168 self
169 }
170}
171fn value_text(value: &ComparisonValue) -> SharedString {
172 match value {
173 ComparisonValue::Bool(true) => "✓".into(),
174 ComparisonValue::Bool(false) => "—".into(),
175 ComparisonValue::Partial | ComparisonValue::PartialWith(_) => "◐".into(),
176 ComparisonValue::Text(v) => v.clone(),
177 }
178}
179fn value_label(value: &ComparisonValue) -> SharedString {
180 match value {
181 ComparisonValue::Bool(true) => "Included".into(),
182 ComparisonValue::Bool(false) => "Not included".into(),
183 ComparisonValue::Partial | ComparisonValue::PartialWith(_) => "Partial".into(),
184 ComparisonValue::Text(v) => v.clone(),
185 }
186}
187fn paint_mark(
189 rect: Bounds<Pixels>,
190 value: &ComparisonValue,
191 progress: f32,
192 own: bool,
193 colors: arc_tokens::ArcColors,
194 window: &mut Window,
195) {
196 let scale = f32::from(rect.size.width) / 22.0;
197 if scale <= 0.0 {
198 return;
199 }
200 let ox = f32::from(rect.origin.x);
201 let oy = f32::from(rect.origin.y);
202 let pt = |x: f32, y: f32| point(px(ox + x * scale), px(oy + y * scale));
203 let p = progress.clamp(0.0, 1.0);
204 let mut line_color = if own {
205 colors.accent
206 } else {
207 colors.text_secondary
208 };
209 line_color.a *= p;
210 let mut ring_color = colors.border_strong;
211 ring_color.a *= p;
212 match value {
213 ComparisonValue::Bool(false) => {
214 if p > 0.01 {
215 let mut b = gpui_kit::PathBuilder::stroke(px(1.75 * scale));
216 b.move_to(pt(6.0, 11.0));
217 b.line_to(pt(16.0, 11.0));
218 if let Ok(path) = b.build() {
219 window.paint_path(path, line_color);
220 }
221 }
222 }
223 ComparisonValue::Partial | ComparisonValue::PartialWith(_) => {
224 let mut circle = gpui_kit::PathBuilder::stroke(px(1.6 * scale));
225 for i in 0..=40 {
226 let a = i as f32 / 40.0 * std::f32::consts::TAU;
227 let (x, y) = (11.0 + a.cos() * 9.25, 11.0 + a.sin() * 9.25);
228 if i == 0 {
229 circle.move_to(pt(x, y));
230 } else {
231 circle.line_to(pt(x, y));
232 }
233 }
234 circle.close();
235 if let Ok(path) = circle.build() {
236 window.paint_path(path, ring_color);
237 }
238 let mut fill = gpui_kit::PathBuilder::fill();
239 fill.move_to(pt(11.0, 1.75));
240 for i in 0..=20 {
241 let a = -std::f32::consts::FRAC_PI_2 + i as f32 / 20.0 * std::f32::consts::PI;
242 fill.line_to(pt(11.0 + a.cos() * 9.25, 11.0 + a.sin() * 9.25));
243 }
244 fill.close();
245 if let Ok(path) = fill.build() {
246 let mut c = line_color;
247 c.a *= 0.35;
248 window.paint_path(path, c);
249 }
250 }
251 ComparisonValue::Bool(true) | ComparisonValue::Text(_) => {
252 let mut circle = gpui_kit::PathBuilder::stroke(px(1.6 * scale));
253 for i in 0..=40 {
254 let a = i as f32 / 40.0 * std::f32::consts::TAU;
255 let (x, y) = (11.0 + a.cos() * 10.0, 11.0 + a.sin() * 10.0);
256 if i == 0 {
257 circle.move_to(pt(x, y));
258 } else {
259 circle.line_to(pt(x, y));
260 }
261 }
262 circle.close();
263 if let Ok(path) = circle.build() {
264 window.paint_path(path, ring_color);
265 }
266 let first = (p * 2.0).clamp(0.0, 1.0);
267 let second = (p * 2.0 - 1.0).clamp(0.0, 1.0);
268 if first > 0.0 {
269 let mut b = gpui_kit::PathBuilder::stroke(px(1.9 * scale));
270 b.move_to(pt(6.6, 11.3));
271 b.line_to(pt(6.6 + (9.6 - 6.6) * first, 11.3 + (14.3 - 11.3) * first));
272 if let Ok(path) = b.build() {
273 window.paint_path(path, line_color);
274 }
275 }
276 if second > 0.0 {
277 let mut b = gpui_kit::PathBuilder::stroke(px(1.9 * scale));
278 b.move_to(pt(9.6, 14.3));
279 b.line_to(pt(
280 9.6 + (15.5 - 9.6) * second,
281 14.3 + (7.9 - 14.3) * second,
282 ));
283 if let Ok(path) = b.build() {
284 window.paint_path(path, line_color);
285 }
286 }
287 }
288 }
289}
290fn differs(values: &[ComparisonValue], visible: &[usize]) -> bool {
291 let missing = ComparisonValue::Bool(false);
292 let Some(first) = visible.first() else {
293 return false;
294 };
295 let first = values.get(*first).unwrap_or(&missing);
296 visible
297 .iter()
298 .skip(1)
299 .any(|i| values.get(*i).unwrap_or(&missing) != first)
300}
301impl RenderOnce for ComparisonTable {
302 fn render(self, w: &mut Window, cx: &mut App) -> impl IntoElement {
303 let colors = cx.arc_theme().colors;
304 let motion = cx.arc_theme().motion;
305 let state = w.use_keyed_state(child_id(&self.id, "state"), cx, |_, _| State {
306 differences: self.default_differences_only,
307 compare: None,
308 done: false,
309 width: Rc::new(Cell::new(BlockTokens::STACK_BELOW)),
310 });
311 let active = self.differences_only.unwrap_or(state.read(cx).differences);
312 let columns = self.columns;
313 let own = columns.iter().position(|c| c.highlight).unwrap_or(0);
314 let compare = self
315 .compare_with
316 .clone()
317 .or_else(|| state.read(cx).compare.clone());
318 let other = compare
319 .and_then(|id| {
320 columns
321 .iter()
322 .position(|c| c.id == id && !c.highlight && columns[own].id != id)
323 })
324 .or_else(|| (0..columns.len()).find(|i| *i != own));
325 let narrow = state.read(cx).width.get() < self.stack_below;
326 let visible: Vec<_> = (0..columns.len())
327 .filter(|i| !narrow || *i == own || Some(*i) == other)
328 .collect();
329 let width = state.read(cx).width.clone();
330 let mut root = super::surface(cx)
331 .id(self.id.clone())
332 .child(
333 canvas(
334 move |bounds, w, _| {
335 let next = f32::from(bounds.size.width);
336 if (width.get() - next).abs() > 0.5 {
337 width.set(next);
338 w.refresh();
339 }
340 },
341 |_, _, _, _| {},
342 )
343 .w_full()
344 .h(px(0.0)),
345 )
346 .child(
347 div()
348 .text_size(Typography::TEXT_XL)
349 .font_medium()
350 .child(self.title.clone()),
351 );
352 if let Some(desc) = self.description {
353 root = root.child(text(desc, cx));
354 }
355 let st = state.clone();
356 let controlled = self.differences_only.is_some();
357 let change = self.on_differences_change;
358 root = root.child(
359 Button::new(child_id(&self.id, "differences"))
360 .label("Only differences")
361 .selected(active)
362 .size(ButtonSize::Sm)
363 .variant(ButtonVariant::Secondary)
364 .on_click(move |_, w, cx| {
365 if !controlled {
366 st.update(cx, |s, _| s.differences = !active);
367 }
368 if let Some(cb) = &change {
369 cb(!active, w, cx);
370 }
371 w.refresh();
372 }),
373 );
374 if narrow {
375 let mut picker = div().flex().flex_wrap().gap(Spacing::S2);
376 for (index, column) in columns.iter().enumerate().filter(|(i, _)| *i != own) {
377 let st = state.clone();
378 let key = column.id.clone();
379 let cb = self.on_compare_change.clone();
380 let controlled = self.compare_with.is_some();
381 picker = picker.child(
382 Button::new(child_id(&self.id, format!("compare-{}", column.id)))
383 .label(column.name.clone())
384 .selected(Some(index) == other)
385 .size(ButtonSize::Sm)
386 .variant(ButtonVariant::Ghost)
387 .on_click(move |_, w, cx| {
388 if !controlled {
389 st.update(cx, |s, _| s.compare = Some(key.clone()));
390 }
391 if let Some(cb) = &cb {
392 cb(&key, w, cx);
393 }
394 w.refresh();
395 }),
396 );
397 }
398 root = root.child(picker);
399 }
400 let feature_width = if narrow {
401 Spacing::S24
402 } else {
403 BlockTokens::FEATURE_WIDTH
404 };
405 let band = oklab_mix(colors.accent, colors.surface, 0.06);
407 let mut header = div()
408 .id(child_id(&self.id, "head"))
409 .role(Role::Row)
410 .flex()
411 .gap(Spacing::S2)
412 .pt(px(self.sticky_top))
413 .border_b_1()
414 .border_color(colors.border)
415 .child(
416 div()
417 .id(child_id(&self.id, "feature-heading"))
418 .role(Role::ColumnHeader)
419 .w(feature_width)
420 .min_h(px(84.0))
421 .flex_none(),
422 );
423 for i in &visible {
424 let c = &columns[*i];
425 let own_col = *i == own;
426 header = header.child(
427 div()
428 .id(child_id(&self.id, format!("head-{}", c.id)))
429 .role(Role::ColumnHeader)
430 .min_w(px(0.0))
431 .min_h(px(84.0))
432 .flex_1()
433 .flex()
434 .flex_col()
435 .items_center()
436 .justify_end()
437 .gap(px(2.0))
438 .p(Spacing::S4)
439 .text_center()
440 .when(own_col, |d| {
441 d.bg(band).rounded_t(Radii::PANEL).rounded_b(px(0.0))
442 })
443 .child(
444 div()
445 .text_size(Typography::TEXT_BASE)
446 .font_medium()
447 .text_color(if own_col {
448 colors.accent_strong
449 } else {
450 colors.foreground
451 })
452 .child(c.name.clone()),
453 )
454 .when_some(c.caption.clone(), |d, v| {
455 d.child(
456 text(v, cx)
457 .text_size(Typography::TEXT_XS)
458 .text_color(colors.text_muted),
459 )
460 }),
461 );
462 }
463 let mut table = div()
464 .id(child_id(&self.id, "table"))
465 .role(Role::Table)
466 .aria_label(self.title)
467 .child(header);
468 let mut body = div()
469 .id(child_id(&self.id, "rows"))
470 .role(Role::RowGroup)
471 .when_some(self.max_height, |d, h| d.max_h(px(h)))
472 .overflow_y_scroll();
473 let mut count = 0;
474 for section in self.sections {
475 let any_visible = section
476 .rows
477 .iter()
478 .any(|r| !active || differs(&r.values, &visible));
479 let section_id = child_id(&self.id, section.id.clone());
480 let p = ArcPresence::new((section_id.clone(), "title"), any_visible)
481 .animate_initial(false)
482 .sample(w, cx);
483 if p.should_render() {
484 let mut band_row = div()
485 .id(child_id(§ion_id, "heading"))
486 .role(Role::Row)
487 .opacity(p.progress)
488 .max_h(BlockTokens::ROW_HEIGHT * p.progress)
489 .overflow_hidden()
490 .flex()
491 .gap(Spacing::S2)
492 .child(
493 div()
494 .id(child_id(§ion_id, "label"))
495 .role(Role::RowHeader)
496 .w(feature_width)
497 .flex_none()
498 .pt(Spacing::S6)
499 .pb(Spacing::S1)
500 .text_size(Typography::TEXT_XS)
501 .font_medium()
502 .text_color(colors.text_muted)
503 .child(section.title),
504 );
505 for i in &visible {
506 band_row = band_row.child(
507 div()
508 .min_w(px(0.0))
509 .flex_1()
510 .min_h(px(20.0))
511 .when(*i == own, |d| d.bg(band)),
512 );
513 }
514 body = body.child(band_row);
515 }
516 for row in section.rows {
517 let show = !active || differs(&row.values, &visible);
518 if show {
519 count += 1;
520 }
521 let id = child_id(&self.id, format!("row-{}", row.id));
522 let p = ArcPresence::new((id.clone(), "row"), show)
523 .animate_initial(false)
524 .sample(w, cx);
525 if !p.should_render() {
526 continue;
527 }
528 let mut line = div()
529 .id(id.clone())
530 .test_support()
531 .role(Role::Row)
532 .opacity(p.progress)
533 .max_h(BlockTokens::ROW_HEIGHT * p.progress)
534 .overflow_hidden()
535 .flex()
536 .gap(Spacing::S2)
537 .hover(move |s| {
538 s.bg(oklab_mix(
539 colors.foreground,
540 gpui_kit::transparent_black(),
541 0.025,
542 ))
543 })
544 .child(
545 div()
546 .id(child_id(&id, "feature"))
547 .role(Role::RowHeader)
548 .w(feature_width)
549 .flex_none()
550 .min_h(px(56.0))
551 .flex()
552 .flex_col()
553 .justify_center()
554 .gap(px(2.0))
555 .text_size(Typography::TEXT_SM)
556 .font_medium()
557 .border_b_1()
558 .border_color(colors.border_subtle)
559 .child(row.feature)
560 .when_some(row.hint, |d, v| {
561 d.child(
562 text(v, cx)
563 .text_size(Typography::TEXT_XS)
564 .text_color(colors.text_muted)
565 .font_normal(),
566 )
567 }),
568 );
569 for i in &visible {
570 let missing = ComparisonValue::Bool(false);
571 let value = row.values.get(*i).unwrap_or(&missing);
572 let own_col = *i == own;
573 let mark = match value {
574 ComparisonValue::Text(_) => {
575 div().child(value_text(value)).into_any_element()
576 }
577 _ => {
578 let sample = arc_spring_with_options(
579 (child_id(&id, format!("mark-{}", columns[*i].id)), "draw"),
580 1.0,
581 SpringOptions::new(motion.spring.snappy).with_initial_value(0.0),
582 w,
583 cx,
584 );
585 if !sample.settled {
586 w.request_animation_frame();
587 }
588 let value = value.clone();
589 let progress = sample.value;
590 canvas(
591 |_, _, _| {},
592 move |rect, _, window, _| {
593 paint_mark(rect, &value, progress, own_col, colors, window)
594 },
595 )
596 .size(px(22.0))
597 .into_any_element()
598 }
599 };
600 line = line.child(
601 div()
602 .id(child_id(&id, columns[*i].id.clone()))
603 .role(Role::Cell)
604 .aria_label(value_label(value))
605 .min_w(px(0.0))
606 .min_h(px(56.0))
607 .flex_1()
608 .flex()
609 .items_center()
610 .justify_center()
611 .border_b_1()
612 .border_color(colors.border_subtle)
613 .when(own_col, |d| d.bg(band))
614 .child(
615 div()
616 .flex()
617 .flex_col()
618 .items_center()
619 .child(mark)
620 .when_some(value.note().cloned(), |d, note| {
621 d.child(
622 div()
623 .text_size(Typography::TEXT_XS)
624 .text_color(colors.text_muted)
625 .child(note),
626 )
627 }),
628 ),
629 );
630 }
631 body = body.child(line);
632 }
633 }
634 let legend = div()
636 .id(child_id(&self.id, "legend"))
637 .role(Role::Cell)
638 .w(feature_width)
639 .flex_none()
640 .flex()
641 .flex_wrap()
642 .gap(Spacing::S2)
643 .text_size(Typography::TEXT_XS)
644 .text_color(colors.text_secondary)
645 .child("✓ Included")
646 .child("◐ Partial")
647 .child("— Not included");
648 let mut foot = div()
649 .id(child_id(&self.id, "foot"))
650 .role(Role::Row)
651 .flex()
652 .gap(Spacing::S2)
653 .pt(Spacing::S2)
654 .items_center()
655 .child(legend);
656 for i in &visible {
657 let own_col = *i == own;
658 let mut cell = div()
659 .id(child_id(&self.id, format!("foot-{}", columns[*i].id)))
660 .role(Role::Cell)
661 .min_w(px(0.0))
662 .flex_1()
663 .pt(Spacing::S4)
664 .pb(Spacing::S4)
665 .flex()
666 .items_center()
667 .justify_center()
668 .when(own_col, |d| {
669 d.bg(band).rounded_b(Radii::PANEL).rounded_t(px(0.0))
670 });
671 if own_col && let Some((label, done_label, action)) = self.cta.clone() {
672 let done = state.read(cx).done;
673 let st = state.clone();
674 let (bg, fg) = if done {
676 (
677 oklab_mix(colors.success, gpui_kit::transparent_black(), 0.14),
678 colors.success,
679 )
680 } else {
681 (colors.foreground, colors.background)
682 };
683 cell = cell.child(
684 div()
685 .id(child_id(&self.id, "cta"))
686 .test_support()
687 .role(Role::Button)
688 .aria_label(if done {
689 done_label.clone().unwrap_or_else(|| label.clone())
690 } else {
691 label.clone()
692 })
693 .cursor_pointer()
694 .h(px(32.0))
695 .px(Spacing::S4)
696 .flex()
697 .items_center()
698 .justify_center()
699 .rounded_full()
700 .bg(bg)
701 .text_color(fg)
702 .text_size(Typography::TEXT_SM)
703 .font_medium()
704 .active(|s| s.opacity(0.9))
705 .on_click({
706 let has_done = done_label.is_some();
707 move |_, w, cx| {
708 action(w, cx);
709 if has_done {
710 st.update(cx, |s, _| s.done = true);
711 }
712 w.refresh();
713 }
714 })
715 .child(if done {
716 done_label.clone().unwrap_or(label)
717 } else {
718 label
719 }),
720 );
721 }
722 foot = foot.child(cell);
723 }
724 table = table.child(body).child(foot);
725 root = root.child(table).child(
726 div()
727 .id(child_id(&self.id, "status"))
728 .role(Role::Status)
729 .child(format!(
730 "{count} rows · {}",
731 if active {
732 "Showing only rows that differ"
733 } else {
734 "Showing all rows"
735 }
736 )),
737 );
738 root.rounded(Radii::PANEL)
739 }
740}
741#[cfg(test)]
742mod tests {
743 use super::*;
744 #[test]
745 fn comparison_values_are_stable() {
746 assert_eq!(value_text(&true.into()), "✓");
747 assert_eq!(value_label(&ComparisonValue::Partial), "Partial");
748 let noted = ComparisonValue::partial("Behind a flag");
749 assert_eq!(value_text(¬ed), "◐");
750 assert_eq!(noted.note().map(|n| n.as_ref()), Some("Behind a flag"));
751 }
752 #[test]
753 fn differences_use_visible_columns_and_normalize_missing_values() {
754 let values = [true.into(), true.into(), false.into()];
755 assert!(!differs(&values, &[0, 1]));
756 assert!(differs(&values, &[0, 2]));
757 assert!(!differs(&[false.into()], &[0, 3]));
758 assert!(!differs(&[], &[]));
759 }
760}