mod projection;
#[cfg(test)]
mod runtime_tests;
mod view;
use std::rc::Rc;
use crate::action::Intent;
use crate::anchored::Anchor;
use gpui_kit::component::menu::{PopupMenu, PopupMenuItem};
use gpui_kit::{
AnyElement, App, AppContext as _, Bounds, Context, Entity, FocusHandle, IntoElement, Pixels,
SharedString, WeakEntity, Window,
};
use subspace_lucide::IconName;
const DEFAULT_GAP: f32 = 4.;
const DEFAULT_CHEVRON_WIDTH: f32 = 28.;
const NO_WIDTH: f32 = 0.;
pub type InlineBuilder = Rc<dyn Fn(&mut Window, &mut App) -> AnyElement>;
#[derive(Clone)]
pub struct OverflowAnchor {
bounds: Bounds<Pixels>,
host: Entity<Anchor>,
}
impl OverflowAnchor {
pub fn bounds(&self) -> Bounds<Pixels> {
self.bounds
}
pub fn host(&self) -> Entity<Anchor> {
self.host.clone()
}
}
#[derive(Clone)]
pub struct PopupEntry(Rc<dyn Fn(OverflowAnchor) -> PopupMenuItem>);
impl PopupEntry {
pub fn new(builder: impl Fn() -> PopupMenuItem + 'static) -> Self {
Self(Rc::new(move |_| builder()))
}
fn build(&self, anchor: OverflowAnchor) -> PopupMenuItem {
(self.0)(anchor)
}
pub fn anchored(builder: impl Fn(OverflowAnchor) -> PopupMenuItem + 'static) -> Self {
Self(Rc::new(builder))
}
}
#[derive(Clone)]
pub struct OverflowUnit {
pub key: SharedString,
pub measured_width: f32,
pub inline: InlineBuilder,
pub popup_entries: Vec<PopupEntry>,
}
impl OverflowUnit {
pub const UNMEASURED_WIDTH: f32 = 0.;
pub fn new(
key: impl Into<SharedString>,
measured_width: f32,
inline: InlineBuilder,
popup_entries: Vec<PopupEntry>,
) -> Self {
Self {
key: key.into(),
measured_width,
inline,
popup_entries,
}
}
pub fn inline<F, E>(
key: impl Into<SharedString>,
measured_width: f32,
inline: F,
popup_entries: Vec<PopupEntry>,
) -> Self
where
F: Fn(&mut Window, &mut App) -> E + 'static,
E: IntoElement,
{
Self::new(
key,
measured_width,
Rc::new(move |window, cx| inline(window, cx).into_any_element()),
popup_entries,
)
}
pub fn icon_button(
id: &'static str,
icon: IconName,
label: &'static str,
on_click: impl Fn(&mut Window, &mut App) + 'static,
) -> Self {
let on_click: Rc<dyn Fn(&mut Window, &mut App)> = Rc::new(on_click);
let menu_click = on_click.clone();
let entry = PopupEntry::new(move || {
let run = menu_click.clone();
PopupMenuItem::new(label)
.icon(icon)
.on_click(move |_, window, cx| run(window, cx))
});
Self::inline(
id,
Self::UNMEASURED_WIDTH,
move |_, _| {
let run = on_click.clone();
crate::action::icon_button(id, Intent::Quiet, icon, label)
.on_click(move |_, window, cx| run(window, cx))
},
vec![entry],
)
}
}
#[derive(Debug, Clone, PartialEq)]
pub struct OverflowPlan {
pub visible: usize,
pub hidden: usize,
}
impl OverflowPlan {
pub fn has_overflow(&self) -> bool {
self.hidden != 0
}
}
pub fn plan_overflow(
available: Option<f32>,
widths: &[f32],
gap: f32,
chevron: f32,
) -> OverflowPlan {
let count = widths.len();
let plan = |visible: usize| OverflowPlan {
visible,
hidden: count - visible,
};
let available = match available {
None => return plan(count),
Some(width) if width <= NO_WIDTH => return plan(0),
Some(_) if widths.iter().any(|width| *width <= 0.0) => return plan(count),
Some(width) => width,
};
let total = widths.iter().sum::<f32>() + gap * count.saturating_sub(1) as f32;
if total <= available {
return plan(count);
}
let mut used = 0.0;
let mut visible = 0;
for width in widths {
let next = used + *width + if visible > 0 { gap } else { 0.0 };
if next + gap + chevron > available {
break;
}
used = next;
visible += 1;
}
plan(visible)
}
pub struct OverflowToolbar {
units: Vec<OverflowUnit>,
widths: Vec<f32>,
viewport: Option<f32>,
gap: f32,
chevron_width: f32,
trigger_bounds: Bounds<Pixels>,
popup: Option<WeakEntity<PopupMenu>>,
popup_dirty: bool,
anchor: Option<Entity<Anchor>>,
focus: Option<FocusHandle>,
projection: projection::Projection,
}
impl OverflowToolbar {
pub fn sync(
slot: &mut Option<Entity<Self>>,
units: Vec<OverflowUnit>,
cx: &mut App,
) -> Entity<Self> {
let toolbar = slot.get_or_insert_with(|| cx.new(|_| Self::new(Vec::new())));
toolbar.update(cx, |toolbar, cx| toolbar.set_units(units, cx));
toolbar.clone()
}
pub fn new(units: Vec<OverflowUnit>) -> Self {
let widths = units.iter().map(|unit| unit.measured_width).collect();
Self {
units,
widths,
viewport: None,
gap: DEFAULT_GAP,
chevron_width: DEFAULT_CHEVRON_WIDTH,
trigger_bounds: Bounds::default(),
popup: None,
popup_dirty: false,
anchor: None,
focus: None,
projection: Default::default(),
}
}
fn popup(menu: PopupMenu, items: Vec<PopupMenuItem>) -> PopupMenu {
items
.into_iter()
.fold(menu.scrollable(true), |menu, item| menu.item(item))
}
pub fn content_width(&self) -> f32 {
self.widths.iter().sum::<f32>() + self.gap * self.widths.len().saturating_sub(1) as f32
}
pub fn set_units(&mut self, units: Vec<OverflowUnit>, cx: &mut Context<Self>) {
let old = self
.units
.iter()
.zip(self.widths.iter())
.map(|(unit, width)| (unit.key.clone(), *width));
let old: std::collections::HashMap<_, _> = old.collect();
self.units = units;
self.widths = self
.units
.iter()
.map(|unit| old.get(&unit.key).copied().unwrap_or(unit.measured_width))
.collect();
self.popup_dirty = true;
cx.notify();
}
pub fn dismiss(&self, window: &mut Window, cx: &mut App) {
if let Some(anchor) = &self.anchor {
anchor.update(cx, |anchor, cx| anchor.dismiss(window, cx));
}
}
pub fn is_open(&self, cx: &App) -> bool {
self.anchor
.as_ref()
.is_some_and(|anchor| anchor.read(cx).is_open())
}
fn plan(&self) -> OverflowPlan {
plan_overflow(self.viewport, &self.widths, self.gap, self.chevron_width)
}
pub(crate) fn anchor_for(&self, key: &str) -> Option<Entity<Anchor>> {
let plan = self.plan();
self.units
.iter()
.position(|unit| unit.key.as_ref() == key)
.filter(|index| *index >= plan.visible)
.and(self.anchor.clone())
}
}
#[cfg(test)]
mod tests {
use super::{OverflowPlan, plan_overflow};
fn plan(available: f32, widths: &[f32], gap: f32, chevron: f32) -> OverflowPlan {
plan_overflow(Some(available), widths, gap, chevron)
}
fn counts(plan: &OverflowPlan) -> (usize, usize) {
(plan.visible, plan.hidden)
}
#[test]
fn exact_fit_has_no_trigger() {
assert_eq!(counts(&plan(108., &[40., 60.], 8., 28.)), (2, 0));
assert_eq!(plan(107., &[40., 60.], 8., 28.).visible, 1);
}
#[test]
fn chevron_reservation_prevents_cutoff_overlap() {
assert_eq!(counts(&plan(70., &[30., 30., 30.], 4., 28.)), (1, 2));
}
#[test]
fn gap_before_chevron_is_reserved() {
assert_eq!(counts(&plan(60., &[32., 32.], 8., 28.)), (0, 2));
}
#[test]
fn atomic_units_are_not_split() {
assert_eq!(counts(&plan(110., &[70., 40.], 8., 28.)), (1, 1));
}
#[test]
fn unmeasured_units_wait_for_real_measurement() {
assert_eq!(counts(&plan(40., &[0., 30.], 8., 28.)), (2, 0));
}
#[test]
fn growth_and_shrink_have_stable_prefixes() {
assert_eq!(plan(90., &[30., 30., 30.], 4., 20.).visible, 2);
assert_eq!(plan(110., &[30., 30., 30.], 4., 20.).visible, 3);
}
#[test]
fn an_unmeasured_row_shows_every_unit_and_a_row_with_no_width_none() {
let widths = [30., 30.];
assert_eq!(counts(&plan_overflow(None, &widths, 4., 20.)), (2, 0));
assert_eq!(counts(&plan_overflow(Some(0.), &widths, 4., 20.)), (0, 2));
}
}