subspace-shell 0.10.1

Subspace Framework shell: the window, switcher, palette, help, Settings and themes. Internal crate; apps depend on `subspace-framework`.
Documentation
//! A Space's right-click menu, on its switcher tab and its navigation rail
//! destination, built from the standard groups: Close Space in Remove, then
//! Space settings… in Place. Closing saves and applies the same choice as
//! turning the Space off in Settings.

use gpui_kit::component::menu::ContextMenu;
use gpui_kit::{
    Context, InteractiveElement, ParentElement, SharedString, Styled, WeakEntity, Window,
};
use subspace_dashboard::Toast;
use subspace_dashboard::anchored::AnchoredContextMenuExt as _;
use subspace_dashboard::prefs;
use subspace_dashboard::row_menu::{self, GroupedMenu, MenuCommand, MenuGroup};
use subspace_lucide::IconName;

use super::cover::cover_while_open;
use super::navigation::NavigationMode;
use super::{ACTIVE_KEY, SubspaceApp};
use crate::settings::board_choice::{self, Applied};

/// The menu's wording.
pub(super) const CLOSE_SPACE: &str = "Close Space";
pub(super) const SPACE_SETTINGS: &str = "Space settings…";
pub(super) const LAST_SPACE: &str = "The last open Space can't be closed.";

/// Adds Space `id`'s right-click menu to its tab. `closable` is false for
/// the last open Space, whose Close item is disabled with the reason. While
/// open, the menu covers the board area.
pub(super) fn with_space_menu<E>(
    element: E,
    id: &'static str,
    closable: bool,
    app: WeakEntity<SubspaceApp>,
) -> ContextMenu<E>
where
    E: InteractiveElement + ParentElement + Styled,
{
    element.anchored_context_menu(move |menu, window, cx| {
        cover_while_open(&app, window, cx);
        row_menu::build(menu, space_commands(id, closable, &app), window, cx)
    })
}

/// Close Space, disabled with the reason for the last open Space, and
/// Space settings….
fn space_commands(id: &'static str, closable: bool, app: &WeakEntity<SubspaceApp>) -> GroupedMenu {
    let close_app = app.clone();
    let settings_app = app.clone();
    let close = MenuCommand::new(
        MenuGroup::Remove,
        CLOSE_SPACE,
        IconName::X,
        move |window, cx| {
            _ = close_app.update(cx, |app, cx| app.close_space(id, window, cx));
        },
    )
    .disabled(!closable, LAST_SPACE);
    let settings = MenuCommand::new(
        MenuGroup::Place,
        SPACE_SETTINGS,
        IconName::Settings,
        move |window, cx| {
            _ = settings_app.update(cx, |app, cx| app.open_board_settings(id, window, cx));
        },
    );
    GroupedMenu::new().with(close).with(settings)
}

/// The tab that takes over from the tab at `index` when it closes: the one
/// before it, or the next one when it is first. None for the last tab.
pub(super) fn neighbour(index: usize, len: usize) -> Option<usize> {
    if len < 2 || index >= len {
        None
    } else if index == 0 {
        Some(1)
    } else {
        Some(index - 1)
    }
}

/// The toast after Space `title` closed, saying where to add it again:
/// `plus`, the place of the Add a Space plus.
fn closed_message(title: &str, applied: Applied, plus: &str) -> String {
    match applied {
        Applied::Now => format!("Closed {title}. Add it again from {plus}."),
        Applied::AfterRestart => format!("Restart the app to close {title}."),
    }
}

/// Where the Add a Space plus is in `navigation`: in the title bar after the
/// tabs, or at the end of the vertical navigation rail.
fn plus_place(navigation: NavigationMode) -> &'static str {
    match navigation {
        NavigationMode::Horizontal => "the plus in the title bar",
        NavigationMode::Vertical => "the plus at the end of the navigation rail",
    }
}

impl SubspaceApp {
    /// Whether a Space can be closed from its tab: never the last one.
    pub(super) fn can_close_space(&self) -> bool {
        self.dashboards.len() > 1
    }

    /// Turns Space `id` off as its Settings switch and Save do. When it was
    /// the current Space, its neighbour becomes current and takes focus.
    pub(super) fn close_space(
        &mut self,
        id: &'static str,
        window: &mut Window,
        cx: &mut Context<Self>,
    ) {
        let Some(index) = self.dashboards.iter().position(|board| board.id == id) else {
            return;
        };
        let Some(next) = neighbour(index, self.dashboards.len()) else {
            return;
        };
        let title = self.dashboards[index].title.clone();
        let next = self.dashboards[next].id;
        let was_active = index == self.active;
        match board_choice::save_board_enabled(id, false, window, cx) {
            Ok(applied) => {
                self.closed_space(&title, applied, was_active.then_some(next), window, cx)
            }
            Err(error) => {
                self.push_toast(Toast::error(format!("Couldn't close {title}: {error}")), cx)
            }
        }
    }

    fn closed_space(
        &mut self,
        title: &SharedString,
        applied: Applied,
        next: Option<&'static str>,
        window: &mut Window,
        cx: &mut Context<Self>,
    ) {
        if let (Applied::Now, Some(next)) = (applied, next) {
            self.follow_neighbour(next, window, cx);
        }
        let message = closed_message(title, applied, plus_place(self.navigation_mode));
        self.push_toast(Toast::info(message), cx);
    }

    /// Makes Space `next` current after the current one closed. While Logs or
    /// Search replaces the board, it stays shown and `next` waits behind it.
    fn follow_neighbour(
        &mut self,
        next: &'static str,
        window: &mut Window,
        cx: &mut Context<Self>,
    ) {
        let Some(index) = self.dashboards.iter().position(|board| board.id == next) else {
            return;
        };
        if self.main.is_board() {
            self.switch_to(index, window, cx);
        } else {
            self.active = index;
            prefs::set(cx, ACTIVE_KEY, next);
        }
    }
}

#[cfg(test)]
mod tests {
    use super::{Applied, NavigationMode, closed_message, neighbour, plus_place};

    #[test]
    fn the_neighbour_is_the_previous_tab_or_the_next_for_the_first() {
        assert_eq!(neighbour(2, 3), Some(1));
        assert_eq!(neighbour(1, 3), Some(0));
        assert_eq!(neighbour(0, 3), Some(1));
        assert_eq!(neighbour(0, 1), None);
        assert_eq!(neighbour(3, 3), None);
    }

    #[test]
    fn the_closed_toast_says_where_to_reopen_the_space() {
        let title_bar = plus_place(NavigationMode::Horizontal);
        let rail = plus_place(NavigationMode::Vertical);
        assert_eq!(
            closed_message("Actions", Applied::Now, title_bar),
            "Closed Actions. Add it again from the plus in the title bar."
        );
        assert_eq!(
            closed_message("Actions", Applied::Now, rail),
            "Closed Actions. Add it again from the plus at the end of the navigation rail."
        );
        for plus in [title_bar, rail] {
            assert_eq!(
                closed_message("Actions", Applied::AfterRestart, plus),
                "Restart the app to close Actions."
            );
        }
    }
}