From 5ca0336a5cfc658fe7bcebd4788c0d5f7445508c Mon Sep 17 00:00:00 2001 From: Martin Ball Date: Wed, 18 Nov 2026 21:02:54 +0000 Subject: [PATCH] ribbon-w1: net change of 5 commits - ribbon-w1: written by an agent - ribbon-w1: finished by an agent - ribbon-w1: finished by an agent - ribbon-w1: review fixes (review-1b) - ribbon-w1: review fixes (review-1c) --- crates/behavior/src/fit.rs | 68 +++- crates/behavior/tests/fit.rs | 43 +- crates/ui-contract/src/contract/paint_ui.rs | 12 + crates/ui-contract/src/runtime/motion.rs | 217 ++++++++++- crates/ui-contract/src/style/cx.rs | 29 +- crates/ui-widgets/src/tabs/rules.rs | 17 +- crates/ui-widgets/src/tabs/strip.rs | 409 ++++++++++++++++++-- crates/ui-widgets/src/tabs/strip/end.rs | 96 ++++- crates/ui-widgets/src/tabs/strip/stories.rs | 87 ++++- crates/ui-widgets/src/tabs/tab.rs | 46 ++- crates/ui-widgets/src/tabs/tab/stories.rs | 15 +- crates/ui-widgets/tests/it/tabs.rs | 244 +++++++++++- 12 files changed, 1173 insertions(+), 110 deletions(-) diff --git a/crates/behavior/src/fit.rs b/crates/behavior/src/fit.rs index c22d4d1b5..d37f3341b 100644 --- a/crates/behavior/src/fit.rs +++ b/crates/behavior/src/fit.rs @@ -1,6 +1,6 @@ //! The fit rules: which tabs, bar items or titles stay in a strip and which go to an overflow menu. [`fit`] and -//! [`fit_whole`] assign tab widths (tabs shrink before they overflow, or keep their width); [`fit_items`] drops -//! command items and titles from the end. All of them read no egui types. +//! [`fit_whole`] assign tab widths (tabs shrink before they overflow, or keep their width); [`fit_items`] shortens +//! items that have a short form, then drops command items and titles from the end. All of them read no egui types. /// Tabs visible on a strip and tabs that need an overflow menu, all in original order. #[derive(Clone, Debug, Default, PartialEq)] @@ -122,10 +122,13 @@ fn fit_keeping_selected(natural: &[f32], selected: usize, available: f32, minimu /// gets less than its natural width; its painter elides the label. A lone tab never reserves a /// button. /// +/// The tabs marked in `kept` take the room after the selected tab before the others, in order while each fits; a +/// kept tab that does not fit overflows. The others then follow the rule above. A `kept` slice that is empty or +/// shorter than `natural` marks no tab past its end, so an empty slice gives the plain rule. +/// /// Dimensions are sanitized as in [`fit`], and the shown widths plus `overflow_width` never /// exceed the sanitized available width. Work and storage are linear in the input count. pub fn fit_whole(natural: &[f32], selected: usize, kept: &[bool], available: f32, overflow_width: f32) -> TabFit { - let _ = kept; // P3(ribbon-w1): rb.R2 let available = tab_extent(available); let natural: Vec = natural.iter().map(|&w| tab_extent(w)).collect(); if natural.iter().map(|&w| f64::from(w)).sum::() <= f64::from(available) { @@ -139,17 +142,33 @@ pub fn fit_whole(natural: &[f32], selected: usize, kept: &[bool], available: f32 let selected = selected.min(natural.len().saturating_sub(1)); let active = natural.get(selected).copied().unwrap_or(0.0).min(budget); let mut room = f64::from(budget - active); + let mut keep = vec![false; natural.len()]; + if let Some(keep) = keep.get_mut(selected) { + *keep = true; + } + // The kept tabs take room first, then the others; each run stops at its first tab that does not fit. + for kept_run in [true, false] { + for (i, &width) in natural.iter().enumerate() { + if i == selected || kept.get(i).copied().unwrap_or(false) != kept_run { + continue; + } + if f64::from(width) > room { + break; + } + room -= f64::from(width); + if let Some(keep) = keep.get_mut(i) { + *keep = true; + } + } + } let mut shown = Vec::new(); let mut overflow = Vec::new(); - let mut full = false; for (i, &width) in natural.iter().enumerate() { if i == selected { shown.push((i, active)); - } else if !full && f64::from(width) <= room { - room -= f64::from(width); + } else if keep.get(i).copied().unwrap_or(false) { shown.push((i, width)); } else { - full = true; overflow.push(i); } } @@ -258,9 +277,11 @@ pub fn run_extent(items: &[FitItem], shown: &[bool], gap: f64, section_gap: f64) } /// Decides which items stay in a strip `available` long. Everything fits and no item is `Menu`: all items show. -/// Otherwise the `Menu` items are in the menu, and the last `Free` item leaves first, one at a time, until the rest -/// and an overflow control `overflow_extent` long, set off by `gap`, fit; `Pinned` items stay even when they alone -/// are longer than `available`. Negative and non-finite lengths count as zero. +/// Otherwise the `Menu` items are in the menu, and the items with a [`FitItem::short`] form take it first, the last +/// one first, until the run fits (listed in [`Fit::short`]); a `Pinned` item shortens as a `Free` one does. Only then +/// does the last `Free` item leave, one at a time, until the rest and an overflow control `overflow_extent` long, +/// set off by `gap`, fit; `Pinned` items stay even when they alone are longer than `available`. Items that leave are +/// never listed as short. Negative and non-finite lengths count as zero. pub fn fit_items(items: &[FitItem], available: f32, gap: f32, section_gap: f32, overflow_extent: f32) -> Fit { let (available, gap, section_gap, overflow_extent) = (item_extent(available), item_extent(gap), item_extent(section_gap), item_extent(overflow_extent)); @@ -268,14 +289,33 @@ pub fn fit_items(items: &[FitItem], available: f32, gap: f32, section_gap: f32, if shown.iter().all(|shown| *shown) && run_extent(items, &shown, gap, section_gap) <= available { return Fit { shown: (0..items.len()).collect(), overflow: Vec::new(), short: Vec::new() }; } - let fits = |shown: &[bool]| { + // The overflow control takes room only while some item is in the menu; a run that every item is in, shortened, + // needs no control. + let fits = |run: &[FitItem], shown: &[bool]| { + let extent = run_extent(run, shown, gap, section_gap); + if shown.iter().all(|shown| *shown) { + return extent <= available; + } let before_control = if shown.iter().any(|shown| *shown) { gap } else { 0.0 }; - run_extent(items, shown, gap, section_gap) + before_control + overflow_extent <= available + extent + before_control + overflow_extent <= available }; - while !fits(&shown) { + // The shadow run holds each item at the extent it takes: shortened items at their `short` extent. + let mut run: Vec = items.to_vec(); + let mut short = vec![false; items.len()]; + while !fits(&run, &shown) { + let Some(last) = (0..items.len()).rev().find(|&at| shown[at] && !short[at] && items[at].short.is_some()) else { + break; + }; + short[last] = true; + if let (Some(item), Some(extent)) = (run.get_mut(last), items[last].short) { + item.extent = extent; + } + } + while !fits(&run, &shown) { let Some(last) = (0..items.len()).rev().find(|&at| shown[at] && items[at].keep == FitKeep::Free) else { break }; shown[last] = false; } let (kept, left): (Vec, Vec) = (0..items.len()).partition(|&at| shown[at]); - Fit { shown: kept, overflow: left, short: Vec::new() } + let short = kept.iter().copied().filter(|&at| short[at]).collect(); + Fit { shown: kept, overflow: left, short } } diff --git a/crates/behavior/tests/fit.rs b/crates/behavior/tests/fit.rs index 7ec8b3f1b..08cd37712 100644 --- a/crates/behavior/tests/fit.rs +++ b/crates/behavior/tests/fit.rs @@ -1,6 +1,6 @@ -//! The fit rules: tab widths (`fit`). +//! The fit rules: tab widths (`fit`) and strip items (`fit_items`). -use craft_behavior::fit::{TabFit, fit}; +use craft_behavior::fit::{FitItem, FitKeep, TabFit, fit, fit_items}; fn total(fit: &TabFit) -> f32 { fit.shown.iter().map(|&(_, width)| width).sum::() + fit.overflow_width @@ -25,6 +25,45 @@ fn overflow_retains_selection_and_partitions_all_tabs() { } } +/// Guards the shortening stage of `fit_items`: short forms go last first, before any free item leaves, a leaving item +/// is not reported short, and items without a short form fit exactly as before (the menu bar, bar items and +/// breadcrumbs build no short forms). +#[test] +fn short_items_shorten_from_the_end_before_any_item_leaves() { + let item = |extent| FitItem::new(extent, 0, FitKeep::Free); + let shortening = [item(50.0).short(20.0), item(50.0), item(50.0).short(20.0)]; + let plain = [item(50.0), item(50.0), item(50.0)]; + let at = |items: &[FitItem], available| fit_items(items, available, 0.0, 0.0, 10.0); + + let wide = at(&shortening, 150.0); + assert!(wide.short.is_empty() && wide.overflow.is_empty(), "a run that fits keeps every full form: {wide:?}"); + + let narrower = at(&shortening, 120.0); + assert!(narrower.overflow.is_empty(), "shortening comes before any item leaves: {narrower:?}"); + assert!(narrower.short.contains(&2) && !narrower.short.contains(&0), "the last short item goes first: {narrower:?}"); + + let narrow = at(&shortening, 90.0); + assert!(narrow.overflow.is_empty(), "every short form is taken before an item leaves: {narrow:?}"); + assert!(narrow.short.contains(&0) && narrow.short.contains(&2), "then the earlier ones: {narrow:?}"); + + let narrowest = at(&shortening, 80.0); + assert!(narrowest.overflow.contains(&2) && narrowest.shown.contains(&0), "then the last free item leaves: {narrowest:?}"); + assert!(narrowest.short.iter().all(|i| narrowest.shown.contains(i)), "a leaving item is not short: {narrowest:?}"); + + for available in [0.0, 40.0, 80.0, 90.0, 120.0, 150.0] { + let fit = at(&plain, available); + assert!(fit.short.is_empty(), "no short form, no short item: {fit:?}"); + let shown = shortening.len() - fit.overflow.len(); + assert_eq!(fit.shown, (0..shown).collect::>(), "items without short forms leave from the end: {fit:?}"); + } + assert!(!at(&plain, 120.0).overflow.is_empty(), "without short forms the narrower run overflows"); + + let pinned = [FitItem::new(80.0, 0, FitKeep::Pinned).short(30.0), FitItem::new(90.0, 0, FitKeep::Pinned).short(30.0)]; + let squeezed = fit_items(&pinned, 40.0, 0.0, 0.0, 0.0); + assert!(squeezed.overflow.is_empty(), "pinned items never leave: {squeezed:?}"); + assert_eq!(squeezed.short.len(), 2, "pinned items shorten as free ones do: {squeezed:?}"); +} + #[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]; diff --git a/crates/ui-contract/src/contract/paint_ui.rs b/crates/ui-contract/src/contract/paint_ui.rs index 2712ffe9c..df0de56f5 100644 --- a/crates/ui-contract/src/contract/paint_ui.rs +++ b/crates/ui-contract/src/contract/paint_ui.rs @@ -219,6 +219,18 @@ impl PaintUi<'_> { self.face_with(part.into(), face, Some(ink)); } + /// [`face`](Self::face) painted `share` as opaque as it would be (1 paints as `face` does, 0 paints nothing): a + /// component fading in or out as the one component that draws it. A share outside 0 to 1 is clamped and a + /// non-finite one leaves the opacity as it was; fades stack with the opacity already in force. + pub fn face_faded(&mut self, part: impl Into, face: C, share: f32) { + let kept = self.ui.opacity(); + if share.is_finite() { + self.ui.set_opacity(kept * share.clamp(0.0, 1.0)); + } + self.face_with(part.into(), face, self.text); + self.ui.set_opacity(kept); + } + fn face_with(&mut self, part: PartRef, face: C, ink: Option<&Stateful>) { let Some(result) = self.results.get(&(part.key, part.index)) else { debug_assert!(false, "face for a part `parts` did not declare"); diff --git a/crates/ui-contract/src/runtime/motion.rs b/crates/ui-contract/src/runtime/motion.rs index a2ddc33f1..46fa3e083 100644 --- a/crates/ui-contract/src/runtime/motion.rs +++ b/crates/ui-contract/src/runtime/motion.rs @@ -7,6 +7,7 @@ use crate::runtime::memory::{self, MemoryStage}; use craft_behavior::{MotionKind, Playback}; use craft_theme::Motion; use egui::{Context, Id, Pos2, Rect, Vec2}; +use std::hash::Hash; /// Which token of `MotionTokens` gives a spec its duration and curve. #[derive(Clone, Copy, Debug, PartialEq, Eq)] @@ -210,6 +211,31 @@ pub struct Presence { pub exiting: bool, } +impl Presence { + /// The presence of an openness `t` whose target is open or closed. + fn at(t: f32, open: bool) -> Self { + Presence { t, visible: open || t > 0.0, exiting: !open && t > 0.0 } + } +} + +/// One key of a keyed presence: the hash of its key, its openness, the frame that last drove it open, and what the +/// caller keeps with it while it shows. +#[derive(Clone)] +struct KeyedEntry

{ + key: Id, + tween: Tween, + /// A key that no pass of the running frame drove open is closing. + open_in: Option, + payload: P, +} + +/// The keys of one keyed presence name, in the order they first opened, and the frame the name was first driven. +#[derive(Clone)] +struct Keyed

{ + born: u64, + entries: Vec>, +} + /// What a viewport's animations asked for in the running pass. #[derive(Default)] pub(crate) struct Wanted { @@ -260,6 +286,55 @@ pub(crate) fn layer_presence(ctx: &Context, base: Id, owner: Id, policy: MotionP presence } +/// Moves `tween` toward `target` at `now` by `spec` under `policy`, or sets it there where the mode does not run +/// `spec`'s kind. Every named tween, keyed or not, and the read of a keyed exit step through here. +fn advance_tween(policy: &MotionPolicy, tween: &mut Tween, target: T, spec: MotionSpec, now: f64) { + if policy.mode.playback(spec.kind) != Playback::Run { + *tween = Tween::at(target); + return; + } + if tween.target() != target { + // A follow steps from its last evaluation toward wherever its target is now; restarting its clock + // would hold it still for a frame each time the target moves. + match spec.curve { + Curve::Tween => tween.retarget(target, now), + Curve::Follow => tween.to = target, + } + } + tween.step(now, spec.motion(policy), spec.curve); +} + +/// The slot of the keyed presence `name` of the component `base`. +fn keyed_slot_of(base: Id, name: &'static str) -> Id { + memory::sub(base, ("presence_keyed", name)) +} + +/// The keys of the keyed presence `name` of the component `base` that are not among `listed`, closing from where +/// they are at this pass's clock, each with its last payload. It reads a copy and stores nothing: the same keys, +/// values and order `Driver::exiting` gives in the same pass, for code that runs before the component's own pass +/// drives this frame's open keys (a collection's layout). +pub(crate) fn peek_exiting( + ctx: &Context, + base: Id, + policy: MotionPolicy, + name: &'static str, + spec: MotionSpec, + listed: &[Id], +) -> Vec<(Presence, P)> { + let Some(keyed) = store::peek_clone::>(ctx, keyed_slot_of(base, name)) else { return Vec::new() }; + let now = frame::clock(ctx); + keyed + .entries + .into_iter() + .filter(|entry| !listed.contains(&entry.key)) + .filter_map(|mut entry| { + advance_tween(&policy, &mut entry.tween, 0.0, spec, now); + let presence = Presence::at(entry.tween.shown(), false); + presence.visible.then_some((presence, entry.payload)) + }) + .collect() +} + /// The hover, press and on tweens of one component. #[derive(Clone)] pub(crate) struct StateTweens([Tween; 3]); @@ -315,7 +390,6 @@ impl Driver<'_> { let sizing = self.stage.is_peek(); let now = frame::clock(ctx); let existing = if sizing { store::peek_clone::>(ctx, id) } else { store::take::>(ctx, id) }; - let runs = self.policy.mode.playback(spec.kind) == Playback::Run; let mut tween = match existing { Some(tween) => tween, None => { @@ -325,19 +399,7 @@ impl Driver<'_> { Tween::at(target) } }; - if !runs { - tween = Tween::at(target); - } else { - if tween.target() != target { - // A follow steps from its last evaluation toward wherever its target is now; restarting its clock - // would hold it still for a frame each time the target moves. - match spec.curve { - Curve::Tween => tween.retarget(target, now), - Curve::Follow => tween.to = target, - } - } - tween.step(now, spec.motion(&self.policy), spec.curve); - } + self.advance(&mut tween, target, spec, now); let shown = tween.shown(); if !sizing { if !tween.is_settled() { @@ -352,9 +414,107 @@ impl Driver<'_> { self.anim(name, f32::from(u8::from(on)), spec) } + /// Moves `tween` toward `target` at `now` by `spec`, or sets it there where the mode does not run `spec`'s kind. + /// Named tweens, keyed or not, step through here. + fn advance(&self, tween: &mut Tween, target: T, spec: MotionSpec, now: f64) { + advance_tween(&self.policy, tween, target, spec, now); + } + + /// The presence of the unkeyed `name`: the one-key case of `presence_keyed`, kept in a plain tween slot because + /// the overlay host reads a layer's openness there (`layer_fading`). pub(crate) fn presence(&self, name: &'static str, open: bool, spec: MotionSpec) -> Presence { - let t = self.anim_bool(name, open, spec); - Presence { t, visible: open || t > 0.0, exiting: !open && t > 0.0 } + Presence::at(self.anim_bool(name, open, spec), open) + } + + /// The slot of a component's keyed presence `name`. + fn keyed_slot(&self, name: &'static str) -> Id { + keyed_slot_of(self.base, name) + } + + /// The frame the running pass belongs to; both passes of one frame share it. + fn frame(&self) -> u64 { + let ctx = self.stage.ctx(); + pass::frame_nr(ctx, pass::current_viewport(ctx)) + } + + /// The keys of `name` as stored; a sizing pass reads a copy and the real pass takes them out to put them back. + /// `None` when the name has never been driven. + fn load_keyed(&self, name: &'static str) -> Option> { + let ctx = self.stage.ctx(); + let id = self.keyed_slot(name); + if self.stage.is_peek() { store::peek_clone::>(ctx, id) } else { store::take::>(ctx, id) } + } + + /// Puts the keys of `name` back after a real pass and asks for the next frame while one of them moves. A sizing + /// pass stores nothing. + fn store_keyed(&self, name: &'static str, keyed: Keyed

) { + if self.stage.is_peek() { + return; + } + let ctx = self.stage.ctx(); + if keyed.entries.iter().any(|entry| !entry.tween.is_settled()) { + note_unsettled(ctx); + } + store::put(ctx, self.keyed_slot(name), keyed); + } + + /// The presence of `key` among the keys of `name`, which keeps `payload` with it while it is visible. In the + /// frame the name is first driven every key starts at its target, as `anim` does; a key that appears later + /// enters from closed. Two passes of one frame step to the same value, because a tween's value depends only on + /// the pass clock. + pub(crate) fn presence_keyed(&self, name: &'static str, key: Id, open: bool, payload: P, spec: MotionSpec) -> Presence { + let ctx = self.stage.ctx(); + let (now, frame) = (frame::clock(ctx), self.frame()); + let mut keyed = self.load_keyed::

(name).unwrap_or_else(|| { + if !self.stage.is_peek() { + memory::adopt::>(ctx, self.stage.owner(), self.keyed_slot(name)); + } + Keyed { born: frame, entries: Vec::new() } + }); + let target = f32::from(u8::from(open)); + let at = match keyed.entries.iter().position(|entry| entry.key == key) { + Some(at) => at, + None => { + let start = if keyed.born == frame { target } else { 0.0 }; + keyed.entries.push(KeyedEntry { key, tween: Tween::at(start), open_in: None, payload: payload.clone() }); + keyed.entries.len() - 1 + } + }; + let mut presence = Presence::at(target, open); + if let Some(entry) = keyed.entries.get_mut(at) { + self.advance(&mut entry.tween, target, spec, now); + entry.open_in = open.then_some(frame); + entry.payload = payload; + presence = Presence::at(entry.tween.shown(), open); + } + if !presence.visible { + keyed.entries.retain(|entry| entry.key != key); + } + self.store_keyed(name, keyed); + presence + } + + /// The keys of `name` that no pass of the running frame drove open, closing from where they are, each with the + /// payload it was last given; a key is dropped, payload and all, once it has faded out. Read it after driving + /// this frame's open keys. + pub(crate) fn exiting(&self, name: &'static str, spec: MotionSpec) -> Vec<(Presence, P)> { + let Some(mut keyed) = self.load_keyed::

(name) else { return Vec::new() }; + let (now, frame) = (frame::clock(self.stage.ctx()), self.frame()); + let mut out = Vec::new(); + keyed.entries.retain_mut(|entry| { + if entry.open_in == Some(frame) { + return true; + } + entry.open_in = None; + self.advance(&mut entry.tween, 0.0, spec, now); + let presence = Presence::at(entry.tween.shown(), false); + if presence.visible { + out.push((presence, entry.payload.clone())); + } + presence.visible + }); + self.store_keyed(name, keyed); + out } pub(crate) fn jump(&self, name: &'static str, value: T) { @@ -433,6 +593,15 @@ pub trait Animate: crate::runtime::memory::sealed::Sealed { fn anim_bool(&self, name: &'static str, on: bool, spec: MotionSpec) -> f32; /// Open-close presence for something shown while it opens and fades out. fn presence(&self, name: &'static str, open: bool, spec: MotionSpec) -> Presence; + /// Open-close presence of one of a set of things under `name`, told apart by `key`, such as the items of a list + /// that enter and leave. `payload` is kept with the key while it is visible, so a thing its owner no longer has + /// can still be drawn while it fades out (`exiting`). The first frame of `name` starts every key at its target; + /// a key that appears later enters from closed. + fn presence_keyed(&self, name: &'static str, key: impl Hash, open: bool, payload: P, spec: MotionSpec) -> Presence; + /// The keys of `name` that no pass of this frame drove open through `presence_keyed`, fading out, each with the + /// payload it was last given; a key is forgotten once it has faded out. Call it after driving the frame's open + /// keys. + fn exiting(&self, name: &'static str, spec: MotionSpec) -> Vec<(Presence, P)>; /// Sets `name` to `value` with no animation. fn jump(&self, name: &'static str, value: T); /// The 0 to 1 position of a loop of `period` seconds, stepped every `tick` seconds when given; `None` when @@ -447,6 +616,14 @@ pub trait Animate: crate::runtime::memory::sealed::Sealed { fn wake_at(&self, at: f64); } +/// The id of a presence key: its hash, so a key needs no `Debug` to tell its presence apart. +pub(crate) fn key_id(key: &impl Hash) -> Id { + use std::hash::Hasher as _; + let mut hasher = std::collections::hash_map::DefaultHasher::new(); + key.hash(&mut hasher); + Id::new(hasher.finish()) +} + /// The types that reach the motion service. pub(crate) trait Drives { fn driver(&self) -> Driver<'_>; @@ -465,6 +642,14 @@ impl Animate for X { self.driver().presence(name, open, spec) } + fn presence_keyed(&self, name: &'static str, key: impl Hash, open: bool, payload: P, spec: MotionSpec) -> Presence { + self.driver().presence_keyed(name, key_id(&key), open, payload, spec) + } + + fn exiting(&self, name: &'static str, spec: MotionSpec) -> Vec<(Presence, P)> { + self.driver().exiting(name, spec) + } + fn jump(&self, name: &'static str, value: T) { self.driver().jump(name, value); } diff --git a/crates/ui-contract/src/style/cx.rs b/crates/ui-contract/src/style/cx.rs index 7b87f6fd5..f3063715d 100644 --- a/crates/ui-contract/src/style/cx.rs +++ b/crates/ui-contract/src/style/cx.rs @@ -9,16 +9,18 @@ use super::paint::{ use super::surface::{SurfaceStyle, surface_style}; use super::tokens::UiTokens; use crate::fonts::stack_facts; -use crate::runtime::env::{AppValues, Scale, StyleValue}; +use crate::runtime::env::{AppValues, MotionPolicy, Scale, StyleValue}; +use crate::runtime::motion::{MotionSpec, Presence}; use crate::runtime::pass_state; use craft_behavior::ControlMetrics; use craft_host::target::Os; use craft_i18n::Direction; use craft_theme::Stroke as StrokeStep; use craft_theme::{BySize, Contrast, ControlSize, Flags, RadiusStep, Rgba, Size, Stateful, States, TokenGroup, Variant, VariantLook, variant::Tone}; -use egui::{Color32, Context, CornerRadius}; +use egui::{Color32, Context, CornerRadius, Id}; use std::any::{Any, TypeId}; use std::collections::HashMap; +use std::hash::Hash; use std::sync::Arc; /// How the icon-only buttons of a scope show their glyph, set by the container that holds them @@ -68,8 +70,9 @@ pub struct StyleCx<'a> { line_ratio: f32, ctx: &'a Context, values: &'a AppValues, - /// The `Ui` a collection's layout hook measures faces in; none elsewhere. - measuring: Option<&'a egui::Ui>, + /// The component whose motion memory `exiting` reads, and the motion policy it runs under; set by the collection + /// hook for the layout it asks of the component. + owner: Option<(Id, MotionPolicy)>, } /// A variant's look as style parts. @@ -162,7 +165,7 @@ impl<'a> StyleCx<'a> { line_ratio, ctx, values, - measuring: None, + owner: None, } } @@ -207,6 +210,22 @@ impl<'a> StyleCx<'a> { StyleCx { measuring: Some(ui), ..*self } } + /// The same context scoped to the component `id`, whose keyed presences `exiting` reads under `policy`. + pub(crate) fn owned_by(&self, id: Id, policy: MotionPolicy) -> StyleCx<'a> { + StyleCx { owner: Some((id, policy)), ..*self } + } + + /// The keyed presences of `name` in the motion memory of the component this context is scoped to, for the keys + /// not among `listed` (the keys its source lists now): each is still fading out, with the payload it was last + /// given and the presence it has at this pass's clock, as `Animate::exiting` computes it. It reads without + /// driving, so a collection's `item_layout` can keep the room of an item that is leaving until its exit ends. + /// Empty outside a collection's layout. + pub fn exiting(&self, name: &'static str, spec: MotionSpec, listed: &[impl Hash]) -> Vec<(Presence, P)> { + let Some((id, policy)) = self.owner else { return Vec::new() }; + let listed: Vec = listed.iter().map(crate::runtime::motion::key_id).collect(); + crate::runtime::motion::peek_exiting(self.ctx, id, policy, name, spec, &listed) + } + /// The same context with another variant. #[doc(hidden)] pub fn with_variant(&self, variant: Variant) -> StyleCx<'a> { diff --git a/crates/ui-widgets/src/tabs/rules.rs b/crates/ui-widgets/src/tabs/rules.rs index 8646a54d7..bb491f3c6 100644 --- a/crates/ui-widgets/src/tabs/rules.rs +++ b/crates/ui-widgets/src/tabs/rules.rs @@ -35,11 +35,12 @@ pub enum FitMode { } impl FitMode { - /// Fits tabs of the `natural` widths into `available`, keeping the `selected` tab. `minimum` is the narrowest a - /// shrinking tab becomes and `overflow` the width of the overflow button. - pub fn fit(self, natural: &[f32], selected: usize, available: f32, minimum: f32, overflow: f32) -> TabFit { + /// Fits tabs of the `natural` widths into `available`, keeping the `selected` tab. Whole widths give the tabs + /// marked in `kept` the room before the other tabs (`fit_whole`); shrinking tabs have no kept tabs. `minimum` is + /// the narrowest a shrinking tab becomes and `overflow` the width of the overflow button. + pub fn fit(self, natural: &[f32], selected: usize, kept: &[bool], available: f32, minimum: f32, overflow: f32) -> TabFit { match self { - FitMode::Whole => fit_whole(natural, selected, &[], available, overflow), // P3(ribbon-w1): rb.R2 + FitMode::Whole => fit_whole(natural, selected, kept, available, overflow), FitMode::Shrink { keep_selected } => fit(natural, selected, available, minimum, overflow, keep_selected), } } @@ -66,7 +67,7 @@ pub enum OverflowMenu { } impl TabKind { - /// How tab widths are fitted: whole titles for document and text tabs, shrinking for panel tabs. + /// How tab widths are fitted: whole titles for document, text and ribbon tabs, shrinking for panel tabs. pub fn fit_mode(self) -> FitMode { match self { Self::Document | Self::Text | Self::Ribbon => FitMode::Whole, @@ -107,14 +108,14 @@ impl TabKind { self == Self::Document } - /// Whether tabs draw only their label, with no surface, indicator or strip fill. + /// Whether tabs draw only their label, with no surface, indicator or strip fill: text and ribbon tabs. pub fn text_only(self) -> bool { - self == Self::Text + matches!(self, Self::Text | Self::Ribbon) } /// Whether the shown tab is marked by one accent underline that slides to the newly shown tab (ribbon tabs). pub fn slides_underline(self) -> bool { - todo!("rb.R1") + self == Self::Ribbon } /// Whether a middle click closes a closable tab. diff --git a/crates/ui-widgets/src/tabs/strip.rs b/crates/ui-widgets/src/tabs/strip.rs index bf60a344b..f327f1026 100644 --- a/crates/ui-widgets/src/tabs/strip.rs +++ b/crates/ui-widgets/src/tabs/strip.rs @@ -1,6 +1,8 @@ //! `TabStrip`: a collection of `Tab`s side by side in one row. The item step owns the lead, the selection, the reorder //! gesture and the drag session; the strip adds the item layout that fits the tabs to its width, the overflow button -//! with its menu of tabs, and the tear-off of a tab dragged away from every strip. +//! with its menu of tabs, and the tear-off of a tab dragged away from every strip. A strip may carry end items +//! (`StripEnd`) beside its tabs; a ribbon strip slides one underline to its shown tab and fades out a contextual tab +//! its source drops. //! //! The tabs are the caller's items (`ShowCollection::show_items` with one `Tab` per key). The source's //! `ItemSource::text` is each tab's name in the overflow menu. The drag payload of a tab is `ListDrag`; a dock that @@ -17,16 +19,20 @@ use super::words::StripWords; use super::{Tab, TabPartEvent, TabRole}; use crate::buttons::IconButton; use crate::contract::{ - Access, Bind, BindMut, Collection, CollectionEvent, CollectionProps, CollectionResponse, Common, Component, ContainerProps, ContextMenuRequest, - Cx, DropKind, DropMark, Entry, ListDrag, Meta, Name, NoValue, Outcome, OverlayUi, Overlays as _, PartsCx, Pointer as _, Props as _, Role, - RowState, SelectMode, ShowShape, Sizing, WindowDropTarget, WordSetCx as _, + Access, Animate as _, Bind, BindMut, Collection, CollectionEvent, CollectionProps, CollectionResponse, Common, Component, ContainerProps, + ContextMenuRequest, Cx, DropKind, DropMark, Entry, ListDrag, Meta, Name, NoValue, Outcome, OverlayUi, Overlays as _, PaintUi, PartsCx, + Pointer as _, PopupKind, Props as _, Role, RowState, SelectMode, ShowContainer as _, ShowShape, Sizing, WindowDropTarget, WordSetCx as _, spec, }; use crate::list::{DropTest, RowTest}; use crate::menu::Menu; +use crate::primitives::{PaintShape, StrokeWidth}; +use crate::runtime::commands::FireSource; use crate::runtime::env::Label; -use crate::style::{ComponentStyle, StyleCx}; +use crate::style::{ComponentStyle, StyleColor, StyleCx}; +use craft_behavior::fit::{FitItem, fit_items}; use craft_behavior::{ - HitLevel, HitPriority, IconId, ItemLayout, ItemSource, Metrics, NavShape, PartKey, PressPhase, ScrollPos, Selection, SelectionChange, Sense, + Flow, HitLevel, HitPriority, IconId, ItemLayout, ItemSource, Metrics, NavShape, PartKey, PressPhase, ScrollPos, Selection, SelectionChange, + Sense, }; use egui::{Id, Pos2, Rect, Response, Vec2}; use std::cell::RefCell; @@ -35,6 +41,16 @@ use std::sync::{Arc, Mutex, PoisonError}; const OVERFLOW: PartKey = PartKey::new("overflow"); +/// One end item: `END.at(position in the slice given to `TabStrip::trailing`)`, which is fixed for a strip's life. +const END: PartKey = PartKey::new("end"); + +/// The popups of the end items that open a menu, one repeat per item position. +const ENDS: &str = "ends"; + +/// One contextual tab fading out: `GHOST.at(position among the tabs fading out)`, a part with no sense that its face +/// is painted on. +const GHOST: PartKey = PartKey::new("ghost"); + /// A tab dragged away from every strip and released: the tabs the drag carried and where the pointer was. #[derive(Clone, Debug, PartialEq)] #[non_exhaustive] @@ -95,6 +111,20 @@ pub struct TabStripStyle { metrics: Metrics, /// The text line a wheel notch given in lines counts. line: f32, + /// The colour of the one underline a ribbon strip slides under its shown tab. + underline: StyleColor, + /// The underline's distance from the row's bottom edge: half its stroke, so the stroke lies inside the row. + underline_inset: f32, +} + +/// Where the fit put one end item: its position in `TabStrip::trailing`, its distance from the start edge, its width +/// and whether it shows its icon only. +#[derive(Clone, Copy, Debug, Default, PartialEq)] +struct EndSlot { + item: usize, + start: f32, + width: f32, + short: bool, } /// What the layout tells the strip's parts and menu after fitting the tabs. @@ -108,6 +138,48 @@ struct Report { overflow: f32, /// Each shown tab's position in the source, distance from the start edge and width. placed: Vec<(usize, f32, f32)>, + /// The end items, in the order given. + ends: Vec, + /// The room at the end edge the end items take with the gap before them; 0 without end items. + ends_room: f32, + /// The slot (distance from the start edge and width) of each contextual tab fading out, in the order + /// `StyleCx::exiting` lists them; `None` for one that has no room in the row. + ghosts: Vec>, +} + +/// The room a contextual tab fading out keeps in the fit until its exit ends: the slot's place among the tabs +/// fading out, the position of the source tab it stood before, and its width. +#[derive(Clone, Copy, Debug)] +struct Reserved { + slot: usize, + before: usize, + width: f32, +} + +/// One place in the fitted row: a tab of the source, or the reserved slot of a tab fading out (an index into +/// `Fitting::ghosts`). +#[derive(Clone, Copy)] +enum Lane { + Tab(usize), + Ghost(usize), +} + +/// What the fit reads besides the tabs' widths: the shown tab, the kind's rule, the tabs kept ahead of the others and +/// the end items. +#[derive(Clone, Debug)] +struct Fitting { + selected: usize, + mode: FitMode, + /// The contextual tabs, by position; empty when the strip has no `roles`. + kept: Vec, + /// The end items as the fit sees them, in the order given. + ends: Vec, + /// The gap between end items, and between the tabs and the first end item. + gap: f32, + /// The slots kept for the contextual tabs fading out. + ghosts: Vec, + /// How many contextual tabs are fading out, those without a slot included. + departed: usize, } /// The item layout of a tab strip: the tabs in one row, each as wide as it measures itself, fitted to the width by @@ -119,8 +191,7 @@ pub struct StripLayout { width: f32, height: f32, measured_height: bool, - selected: usize, - mode: FitMode, + fitting: Fitting, shown: Vec, left: Vec, wide: Vec, @@ -130,7 +201,7 @@ pub struct StripLayout { } impl StripLayout { - fn new(count: usize, width: f32, height: f32, selected: usize, mode: FitMode, report: Arc>, ctx: egui::Context) -> Self { + fn new(count: usize, width: f32, height: f32, fitting: Fitting, report: Arc>, ctx: egui::Context) -> Self { let each = if count == 0 { 0.0 } else { width / count as f32 }; let mut layout = StripLayout { ideal: vec![each; count], @@ -138,8 +209,7 @@ impl StripLayout { width, height, measured_height: false, - selected, - mode, + fitting, shown: Vec::new(), left: Vec::new(), wide: Vec::new(), @@ -150,27 +220,105 @@ impl StripLayout { layout } - /// Places the tabs the fit keeps from the start edge; the others are not listed as visible, so they are not built. The overflow button - /// is as wide as the row is high. + /// The end items' places and the room they take at the end edge. They get the room the tabs' natural widths + /// leave and drop their labels from the last one first (`fit_items`, rb.R4); they are `Pinned`, so once every one + /// is short they keep that room and the tabs overflow instead. + fn fit_ends(&self) -> (f32, Vec) { + let Fitting { ends, gap, ghosts, .. } = &self.fitting; + if ends.is_empty() { + return (0.0, Vec::new()); + } + let natural = self.ideal.iter().sum::() + ghosts.iter().map(|ghost| ghost.width).sum::(); + let fit = fit_items(ends, self.width - natural - gap, *gap, *gap, 0.0); + let sized: Vec<(usize, f32, bool)> = fit + .shown + .iter() + .filter_map(|&at| { + let item = ends.get(at)?; + let short = fit.short.contains(&at); + Some((at, if short { item.short.unwrap_or(item.extent) } else { item.extent }, short)) + }) + .collect(); + let run = sized.iter().map(|&(_, width, _)| width).sum::() + gap * sized.len().saturating_sub(1) as f32; + let mut start = self.width - run; + let slots = sized + .into_iter() + .map(|(item, width, short)| { + let slot = EndSlot { item, start, width, short }; + start += width + gap; + slot + }) + .collect(); + (run + gap, slots) + } + + /// Places the tabs the fit keeps from the start edge; the others are not listed as visible, so they are not built. + /// The end items take their room at the end edge first, and the tabs fit in what is left. The overflow button is + /// as wide as the row is high. A contextual tab fading out takes part in the fit at the place it left, as a tab + /// of its width, so the row holds still until its exit ends. fn refit(&mut self) { let count = self.ideal.len(); - let minimum = self.min.iter().copied().fold(0.0, f32::max); - let fit = self.mode.fit(&self.ideal, self.selected, self.width, minimum, self.height); - self.shown = vec![false; count]; - self.left = vec![self.width; count]; - self.wide = vec![0.0; count]; + let (ends_room, ends) = self.fit_ends(); + let StripLayout { ideal, min, width, height, fitting, shown, left, wide, report, ctx, .. } = self; + let Fitting { selected, mode, kept, ghosts, departed, .. } = &*fitting; + let mut lane = Vec::with_capacity(count + ghosts.len()); + for at in 0..=count { + lane.extend(ghosts.iter().enumerate().filter(|(_, ghost)| ghost.before == at).map(|(k, _)| Lane::Ghost(k))); + if at < count { + lane.push(Lane::Tab(at)); + } + } + let natural: Vec = lane + .iter() + .map(|place| match *place { + Lane::Tab(at) => ideal.get(at).copied().unwrap_or(0.0), + Lane::Ghost(k) => ghosts.get(k).map_or(0.0, |ghost| ghost.width), + }) + .collect(); + let held: Vec = lane + .iter() + .map(|place| match *place { + Lane::Tab(at) => kept.get(at).copied().unwrap_or(false), + Lane::Ghost(_) => true, + }) + .collect(); + let selected = lane.iter().position(|place| matches!(*place, Lane::Tab(at) if at == *selected)).unwrap_or(usize::MAX); + let minimum = min.iter().copied().fold(0.0, f32::max); + let fit = mode.fit(&natural, selected, &held, (*width - ends_room).max(0.0), minimum, *height); + *shown = vec![false; count]; + *left = vec![*width; count]; + *wide = vec![0.0; count]; let mut at = 0.0; let mut placed = Vec::with_capacity(fit.shown.len()); - for &(index, width) in &fit.shown { - self.shown[index] = true; - self.left[index] = at; - self.wide[index] = width; - placed.push((index, at, width)); - at += width; + let mut slots: Vec> = vec![None; *departed]; + for &(position, extent) in &fit.shown { + match lane.get(position) { + Some(&Lane::Tab(index)) => { + shown[index] = true; + left[index] = at; + wide[index] = extent; + placed.push((index, at, extent)); + } + Some(&Lane::Ghost(k)) => { + if let Some(slot) = ghosts.get(k).and_then(|ghost| slots.get_mut(ghost.slot)) { + *slot = Some((at, extent)); + } + } + None => {} + } + at += extent; } - if !crate::runtime::measure::active(&self.ctx) { - *self.report.lock().unwrap_or_else(PoisonError::into_inner) = - Report { hidden: fit.overflow, tabs_end: at, overflow: fit.overflow_width, placed }; + let hidden: Vec = fit + .overflow + .iter() + .filter_map(|&position| match lane.get(position) { + Some(&Lane::Tab(index)) => Some(index), + _ => None, + }) + .collect(); + if !crate::runtime::measure::active(ctx) { + *report.lock().unwrap_or_else(PoisonError::into_inner) = + Report { hidden, tabs_end: at, overflow: fit.overflow_width, placed, ends, ends_room, ghosts: slots }; } } } @@ -254,6 +402,25 @@ impl WindowDropTarget> for TearOff { } } +/// The keyed presence of a ribbon strip's contextual tabs, one key per tab key (rb.R2a). +const LEAVE: &str = "contextual"; + +/// What a contextual tab's presence keeps of it while it shows and fades out after leaving the source: its name, the +/// position it had in the source and its width; no width while it sat in the overflow menu (rb.R2, S-L72). +#[derive(Clone, Debug)] +struct Ghost { + label: String, + before: usize, + width: Option, +} + +/// A departed contextual tab drawn this pass: its name and opacity. +#[derive(Clone, Debug)] +struct Fading { + label: String, + alpha: f32, +} + /// The role of the tab of a key: `TabStrip::roles`. pub struct TabRoles<'a, K>(Box TabRole + 'a>); @@ -315,6 +482,10 @@ pub struct TabStrip<'a, K: Clone + Eq + Hash + Send + Sync + std::fmt::Debug + ' /// dragged tabs would go. #[prop(func = "Fn(&ListDrag, Option<&K>, usize) -> bool")] accepts: Option>, + /// The items at the reading end, beside the tabs. + trailing: &'a [StripEnd<'a>], + /// The contextual tabs fading out this pass, each as opaque as its presence. + ghosts: Vec, held: Bind<'a, Selection>, report: Arc>, /// Each tab's key and name, as the source listed them this pass. @@ -358,6 +529,8 @@ impl<'a, K: Clone + Eq + Hash + Send + Sync + std::fmt::Debug + 'static> TabStri roles: None, drops: Vec::new(), accepts: None, + trailing: &[], + ghosts: Vec::new(), held: Bind::kept(), report: Arc::new(Mutex::new(Report::default())), texts: RefCell::new(Vec::new()), @@ -386,6 +559,15 @@ impl<'a, K: Clone + Eq + Hash + Send + Sync + std::fmt::Debug + 'static> TabStri self } + /// Sets the items at the reading end of the strip, beside the tabs: each runs its command or opens its menu. When + /// the room runs short they drop their labels, the last item first, before any tab overflows; they keep their + /// icons whatever the room. + #[must_use] + pub fn trailing(mut self, items: &'a [StripEnd<'a>]) -> Self { + self.trailing = items; + self + } + /// With `wheel_selects`, the wheel's whole notches step the shown tab through the tabs in the source's order: /// down to later tabs, up to earlier ones. fn wheel_step(&mut self, cx: &mut Cx<'_, Self>) { @@ -411,10 +593,10 @@ impl<'a, K: Clone + Eq + Hash + Send + Sync + std::fmt::Debug + 'static> TabStri self.report.lock().unwrap_or_else(PoisonError::into_inner).clone() } - /// The part of the row no tab and no overflow button takes, in screen space. + /// The part of the row no tab, no overflow button and no end item takes, in screen space. fn empty_room(&self, content: Rect, rtl: bool) -> Rect { let report = self.report(); - let rest = craft_behavior::Flow::new(content, rtl).take_start(report.tabs_end).1; + let rest = Flow::new(content, rtl).take_end(report.ends_room).1.take_start(report.tabs_end).1; let rest = match (report.overflow > 0.0, self.kind.overflow_place()) { (false, _) => rest, (true, OverflowPlace::StripEnd) => rest.take_end(report.overflow).1, @@ -437,6 +619,88 @@ impl<'a, K: Clone + Eq + Hash + Send + Sync + std::fmt::Debug + 'static> TabStri }) .collect() } + + /// The leave motion of a ribbon strip with `roles`: every contextual tab the source lists drives its own keyed + /// presence open, carrying its name and slot; one the source no longer lists comes back from `exiting` and fades + /// out at its last slot. It is drawn only, so it has no hit area, no access node and no overflow entry, and the + /// presence drops its name and slot once the fade ends. A tab that comes back stops fading; one that enters is an + /// item of the source like any other, hit and listed from its first pass. + /// + /// The strip keeps nothing of its own. A rerun pass of one frame drives the same keys at the same clock, so it + /// draws what the first pass drew. + fn track_leaving(&mut self, cx: &mut Cx<'_, Self>) { + self.ghosts.clear(); + let Some(roles) = self.roles.as_ref().filter(|_| self.kind.slides_underline()) else { return }; + let report = self.report(); + let texts = self.texts.borrow(); + for (index, (key, label)) in texts.iter().enumerate() { + if roles.role(key) != TabRole::Contextual { + continue; + } + let width = report.placed.iter().find(|(at, ..)| *at == index).map(|&(_, _, width)| width); + let _ = cx.presence_keyed(LEAVE, key, true, Ghost { label: label.clone(), before: index, width }, spec::OPEN_FADE); + } + drop(texts); + // The same keys in the same order as the layout reserved their slots from (`reserved`). + self.ghosts = cx.exiting::(LEAVE, spec::OPEN_FADE).into_iter().map(|(presence, ghost)| Fading { label: ghost.label, alpha: presence.t }).collect(); + } + + /// The menus of the end items that open one, each below its item. + fn end_menus(&self, ui: &mut OverlayUi<'_>, cx: &mut Cx<'_, Self>) { + for slot in self.report().ends { + let Some(end) = self.trailing.get(slot.item).filter(|end| end.opens_menu()) else { continue }; + let popup = cx.popup(ENDS).at(slot.item); + let layer = crate::menu::layer(false).anchor(ui.anchor_part(END.at(slot.item as u64))); + let name = end.label().clone(); + let ran = ui.show(popup, layer, |ui, _| Menu::inline(name.clone()).show(ui, |ui, _| end.menu_rows(ui)).inner.flatten()).flatten(); + if let Some(command) = ran { + cx.fire(command, FireSource::Menu); + } + } + } + + /// The one underline of a ribbon strip under its shown tab. Its start and width run toward the shown tab's slot + /// from where they are painted, so a tab shown mid-motion turns the underline where it is; under reduced motion + /// they jump (`Animate`). + fn paint_underline(&self, ui: &mut PaintUi<'_>, cx: &Cx<'_, Self>, report: &Report) { + let texts = self.texts.borrow(); + let Some(&(_, start, width)) = + report.placed.iter().find(|(index, ..)| texts.get(*index).is_some_and(|(key, _)| self.shown.as_ref() == Some(key))) + else { + return; + }; + let start = cx.anim("underline_start", start, spec::MOVE); + let width = cx.anim("underline_width", width, spec::MOVE); + let rect = Flow::new(cx.core.content_rect, cx.flow.is_rtl()).span(start, width); + let y = rect.bottom() - cx.style.underline_inset; + ui.draw().stroke(&PaintShape::Path(vec![Pos2::new(rect.left(), y), Pos2::new(rect.right(), y)]), StrokeWidth::Thick, cx.style.underline); + } + + /// The slots the departing contextual tabs keep in the fit, and how many tabs are departing. `listed` are the + /// keys the source lists now; a tab that sat in the overflow menu keeps no slot. + fn reserved(&self, cx: &StyleCx<'_>, listed: &[K]) -> (Vec, usize) { + if self.roles.is_none() || !self.kind.slides_underline() { + return (Vec::new(), 0); + } + let departing = cx.exiting::(LEAVE, spec::OPEN_FADE, listed); + let reserved = departing + .iter() + .enumerate() + .filter_map(|(slot, (_, ghost))| Some(Reserved { slot, before: ghost.before.min(listed.len()), width: ghost.width? })) + .collect(); + (reserved, departing.len()) + } + + /// The departed contextual tabs at the slots the fit kept for them, each painted as the `Tab` it was, as opaque + /// as its presence has left it. + fn paint_ghosts(&self, ui: &mut PaintUi<'_>, report: &Report) { + for (at, fading) in self.ghosts.iter().enumerate() { + if report.ghosts.get(at).copied().flatten().is_some() { + let tab = Tab::new(fading.label.clone()).kind(TabKind::Ribbon).role(TabRole::Contextual); + ui.face_faded(GHOST.at(at as u64), tab, fading.alpha); + } + } + } } impl Component for TabStrip<'_, K> { @@ -445,7 +709,13 @@ impl Component f type Output = TabStripOutput; fn style(cx: &StyleCx<'_>, _: TabStripStyleKey) -> TabStripStyle { - TabStripStyle { metrics: Metrics::new(), line: cx.tokens.typography.body.line_height } + let tokens = cx.tokens; + TabStripStyle { + metrics: Metrics::new(), + line: tokens.typography.body.line_height, + underline: cx.color(tokens.color.accent.solid), + underline_inset: tokens.stroke.thick / 2.0, + } } fn sense(&self) -> Sense { @@ -453,17 +723,41 @@ impl Component f if self.wheel_selects { sense | Sense::WHEEL_Y } else { sense } } - /// The overflow button, over the end of the row or right after the last shown tab. + /// The end items at the end of the row, a focus stop each, and the overflow button, at the end of the room the + /// end items leave or right after the last shown tab. fn parts(&mut self, _: Rect, cx: &mut PartsCx<'_, Self>) { self.more = None; let report = self.report(); + let flow = Flow::new(cx.content_rect, cx.flow.is_rtl()); + for slot in &report.ends { + let Some(end) = self.trailing.get(slot.item) else { continue }; + let enabled = end.enabled::(&**cx); + let part = cx + .part(END.at(slot.item as u64), flow.span(slot.start, slot.width)) + .sense(Sense::CLICK | Sense::FOCUS) + .priority(HitPriority::new(HitLevel::Edge, 0)) + .over() + .focusable() + .inactive(!enabled); + // An icon-only item keeps its name as its tooltip. + let part = if slot.short { part.tooltip(end.label().clone()) } else { part }; + if end.opens_menu() { + part.toggles_at(ENDS, slot.item); + } + } + // A tab fading out has a part to paint its face on and no sense, so it is neither hit nor focused. + for (at, slot) in report.ghosts.iter().enumerate() { + if let Some((start, width)) = *slot { + let _ = cx.part(GHOST.at(at as u64), flow.span(start, width)); + } + } if report.overflow <= 0.0 { return; } - let flow = craft_behavior::Flow::new(cx.content_rect, cx.flow.is_rtl()); + let tabs = flow.take_end(report.ends_room).1; let slot = match self.kind.overflow_place() { - OverflowPlace::StripEnd => flow.take_end(report.overflow).0, - OverflowPlace::AfterTabs => flow.take_start(report.tabs_end).1.take_start(report.overflow).0, + OverflowPlace::StripEnd => tabs.take_end(report.overflow).0, + OverflowPlace::AfterTabs => tabs.take_start(report.tabs_end).1.take_start(report.overflow).0, }; self.more = Some(slot); cx.part(OVERFLOW, slot) @@ -488,6 +782,15 @@ impl Component f self.empty_drag = matches!(press.phase, PressPhase::DragStart { .. }); self.empty_double = press.double_pressed(); } + for slot in self.report().ends { + let Some(end) = self.trailing.get(slot.item) else { continue }; + if let Some(command) = end.command_ref() + && let Some(source) = cx.part_activated(END.at(slot.item as u64)) + { + cx.fire(command.clone(), source); + } + } + self.track_leaving(cx); self.wheel_step(cx); if !self.tear_off { return; @@ -501,8 +804,10 @@ impl Component f } } - /// The overflow menu: every tab with the shown one checked, or only the hidden tabs, by the kind. + /// The end items' menus, and the overflow menu: every tab with the shown one checked, or only the hidden tabs, by + /// the kind. fn overlay(&mut self, ui: &mut OverlayUi<'_>, cx: &mut Cx<'_, Self>) { + self.end_menus(ui, cx); if self.more.is_none() { return; } @@ -523,14 +828,34 @@ impl Component f } } + /// The overflow button and each end item are buttons named by their labels; an end item with a menu says so. fn access(&self, access: &mut Access, cx: &Cx<'_, Self>) { if self.more.is_some() { let node = access.node(OVERFLOW, Role::BUTTON); node.name = Name::Text(cx.words::().more.as_str().to_owned()); } + for slot in self.report().ends { + let Some(end) = self.trailing.get(slot.item) else { continue }; + let node = access.node(END.at(slot.item as u64), Role::BUTTON); + node.name = Name::Text(end.label().as_str().to_owned()); + if end.opens_menu() { + node.has_popup(PopupKind::Menu); + } + } } - fn paint_over(&mut self, ui: &mut crate::contract::PaintUi<'_>, cx: &Cx<'_, Self>) { + /// The end items' faces, the sliding underline of a ribbon strip, the tabs fading out, and the overflow button. + fn paint_over(&mut self, ui: &mut PaintUi<'_>, cx: &Cx<'_, Self>) { + let report = self.report(); + for slot in &report.ends { + if let Some(end) = self.trailing.get(slot.item) { + end.paint(ui, END.at(slot.item as u64), slot.short); + } + } + if self.kind.slides_underline() { + self.paint_underline(ui, cx, &report); + } + self.paint_ghosts(ui, &report); if self.more.is_some() { ui.face(OVERFLOW, IconButton::new(IconId::new("more")).label(cx.words::().more.clone())); } @@ -588,7 +913,17 @@ impl Collection let count = source.len(); *self.texts.borrow_mut() = (0..count).map(|at| (source.key(at), source.text(at).map(|text| text.into_owned()).unwrap_or_default())).collect(); let selected = self.shown.as_ref().and_then(|key| source.index_of(key)).unwrap_or(usize::MAX); - StripLayout::new(count, width, cx.tokens.size.bar.tab, selected, self.kind.fit_mode(), self.report.clone(), cx.frame_ctx().clone()) + let keys: Vec = (0..count).map(|at| source.key(at)).collect(); + // The roles are inputs of the fit: it runs here, before any tab is built. + let kept = match &self.roles { + Some(roles) => keys.iter().map(|key| roles.role(key) == TabRole::Contextual).collect(), + None => Vec::new(), + }; + let (ghosts, departed) = self.reserved(cx, &keys); + // Each end item is measured in this pass, with its label and icon only. + let ends = self.trailing.iter().map(|end| end.fit_item(cx)).collect(); + let fitting = Fitting { selected, mode: self.kind.fit_mode(), kept, ends, gap: cx.tokens.space.gap.inline, ghosts, departed }; + StripLayout::new(count, width, cx.tokens.size.bar.tab, fitting, self.report.clone(), cx.frame_ctx().clone()) } /// Every tab takes the strip's kind and size. diff --git a/crates/ui-widgets/src/tabs/strip/end.rs b/crates/ui-widgets/src/tabs/strip/end.rs index 681b5a155..4c21c10af 100644 --- a/crates/ui-widgets/src/tabs/strip/end.rs +++ b/crates/ui-widgets/src/tabs/strip/end.rs @@ -1,13 +1,22 @@ //! `StripEnd`: an item at the reading end of a tab strip, beside the tabs. +//! +//! The strip fits, places and runs the items; this file gives each item its two faces (with its label, and icon only), +//! its measure for the fit, its part's state and its menu. -use crate::contract::Entry; +use crate::buttons::{Button, IconButton}; +use crate::contract::{Component, Entry, MeasureCx, PaintUi, Props as _}; +use crate::menu::entry_rows; use crate::primitives::IconSpec; use crate::runtime::commands::CommandRef; use crate::runtime::env::Label; +use crate::style::StyleCx; +use craft_behavior::PartRef; +use craft_behavior::fit::{FitItem, FitKeep}; use craft_theme::Variant; +use egui::Ui; /// What an end item does when pressed. -#[allow(dead_code)] // P3(ribbon-w1): rb.R3 +#[derive(Clone)] enum EndAction<'a> { Command(CommandRef), Menu(&'a [Entry]), @@ -15,7 +24,7 @@ enum EndAction<'a> { /// An item at the reading end of a `TabStrip`: a button that runs a command or opens a menu. It drops its label before /// the tabs overflow. -#[allow(dead_code)] // P3(ribbon-w1): rb.R3 +#[derive(Clone)] pub struct StripEnd<'a> { label: Label, icon: IconSpec<'a>, @@ -24,22 +33,87 @@ pub struct StripEnd<'a> { } impl<'a> StripEnd<'a> { - /// An item that runs `command`, named `label`, with `icon`. + /// An item that runs `command`, named `label`, with `icon`. It is enabled while the command is. pub fn command(label: impl Into