mirror of
https://github.com/storytold/craft-libs.git
synced 2026-11-26 05:37:04 +00:00
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)
This commit is contained in:
+54
-14
@@ -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<f32> = natural.iter().map(|&w| tab_extent(w)).collect();
|
||||
if natural.iter().map(|&w| f64::from(w)).sum::<f64>() <= 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<FitItem> = 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<usize>, Vec<usize>) = (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 }
|
||||
}
|
||||
|
||||
@@ -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::<f32>() + 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::<Vec<_>>(), "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];
|
||||
|
||||
@@ -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<C: Show>(&mut self, part: impl Into<PartRef>, 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<C: Show>(&mut self, part: PartRef, face: C, ink: Option<&Stateful<StyleColor>>) {
|
||||
let Some(result) = self.results.get(&(part.key, part.index)) else {
|
||||
debug_assert!(false, "face for a part `parts` did not declare");
|
||||
|
||||
@@ -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<P> {
|
||||
key: Id,
|
||||
tween: Tween<f32>,
|
||||
/// A key that no pass of the running frame drove open is closing.
|
||||
open_in: Option<u64>,
|
||||
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<P> {
|
||||
born: u64,
|
||||
entries: Vec<KeyedEntry<P>>,
|
||||
}
|
||||
|
||||
/// 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<T: Interpolate>(policy: &MotionPolicy, tween: &mut Tween<T>, 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<P: Clone + Send + Sync + 'static>(
|
||||
ctx: &Context,
|
||||
base: Id,
|
||||
policy: MotionPolicy,
|
||||
name: &'static str,
|
||||
spec: MotionSpec,
|
||||
listed: &[Id],
|
||||
) -> Vec<(Presence, P)> {
|
||||
let Some(keyed) = store::peek_clone::<Keyed<P>>(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<f32>; 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::<Tween<T>>(ctx, id) } else { store::take::<Tween<T>>(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<T: Interpolate>(&self, tween: &mut Tween<T>, 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<P: Clone + Send + Sync + 'static>(&self, name: &'static str) -> Option<Keyed<P>> {
|
||||
let ctx = self.stage.ctx();
|
||||
let id = self.keyed_slot(name);
|
||||
if self.stage.is_peek() { store::peek_clone::<Keyed<P>>(ctx, id) } else { store::take::<Keyed<P>>(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<P: Clone + Send + Sync + 'static>(&self, name: &'static str, keyed: Keyed<P>) {
|
||||
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<P: Clone + Send + Sync + 'static>(&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::<P>(name).unwrap_or_else(|| {
|
||||
if !self.stage.is_peek() {
|
||||
memory::adopt::<Keyed<P>>(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<P: Clone + Send + Sync + 'static>(&self, name: &'static str, spec: MotionSpec) -> Vec<(Presence, P)> {
|
||||
let Some(mut keyed) = self.load_keyed::<P>(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<T: Interpolate>(&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<P: Clone + Send + Sync + 'static>(&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<P: Clone + Send + Sync + 'static>(&self, name: &'static str, spec: MotionSpec) -> Vec<(Presence, P)>;
|
||||
/// Sets `name` to `value` with no animation.
|
||||
fn jump<T: Interpolate>(&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<X: Drives + crate::runtime::memory::sealed::Sealed> Animate for X {
|
||||
self.driver().presence(name, open, spec)
|
||||
}
|
||||
|
||||
fn presence_keyed<P: Clone + Send + Sync + 'static>(&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<P: Clone + Send + Sync + 'static>(&self, name: &'static str, spec: MotionSpec) -> Vec<(Presence, P)> {
|
||||
self.driver().exiting(name, spec)
|
||||
}
|
||||
|
||||
fn jump<T: Interpolate>(&self, name: &'static str, value: T) {
|
||||
self.driver().jump(name, value);
|
||||
}
|
||||
|
||||
@@ -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<P: Clone + Send + Sync + 'static>(&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<Id> = 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> {
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -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<K>`; 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<EndSlot>,
|
||||
/// 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<Option<(f32, f32)>>,
|
||||
}
|
||||
|
||||
/// 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<bool>,
|
||||
/// The end items as the fit sees them, in the order given.
|
||||
ends: Vec<FitItem>,
|
||||
/// 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<Reserved>,
|
||||
/// 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<bool>,
|
||||
left: Vec<f32>,
|
||||
wide: Vec<f32>,
|
||||
@@ -130,7 +201,7 @@ pub struct StripLayout {
|
||||
}
|
||||
|
||||
impl StripLayout {
|
||||
fn new(count: usize, width: f32, height: f32, selected: usize, mode: FitMode, report: Arc<Mutex<Report>>, ctx: egui::Context) -> Self {
|
||||
fn new(count: usize, width: f32, height: f32, fitting: Fitting, report: Arc<Mutex<Report>>, 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<EndSlot>) {
|
||||
let Fitting { ends, gap, ghosts, .. } = &self.fitting;
|
||||
if ends.is_empty() {
|
||||
return (0.0, Vec::new());
|
||||
}
|
||||
let natural = self.ideal.iter().sum::<f32>() + ghosts.iter().map(|ghost| ghost.width).sum::<f32>();
|
||||
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::<f32>() + 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<f32> = 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<bool> = 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<Option<(f32, f32)>> = 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<usize> = 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<K: Send + Sync + 'static> WindowDropTarget<ListDrag<K>> 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<f32>,
|
||||
}
|
||||
|
||||
/// 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<dyn Fn(&K) -> 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<K>, Option<&K>, usize) -> bool")]
|
||||
accepts: Option<DropTest<'a, K>>,
|
||||
/// 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<Fading>,
|
||||
held: Bind<'a, Selection<K>>,
|
||||
report: Arc<Mutex<Report>>,
|
||||
/// 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::<Ghost>(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<Reserved>, usize) {
|
||||
if self.roles.is_none() || !self.kind.slides_underline() {
|
||||
return (Vec::new(), 0);
|
||||
}
|
||||
let departing = cx.exiting::<Ghost>(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<K: Clone + Eq + Hash + Send + Sync + std::fmt::Debug + 'static> Component for TabStrip<'_, K> {
|
||||
@@ -445,7 +709,13 @@ impl<K: Clone + Eq + Hash + Send + Sync + std::fmt::Debug + 'static> Component f
|
||||
type Output = TabStripOutput<K>;
|
||||
|
||||
fn style(cx: &StyleCx<'_>, _: TabStripStyleKey<K>) -> 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<K: Clone + Eq + Hash + Send + Sync + std::fmt::Debug + 'static> 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::<Self>(&**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<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();
|
||||
}
|
||||
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<K: Clone + Eq + Hash + Send + Sync + std::fmt::Debug + 'static> 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<K: Clone + Eq + Hash + Send + Sync + std::fmt::Debug + 'static> 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::<StripWords>().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::<StripWords>().more.clone()));
|
||||
}
|
||||
@@ -588,7 +913,17 @@ impl<K: Clone + Eq + Hash + Send + Sync + std::fmt::Debug + 'static> 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<K> = (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.
|
||||
|
||||
@@ -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<CommandRef>]),
|
||||
@@ -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<Label>, icon: IconSpec<'a>, command: impl Into<CommandRef>) -> Self {
|
||||
let _ = (label.into(), icon, command.into());
|
||||
todo!("rb.R3")
|
||||
StripEnd { label: label.into(), icon, action: EndAction::Command(command.into()), variant: Variant::GHOST }
|
||||
}
|
||||
|
||||
/// An item that opens a menu of `entries`, named `label`, with `icon`.
|
||||
pub fn menu(label: impl Into<Label>, icon: IconSpec<'a>, entries: &'a [Entry<CommandRef>]) -> Self {
|
||||
let _ = (label.into(), icon, entries);
|
||||
todo!("rb.R3")
|
||||
StripEnd { label: label.into(), icon, action: EndAction::Menu(entries), variant: Variant::GHOST }
|
||||
}
|
||||
|
||||
/// Sets the button variant of the item.
|
||||
#[must_use]
|
||||
pub fn variant(self, variant: Variant) -> Self {
|
||||
let _ = variant;
|
||||
todo!("rb.R3")
|
||||
pub fn variant(mut self, variant: Variant) -> Self {
|
||||
self.variant = variant;
|
||||
self
|
||||
}
|
||||
|
||||
/// The item's name: the label its full face shows, and its accessible name in either form.
|
||||
pub(super) fn label(&self) -> &Label {
|
||||
&self.label
|
||||
}
|
||||
|
||||
/// The command the item runs when pressed; `None` for a menu item, which opens its menu instead.
|
||||
pub(super) fn command_ref(&self) -> Option<&CommandRef> {
|
||||
match &self.action {
|
||||
EndAction::Command(command) => Some(command),
|
||||
EndAction::Menu(_) => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether the item opens a menu.
|
||||
pub(super) fn opens_menu(&self) -> bool {
|
||||
matches!(self.action, EndAction::Menu(_))
|
||||
}
|
||||
|
||||
/// Whether the item can be pressed: a command item while its command is enabled, a menu item always.
|
||||
pub(super) fn enabled<C: Component>(&self, cx: &MeasureCx<'_, C>) -> bool {
|
||||
self.command_ref().is_none_or(|command| cx.resolve_command(command.clone()).is_none_or(|resolved| resolved.enabled))
|
||||
}
|
||||
|
||||
/// The face with the label beside the icon.
|
||||
fn full_face(&self) -> Button<'a> {
|
||||
let face = Button::new(self.label.clone()).icon(self.icon.clone()).variant(self.variant);
|
||||
match self.command_ref() {
|
||||
Some(command) => face.command(command.clone()).label(self.label.clone()),
|
||||
None => face,
|
||||
}
|
||||
}
|
||||
|
||||
/// The face with the icon only; the label stays its name and tooltip.
|
||||
fn short_face(&self) -> IconButton<'a> {
|
||||
let face = IconButton::new(self.icon.clone()).variant(self.variant);
|
||||
match self.command_ref() {
|
||||
Some(command) => face.command(command.clone()).label(self.label.clone()),
|
||||
None => face.label(self.label.clone()),
|
||||
}
|
||||
}
|
||||
|
||||
/// The item as the fit sees it: its full width, and its icon-only width as the short form. It never leaves the
|
||||
/// strip, since the tabs overflow before the end items give up their room.
|
||||
pub(super) fn fit_item(&self, cx: &StyleCx<'_>) -> FitItem {
|
||||
|
||||
let full = cx.face(self.full_face()).x;
|
||||
let short = cx.face(self.short_face()).x;
|
||||
FitItem::new(full, 0, FitKeep::Pinned).short(short)
|
||||
}
|
||||
|
||||
/// Paints the item's face on `part`, icon only when the fit shortened it.
|
||||
pub(super) fn paint(&self, ui: &mut PaintUi<'_>, part: PartRef, short: bool) {
|
||||
if short {
|
||||
ui.face(part, self.short_face());
|
||||
} else {
|
||||
ui.face(part, self.full_face());
|
||||
}
|
||||
}
|
||||
|
||||
/// The rows of a menu item's menu, shown as every menu shows its entries (`entry_rows`), and the command of the
|
||||
/// row that ran this pass.
|
||||
pub(super) fn menu_rows(&self, ui: &mut Ui) -> Option<CommandRef> {
|
||||
let EndAction::Menu(entries) = &self.action else { return None };
|
||||
let ran = entry_rows(ui, entries)?;
|
||||
entries.get(ran)?.value().cloned()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,10 +1,11 @@
|
||||
//! Stories of `TabStrip`.
|
||||
|
||||
use super::{TabKind, TabStrip};
|
||||
use crate::contract::{ReorderRule, ShowCollection as _};
|
||||
use crate::tabs::Tab;
|
||||
use super::{StripEnd, TabKind, TabStrip};
|
||||
use crate::contract::{CollectionEvent, Entry, ReorderRule, ShowCollection as _};
|
||||
use crate::runtime::commands::{CommandRef, EditCommands};
|
||||
use crate::tabs::{Tab, TabRole};
|
||||
use crate::testing::{Drive, Fixture, StoryData, StoryOutput, story};
|
||||
use craft_behavior::{DisplayOrder, ItemSource};
|
||||
use craft_behavior::{DisplayOrder, IconId, ItemSource, SelectionChange};
|
||||
use egui::{Key, Modifiers, Ui};
|
||||
use std::borrow::Cow;
|
||||
|
||||
@@ -103,3 +104,81 @@ fn tab_strip_panel_narrow(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
|
||||
strip(ui, data, TabStrip::new("Panels").shown(1), &TITLES, TITLES.len(), TabKind::Panel)
|
||||
})
|
||||
}
|
||||
|
||||
/// The ribbon's tab names; the last is the contextual tab.
|
||||
const RIBBON: [&str; 6] = ["File", "Home", "Insert", "Layout", "Review", "Table Design"];
|
||||
|
||||
/// The ribbon tabs without the contextual one, and with it.
|
||||
const PLAIN: [usize; 5] = [0, 1, 2, 3, 4];
|
||||
const WITH_TABLE: [usize; 6] = [0, 1, 2, 3, 4, 5];
|
||||
|
||||
/// The role of a ribbon story's tab: the last one is contextual.
|
||||
fn ribbon_role(key: &usize) -> TabRole {
|
||||
if *key == RIBBON.len() - 1 { TabRole::Contextual } else { TabRole::Standard }
|
||||
}
|
||||
|
||||
/// A ribbon strip of the tabs `open`, showing Home until a tab is picked.
|
||||
fn ribbon(ui: &mut Ui, data: &mut StoryData, strip: TabStrip<'_, usize>, open: &[usize]) -> StoryOutput {
|
||||
let shown = data.value("shown", 1_usize);
|
||||
let source = Documents { open, titles: &RIBBON };
|
||||
let out = strip
|
||||
.kind(TabKind::Ribbon)
|
||||
.shown(*shown)
|
||||
.roles(ribbon_role)
|
||||
.show_items(ui, &source, &mut |key, _| Tab::new(RIBBON[*key]).role(ribbon_role(key)));
|
||||
for event in &out.response.events {
|
||||
if let CollectionEvent::Selection(SelectionChange::Set(keys)) = event
|
||||
&& let Some(key) = keys.last()
|
||||
{
|
||||
*shown = *key;
|
||||
}
|
||||
}
|
||||
out.into()
|
||||
}
|
||||
|
||||
/// The rows of the Comments item's menu.
|
||||
fn comment_rows() -> Vec<Entry<CommandRef>> {
|
||||
vec![Entry::new(EditCommands::Cut.into(), "New comment"), Entry::new(EditCommands::Paste.into(), "Show comments")]
|
||||
}
|
||||
|
||||
/// A command item and a menu item at the strip's end.
|
||||
fn end_items(rows: &[Entry<CommandRef>]) -> [StripEnd<'_>; 2] {
|
||||
[StripEnd::command("Share", IconId::new("link").into(), EditCommands::Copy), StripEnd::menu("Comments", IconId::new("list").into(), rows)]
|
||||
}
|
||||
|
||||
/// The width the narrow ribbon story's room is held to: every tab whole, the end items icon only.
|
||||
const RIBBON_NARROW_ROOM: f32 = 340.0;
|
||||
|
||||
/// The frames the leave story lists its contextual tab for before the source drops it.
|
||||
const TABLE_FRAMES: usize = 30;
|
||||
|
||||
#[story(TabStrip<'static, usize>, covers = [], drive = Drive::Never)]
|
||||
fn tab_strip_ribbon(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
|
||||
ribbon(ui, data, TabStrip::new("Ribbon"), &WITH_TABLE)
|
||||
}
|
||||
|
||||
#[story(TabStrip<'static, usize>, covers = [], drive = Drive::Never)]
|
||||
fn tab_strip_ribbon_end_items(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
|
||||
let rows = comment_rows();
|
||||
let items = end_items(&rows);
|
||||
ribbon(ui, data, TabStrip::new("Ribbon").trailing(&items), &PLAIN)
|
||||
}
|
||||
|
||||
#[story(TabStrip<'static, usize>, covers = [], drive = Drive::Never)]
|
||||
fn tab_strip_ribbon_end_items_narrow(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
|
||||
let rows = comment_rows();
|
||||
let items = end_items(&rows);
|
||||
crate::testing::memory::scoped(ui, |ui| {
|
||||
ui.set_max_width(RIBBON_NARROW_ROOM);
|
||||
ribbon(ui, data, TabStrip::new("Ribbon").trailing(&items), &PLAIN)
|
||||
})
|
||||
}
|
||||
|
||||
/// The contextual tab is listed for the first frames and then dropped by the source: it fades out at its slot.
|
||||
#[story(TabStrip<'static, usize>, covers = [], drive = Drive::Never)]
|
||||
fn tab_strip_ribbon_contextual_leaves(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
|
||||
let frames = data.value("frames", 0_usize);
|
||||
*frames += 1;
|
||||
let open: &[usize] = if *frames <= TABLE_FRAMES { &WITH_TABLE } else { &PLAIN };
|
||||
ribbon(ui, data, TabStrip::new("Ribbon"), open)
|
||||
}
|
||||
|
||||
@@ -15,7 +15,7 @@ use crate::contract::{
|
||||
use crate::display::Progress;
|
||||
use crate::primitives::{IconSpec, PaintShape, RectSide, StrokeWidth, TextRun, Wrap};
|
||||
use crate::runtime::env::Label;
|
||||
use crate::style::{ComponentStyle, Flags, IconLook, RuleKind, StyleColor, StyleCx, SurfaceLook, TextLook};
|
||||
use crate::style::{ComponentStyle, Flags, IconLook, RuleKind, StyleColor, StyleCx, SurfaceLook, TextLook, UiTokens};
|
||||
use craft_behavior::{Flow, IconId, Insets, Metrics, PartKey, PointerButton, PressPhase, Proposal, Sense};
|
||||
use craft_theme::{Contrast, Rgba, Stateful, States, TypeRole};
|
||||
use egui::{Pos2, Rect, Response, Vec2};
|
||||
@@ -24,7 +24,7 @@ use egui::{Pos2, Rect, Response, Vec2};
|
||||
mod stories;
|
||||
|
||||
/// The role of a tab in its strip.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
|
||||
#[non_exhaustive]
|
||||
pub enum TabRole {
|
||||
/// An ordinary tab.
|
||||
@@ -103,9 +103,12 @@ pub struct TabStyle {
|
||||
surface: SurfaceLook,
|
||||
#[style(metrics)]
|
||||
metrics: Metrics,
|
||||
/// The label: the text colour on the selected tab, muted on the others, also under the pointer.
|
||||
/// The label: the text colour on the selected tab, muted on the others, also under the pointer. A ribbon tab's
|
||||
/// label is in the accent text colour when shown or contextual, and measures at the shown tab's semibold type.
|
||||
#[style(text)]
|
||||
label: TextLook,
|
||||
/// The label's type on a tab that is not shown: the ribbon's regular weight, the label's own type elsewhere.
|
||||
idle_role: TypeRole,
|
||||
/// The detail, which stays readable while the label is cut.
|
||||
#[style(text)]
|
||||
detail: TextLook,
|
||||
@@ -143,7 +146,8 @@ pub struct Tab<'a> {
|
||||
#[style_key]
|
||||
#[prop]
|
||||
kind: TabKind,
|
||||
/// Whether the tab is a standard one or a contextual one.
|
||||
/// Whether the tab is a standard one or a contextual one; a contextual ribbon tab takes the accent text colour.
|
||||
#[style_key]
|
||||
#[prop]
|
||||
role: TabRole,
|
||||
/// Large Tabs: the strip's taller form with the body type.
|
||||
@@ -238,9 +242,18 @@ impl Component for Tab<'_> {
|
||||
let tokens = cx.tokens;
|
||||
let (colors, space, size, stroke) = (&tokens.color, &tokens.space, &tokens.size, &tokens.stroke);
|
||||
let text_only = key.kind.text_only();
|
||||
let ribbon = key.kind == TabKind::Ribbon;
|
||||
let c = |rgba: Rgba| cx.color(rgba);
|
||||
let clear = Rgba::TRANSPARENT;
|
||||
let role = if text_only || key.large { TypeRole::Body } else { TypeRole::Label };
|
||||
// A ribbon tab measures at the shown tab's semibold type, so showing a tab does not move its neighbours.
|
||||
let role = if ribbon {
|
||||
TypeRole::BodyStrong
|
||||
} else if text_only || key.large {
|
||||
TypeRole::Body
|
||||
} else {
|
||||
TypeRole::Label
|
||||
};
|
||||
let idle_role = if ribbon { TypeRole::Body } else { role };
|
||||
let line = |role: TypeRole| tokens.typography.get(role).line_height;
|
||||
let height = if text_only {
|
||||
line(role) + space.gap.tight + stroke.thick
|
||||
@@ -253,16 +266,24 @@ impl Component for Tab<'_> {
|
||||
};
|
||||
let pad_x = if text_only { 0.0 } else { 2.0 * space.pad.control };
|
||||
let panel = colors.surface.panel;
|
||||
let fill = if text_only {
|
||||
let hover = c(colors.state.hover);
|
||||
let fill = if ribbon {
|
||||
Stateful::new(c(clear)).off(States::new(c(clear), hover, c(clear), c(clear))).on(States::new(c(clear), c(clear), c(clear), c(clear)))
|
||||
} else if text_only {
|
||||
Stateful::new(c(clear))
|
||||
} else {
|
||||
Stateful::new(c(clear)).off(States::new(c(clear), c(panel), c(panel), c(clear))).on(States::new(c(panel), c(panel), c(panel), c(panel)))
|
||||
};
|
||||
let surface = SurfaceLook::new(fill);
|
||||
let surface = if ribbon { SurfaceLook::new(fill).radius(UiTokens::corner(tokens.shape.radius.sm)) } else { SurfaceLook::new(fill) };
|
||||
let disabled = c(colors.text.disabled);
|
||||
let ink = |off: Rgba, on: Rgba| {
|
||||
Stateful::new(c(off)).off(States::new(c(off), c(off), c(off), disabled)).on(States::new(c(on), c(on), c(on), disabled))
|
||||
};
|
||||
let label_ink = match (ribbon, key.role) {
|
||||
(true, TabRole::Contextual) => ink(colors.accent.text, colors.accent.text),
|
||||
(true, _) => ink(colors.text.muted, colors.accent.text),
|
||||
_ => ink(colors.text.muted, colors.text.normal),
|
||||
};
|
||||
let sizes = Sizes {
|
||||
gap: space.gap.inline,
|
||||
icon: size.icon.sm,
|
||||
@@ -277,9 +298,10 @@ impl Component for Tab<'_> {
|
||||
TabStyle {
|
||||
surface,
|
||||
metrics: Metrics::new().padding(Insets::new(pad_x, pad_x, 0.0, 0.0)).min_size(Vec2::new(0.0, height)).gap(sizes.gap),
|
||||
label: TextLook::new(role, ink(colors.text.muted, colors.text.normal)),
|
||||
label: TextLook::new(role, label_ink.clone()),
|
||||
idle_role,
|
||||
detail: TextLook::new(TypeRole::Caption, ink(colors.text.faint, colors.text.faint)),
|
||||
icon: IconLook::new(sizes.icon, ink(colors.text.muted, colors.text.normal)),
|
||||
icon: IconLook::new(sizes.icon, label_ink),
|
||||
underline: c(colors.text.normal),
|
||||
indicator: (!text_only && cx.contrast() == Contrast::High).then(|| c(colors.accent.solid)),
|
||||
divider: key.kind.trailing_divider(),
|
||||
@@ -427,12 +449,14 @@ impl Component for Tab<'_> {
|
||||
let bar = Rect::from_min_size(rect.min, Vec2::new(rect.width(), sizes.indicator.min(rect.height())));
|
||||
draw.fill(&PaintShape::Rect(bar, egui::CornerRadius::ZERO), color);
|
||||
}
|
||||
if sizes.text_only && selected {
|
||||
// A strip that slides its underline paints the one underline itself.
|
||||
if sizes.text_only && selected && !self.kind.slides_underline() {
|
||||
let y = placed.label.bottom() + sizes.underline_gap;
|
||||
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));
|
||||
let role = if selected { style.label.role } else { style.idle_role };
|
||||
let label = TextRun::new(cx.resolved.label).role(role).color(cx.resolve(&style.label.color));
|
||||
draw.text(placed.label, &if self.kind.clips_label() { label.wrap(Wrap::Clip) } else { 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());
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
//! Stories of `Tab`.
|
||||
|
||||
use super::{Tab, TabKind};
|
||||
use super::{Tab, TabKind, TabRole};
|
||||
use crate::contract::{Props as _, SetPosition, Show as _};
|
||||
use crate::testing::{Drive, StoryData, StoryOutput, story};
|
||||
use craft_behavior::IconId;
|
||||
@@ -35,3 +35,16 @@ fn tab_panel(ui: &mut Ui, _: &mut StoryData) -> StoryOutput {
|
||||
fn tab_text(ui: &mut Ui, _: &mut StoryData) -> StoryOutput {
|
||||
Tab::new("General").position(SetPosition::new(1).of(3)).kind(TabKind::Text).selected(true).show(ui).into()
|
||||
}
|
||||
|
||||
/// A shown ribbon tab: its label in semibold and the accent text colour, with no underline of its own (the strip
|
||||
/// slides one).
|
||||
#[story(Tab<'static>, covers = [], drive = Drive::Never)]
|
||||
fn tab_ribbon(ui: &mut Ui, _: &mut StoryData) -> StoryOutput {
|
||||
Tab::new("Home").position(SetPosition::new(0).of(4)).kind(TabKind::Ribbon).selected(true).show(ui).into()
|
||||
}
|
||||
|
||||
/// A contextual ribbon tab that is not shown: its label stays in the accent text colour.
|
||||
#[story(Tab<'static>, covers = [], drive = Drive::Never)]
|
||||
fn tab_ribbon_contextual(ui: &mut Ui, _: &mut StoryData) -> StoryOutput {
|
||||
Tab::new("Table Design").position(SetPosition::new(3).of(4)).kind(TabKind::Ribbon).role(TabRole::Contextual).show(ui).into()
|
||||
}
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
use craft_behavior::{SelectionChange, keyed};
|
||||
use craft_ui::contract::{CollectionEvent, Role, ShowCollection as _};
|
||||
use craft_ui::runtime::egui::access::AccessTree;
|
||||
use craft_ui::tabs::{Tab, TabKind, TabStrip};
|
||||
use craft_ui::tabs::{Tab, TabKind, TabRole, TabStrip};
|
||||
use craft_ui::testing::focus::AccessActionKind;
|
||||
use craft_ui::testing::pointer::{moved, press, release};
|
||||
use craft_ui::testing::{Fixture, Frames, trial};
|
||||
@@ -364,3 +364,245 @@ fn panel_tabs_keep_the_shown_tab_whole_and_overflow_from_the_end() {
|
||||
}
|
||||
assert!(fewer < PANELS.len(), "the narrowest room overflows");
|
||||
}
|
||||
|
||||
/// The ribbon's tab names; the last is the contextual tab.
|
||||
const RIBBON: [&str; 6] = ["File", "Home", "Insert", "Layout", "Review", "Table Design"];
|
||||
|
||||
/// The key of the contextual tab.
|
||||
const TABLE: usize = 5;
|
||||
|
||||
/// The role of a ribbon trial's tab: the last one is contextual.
|
||||
fn ribbon_role(key: &usize) -> TabRole {
|
||||
if *key == TABLE { TabRole::Contextual } else { TabRole::Standard }
|
||||
}
|
||||
|
||||
/// The sliding underline a frame painted in the tab row `row`: the horizontal two-point line in its band, as its left
|
||||
/// and right x. Ribbon tabs paint no line of their own.
|
||||
fn underline(shapes: &[egui::Shape], row: Rect) -> Option<(f32, f32)> {
|
||||
shapes.iter().find_map(|shape| match shape {
|
||||
egui::Shape::Path(path) if !path.closed && path.points.len() == 2 => {
|
||||
let (a, b) = (path.points[0], path.points[1]);
|
||||
let flat = (a.y - b.y).abs() < 0.01;
|
||||
(flat && a.y >= row.top() && a.y <= row.bottom()).then(|| (a.x.min(b.x), a.x.max(b.x)))
|
||||
}
|
||||
_ => None,
|
||||
})
|
||||
}
|
||||
|
||||
/// A ribbon strip's one underline runs to a newly shown tab, and a tab shown while it runs turns it where it is: at the
|
||||
/// reversal it lies between the two tabs, and it comes back to rest under the first tab without a jump. The wheel
|
||||
/// shows the tabs, one frame per change.
|
||||
#[trial]
|
||||
fn the_ribbon_underline_retargets_from_its_shown_position_mid_motion() {
|
||||
use craft_ui::testing::pointer;
|
||||
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("Ribbon").kind(TabKind::Ribbon).wheel_selects().shown(now.get());
|
||||
let out = strip.show_items(ui, &source, &mut |key, _| Tab::new(RIBBON[*key]));
|
||||
for event in &out.response.events {
|
||||
if let CollectionEvent::Selection(SelectionChange::Set(keys)) = event
|
||||
&& let Some(key) = keys.last()
|
||||
{
|
||||
now.set(*key);
|
||||
}
|
||||
}
|
||||
});
|
||||
fixture.room(egui::Vec2::new(640.0, 120.0)).settle();
|
||||
let (first, third) = (tab_rect(fixture.tree(), RIBBON[0]), tab_rect(fixture.tree(), RIBBON[2]));
|
||||
let row = first.union(third);
|
||||
let rest = underline(&fixture.frame_shapes(), row).expect("the shown tab's underline");
|
||||
assert!((rest.0 - first.left()).abs() < 0.5 && (rest.1 - first.right()).abs() < 0.5, "at rest it spans the first tab: {rest:?} {first:?}");
|
||||
|
||||
fixture.frame(vec![pointer::moved(row.center())]).idle(1);
|
||||
fixture.frame(vec![pointer::wheel_lines(-2.0)]);
|
||||
assert_eq!(shown.get(), 2, "two notches down show the third tab");
|
||||
let going: Vec<f32> = (0..2).filter_map(|_| underline(&fixture.frame_shapes(), row)).map(|line| line.0).collect();
|
||||
assert!(
|
||||
going.len() == 2 && going[1] > first.left() + 0.5 && going[1] < third.left() - 0.5,
|
||||
"the underline is on its way to the third tab: {going:?} {first:?} {third:?}"
|
||||
);
|
||||
|
||||
fixture.frame(vec![pointer::wheel_lines(2.0)]);
|
||||
assert_eq!(shown.get(), 0, "two notches up show the first tab again");
|
||||
let distance = third.left() - first.left();
|
||||
let turned = underline(&fixture.frame_shapes(), row).expect("the underline at the reversal").0;
|
||||
assert!(
|
||||
turned > first.left() + 0.5 && turned < third.left() - 0.5,
|
||||
"at the reversal the underline lies between the two tabs, not at either target: {turned} {first:?} {third:?}"
|
||||
);
|
||||
assert!((turned - going[1]).abs() < distance / 2.0, "the reversal starts where the underline was: {going:?} then {turned}");
|
||||
let mut last = turned;
|
||||
for _ in 0..30 {
|
||||
let at = underline(&fixture.frame_shapes(), row).expect("the underline while it returns").0;
|
||||
assert!(at <= last + 0.5, "the underline only moves back toward the first tab: {last} then {at}");
|
||||
assert!((last - at).abs() < distance / 2.0, "the underline does not jump: {last} then {at}");
|
||||
last = at;
|
||||
}
|
||||
assert!((last - first.left()).abs() < 0.5, "the underline comes to rest under the first tab: {last} {first:?}");
|
||||
}
|
||||
|
||||
/// What a ribbon strip of the six tabs with two end items shows in a room `room` wide: the tabs on the strip with their
|
||||
/// widths, whether each end item paints its label, each end item's width, and whether the overflow button is there.
|
||||
struct EndView {
|
||||
tabs: Vec<(&'static str, f32)>,
|
||||
share_label: bool,
|
||||
comments_label: bool,
|
||||
share: f32,
|
||||
comments: f32,
|
||||
overflow: bool,
|
||||
}
|
||||
|
||||
impl EndView {
|
||||
fn shows(&self, name: &str) -> bool {
|
||||
self.tabs.iter().any(|(shown, _)| *shown == name)
|
||||
}
|
||||
}
|
||||
|
||||
fn end_view(room: f32) -> EndView {
|
||||
use craft_behavior::IconId;
|
||||
use craft_ui::contract::Entry;
|
||||
use craft_ui::runtime::commands::{CommandRef, EditCommands};
|
||||
use craft_ui::tabs::StripEnd;
|
||||
let rows: [Entry<CommandRef>; 1] = [Entry::new(EditCommands::Paste.into(), "Show comments")];
|
||||
let items = [StripEnd::command("Share", IconId::new("link").into(), EditCommands::Copy), StripEnd::menu("Comments", IconId::new("list").into(), &rows)];
|
||||
let mut frames = Frames::new();
|
||||
let mut show = |ui: &mut Ui| {
|
||||
ui.set_max_width(room);
|
||||
let keys: Vec<usize> = (0..RIBBON.len()).collect();
|
||||
let source = keyed(&keys, |key: &usize| *key);
|
||||
let strip = TabStrip::new("Ribbon").kind(TabKind::Ribbon).shown(1).roles(ribbon_role).trailing(&items);
|
||||
strip.show_items(ui, &source, &mut |key, _| Tab::new(RIBBON[*key]).role(ribbon_role(key)));
|
||||
};
|
||||
frames.idle(3, &mut show);
|
||||
let tree = frames.tree();
|
||||
let painted = |name: &str| frames.texts().iter().any(|text| text.text == name);
|
||||
let buttons = tree.with_role(Role::BUTTON);
|
||||
let width = |name: &str| {
|
||||
buttons.iter().find(|key| tree.name_of(**key) == Some(name)).and_then(|key| tree.bounds_of(*key)).map_or(0.0, |rect| rect.width())
|
||||
};
|
||||
EndView {
|
||||
tabs: RIBBON.iter().filter_map(|name| tab_rects(&tree, name).first().map(|rect| (*name, rect.width()))).collect(),
|
||||
share_label: painted("Share"),
|
||||
comments_label: painted("Comments"),
|
||||
share: width("Share"),
|
||||
comments: width("Comments"),
|
||||
overflow: buttons.iter().any(|key| !matches!(tree.name_of(*key), Some("Share" | "Comments"))),
|
||||
}
|
||||
}
|
||||
|
||||
/// As the room narrows, the end items drop their labels, the last one first, before any tab overflows; then the tabs
|
||||
/// overflow while the items keep their icons. The shown tab and the contextual tab stay on the strip while a plain tab
|
||||
/// overflows, and the contextual tab gives way only to plain tabs narrower than itself.
|
||||
#[trial]
|
||||
fn end_items_drop_their_labels_before_a_tab_overflows() {
|
||||
let wide = end_view(2000.0);
|
||||
assert_eq!(wide.tabs.len(), RIBBON.len(), "every tab fits a wide room");
|
||||
assert!(wide.share_label && wide.comments_label && !wide.overflow, "a wide room shows both labels and no overflow");
|
||||
let table = wide.tabs.iter().find(|(name, _)| *name == RIBBON[TABLE]).map_or(0.0, |&(_, width)| width);
|
||||
let (mut comments_only, mut all_short, mut kept) = (false, false, false);
|
||||
// A coarse sweep from the width that holds every tab and both labels down to a room that overflows most tabs;
|
||||
// each stage of the order lasts for several steps.
|
||||
const STEP: f32 = 16.0;
|
||||
const FLOOR: f32 = 200.0;
|
||||
let top = wide.tabs.iter().map(|&(_, width)| width).sum::<f32>() + wide.share + wide.comments;
|
||||
for step in 0..=((top + STEP - FLOOR) / STEP) as usize {
|
||||
let room = top + STEP - step as f32 * STEP;
|
||||
let view = end_view(room);
|
||||
assert!(view.share_label || !view.comments_label, "Comments drops its label before Share in {room}");
|
||||
assert!(view.share > 0.0 && view.comments > 0.0, "the end items stay in {room}");
|
||||
if !view.comments_label {
|
||||
assert!(view.comments < wide.comments - 0.5, "an item without its label is narrower in {room}");
|
||||
}
|
||||
let all_tabs = view.tabs.len() == RIBBON.len();
|
||||
assert_eq!(view.overflow, !all_tabs, "the overflow button is there only while a tab overflows in {room}");
|
||||
if all_tabs {
|
||||
comments_only |= view.share_label && !view.comments_label;
|
||||
all_short |= !view.share_label && !view.comments_label;
|
||||
continue;
|
||||
}
|
||||
assert!(!view.share_label && !view.comments_label, "both items are icon only before a tab overflows in {room}");
|
||||
assert!(view.shows(RIBBON[1]), "the shown tab stays in {room}");
|
||||
if view.shows(RIBBON[TABLE]) {
|
||||
kept = true;
|
||||
} else {
|
||||
let wider = view.tabs.iter().filter(|(name, _)| *name != RIBBON[1]).find(|&&(_, width)| width >= table);
|
||||
assert!(wider.is_none(), "the contextual tab gives way only to narrower plain tabs in {room}: {:?}", view.tabs);
|
||||
}
|
||||
}
|
||||
assert!(comments_only, "a room shows Share whole and Comments icon only with every tab");
|
||||
assert!(all_short, "a room shows both items icon only with every tab");
|
||||
assert!(kept, "a room keeps the contextual tab while a plain tab overflows");
|
||||
}
|
||||
|
||||
/// A contextual tab the source drops fades out at its slot: while it fades it has no node, a click on its slot
|
||||
/// selects nothing and the overflow menu does not list it; once the fade ends it is not painted. A frame of two
|
||||
/// passes paints the fade as one does. A contextual tab that comes back is hit from its first frame.
|
||||
#[trial]
|
||||
fn a_contextual_tab_that_leaves_is_not_hit_or_listed_while_it_fades() {
|
||||
let (listed, discard) = (Rc::new(Cell::new(true)), Rc::new(Cell::new(false)));
|
||||
let picked = Rc::new(RefCell::new(Vec::new()));
|
||||
let shown = Rc::new(Cell::new(1_usize));
|
||||
let (lists, asks, seen, now) = (listed.clone(), discard.clone(), picked.clone(), shown.clone());
|
||||
let mut fixture = Fixture::new(move |ui| {
|
||||
let keys: Vec<usize> = (0..RIBBON.len()).filter(|&key| key != TABLE || lists.get()).collect();
|
||||
let source = keyed(&keys, |key: &usize| *key);
|
||||
let strip = TabStrip::new("Ribbon").kind(TabKind::Ribbon).shown(now.get()).roles(ribbon_role);
|
||||
let out = strip.show_items(ui, &source, &mut |key, _| Tab::new(RIBBON[*key]).role(ribbon_role(key)));
|
||||
for event in &out.response.events {
|
||||
if let CollectionEvent::Selection(SelectionChange::Set(keys)) = event
|
||||
&& let Some(key) = keys.last()
|
||||
{
|
||||
seen.borrow_mut().push(*key);
|
||||
now.set(*key);
|
||||
}
|
||||
}
|
||||
if asks.get() && ui.ctx().current_pass_index() == 0 {
|
||||
ui.ctx().request_discard("the trial runs the frame twice");
|
||||
}
|
||||
});
|
||||
fixture.room(egui::Vec2::new(640.0, 120.0)).settle();
|
||||
let home = fixture.by_label(RIBBON[1]).expect("the shown tab's node").rect;
|
||||
let table = fixture.by_label(RIBBON[TABLE]).expect("the contextual tab's node").rect;
|
||||
// A room for the shown tab, the contextual tab and the overflow button: plain tabs overflow.
|
||||
let room = home.width() + table.width() + 2.0 * home.height();
|
||||
fixture.room(egui::Vec2::new(room, 120.0)).settle();
|
||||
let hidden: Vec<&str> = RIBBON.iter().copied().filter(|name| tab_rects(fixture.tree(), name).is_empty()).collect();
|
||||
assert!(!hidden.is_empty(), "a plain tab overflows in {room}");
|
||||
let table = tab_rect(fixture.tree(), RIBBON[TABLE]);
|
||||
fixture.key(Key::Tab, Modifiers::NONE);
|
||||
|
||||
listed.set(false);
|
||||
discard.set(true);
|
||||
fixture.frame(Vec::new());
|
||||
discard.set(false);
|
||||
assert_eq!(fixture.passes(), 2, "the frame the tab leaves in runs two passes");
|
||||
let painted = |fixture: &Fixture| fixture.texts().iter().any(|text| text.text == RIBBON[TABLE]);
|
||||
assert!(painted(&fixture), "the departed tab fades at its slot after a frame of two passes");
|
||||
assert!(fixture.by_label(RIBBON[TABLE]).is_none(), "the departed tab has no node");
|
||||
|
||||
fixture.key(Key::ArrowDown, Modifiers::ALT);
|
||||
assert!(hidden.iter().all(|name| fixture.by_label(name).is_some()), "the overflow menu is open and lists the plain tabs: {hidden:?}");
|
||||
assert!(fixture.by_label(RIBBON[TABLE]).is_none(), "the overflow menu does not list the departed tab");
|
||||
assert!(painted(&fixture), "the departed tab is still fading");
|
||||
fixture.key(Key::Escape, Modifiers::NONE);
|
||||
|
||||
picked.borrow_mut().clear();
|
||||
fixture.click_at(table.center());
|
||||
assert!(picked.borrow().is_empty(), "a click on the departed tab's slot selects nothing: {:?}", picked.borrow());
|
||||
assert!(
|
||||
hidden.iter().all(|name| tab_rects(fixture.tree(), name).is_empty()),
|
||||
"no plain tab moves into the slot while the departed tab fades: {hidden:?}"
|
||||
);
|
||||
fixture.idle(30);
|
||||
assert!(!painted(&fixture), "the departed tab is gone once the fade ends");
|
||||
assert!(hidden.iter().any(|name| !tab_rects(fixture.tree(), name).is_empty()), "the strip refits once the exit ends: {hidden:?}");
|
||||
|
||||
listed.set(true);
|
||||
fixture.frame(Vec::new());
|
||||
let back = fixture.by_label(RIBBON[TABLE]).expect("a contextual tab that enters has a node once listed");
|
||||
fixture.click(&back);
|
||||
assert_eq!(shown.get(), TABLE, "a click on the entering tab shows it");
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user