1use std::cell::Cell;
9use std::collections::HashSet;
10
11use gpui_kit::component::menu::PopupMenu;
12use gpui_kit::{AnyElement, App, Context, Entity, ScrollHandle, SharedString, Window};
13
14use crate::row_menu::{self, MenuChat, RowMenu};
15use crate::tokens::Tone;
16use crate::{Dashboard, DashboardEvent};
17
18const LIST_TAIL_HEIGHT_PX: f32 = 48.;
20const WRAPPED_ROW_PADDING_Y_PX: f32 = 4.;
22const COMFORTABLE_ROW_SCALE: f32 = 1.125;
24const ROW_FILL_GAP_PX: f32 = 1.;
26const ROW_PADDING_LEFT_PX: f32 = 6.;
28const FOLD_ARROW_WIDTH_PX: f32 = 14.;
30const ROW_ID_MIN_WIDTH_PX: f32 = 56.;
32const PROP_ROW_MIN_HEIGHT_PX: f32 = 28.;
34const PROP_LABEL_WIDTH_PX: f32 = 96.;
36const SECTION_TOP_MARGIN_PX: f32 = 18.;
38const SECTION_TOP_PADDING_PX: f32 = 12.;
39const PANEL_TITLE_SIZE_PX: f32 = 16.;
41const PANEL_TITLE_MARGIN_PX: f32 = 14.;
42
43#[derive(Debug, Clone, PartialEq, Eq)]
45pub struct Glyph {
46 pub text: SharedString,
47 pub tone: Tone,
48 pub rgb: Option<u32>,
51}
52
53impl Glyph {
54 pub fn new(text: impl Into<SharedString>, tone: Tone) -> Self {
55 Self {
56 text: text.into(),
57 tone,
58 rgb: None,
59 }
60 }
61
62 pub fn rgb(text: impl Into<SharedString>, rgb: u32) -> Self {
64 Self {
65 text: text.into(),
66 tone: Tone::Fg,
67 rgb: Some(rgb),
68 }
69 }
70}
71
72#[derive(Debug, Clone, PartialEq, Eq)]
74pub struct Row {
75 pub key: SharedString,
78 pub icon: Glyph,
79 pub id: Option<SharedString>,
81 pub title: SharedString,
82 pub trailing: Vec<Glyph>,
83 pub done: bool,
85 pub indent: u8,
88}
89
90#[derive(Debug, Clone, PartialEq, Eq)]
92pub struct Group {
93 pub key: SharedString,
94 pub icon: Glyph,
95 pub name: SharedString,
96 pub count: Option<SharedString>,
98 pub rows: Vec<Row>,
99}
100
101#[derive(Debug, Clone, PartialEq, Eq)]
105pub enum GroupNote {
106 Loading(SharedString),
108 Empty(SharedString),
110}
111
112impl GroupNote {
113 pub fn label(&self, group: &str) -> SharedString {
117 let (Self::Loading(message) | Self::Empty(message)) = self;
118 let message = message.trim_end_matches(['…', '.']);
119 let mut chars = message.chars();
120 let first = chars.next().map(|c| c.to_lowercase().to_string());
121 format!("{group}: {}{}", first.unwrap_or_default(), chars.as_str()).into()
122 }
123}
124
125#[derive(Debug, Clone, PartialEq, Eq)]
132pub struct GroupCaption {
133 pub before: SharedString,
136 pub label: SharedString,
137}
138
139impl GroupCaption {
140 pub fn new(before: impl Into<SharedString>, label: impl Into<SharedString>) -> Self {
141 Self {
142 before: before.into(),
143 label: label.into(),
144 }
145 }
146}
147
148#[derive(Debug, Clone, PartialEq, Eq)]
152pub struct GroupIndicator {
153 pub icon: subspace_lucide::SvgIcon,
154 pub tone: crate::tokens::Tone,
155 pub label: SharedString,
157 pub tooltip: SharedString,
159}
160
161#[derive(Debug, Clone, PartialEq, Eq)]
163pub enum Body {
164 Text(SharedString),
165 Markdown(SharedString),
166 Html(SharedString),
168}
169
170impl<T: Into<SharedString>> From<T> for Body {
171 fn from(text: T) -> Self {
172 Self::Text(text.into())
173 }
174}
175
176#[derive(Debug, Clone, PartialEq, Eq)]
178pub struct Section {
179 pub heading: SharedString,
180 pub body: Body,
181}
182
183impl Section {
184 pub fn text(heading: impl Into<SharedString>, body: impl Into<SharedString>) -> Self {
185 Self {
186 heading: heading.into(),
187 body: Body::Text(body.into()),
188 }
189 }
190
191 pub fn markdown(heading: impl Into<SharedString>, body: impl Into<SharedString>) -> Self {
192 Self {
193 heading: heading.into(),
194 body: Body::Markdown(body.into()),
195 }
196 }
197
198 pub fn html(heading: impl Into<SharedString>, body: impl Into<SharedString>) -> Self {
199 Self {
200 heading: heading.into(),
201 body: Body::Html(body.into()),
202 }
203 }
204}
205
206#[derive(Debug, Clone, PartialEq, Eq)]
208pub struct ServiceLink {
209 pub label: SharedString,
210 pub url: SharedString,
211}
212
213impl ServiceLink {
214 pub fn new(label: impl Into<SharedString>, url: impl Into<SharedString>) -> Self {
215 Self {
216 label: label.into(),
217 url: url.into(),
218 }
219 }
220}
221
222#[derive(Debug, Clone, PartialEq, Eq, Default)]
224pub struct Detail {
225 pub kind: SharedString,
227 pub id: SharedString,
228 pub title: SharedString,
229 pub link: Option<ServiceLink>,
231 pub props: Vec<(SharedString, SharedString)>,
233 pub sections: Vec<Section>,
234}
235
236#[derive(Debug, Clone, Default, PartialEq, Eq)]
238pub enum LoadStatus {
239 #[default]
240 Ready,
241 Loading,
242 Failed {
243 title: SharedString,
244 message: SharedString,
245 },
246}
247
248#[derive(Debug, Clone, Default)]
251pub struct ListState {
252 groups: Vec<Group>,
253 folded: HashSet<SharedString>,
254 selected: Option<SharedString>,
255 detail_open: bool,
256 status: LoadStatus,
257 scroll: ScrollHandle,
258 scroll_pending: Cell<bool>,
260}
261
262impl ListState {
263 pub fn new(groups: Vec<Group>) -> Self {
264 Self {
265 groups,
266 ..Self::default()
267 }
268 }
269
270 pub fn groups(&self) -> &[Group] {
272 &self.groups
273 }
274
275 pub fn set_groups(&mut self, groups: Vec<Group>) {
278 self.groups = groups;
279 if self
280 .selected
281 .as_ref()
282 .is_some_and(|key| !self.visible_keys().contains(key))
283 {
284 self.selected = None;
285 self.detail_open = false;
286 }
287 }
288
289 pub fn status(&self) -> &LoadStatus {
291 &self.status
292 }
293
294 pub fn set_status(&mut self, status: LoadStatus) {
297 self.status = status;
298 }
299
300 #[cfg(test)]
301 pub fn row_count(&self) -> usize {
302 self.groups.iter().map(|g| g.rows.len()).sum()
303 }
304
305 pub fn rows(&self) -> impl Iterator<Item = &Row> {
306 self.groups.iter().flat_map(|g| &g.rows)
307 }
308
309 pub fn selected(&self) -> Option<&SharedString> {
310 self.selected.as_ref()
311 }
312
313 pub fn is_folded(&self, group: &str) -> bool {
314 self.folded.contains(group)
315 }
316
317 pub fn selected_row(&self) -> Option<&Row> {
319 let key = self.selected.as_ref()?;
320 self.rows().find(|row| &row.key == key)
321 }
322
323 pub fn open_row(&self) -> Option<&Row> {
325 self.detail_open.then(|| self.selected_row()).flatten()
326 }
327
328 pub fn scroll_handle(&self) -> &ScrollHandle {
331 &self.scroll
332 }
333
334 pub fn scroll_to_selected(&self) {
337 self.scroll_pending.set(true);
338 }
339
340 pub fn take_scroll_request(&self) -> Option<usize> {
343 if !self.scroll_pending.replace(false) {
344 return None;
345 }
346 let key = self.selected.as_ref()?;
347 self.visible_keys().iter().position(|k| k == key)
348 }
349
350 pub fn visible_keys(&self) -> Vec<SharedString> {
352 let mut keys = Vec::new();
353 for group in &self.groups {
354 keys.push(group.key.clone());
355 if !self.folded.contains(&group.key) {
356 keys.extend(group.rows.iter().map(|row| row.key.clone()));
357 }
358 }
359 keys
360 }
361
362 pub fn select(&mut self, key: SharedString) {
363 self.selected = Some(key);
364 self.scroll_to_selected();
365 if self.selected_row().is_none() {
367 self.detail_open = false;
368 }
369 }
370
371 pub fn step(&mut self, step: isize) {
374 let keys = self.visible_keys();
375 let next = match self
376 .selected
377 .as_ref()
378 .and_then(|key| keys.iter().position(|k| k == key))
379 {
380 Some(index) => index
381 .saturating_add_signed(step)
382 .min(keys.len().saturating_sub(1)),
383 None => 0,
384 };
385 if let Some(key) = keys.get(next) {
386 self.select(key.clone());
387 }
388 }
389
390 pub fn select_end(&mut self, last: bool) {
392 let keys = self.visible_keys();
393 let key = if last { keys.last() } else { keys.first() };
394 if let Some(key) = key {
395 self.select(key.clone());
396 }
397 }
398
399 pub fn step_row(&mut self, step: isize) -> Option<SharedString> {
402 let rows: Vec<SharedString> = self
403 .visible_keys()
404 .into_iter()
405 .filter(|key| self.rows().any(|row| &row.key == key))
406 .collect();
407 let current = self
408 .selected
409 .as_ref()
410 .and_then(|key| rows.iter().position(|k| k == key))?;
411 let next = current
412 .saturating_add_signed(step)
413 .min(rows.len().saturating_sub(1));
414 let key = rows.get(next)?.clone();
415 self.selected = Some(key.clone());
416 self.detail_open = true;
417 self.scroll_to_selected();
418 Some(key)
419 }
420
421 pub fn activate(&mut self) -> Option<SharedString> {
424 let key = self.selected.clone()?;
425 if self.groups.iter().any(|g| g.key == key) {
426 self.toggle(&key);
427 None
428 } else {
429 self.detail_open = true;
430 Some(key)
431 }
432 }
433
434 pub fn reveal(&mut self, key: &str) -> bool {
437 let Some(group) = self
438 .groups
439 .iter()
440 .find(|g| g.rows.iter().any(|row| row.key == key))
441 else {
442 return false;
443 };
444 self.folded.remove(&group.key.clone());
445 self.selected = Some(SharedString::from(key.to_string()));
446 self.detail_open = true;
447 self.scroll_to_selected();
448 true
449 }
450
451 pub fn toggle(&mut self, group: &SharedString) {
452 if !self.folded.remove(group) {
453 self.folded.insert(group.clone());
454 }
455 }
456
457 pub fn close_detail(&mut self) {
458 self.detail_open = false;
459 }
460}
461
462pub trait ListDashboard: Dashboard {
464 fn can_navigate(&self, _cx: &App) -> bool {
466 true
467 }
468 fn list(&self) -> &ListState;
469 fn list_mut(&mut self) -> &mut ListState;
470 fn detail(&self, key: &str) -> Option<Detail>;
472
473 fn row_leading(&self, _row: &Row, _cx: &App) -> Option<AnyElement> {
475 None
476 }
477
478 fn row_trailing(&self, _row: &Row, _cx: &App) -> Option<AnyElement> {
482 None
483 }
484
485 fn group_leading(&self, _group: &Group, _cx: &App) -> Option<AnyElement> {
488 None
489 }
490
491 fn list_side_inset(&self) -> Option<gpui_kit::Pixels> {
493 None
494 }
495
496 fn group_count_after_name(&self) -> bool {
498 false
499 }
500
501 fn group_heading_matches_row(&self) -> bool {
503 false
504 }
505
506 fn comfortable_rows(&self) -> bool {
510 false
511 }
512
513 fn row_emphasis(&self, _row: &Row, _cx: &App) -> bool {
515 false
516 }
517
518 fn row_accessible_label(&self, row: &Row, _cx: &App) -> SharedString {
520 row.title.clone()
521 }
522
523 fn menu_chat(&self) -> MenuChat {
526 MenuChat::Offered
527 }
528
529 fn empty_message(&self) -> (SharedString, SharedString) {
531 (
532 "Nothing to show".into(),
533 "Try another filter, or reload.".into(),
534 )
535 }
536
537 fn empty_actions(&self, _cx: &mut Context<Self>) -> Option<Vec<AnyElement>> {
541 None
542 }
543
544 fn panel_extra(&self, _key: &str, _cx: &App) -> Option<AnyElement> {
547 None
548 }
549
550 fn panel_footer(&self, _key: &str, _cx: &App) -> Option<AnyElement> {
552 None
553 }
554
555 fn panel_scroll_handle(&self, _key: &str) -> Option<ScrollHandle> {
557 None
558 }
559
560 fn panel_content_owns_scroll(&self, _key: &str) -> bool {
563 false
564 }
565
566 fn min_list_width(&self) -> f32 {
568 0.0
569 }
570
571 fn on_selection_changed(&mut self, _selected: Option<SharedString>, _cx: &mut Context<Self>) {}
574
575 fn on_open(&mut self, _key: SharedString, _cx: &mut Context<Self>) {}
578
579 fn on_panel_toggled(&mut self, _open: bool, _cx: &mut Context<Self>) {}
581
582 fn on_activate(&mut self, _key: &SharedString, _cx: &mut Context<Self>) -> bool {
586 false
587 }
588
589 fn activates_on_click(&self, _row: &Row) -> bool {
593 true
594 }
595
596 fn row_menu(&self, row: &Row) -> RowMenu {
601 RowMenu::from_row(row)
602 }
603
604 fn row_commands(_board: &Entity<Self>, _cx: &App) -> Vec<row_menu::MenuCommand>
610 where
611 Self: Sized,
612 {
613 Vec::new()
614 }
615
616 fn extend_row_menu(&self, menu: PopupMenu, _cx: &App) -> PopupMenu {
619 menu
620 }
621
622 fn row_submenus(
629 _board: &Entity<Self>,
630 menu: PopupMenu,
631 _window: &mut Window,
632 _cx: &mut Context<PopupMenu>,
633 ) -> PopupMenu
634 where
635 Self: Sized,
636 {
637 menu
638 }
639
640 fn panel_header_label(&self, _key: &str) -> Option<SharedString> {
642 None
643 }
644
645 fn group_menu(&self, _group: &Group) -> Option<RowMenu> {
650 None
651 }
652
653 fn group_indicators(&self, _group: &Group, _cx: &App) -> Vec<GroupIndicator> {
657 vec![]
658 }
659
660 fn group_captions(&self, _group: &Group, _cx: &App) -> Vec<GroupCaption> {
665 Vec::new()
666 }
667
668 fn group_note(&self, _group: &Group, _cx: &App) -> Option<GroupNote> {
673 None
674 }
675}
676
677pub fn update<D: ListDashboard>(
681 this: &mut D,
682 cx: &mut Context<D>,
683 change: impl FnOnce(&mut ListState),
684) {
685 if !this.can_navigate(cx) {
686 return;
687 }
688 let list = this.list();
689 let selected = list.selected().cloned();
690 let open = list.open_row().map(|row| row.key.clone());
691 change(this.list_mut());
692 let list = this.list();
693 let now_selected = list.selected().cloned();
694 let now_open = list.open_row().map(|row| row.key.clone());
695 if now_selected != selected {
696 this.on_selection_changed(now_selected, cx);
697 }
698 if now_open.is_some() != open.is_some() {
699 this.on_panel_toggled(now_open.is_some(), cx);
700 }
701 if let Some(key) = now_open.filter(|key| Some(key) != open.as_ref()) {
702 cx.emit(DashboardEvent::Opened(key.clone()));
703 this.on_open(key, cx);
704 }
705 cx.notify();
706}
707
708pub(crate) fn activate<D: ListDashboard>(this: &mut D, cx: &mut Context<D>) {
711 if !this.can_navigate(cx) {
712 return;
713 }
714 if let Some(key) = this.list().selected().cloned()
715 && this.on_activate(&key, cx)
716 {
717 cx.notify();
718 return;
719 }
720 update(this, cx, |list| {
721 list.activate();
722 });
723}
724
725mod menu;
726mod view;
727
728pub(crate) use menu::line_menu;
729pub use view::{header, render, render_body, render_under};
730
731#[cfg(test)]
732#[path = "list/header_tests.rs"]
733mod header_tests;
734
735#[cfg(test)]
736#[path = "list/note_tests.rs"]
737mod note_tests;
738
739#[cfg(test)]
740#[path = "list/caption_tests.rs"]
741mod caption_tests;
742
743#[cfg(test)]
744mod tests {
745 use super::{Body, Glyph, Group, GroupIndicator, ListState, Row, Section};
746 use crate::tokens::Tone;
747 use gpui_kit::SharedString;
748
749 #[test]
750 fn string_conversions_keep_plain_text_distinct_from_explicit_markup() {
751 let text = "<strong>Display as text</strong>";
752 let expected = Body::Text(text.into());
753 assert_eq!(Body::from(SharedString::from(text)), expected);
754 assert_eq!(Body::from(text), expected);
755 assert_eq!(Body::from(text.to_owned()), expected);
756 assert_eq!(Section::text("Heading", text).body, expected);
757 assert_eq!(
758 Section::markdown("Heading", text).body,
759 Body::Markdown(text.into())
760 );
761 assert_eq!(Section::html("Heading", text).body, Body::Html(text.into()));
762 }
763
764 #[test]
765 fn group_indicators_are_an_independent_presentation_mark_per_group() {
766 let a = GroupIndicator {
767 icon: subspace_lucide::IconName::ShieldCheck,
768 tone: Tone::Green,
769 label: "Scanning enabled".into(),
770 tooltip: "Code scanning is enabled".into(),
771 };
772 let b = a.clone();
773 assert_eq!(a, b);
774
775 let different_tone = GroupIndicator {
776 tone: Tone::Red,
777 ..a.clone()
778 };
779 assert_ne!(a, different_tone);
780 }
781
782 fn row(key: &'static str) -> Row {
783 Row {
784 key: key.into(),
785 icon: Glyph::new("●", Tone::Yellow),
786 id: None,
787 title: key.into(),
788 trailing: Vec::new(),
789 done: false,
790 indent: 0,
791 }
792 }
793
794 fn state() -> ListState {
795 ListState::new(vec![
796 Group {
797 key: "g1".into(),
798 icon: Glyph::new("◆", Tone::Blue),
799 name: "Group 1".into(),
800 count: None,
801 rows: vec![row("a"), row("b")],
802 },
803 Group {
804 key: "g2".into(),
805 icon: Glyph::new("◆", Tone::Blue),
806 name: "Group 2".into(),
807 count: None,
808 rows: vec![row("c")],
809 },
810 ])
811 }
812
813 fn keys(state: &ListState) -> Vec<String> {
814 state
815 .visible_keys()
816 .iter()
817 .map(ToString::to_string)
818 .collect()
819 }
820
821 #[test]
822 fn stepping_walks_headers_and_rows_and_stops_at_the_ends() {
823 let mut list = state();
824 list.step(1);
825 assert_eq!(list.selected().map(AsRef::as_ref), Some("g1"));
826 list.step(-1);
827 assert_eq!(list.selected().map(AsRef::as_ref), Some("g1"));
828 for _ in 0..10 {
829 list.step(1);
830 }
831 assert_eq!(list.selected().map(AsRef::as_ref), Some("c"));
832 assert_eq!(list.row_count(), 3);
833 list.select_end(false);
834 assert_eq!(list.selected().map(AsRef::as_ref), Some("g1"));
835 }
836
837 #[test]
838 fn enter_folds_a_group_and_opens_a_row() {
839 let mut list = state();
840 list.select("g1".into());
841 assert_eq!(list.activate(), None);
842 assert_eq!(keys(&list), ["g1", "g2", "c"]);
843 list.activate();
844 assert_eq!(keys(&list), ["g1", "a", "b", "g2", "c"]);
845
846 list.select("a".into());
847 assert!(list.open_row().is_none());
848 assert_eq!(list.activate().as_deref(), Some("a"));
849 assert_eq!(list.open_row().map(|r| r.key.as_ref()), Some("a"));
850 list.step(1);
852 assert_eq!(list.open_row().map(|r| r.key.as_ref()), Some("b"));
853 list.step(1);
855 assert!(list.open_row().is_none());
856 list.step(1);
857 assert!(list.open_row().is_none(), "the panel stays closed");
858 list.activate();
859 list.close_detail();
860 assert!(list.open_row().is_none());
861 }
862
863 #[test]
864 fn panel_steps_skip_group_headers() {
865 let mut list = state();
866 list.select("b".into());
867 assert_eq!(list.step_row(1).as_deref(), Some("c"));
868 assert_eq!(list.open_row().map(|r| r.key.as_ref()), Some("c"));
869 assert_eq!(list.step_row(1).as_deref(), Some("c"), "stops at the end");
870 assert_eq!(list.step_row(-2).as_deref(), Some("a"));
871 }
872
873 #[test]
874 fn reveal_unfolds_selects_and_opens() {
875 let mut list = state();
876 list.toggle(&"g2".into());
877 assert!(list.reveal("c"));
878 assert_eq!(keys(&list), ["g1", "a", "b", "g2", "c"]);
879 assert_eq!(list.open_row().map(|r| r.key.as_ref()), Some("c"));
880 assert!(!list.reveal("missing"));
881 }
882
883 #[test]
884 fn replacing_groups_keeps_a_selection_that_is_still_shown() {
885 let mut list = state();
886 list.select("c".into());
887 list.set_groups(state().groups().to_vec());
888 assert_eq!(list.selected().map(AsRef::as_ref), Some("c"));
889 list.set_groups(Vec::new());
890 assert!(list.selected().is_none());
891 }
892}