diff --git a/crates/behavior/src/fit.rs b/crates/behavior/src/fit.rs index 3550e4563..8b57e2b93 100644 --- a/crates/behavior/src/fit.rs +++ b/crates/behavior/src/fit.rs @@ -32,7 +32,11 @@ fn tab_extent(value: f32) -> f32 { /// points. Empty input and an out-of-range selection are valid. The widths of all shown tabs plus /// `overflow_width` never exceed the sanitized available width. Work and storage are linear in /// the input count (with at most 32 fitting passes); callers keep their own tab-count policy. -pub fn fit(natural: &[f32], selected: usize, available: f32, minimum_width: f32, overflow_width: f32) -> TabFit { +/// +/// With `keep_selected` the selected tab keeps its natural width (only a tab wider than the strip minus the +/// button shrinks); the other tabs share the rest down to `minimum_width`, and the ones that still do not fit go to +/// the overflow, the last ones first. +pub fn fit(natural: &[f32], selected: usize, available: f32, minimum_width: f32, overflow_width: f32, keep_selected: bool) -> TabFit { let available = tab_extent(available); let minimum_width = tab_extent(minimum_width); let natural: Vec = natural.iter().map(|&w| tab_extent(w)).collect(); @@ -45,6 +49,9 @@ pub fn fit(natural: &[f32], selected: usize, available: f32, minimum_width: f32, return TabFit { shown: vec![(0, available)], ..Default::default() }; } let floor = |w: f32| w.min(minimum_width); + if keep_selected { + return fit_keeping_selected(&natural, selected, available, minimum_width, overflow_width); + } if natural.iter().map(|&w| f64::from(floor(w))).sum::() <= f64::from(available) { return TabFit { shown: squeeze(&natural, &all, available, minimum_width), ..Default::default() }; } @@ -68,6 +75,44 @@ pub fn fit(natural: &[f32], selected: usize, available: f32, minimum_width: f32, TabFit { shown, overflow, overflow_width } } +/// [`fit`] with the selected tab at its natural width: the others squeeze beside it, then overflow from the end. +fn fit_keeping_selected(natural: &[f32], selected: usize, available: f32, minimum_width: f32, overflow_width: f32) -> TabFit { + let selected = selected.min(natural.len().saturating_sub(1)); + let floor = |i: usize| natural.get(i).copied().unwrap_or(0.0).min(minimum_width); + let others: Vec = (0..natural.len()).filter(|&i| i != selected).collect(); + let pinned = natural.get(selected).copied().unwrap_or(0.0); + let floors: f64 = others.iter().map(|&i| f64::from(floor(i))).sum(); + let (kept, room, overflow_width) = if floors + f64::from(pinned) <= f64::from(available) { + (others, available - pinned, 0.0) + } else { + let overflow_width = tab_extent(overflow_width).min(available); + let room = (available - overflow_width - pinned).max(0.0); + let mut used = 0.0f64; + let kept: Vec = others + .into_iter() + .take_while(|&i| { + used += f64::from(floor(i)); + used <= f64::from(room) + }) + .collect(); + (kept, room, overflow_width) + }; + let squeezed = squeeze(natural, &kept, room, minimum_width); + let pinned = pinned.min(available - overflow_width); + let mut shown = Vec::with_capacity(squeezed.len() + 1); + let mut overflow = Vec::new(); + for i in 0..natural.len() { + if i == selected { + shown.push((i, pinned)); + } else if let Some(&(_, width)) = squeezed.iter().find(|&&(at, _)| at == i) { + shown.push((i, width)); + } else { + overflow.push(i); + } + } + TabFit { shown, overflow, overflow_width } +} + /// Fit tabs at their natural widths; the tabs that do not fit go to an overflow menu. /// /// Tabs are shown in input order up to the first one that does not fit beside the selected tab diff --git a/crates/behavior/tests/fit.rs b/crates/behavior/tests/fit.rs index e570866d3..131bac9a1 100644 --- a/crates/behavior/tests/fit.rs +++ b/crates/behavior/tests/fit.rs @@ -11,7 +11,7 @@ fn overflow_retains_selection_and_partitions_all_tabs() { let natural = [80.0, 90.0, 85.0, 95.0]; for selected in [0, 1, 2, 3, usize::MAX] { for available in [0.0, 1.0, 5.0, 18.0, 19.0, 55.0, 120.0, 200.0, 500.0] { - let f = fit(&natural, selected, available, 40.0, 18.0); + let f = fit(&natural, selected, available, 40.0, 18.0, false); let selected = selected.min(natural.len() - 1); assert!(f.shown.iter().any(|&(i, _)| i == selected), "{selected} at {available}: {f:?}"); assert!(!f.overflow.contains(&selected)); @@ -24,3 +24,33 @@ fn overflow_retains_selection_and_partitions_all_tabs() { } } } + +#[test] +fn kept_selection_keeps_its_width_and_overflow_starts_at_the_end() { + let natural = [80.0, 90.0, 85.0, 95.0, 70.0]; + for selected in 0..natural.len() { + for available in [0.0, 30.0, 60.0, 120.0, 160.0, 200.0, 260.0, 300.0, 420.0, 500.0] { + let f = fit(&natural, selected, available, 40.0, 18.0, true); + assert!(f.shown.iter().any(|&(i, _)| i == selected), "{selected} at {available}: {f:?}"); + assert!(total(&f) <= available + 0.001, "{available}: {f:?}"); + let kept = f.shown.iter().find(|&&(i, _)| i == selected).map(|&(_, w)| w).unwrap_or(0.0); + if natural[selected] + f.overflow_width <= available { + assert!((kept - natural[selected]).abs() < 0.001, "the shown tab keeps its width: {f:?}"); + } + for &(i, width) in &f.shown { + if i != selected { + assert!(width >= natural[i].min(40.0) - 0.001, "others keep the minimum: {f:?}"); + } + } + let others_hidden: Vec = f.overflow.clone(); + let others: Vec = (0..natural.len()).filter(|&i| i != selected).collect(); + let first_hidden = others.iter().position(|i| others_hidden.contains(i)); + if let Some(at) = first_hidden { + assert!(others[at..].iter().all(|i| others_hidden.contains(i)), "overflow takes the last tabs: {f:?}"); + assert!(f.overflow_width > 0.0); + } else { + assert_eq!(f.overflow_width, 0.0); + } + } + } +} diff --git a/crates/ui-widgets/src/tabs/rules.rs b/crates/ui-widgets/src/tabs/rules.rs index 7c36a791e..f6f5bb7ad 100644 --- a/crates/ui-widgets/src/tabs/rules.rs +++ b/crates/ui-widgets/src/tabs/rules.rs @@ -23,8 +23,12 @@ pub enum TabKind { pub enum FitMode { /// Whole widths; only an active tab wider than the strip is cut. Whole, - /// The widest tabs shrink to the minimum width, then the rest overflow. - Shrink, + /// The widest tabs shrink to the minimum width, then the rest overflow. With `keep_selected` the selected tab is + /// not among the tabs that shrink, and the overflow takes the last tabs first. + Shrink { + /// Whether the selected tab keeps its natural width. + keep_selected: bool, + }, } impl FitMode { @@ -33,7 +37,7 @@ impl FitMode { pub fn fit(self, natural: &[f32], selected: usize, available: f32, minimum: f32, overflow: f32) -> TabFit { match self { FitMode::Whole => fit_whole(natural, selected, available, overflow), - FitMode::Shrink => fit(natural, selected, available, minimum, overflow), + FitMode::Shrink { keep_selected } => fit(natural, selected, available, minimum, overflow, keep_selected), } } } @@ -63,10 +67,21 @@ impl TabKind { pub fn fit_mode(self) -> FitMode { match self { Self::Document | Self::Text => FitMode::Whole, - Self::Panel => FitMode::Shrink, + Self::Panel => FitMode::Shrink { keep_selected: self.keeps_active_width() }, } } + /// Whether the shown tab keeps its whole title while the other tabs shrink: panel tabs. + pub fn keeps_active_width(self) -> bool { + self == Self::Panel + } + + /// Whether a label too long for its tab is clipped at the tab's edge (panel tabs, which shrink to their first + /// letters) instead of ending in an ellipsis. + pub fn clips_label(self) -> bool { + self == Self::Panel + } + /// Where the overflow button sits: at the strip's end for document and text tabs, after the last tab for panel /// tabs. pub fn overflow_place(self) -> OverflowPlace { diff --git a/crates/ui-widgets/src/tabs/strip/stories.rs b/crates/ui-widgets/src/tabs/strip/stories.rs index 483774186..95830e1bf 100644 --- a/crates/ui-widgets/src/tabs/strip/stories.rs +++ b/crates/ui-widgets/src/tabs/strip/stories.rs @@ -92,3 +92,14 @@ fn tab_strip_empty(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { fn tab_strip_panel(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { strip(ui, data, TabStrip::new("Panels").shown(1), &TITLES, 4, TabKind::Panel) } + +/// The width the narrow panel story's room is held to: the shown tab whole, the others at their first letters. +const NARROW_ROOM: f32 = 260.0; + +#[story(TabStrip<'static, usize>, covers = [], drive = Drive::Never)] +fn tab_strip_panel_narrow(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { + crate::testing::memory::scoped(ui, |ui| { + ui.set_max_width(NARROW_ROOM); + strip(ui, data, TabStrip::new("Panels").shown(1), &TITLES, TITLES.len(), TabKind::Panel) + }) +} diff --git a/crates/ui-widgets/src/tabs/tab.rs b/crates/ui-widgets/src/tabs/tab.rs index ecaac48c4..12a9ef292 100644 --- a/crates/ui-widgets/src/tabs/tab.rs +++ b/crates/ui-widgets/src/tabs/tab.rs @@ -2,7 +2,7 @@ //! //! Selection, the lead, the focus ring and the drag ghost belong to the collection that shows the tab; the tab draws //! the look the item step gives it and reports what its own parts do. The strip gives the tab a rect: the tab's -//! measure is its natural width (`Proposal::Min` the narrowest it shrinks to), and a narrower rect cuts the label +//! measure is its natural width (`Proposal::Min` the room for the first letters of its title), and a narrower rect cuts the label //! first, then the detail, and shows the whole text as a tooltip. use super::rules::{CloseSide, TabKind, close_side}; @@ -59,6 +59,9 @@ const TEXT: PartKey = PartKey::new("text"); const CLOSE: PartKey = PartKey::new("close"); const PROGRESS: PartKey = PartKey::new("progress"); +/// How many of a title's first letters a shrunk tab still shows. +const MIN_LETTERS: usize = 3; + /// The modified mark. const MARK: &str = "*"; @@ -72,8 +75,6 @@ struct Sizes { close_box: f32, /// Room after a text tab's contents. tail: f32, - /// The narrowest content width: what a shrinking tab keeps. - min_content: f32, label_line: f32, detail_line: f32, underline_gap: f32, @@ -252,7 +253,6 @@ impl Component for Tab<'_> { icon: size.icon.sm, close_box: size.icon.md, tail: if text_only { space.gap.section } else { 0.0 }, - min_content: size.icon.md, label_line: line(role), detail_line: line(TypeRole::Caption), underline_gap: space.gap.tight, @@ -276,7 +276,9 @@ impl Component for Tab<'_> { fn measure(&mut self, cx: &MeasureCx<'_, Self>) -> Vec2 { let sizes = &cx.style.sizes; if cx.proposal == Proposal::Min { - return Vec2::new(sizes.min_content, sizes.label_line); + let first: String = cx.resolved.label.chars().take(MIN_LETTERS).collect(); + let letters = cx.layout_at(&self.label_run(cx.style, &first), f32::INFINITY).size().x; + return Vec2::new(letters, sizes.label_line); } let width = |run: &TextRun<'_>| cx.layout_at(run, f32::INFINITY).size().x; let mut natural = sizes.tail + width(&self.label_run(cx.style, cx.resolved.label)); @@ -415,8 +417,12 @@ impl Component for Tab<'_> { let line = PaintShape::Path(vec![Pos2::new(placed.label.left(), y), Pos2::new(placed.label.right(), y)]); draw.stroke(&line, StrokeWidth::Thick, style.underline); } - let label = self.label_run(style, cx.resolved.label).color(cx.resolve(&style.label.color)).elide(); - draw.text(placed.label, &label); + let label = self.label_run(style, cx.resolved.label).color(cx.resolve(&style.label.color)); + if self.kind.clips_label() { + draw.clipped(placed.label, |draw| draw.text(placed.label, &label)); + } else { + draw.text(placed.label, &label.elide()); + } if let (Some(at), Some(detail)) = (placed.detail, self.detail_text()) { draw.text(at, &TextRun::new(detail).role(style.detail.role).color(cx.resolve(&style.detail.color)).elide()); } diff --git a/crates/ui-widgets/tests/it/tabs.rs b/crates/ui-widgets/tests/it/tabs.rs index e48239e9a..3ab12a907 100644 --- a/crates/ui-widgets/tests/it/tabs.rs +++ b/crates/ui-widgets/tests/it/tabs.rs @@ -321,3 +321,46 @@ fn the_strip_reports_the_tab_under_the_pointer_while_another_root_holds_the_pres fixture.frame(vec![]); assert_eq!(*seen.borrow(), None, "the empty room has no tab"); } + +const PANELS: [&str; 6] = ["Layers", "Channels", "Properties", "Adjustments", "History", "Navigator"]; + +/// The widths of the panel tabs a strip shows in a room `room` wide, by title, with the second panel shown. +fn panel_widths(room: f32) -> Vec<(&'static str, f32)> { + let mut frames = Frames::new(); + let mut show = |ui: &mut Ui| { + ui.set_max_width(room); + let keys = [0_usize, 1, 2, 3, 4, 5]; + let source = keyed(&keys, |key: &usize| *key); + TabStrip::new("Panels").kind(TabKind::Panel).shown(1).show_items(ui, &source, &mut |key, _| Tab::new(PANELS[*key])); + }; + frames.idle(3, &mut show); + let tree = frames.tree(); + PANELS.iter().filter_map(|name| tab_rects(&tree, name).first().map(|rect| (*name, rect.width()))).collect() +} + +/// Panel tabs shrink around the shown tab: it keeps its whole title while the others keep their first letters, and +/// tabs overflow from the end only when even those do not fit. +#[trial] +fn panel_tabs_keep_the_shown_tab_whole_and_overflow_from_the_end() { + let wide = panel_widths(2000.0); + assert_eq!(wide.len(), PANELS.len(), "every tab fits in a wide room"); + let natural_shown = wide[1].1; + let mut fewer = wide.len(); + for room in [700.0, 500.0, 400.0, 300.0, 220.0] { + let shown = panel_widths(room); + assert!(!shown.is_empty() && shown.len() <= fewer, "rooms below shrink tabs, never add them: {room} {shown:?}"); + fewer = shown.len(); + let active = shown.iter().find(|(name, _)| *name == PANELS[1]).expect("the shown tab stays"); + assert!((active.1 - natural_shown).abs() < 1.0, "the shown tab keeps its width in {room}: {shown:?}"); + let others: Vec = shown.iter().filter(|(name, _)| *name != PANELS[1]).map(|&(_, w)| w).collect(); + let least = others.iter().copied().fold(f32::INFINITY, f32::min); + assert!(least > 0.0, "every shown tab keeps room for letters in {room}: {shown:?}"); + let hidden: Vec<&str> = PANELS.iter().copied().filter(|name| shown.iter().all(|(shown, _)| shown != name)).collect(); + let first = PANELS.iter().position(|name| hidden.contains(name)); + if let Some(first) = first { + let after = PANELS[first..].iter().filter(|name| **name != PANELS[1]); + assert!(after.into_iter().all(|name| hidden.contains(name)), "overflow takes the last tabs: {hidden:?}"); + } + } + assert!(fewer < PANELS.len(), "the narrowest room overflows"); +}