use std::rc::Rc;
use gpui_kit::component::ActiveTheme as _;
use gpui_kit::component::button::Button;
use gpui_kit::prelude::FluentBuilder as _;
use gpui_kit::{
AnyElement, App, ClickEvent, FocusHandle, InteractiveElement as _, IntoElement as _,
ParentElement as _, Role, SharedString, StatefulInteractiveElement as _, TestSupportExt as _,
Window,
};
use super::super::row_parts::count_mark;
use crate::segmented;
use crate::tokens::Tokens;
pub const INSPECTOR_MAX_TABS: usize = 3;
pub(super) const TAB_LIST_ID: &str = "workspace-inspector-tabs";
pub(super) const TAB_ID: &str = "workspace-inspector-tab";
pub(super) type SelectHandler = Rc<dyn Fn(usize, &ClickEvent, &mut Window, &mut App)>;
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct InspectorTab {
pub label: SharedString,
pub count: Option<SharedString>,
}
impl InspectorTab {
pub fn new(label: impl Into<SharedString>) -> Self {
Self {
label: label.into(),
count: None,
}
}
pub fn count(mut self, count: impl Into<SharedString>) -> Self {
self.count = Some(count.into());
self
}
pub fn accessible_label(&self) -> SharedString {
match &self.count {
Some(count) => format!("{}, {count}", self.label).into(),
None => self.label.clone(),
}
}
}
pub(super) struct InspectorTabs {
pub(super) tabs: Vec<InspectorTab>,
pub(super) selected: usize,
pub(super) on_select: SelectHandler,
pub(super) focus: Option<(usize, FocusHandle)>,
}
pub(super) fn kept(tabs: Vec<InspectorTab>, selected: usize) -> (Vec<InspectorTab>, Option<usize>) {
let tabs: Vec<_> = tabs.into_iter().take(INSPECTOR_MAX_TABS).collect();
let selected = (selected < tabs.len()).then_some(selected);
(tabs, selected)
}
pub(super) fn tab_list(
name: SharedString,
tabs: InspectorTabs,
tokens: &Tokens,
cx: &App,
) -> AnyElement {
let (items, selected) = kept(tabs.tabs, tabs.selected);
let mono = cx.theme().mono_font_family.clone();
let on_select = tabs.on_select;
segmented::frame(tokens)
.id(TAB_LIST_ID)
.test_support()
.role(Role::TabList)
.aria_label(name)
.children(items.into_iter().enumerate().map(|(index, tab)| {
let chosen = selected == Some(index);
let callback = on_select.clone();
let template = Button::new((TAB_ID, index)).role(Role::Tab);
let name = tab.accessible_label();
segmented::segment(template, tab.label, chosen, tokens)
.when_some(
tabs.focus.as_ref().filter(|(tracked, _)| *tracked == index),
|button, (_, focus)| button.track_focus(focus),
)
.accessibility_label(name)
.aria_selected(chosen)
.children(
tab.count
.map(|count| count_mark(count, mono.clone(), tokens)),
)
.on_click(move |event, window, cx| callback(index, event, window, cx))
}))
.into_any_element()
}
pub(super) fn panel_label(tabs: &InspectorTabs) -> Option<SharedString> {
tabs.tabs
.get(tabs.selected)
.filter(|_| tabs.selected < INSPECTOR_MAX_TABS)
.map(|tab| tab.label.clone())
}