TabStrip wheel_selects: the wheel over the strip steps the shown tab by the collection's wheel notch; a collection that senses the wheel registers in the item step with its notch; DockConfig::wheel_selects_tabs passes it to dock groups

This commit is contained in:
aiongg
2026-11-12 14:32:45 +00:00
parent 94113ca1d7
commit c7362a6790
10 changed files with 159 additions and 25 deletions
+9 -4
View File
@@ -125,6 +125,14 @@ pub enum WheelNotch {
impl WheelNotch {
/// The distance of a taker that states none.
pub const DEFAULT: WheelNotch = WheelNotch::Points(40.0);
/// The notch in points, for a taker whose view is `extent` points along the axis.
pub fn points(self, extent: f32) -> f32 {
match self {
WheelNotch::Points(points) => points,
WheelNotch::ViewShare(share) => extent * share,
}
}
}
impl<O> WheelTaker<O> {
@@ -211,10 +219,7 @@ impl<O> WheelTaker<O> {
let size = self.rect.size();
match unit {
WheelUnit::Point => scroll,
WheelUnit::Line => match self.notch {
WheelNotch::Points(points) => scroll * points,
WheelNotch::ViewShare(share) => scroll * size * share,
},
WheelUnit::Line => Vec2::new(scroll.x * self.notch.points(size.x), scroll.y * self.notch.points(size.y)),
WheelUnit::Page => scroll * size,
}
}
@@ -521,6 +521,11 @@ impl CollectionProps {
self
}
/// The wheel distance of one notch, with a text line `line` points high: the set notch, else the default.
pub fn wheel_notch(&self, line: f32) -> craft_behavior::WheelNotch {
self.notch.map_or(craft_behavior::WheelNotch::DEFAULT, |notch| notch.wheel(line))
}
/// The axis the rows overflow along (see [`CollectionProps::overflow`]).
#[must_use]
pub const fn overflow(mut self, axis: Axis) -> Self {
+4
View File
@@ -143,6 +143,9 @@ pub(super) struct ItemsHooks<'s, 'r, C: Collection> {
/// run, the width in a measuring run (the real run shows a collection that fills across the column it is held in).
from_content: (bool, bool),
scrolls: bool,
/// The collection senses the wheel itself (a tab strip stepping its tabs): the wheel is its own, not the rows'
/// scroll.
own_wheel: bool,
/// The collection shows at most `max_rows` rows: its height is bounded by its rows, whatever its sizing.
capped: bool,
/// The distance one wheel notch scrolls the rows, from `CollectionProps::notch`.
@@ -211,6 +214,7 @@ impl<'s, 'r, C: Collection> ItemsHooks<'s, 'r, C> {
room: Vec2::ZERO,
from_content: (false, false),
scrolls: true,
own_wheel: false,
capped: false,
notch: craft_behavior::WheelNotch::DEFAULT,
overflow: Axis::Y,
+18 -5
View File
@@ -22,8 +22,7 @@ use crate::runtime::memory::{MemoryStage, sub};
use crate::runtime::{focus, keys, layout_memory, lazy, overlay, wheel};
use crate::style::{ComponentStyle as _, ScrollBarKind, StyleCx, SurfaceKind, scroll_bar_look, surface_style};
use craft_behavior::{
Axis, CancelReason, EditEvent, Intent, ItemLayout, Mixed, Proposal, ScrollPos, ScrollSpan, SelectionModel, Sense, WheelNotch, WheelRoom,
WheelTaker,
Axis, CancelReason, EditEvent, Intent, ItemLayout, Mixed, Proposal, ScrollPos, ScrollSpan, SelectionModel, Sense, WheelRoom, WheelTaker,
};
use egui::{Context, Id, Pos2, Rect, Ui, UiBuilder, Vec2};
use std::rc::Rc;
@@ -86,6 +85,7 @@ impl<C: Collection> ShapeHooks<C> for ItemsHooks<'_, '_, C> {
);
// A capped collection is bounded by its rows, so it scrolls them inside a scrolling body too.
self.scrolls = self.capped || (!natural && !shared);
self.own_wheel = crate::contract::Component::sense(comp).intersects(Sense::WHEEL | Sense::WHEEL_X | Sense::WHEEL_Y | Sense::WHEEL_ZOOM);
self.overflow = overflow;
self.selection = match comp.selection() {
Some(bind) => match bind.get() {
@@ -133,7 +133,13 @@ impl<C: Collection> ShapeHooks<C> for ItemsHooks<'_, '_, C> {
let view = self.last.view.map_or(0.0, |view| view[3] - view[1]);
if self.scrolls {
let quiet = stage.is_peek() || crate::runtime::measure::active(&ctx);
let taken = if quiet { wheel::peek(&ctx, id) } else { wheel::take(&ctx, id) };
let taken = if self.own_wheel {
None
} else if quiet {
wheel::peek(&ctx, id)
} else {
wheel::take(&ctx, id)
};
if let Some(share) = taken {
self.offset -= f64::from(share.scroll.y);
self.offset_x -= f64::from(share.scroll.x);
@@ -280,7 +286,7 @@ impl<C: Collection> ShapeHooks<C> for ItemsHooks<'_, '_, C> {
fn parts(&mut self, comp: &mut C, _: Rect, pcx: &mut PartsCx<'_, C>) {
self.header.parts(pcx);
self.notch = comp.items().notch.map_or(WheelNotch::DEFAULT, |notch| notch.wheel(pcx.tokens.typography.body.line_height));
self.notch = comp.items().wheel_notch(pcx.tokens.typography.body.line_height);
if !self.scrolls {
return;
}
@@ -299,7 +305,14 @@ impl<C: Collection> ShapeHooks<C> for ItemsHooks<'_, '_, C> {
fn sensed(&mut self, comp: &mut C, cx: &mut Cx<'_, C>) {
cx.core.collection_selection = Some(Box::new(self.selection.clone()));
if self.scrolls {
if self.own_wheel {
// A collection that takes the wheel itself reads it in its own notches, in place of the rows' scroll.
if cx.core.resolved.enabled
&& let Some(taker) = WheelTaker::for_sense(cx.core.id, cx.core.rect, crate::contract::Component::sense(comp))
{
wheel::register(&cx.core.ctx, taker.notch(self.notch).gated(cx.core.env.wheel() == WheelScope::Gated));
}
} else if self.scrolls {
// The taker covers the whole collection, header row and frame included: the wheel over the header scrolls
// the rows (Shift sideways).
let view = self.below_header(cx.core.content_rect);
+8 -2
View File
@@ -850,8 +850,14 @@ fn run_in_host(p: &mut Pass<'_, '_, '_>, ui: &mut Ui, host_at: Option<ShowAt>, h
let member = if arena || facts.text() { None } else { env.arena };
stops_step(StopsStep { ctx: &ctx, id, rtl, env, resolved, inert, holder_widget, member, own, text_keys }, e, facts, &parts);
// A body's wheel share is its scroll taker (body step, step 7); the gate value does not take the wheel. A body root that
// senses the wheel itself (a canvas) registers like any other component.
if !inert && (e.shape() != ShapeKind::Body || own.intersects(Sense::WHEEL | Sense::WHEEL_X)) {
// senses the wheel itself (a canvas) registers like any other component. A collection that senses the wheel itself
// registers in the item step, with its notch.
let registers = match e.shape() {
ShapeKind::Leaf => true,
ShapeKind::Body => own.intersects(Sense::WHEEL | Sense::WHEEL_X),
ShapeKind::Item => !own.intersects(Sense::WHEEL | Sense::WHEEL_X | Sense::WHEEL_Y | Sense::WHEEL_ZOOM),
};
if !inert && registers {
steps::register_wheel(&ctx, id, rect, own, e.bound().0 && !facts.binds_view, env.wheel);
}
// 8 sense
+10
View File
@@ -76,6 +76,8 @@ pub struct DockConfig {
/// closes them, for tabs that act as documents. Off: panels close from their menu. Accordion headers and iconic
/// columns never show it.
pub tab_close_buttons: bool,
/// The wheel over a tab strip shows the next or previous panel, one per wheel notch.
pub wheel_selects_tabs: bool,
/// A floating window opens in an OS window of its own where the window host opens OS windows and reports where
/// they are on the desktop (not on Wayland) and its panels allow it (`PanelSpec::allow_native`). Elsewhere, and
/// with this off, it shows in the app window.
@@ -95,6 +97,7 @@ impl Default for DockConfig {
close_menu_items: true,
close_button: true,
tab_close_buttons: false,
wheel_selects_tabs: false,
native_windows: true,
}
}
@@ -171,6 +174,13 @@ impl DockConfig {
self
}
/// Wheel selection of tabs on or off.
#[must_use]
pub fn wheel_selects_tabs(mut self, on: bool) -> Self {
self.wheel_selects_tabs = on;
self
}
/// Native floating windows on or off.
#[must_use]
pub fn native_windows(mut self, on: bool) -> Self {
+15 -8
View File
@@ -229,6 +229,9 @@ pub struct DockGroup<'a, P: Clone + Hash + Send + Sync + 'static> {
/// Tabs of panels that are closable show a close button and close on a middle click.
#[prop(flag)]
closable: bool,
/// The wheel over the tabs shows the next or previous panel, one per wheel notch.
#[prop(flag)]
wheel_selects_tabs: bool,
/// The dock whose drop registry the group's spots go to.
#[prop]
dock: Option<Id>,
@@ -267,6 +270,7 @@ impl<'a, P: Clone + Hash + Send + Sync + 'static> DockGroup<'a, P> {
minimized: false,
movable: true,
closable: false,
wheel_selects_tabs: false,
dock: None,
zones: ZoneRule::Fraction,
menu: Vec::new(),
@@ -426,7 +430,7 @@ impl<P: Clone + Hash + Send + Sync + 'static> Container for DockGroup<'_, P> {
let words = cx.words::<DockWords>();
let from = PanelKey::of(&self.anchor);
let started = drop::started(&cx.env);
let (panels, active, closable) = (self.panels, self.active, self.closable);
let (panels, active, closable, wheel_selects) = (self.panels, self.active, self.closable, self.wheel_selects_tabs);
let menu_rows = self.menu.clone();
let panel_menu = words.panel_menu.clone();
let mut extra = self.extra.take();
@@ -448,17 +452,20 @@ impl<P: Clone + Hash + Send + Sync + 'static> Container for DockGroup<'_, P> {
let source = keyed(panels, |panel: &PanelTitle| panel.key).with_text(|panel| Cow::Borrowed(panel.title.as_str()));
let closes = |panel: &PanelTitle| closable && panel.closable;
let kind = if panels.iter().any(closes) { TabKind::Document } else { TabKind::Panel };
let strip = TabStrip::new(name.clone())
let mut strip = TabStrip::new(name.clone())
.kind(kind)
.shown(active)
.tear_off()
.natural_height(true)
.drag_payload(move |drag: &ListDrag<PanelKey>| Some(PanelDrag { panel: drag.grabbed, from, source: Some(size), started }))
.show_items(ui, &source, &mut |key, _| {
let panel = panels.iter().find(|panel| &panel.key == key);
let title = panel.map_or_else(Label::default, |panel| panel.title.clone());
Tab::new(title).closable(panel.is_some_and(closes))
});
.drag_payload(move |drag: &ListDrag<PanelKey>| Some(PanelDrag { panel: drag.grabbed, from, source: Some(size), started }));
if wheel_selects {
strip = strip.wheel_selects();
}
let strip = strip.show_items(ui, &source, &mut |key, _| {
let panel = panels.iter().find(|panel| &panel.key == key);
let title = panel.map_or_else(Label::default, |panel| panel.title.clone());
Tab::new(title).closable(panel.is_some_and(closes))
});
let strip_id = strip.response.response.id;
// A press on the group's empty body focuses its panel, as in Photoshop.
if surface_pressed {
@@ -698,6 +698,9 @@ impl<P: Clone + Eq + Hash + Debug + Send + Sync + 'static> Pass<'_, P> {
if scene.config.tab_close_buttons {
group = group.closable();
}
if scene.config.wheel_selects_tabs {
group = group.wheel_selects_tabs();
}
group
};
let rect = match at {
+46 -6
View File
@@ -15,14 +15,16 @@ use super::{Tab, TabPartEvent};
use crate::buttons::IconButton;
use crate::contract::{
Access, Bind, BindMut, Collection, CollectionEvent, CollectionProps, CollectionResponse, Common, Component, ContainerProps, ContextMenuRequest,
Cx, DropKind, DropMark, Entry, ListDrag, Name, NoValue, Outcome, OverlayUi, Overlays as _, PartsCx, Pointer as _, Props as _, Role, RowState,
SelectMode, Sizing, WindowDropTarget, WordSetCx as _,
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 _,
};
use crate::list::{DropTest, RowTest};
use crate::menu::Menu;
use crate::runtime::env::Label;
use crate::style::{ComponentStyle, StyleCx};
use craft_behavior::{HitLevel, HitPriority, IconId, ItemLayout, ItemSource, Metrics, NavShape, PartKey, PressPhase, ScrollPos, Selection, Sense};
use craft_behavior::{
HitLevel, HitPriority, IconId, ItemLayout, ItemSource, Metrics, NavShape, PartKey, PressPhase, ScrollPos, Selection, SelectionChange, Sense,
};
use egui::{Id, Pos2, Rect, Response, Vec2};
use std::cell::RefCell;
use std::hash::Hash;
@@ -88,6 +90,8 @@ impl<K> Outcome for TabStripOutput<K> {
pub struct TabStripStyle {
#[style(metrics)]
metrics: Metrics,
/// The text line a wheel notch given in lines counts.
line: f32,
}
/// What the layout tells the strip's parts and menu after fitting the tabs.
@@ -276,6 +280,10 @@ pub struct TabStrip<'a, K: Clone + Eq + Hash + Send + Sync + std::fmt::Debug + '
/// A tab dragged out and released where no target takes it is reported as `torn_off`.
#[prop(flag)]
tear_off: bool,
/// The wheel over the strip shows the next or previous tab, one per wheel notch, stopping at the ends; not with
/// Ctrl or Cmd held.
#[prop(flag)]
wheel_selects: bool,
/// Which tabs may be dragged.
#[prop(func = "Fn(&K) -> bool")]
can_drag: Option<RowTest<'a, K>>,
@@ -292,6 +300,8 @@ pub struct TabStrip<'a, K: Clone + Eq + Hash + Send + Sync + std::fmt::Debug + '
more: Option<Rect>,
picked: Option<K>,
torn: Option<TornOff<K>>,
/// The tab the wheel stepped to this pass.
wheeled: Option<K>,
empty_drag: bool,
empty_double: bool,
}
@@ -307,6 +317,7 @@ impl<'a, K: Clone + Eq + Hash + Send + Sync + std::fmt::Debug + 'static> TabStri
large: false,
shown: None,
tear_off: false,
wheel_selects: false,
can_drag: None,
drops: Vec::new(),
accepts: None,
@@ -316,6 +327,7 @@ impl<'a, K: Clone + Eq + Hash + Send + Sync + std::fmt::Debug + 'static> TabStri
more: None,
picked: None,
torn: None,
wheeled: None,
empty_drag: false,
empty_double: false,
}
@@ -337,6 +349,27 @@ impl<'a, K: Clone + Eq + Hash + Send + Sync + std::fmt::Debug + 'static> TabStri
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>) {
if !self.wheel_selects {
return;
}
let Some(wheel) = cx.take_wheel().filter(|wheel| !wheel.mods.cmd && !wheel.mods.ctrl) else { return };
let notch = self.items.wheel_notch(cx.style.line).points(cx.rect.height());
let steps = if notch > 0.0 { (wheel.scroll.y / notch).trunc() } else { 0.0 };
if steps == 0.0 || !steps.is_finite() {
return;
}
let texts = self.texts.borrow();
let Some(at) = self.shown.as_ref().and_then(|shown| texts.iter().position(|(key, _)| key == shown)) else { return };
let last = texts.len().saturating_sub(1) as i64;
let to = (at as i64 - steps as i64).clamp(0, last) as usize;
if to != at {
self.wheeled = Some(texts[to].0.clone());
}
}
fn report(&self) -> Report {
self.report.lock().unwrap_or_else(PoisonError::into_inner).clone()
}
@@ -374,8 +407,13 @@ impl<K: Clone + Eq + Hash + Send + Sync + std::fmt::Debug + 'static> Component f
type Style = TabStripStyle;
type Output = TabStripOutput<K>;
fn style(_: &StyleCx<'_>, _: TabStripStyleKey<K>) -> TabStripStyle {
TabStripStyle { metrics: Metrics::new() }
fn style(cx: &StyleCx<'_>, _: TabStripStyleKey<K>) -> TabStripStyle {
TabStripStyle { metrics: Metrics::new(), line: cx.tokens.typography.body.line_height }
}
fn sense(&self) -> Sense {
let sense = <<Self as Meta>::Shape as ShowShape>::DEFAULT_SENSE;
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.
@@ -413,6 +451,7 @@ impl<K: Clone + Eq + Hash + Send + Sync + std::fmt::Debug + 'static> Component f
self.empty_drag = matches!(press.phase, PressPhase::DragStart { .. });
self.empty_double = press.double_pressed();
}
self.wheel_step(cx);
if !self.tear_off {
return;
}
@@ -462,7 +501,7 @@ impl<K: Clone + Eq + Hash + Send + Sync + std::fmt::Debug + 'static> Component f
fn finish(self, mut cx: Cx<'_, Self>) -> TabStripOutput<K> {
let tab_rects = self.tab_rects(&cx);
let TabStrip { picked, torn, empty_drag, empty_double, .. } = self;
let TabStrip { picked, torn, wheeled, empty_drag, empty_double, .. } = self;
let mut response = cx.collection_response();
let (mut closed, mut menu) = (Vec::new(), None);
let mut kept = Vec::with_capacity(response.events.len());
@@ -473,6 +512,7 @@ impl<K: Clone + Eq + Hash + Send + Sync + std::fmt::Debug + 'static> Component f
other => kept.push(other),
}
}
kept.extend(wheeled.map(|key| CollectionEvent::Selection(SelectionChange::Set(vec![key]))));
response.events = kept;
TabStripOutput { response, closed, menu, picked, torn_off: torn, tab_rects, empty_drag, empty_double }
}
+41
View File
@@ -65,6 +65,47 @@ fn the_close_button_and_its_node_close_a_tab() {
assert_eq!(closed.borrow().clone(), vec![1, 0], "an AccessKit Click on the close node closes its tab");
}
/// A strip of the three titles showing tab 0 that applies its selection changes, with or without `wheel_selects`;
/// returns the fixture and the tab it shows.
fn wheel_rig(wheel_selects: bool) -> (Fixture, Rc<Cell<usize>>) {
let shown = Rc::new(Cell::new(0_usize));
let now = shown.clone();
let mut fixture = Fixture::new(move |ui| {
let keys = [0_usize, 1, 2];
let source = keyed(&keys, |key: &usize| *key);
let strip = TabStrip::new("Documents").shown(now.get());
let strip = if wheel_selects { strip.wheel_selects() } else { strip };
let out = strip.show_items(ui, &source, &mut |key, _| Tab::new(TITLES[*key]));
for event in &out.response.events {
if let CollectionEvent::Selection(SelectionChange::Set(keys)) = event
&& let Some(key) = keys.last()
{
now.set(*key);
}
}
});
fixture.settle();
(fixture, shown)
}
/// With `wheel_selects`, a wheel notch down over the strip shows the next tab and a notch up the previous one; without
/// it the wheel shows no other tab.
#[trial]
fn the_wheel_steps_the_shown_tab_only_where_the_strip_asks_for_it() {
use craft_ui::testing::pointer;
for wheel_selects in [true, false] {
let (mut fixture, shown) = wheel_rig(wheel_selects);
let over = fixture.by_label("Two").expect("the tab's node").center();
fixture.frame(vec![pointer::moved(over)]).idle(1);
fixture.frame(vec![pointer::wheel_lines(-1.0)]).idle(2);
assert_eq!(shown.get(), usize::from(wheel_selects), "a notch down, wheel_selects {wheel_selects}");
if wheel_selects {
fixture.frame(vec![pointer::wheel_lines(1.0)]).idle(2);
assert_eq!(shown.get(), 0, "a notch up shows the previous tab");
}
}
}
/// A double click on the empty room after the last document tab asks for a new document; a double click on a tab
/// activates it and asks for none.
#[trial]