Skip to main content

subspace_dashboard/
list.rs

1//! The shared list view: group header rows, item rows and the detail panel.
2//!
3//! [`ListState`] is plain data: the groups, the selection, the folded groups,
4//! whether the detail panel is open and the load status. [`render`] draws it
5//! for any [`ListDashboard`], with the loading, empty and error states
6//! (REQ-13), the wrap setting (REQ-09) and the density tokens (REQ-10).
7
8use 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
18/// Blank space under the last line, so it clears the window edge.
19const LIST_TAIL_HEIGHT_PX: f32 = 48.;
20/// Vertical padding of a wrapped row, which has no fixed height.
21const WRAPPED_ROW_PADDING_Y_PX: f32 = 4.;
22/// How much taller a comfortable row is than the theme's row height.
23const COMFORTABLE_ROW_SCALE: f32 = 1.125;
24/// Space above and below an inset row's rounded fill.
25const ROW_FILL_GAP_PX: f32 = 1.;
26/// Left padding of a row, before the group indent.
27const ROW_PADDING_LEFT_PX: f32 = 6.;
28/// Width of the fold arrow in a group header.
29const FOLD_ARROW_WIDTH_PX: f32 = 14.;
30/// Least width of a row's short id, so the titles line up.
31const ROW_ID_MIN_WIDTH_PX: f32 = 56.;
32/// Least height of one property line in the detail panel.
33const PROP_ROW_MIN_HEIGHT_PX: f32 = 28.;
34/// Width of the property label column.
35const PROP_LABEL_WIDTH_PX: f32 = 96.;
36/// Space above a panel section, and above the extra content under them.
37const SECTION_TOP_MARGIN_PX: f32 = 18.;
38const SECTION_TOP_PADDING_PX: f32 = 12.;
39/// The panel title.
40const PANEL_TITLE_SIZE_PX: f32 = 16.;
41const PANEL_TITLE_MARGIN_PX: f32 = 14.;
42
43/// A short coloured glyph: a row's type icon or a trailing state mark.
44#[derive(Debug, Clone, PartialEq, Eq)]
45pub struct Glyph {
46    pub text: SharedString,
47    pub tone: Tone,
48    /// An exact colour as `0xRRGGBB`, such as a GitHub label's; it wins over
49    /// `tone`.
50    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    /// A glyph in the exact colour `rgb` (`0xRRGGBB`).
63    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/// One list row: icon, muted id, title, then trailing glyphs.
73#[derive(Debug, Clone, PartialEq, Eq)]
74pub struct Row {
75    /// Unique in the list; the dashboard looks its details up by this key.
76    /// Also the row's item search document id, by convention.
77    pub key: SharedString,
78    pub icon: Glyph,
79    /// Short identifier, such as `1258950` or `repo#123`.
80    pub id: Option<SharedString>,
81    pub title: SharedString,
82    pub trailing: Vec<Glyph>,
83    /// Finished items show a muted title.
84    pub done: bool,
85    /// Extra indent levels under the group header, for a nested row such as
86    /// a pull request under its project's main branch.
87    pub indent: u8,
88}
89
90/// A group header (a repository, project or parent item) and its rows.
91#[derive(Debug, Clone, PartialEq, Eq)]
92pub struct Group {
93    pub key: SharedString,
94    pub icon: Glyph,
95    pub name: SharedString,
96    /// Shown at the right of the header.
97    pub count: Option<SharedString>,
98    pub rows: Vec<Row>,
99}
100
101/// A quiet line under a group's rows that is not a row: what the group is
102/// waiting for, or why it has nothing to show. It takes no selection and no
103/// keyboard stop, and folding the group hides it.
104#[derive(Debug, Clone, PartialEq, Eq)]
105pub enum GroupNote {
106    /// The group's rows are still on their way, such as "Loading runs…".
107    Loading(SharedString),
108    /// The group loaded with nothing to show, such as "No failed runs".
109    Empty(SharedString),
110}
111
112impl GroupNote {
113    /// The accessible name of group `group`'s note line, such as
114    /// "acme/api: loading runs": the group, then the message in lower case
115    /// without its trailing ellipsis or full stop.
116    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/// A caption inside a group, above the row `before`, naming the run of rows
126/// under it, such as "Ships" or "People". It shows in capitals; its
127/// accessible name and id keep the text as written. It is not a row: it
128/// takes no selection and no keyboard stop, the list keys and the panel's
129/// steps pass over it, a selection restored after new groups never lands on
130/// it, and folding the group hides it.
131#[derive(Debug, Clone, PartialEq, Eq)]
132pub struct GroupCaption {
133    /// The key of the row the caption sits above. A caption whose row is not
134    /// in the group is not drawn.
135    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/// A small, non-interactive status mark shown at the right of a group
149/// header, such as a repository's scanning status. Presentation only: it
150/// carries no click behaviour of its own.
151#[derive(Debug, Clone, PartialEq, Eq)]
152pub struct GroupIndicator {
153    pub icon: subspace_lucide::SvgIcon,
154    pub tone: crate::tokens::Tone,
155    /// Read by assistive technology; also the row's accessible name.
156    pub label: SharedString,
157    /// Shown in a hover tooltip.
158    pub tooltip: SharedString,
159}
160
161/// The text of a panel section.
162#[derive(Debug, Clone, PartialEq, Eq)]
163pub enum Body {
164    Text(SharedString),
165    Markdown(SharedString),
166    /// Service HTML, such as an Azure DevOps description; sanitised for display.
167    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/// A labelled block of text in the detail panel.
177#[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/// A link to the item's page in its service, such as "GitHub ↗".
207#[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/// What the detail panel shows for one row.
223#[derive(Debug, Clone, PartialEq, Eq, Default)]
224pub struct Detail {
225    /// The panel bar's type label, such as `Product Backlog Item`.
226    pub kind: SharedString,
227    pub id: SharedString,
228    pub title: SharedString,
229    /// The item's page in its service.
230    pub link: Option<ServiceLink>,
231    /// Label and value pairs, in order.
232    pub props: Vec<(SharedString, SharedString)>,
233    pub sections: Vec<Section>,
234}
235
236/// Whether the list has loaded (REQ-13).
237#[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/// The list's groups, selection, folded groups, panel and load status, and
249/// its scroll position.
250#[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    /// The next render scrolls the selected line into view.
259    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    // qual:allow(dry, boilerplate) reason: "Read-only groups keep mutation behind set_groups, which reconciles selection and the open panel."
271    pub fn groups(&self) -> &[Group] {
272        &self.groups
273    }
274
275    /// Replace the groups. The selection stays when its key is still shown.
276    // qual:api
277    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    // qual:allow(dry, boilerplate) reason: "The shared renderer borrows load status through this public reader; the behavioral state remains private and cannot be replaced directly by callers."
290    pub fn status(&self) -> &LoadStatus {
291        &self.status
292    }
293
294    // qual:api
295    // qual:allow(dry, boilerplate) reason: "This setter is the public write boundary for private load state; exposing the field would make its representation part of the API."
296    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    /// The selected row, when a row (not a group header) is selected.
318    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    /// The row whose details are open.
324    pub fn open_row(&self) -> Option<&Row> {
325        self.detail_open.then(|| self.selected_row()).flatten()
326    }
327
328    /// The list's scroll handle, for a dashboard that draws the rows itself.
329    // qual:allow(dry, boilerplate) reason: "ListState owns the same scroll handle used by rendering and selection navigation; custom dashboards may borrow it but must not replace its identity."
330    pub fn scroll_handle(&self) -> &ScrollHandle {
331        &self.scroll
332    }
333
334    /// Scroll the selected line into view at the next render. Selection
335    /// changes through [`ListState`] ask for this themselves.
336    pub fn scroll_to_selected(&self) {
337        self.scroll_pending.set(true);
338    }
339
340    /// Takes the pending scroll request: the selected line's position among
341    /// the visible lines, when one is pending.
342    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    /// Keys in display order: each group header, then its rows unless folded.
351    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        // The panel follows the selection while it is open.
366        if self.selected_row().is_none() {
367            self.detail_open = false;
368        }
369    }
370
371    /// Move the selection by `step` visible lines; the first move selects
372    /// the first line. Stops at either end.
373    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    /// Select the first (`last` false) or the last visible line.
391    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    /// The panel's previous and next: move to the next visible row, skipping
400    /// group headers, and keep the panel open. Returns the new row's key.
401    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    /// Enter: fold or unfold a selected group, or open a selected row.
422    /// Returns the key of the row whose details opened.
423    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    /// Show the row `key` wherever it is: unfold its group, select it and
435    /// open its details (REQ-05). False when no row has the key.
436    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
462/// A dashboard drawn as grouped rows with a detail panel.
463pub trait ListDashboard: Dashboard {
464    /// A write dialog can prevent selection/panel changes until it finishes.
465    fn can_navigate(&self, _cx: &App) -> bool {
466        true
467    }
468    fn list(&self) -> &ListState;
469    fn list_mut(&mut self) -> &mut ListState;
470    /// The details of row `key`.
471    fn detail(&self, key: &str) -> Option<Detail>;
472
473    /// Optional domain identity in place of the default glyph, such as chat avatars.
474    fn row_leading(&self, _row: &Row, _cx: &App) -> Option<AnyElement> {
475        None
476    }
477
478    /// Optional lanes after the title in place of the row's trailing glyphs,
479    /// such as labels, a grouping and an owner. `None`, the default,
480    /// draws [`Row::trailing`].
481    fn row_trailing(&self, _row: &Row, _cx: &App) -> Option<AnyElement> {
482        None
483    }
484
485    /// Optional mark in place of a group header's glyph, such as a workflow
486    /// state's icon. `None`, the default, draws [`Group::icon`].
487    fn group_leading(&self, _group: &Group, _cx: &App) -> Option<AnyElement> {
488        None
489    }
490
491    /// Optional board-specific content inset; the theme remains the default.
492    fn list_side_inset(&self) -> Option<gpui_kit::Pixels> {
493        None
494    }
495
496    /// Keep a group's count next to its name instead of at the trailing edge.
497    fn group_count_after_name(&self) -> bool {
498        false
499    }
500
501    /// Use the row font size for group names while keeping the theme's heading styling.
502    fn group_heading_matches_row(&self) -> bool {
503        false
504    }
505
506    /// Comfortable rows: a step taller than the theme's row height, and group
507    /// headers set apart by space and a hairline rather than a filled band.
508    /// The theme's density still sets the base size.
509    fn comfortable_rows(&self) -> bool {
510        false
511    }
512
513    /// Emphasize the title without changing the leading identity column.
514    fn row_emphasis(&self, _row: &Row, _cx: &App) -> bool {
515        false
516    }
517
518    /// Accessible row name, including board-owned attention state when needed.
519    fn row_accessible_label(&self, row: &Row, _cx: &App) -> SharedString {
520        row.title.clone()
521    }
522
523    /// Whether the list's own empty, error and banner text offers the chat
524    /// in its menu. Rows say so through [`ListDashboard::row_menu`].
525    fn menu_chat(&self) -> MenuChat {
526        MenuChat::Offered
527    }
528
529    /// The title and hint when there is nothing to show.
530    fn empty_message(&self) -> (SharedString, SharedString) {
531        (
532            "Nothing to show".into(),
533            "Try another filter, or reload.".into(),
534        )
535    }
536
537    /// The empty state's actions. `None`, the default, offers Configure,
538    /// which opens the board's settings; override when the board itself
539    /// owns the next step, such as choosing repositories.
540    fn empty_actions(&self, _cx: &mut Context<Self>) -> Option<Vec<AnyElement>> {
541        None
542    }
543
544    /// More panel content under the sections of row `key`, such as a
545    /// composer.
546    fn panel_extra(&self, _key: &str, _cx: &App) -> Option<AnyElement> {
547        None
548    }
549
550    /// Content pinned below the scrolling details, such as a chat composer.
551    fn panel_footer(&self, _key: &str, _cx: &App) -> Option<AnyElement> {
552        None
553    }
554
555    /// An optional handle for controlling the detail body's scroll position.
556    fn panel_scroll_handle(&self, _key: &str) -> Option<ScrollHandle> {
557        None
558    }
559
560    /// Let bounded panel content own scrolling, with the footer outside it.
561    /// In this mode the panel ignores `panel_scroll_handle`.
562    fn panel_content_owns_scroll(&self, _key: &str) -> bool {
563        false
564    }
565
566    /// Room reserved for the list when the inspector or Copilot narrows the board.
567    fn min_list_width(&self) -> f32 {
568        0.0
569    }
570
571    /// The selection moved to `selected` (keys, clicks, the panel's steps,
572    /// a search result). Changes made through [`update`] call this.
573    fn on_selection_changed(&mut self, _selected: Option<SharedString>, _cx: &mut Context<Self>) {}
574
575    /// Row `key`'s details opened, or the open panel moved to row `key`:
576    /// the place to start loading what the panel shows.
577    fn on_open(&mut self, _key: SharedString, _cx: &mut Context<Self>) {}
578
579    /// The detail panel opened (`true`) or closed.
580    fn on_panel_toggled(&mut self, _open: bool, _cx: &mut Context<Self>) {}
581
582    /// Enter or a click on line `key`, before the list folds a group or
583    /// opens a row. Return `true` when the dashboard handled it, such as a
584    /// "load more" line.
585    fn on_activate(&mut self, _key: &SharedString, _cx: &mut Context<Self>) -> bool {
586        false
587    }
588
589    /// Whether a click on `row` activates it, as Enter does. `false` makes
590    /// a click only select the row and a double click activate it, for a
591    /// row whose action changes something, such as joining a channel.
592    fn activates_on_click(&self, _row: &Row) -> bool {
593        true
594    }
595
596    /// What the row's right-click menu offers. The default gives the row's
597    /// title and id, with its details to open; add the item's link by
598    /// overriding. The standard commands take their places among the
599    /// seven groups of [`row_menu::MenuGroup`].
600    fn row_menu(&self, row: &Row) -> RowMenu {
601        RowMenu::from_row(row)
602    }
603
604    /// The board's own commands for the line the menu is for, each in the
605    /// group it belongs to: the item's verbs in `MenuGroup::Act`, leaving or
606    /// removing in `MenuGroup::Remove`. The menu orders the groups. The line
607    /// was selected before this runs, so `board.read(cx).list().selected()`
608    /// is the line the menu is for.
609    fn row_commands(_board: &Entity<Self>, _cx: &App) -> Vec<row_menu::MenuCommand>
610    where
611        Self: Sized,
612    {
613        Vec::new()
614    }
615
616    /// Append board-owned entries to the row menu's Act group. Prefer
617    /// [`Self::row_commands`], which places each command in its group.
618    fn extend_row_menu(&self, menu: PopupMenu, _cx: &App) -> PopupMenu {
619        menu
620    }
621
622    /// Append board-owned submenus after [`Self::extend_row_menu`], in the
623    /// Act group. The menu's own context builds them; `board` reads the
624    /// dashboard and acts on it from the entries. The line was selected
625    /// before this runs, so `board.read(cx).list().selected()` is the line
626    /// the menu is for. Prefer `MenuCommand::submenu` in
627    /// [`Self::row_commands`].
628    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    /// Optional friendly header text. The underlying ID stays available to menus.
641    fn panel_header_label(&self, _key: &str) -> Option<SharedString> {
642        None
643    }
644
645    /// What a group header's right-click menu offers. `None`, the default,
646    /// gives a header no menu: a repository or a section is not an item.
647    /// Override where the header stands for one; its menu also offers Fold
648    /// group or Unfold group in the View group.
649    fn group_menu(&self, _group: &Group) -> Option<RowMenu> {
650        None
651    }
652
653    /// Status marks shown at the right of a group header, after its name
654    /// and count, such as a repository's scanning status. Empty by default,
655    /// which preserves every existing board's header.
656    fn group_indicators(&self, _group: &Group, _cx: &App) -> Vec<GroupIndicator> {
657        vec![]
658    }
659
660    /// Captions inside group `group`, each above the row it names, such as
661    /// "Ships" above a fleet's ships and "People" above its people. Empty,
662    /// the default, draws none, which preserves every existing board's
663    /// groups.
664    fn group_captions(&self, _group: &Group, _cx: &App) -> Vec<GroupCaption> {
665        Vec::new()
666    }
667
668    /// A quiet line under a group's rows, such as "Loading runs…" while the
669    /// group's records load or "No failed runs" when a filter matches none.
670    /// `None`, the default, draws nothing, which preserves every existing
671    /// board's groups.
672    fn group_note(&self, _group: &Group, _cx: &App) -> Option<GroupNote> {
673        None
674    }
675}
676
677/// Changes the list with `change`, then calls the [`ListDashboard`] hooks
678/// for what changed, tells the shell which row opened, and redraws. Use it
679/// for selection and panel changes made outside the list's own keys.
680pub 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
708/// Enter: the dashboard's [`ListDashboard::on_activate`] first, then fold
709/// the selected group or open the selected row.
710pub(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        // The open panel follows the selection to the next row.
851        list.step(1);
852        assert_eq!(list.open_row().map(|r| r.key.as_ref()), Some("b"));
853        // A group header has no details, so the panel closes.
854        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}