ribbon-w2: net change of 6 commits

- ribbon-w2: written by an agent
- ribbon-w2: finished by an agent
- ribbon-w2: finished by an agent
- ribbon-w2: finished by an agent
- ribbon-w2: review fixes (review-1)
- ribbon-w2: review fixes (review-1b)
This commit is contained in:
Martin Ball
2026-11-18 21:02:54 +00:00
parent 5ca0336a5c
commit 9dd16ce7ba
26 changed files with 1370 additions and 105 deletions
@@ -96,11 +96,19 @@ pub struct ShownRow<K> {
pub cells: Vec<(ColumnKey, egui::Rect)>,
/// The openers the row's item asked for (`ItemCx::part_opener`), each with the part's response this pass.
pub openers: Vec<(crate::contract::ItemOpener, Response)>,
/// The pointer is over the row and the collection owns the hover (no press or layer above holds it).
pub hovered: bool,
}
impl<K> ShownRow<K> {
pub(crate) fn new(key: K, rect: egui::Rect, cells: Vec<(ColumnKey, egui::Rect)>) -> Self {
ShownRow { key, rect, cells, openers: Vec::new() }
ShownRow { key, rect, cells, openers: Vec::new(), hovered: false }
}
/// The row with its hover fact set.
pub(crate) fn with_hover(mut self, hovered: bool) -> Self {
self.hovered = hovered;
self
}
}
@@ -65,8 +65,13 @@ pub trait Pointer {
}
impl Pointer for CxCore<'_> {
/// Step 12 leaves the report; a run that stopped before it (a sizing pass) reports no stay, so its output never
/// repeats an `entered` or `left` the real pass reported.
fn hover(&self) -> Hover {
todo!("cv.K45")
if !self.stated || self.face_mode {
return Hover::default();
}
self.memory.recall::<Hover>(crate::contract::steps::ShownState::hover_slot(self.id))
}
fn part(&self, part: impl Into<PartRef>) -> &PartResult {
@@ -662,7 +662,7 @@ impl<C: Collection> ShapeHooks<C> for ItemsHooks<'_, '_, C> {
row = self.screen(&layout, rect, at, offset, rtl);
}
}
shown_rows.push(ShownRow::new(key.clone(), row, shown_cells.clone()));
shown_rows.push(ShownRow::new(key.clone(), row, shown_cells.clone()).with_hover(state.hovered));
let Some((mut row_ui, installed)) = row_ui else {
debug_assert!(tip.is_none(), "a member of a collection's run takes no rich tooltip");
let shown = shown_rows.len() - 1;
+15 -2
View File
@@ -2,7 +2,7 @@
use super::paint::surface_ink;
use crate::contract::run::ErasedPass;
use crate::contract::{Component, Cx, Validity};
use crate::contract::{Component, Cx, Hover, Validity};
use crate::runtime::access::scope;
use crate::runtime::motion::{Drives as _, spec};
use crate::style::{Flags, Ink, StateSet, StyleView};
@@ -98,7 +98,20 @@ pub(crate) fn state(p: &mut dyn ErasedPass<'_>, style: &dyn StyleView, open: boo
} else {
State::Rest
};
p.shown_state().last_state = (hovered, visible);
let clicked = crate::runtime::egui::response::pointer_clicked(&core.response);
let face = core.face_mode;
let shown = p.shown_state();
let was = shown.last_state.0;
shown.last_state = (hovered, visible);
// The click is held while the pointer stays over the control and dropped in the pass it leaves. A pass that sees
// no click (a second pass of a frame gets no input) keeps what the first pass held.
shown.clicked_over = hovered && (clicked || shown.clicked_over);
let report = Hover { over: hovered, entered: hovered && !was, left: was && !hovered, clicked: shown.clicked_over };
// A face shows a look, not a stay of the pointer: it keeps no report.
if !face {
let core = p.core();
*core.memory.shown::<Hover>(super::ShownState::hover_slot(core.id)) = report;
}
let t = ease(p, [hovered, pressed, flags.intersects(Flags::ON)]);
let core = p.core();
core.state = StateSet::new(state, flags, t);
@@ -127,8 +127,11 @@ pub(crate) fn register_stops(input: &StopsIn<'_>) -> Vec<Stop> {
after_header
}
/// Whether the component is a focus stop: an enabled one, or a disabled one whose tooltip has a `disabled_text`, which
/// shows its reason on keyboard focus (testing 22.4). Step 9 still drops its activations and edits.
/// Whether the component is a focus stop: an enabled one, or a disabled one with a reason to show on keyboard focus
/// (testing 22.4): its tooltip's `disabled_text`, or its bound command's hint, which its tooltip shows. Step 9 still
/// drops its activations and edits.
pub(crate) fn takes_focus(resolved: &Resolved<'_>) -> bool {
resolved.enabled || resolved.tooltip.is_some_and(|tooltip| tooltip.spec().disabled_text.is_some())
resolved.enabled
|| resolved.tooltip.is_some_and(|tooltip| tooltip.spec().disabled_text.is_some())
|| resolved.command.and_then(|command| command.hint.as_deref()).is_some_and(|hint| !hint.is_empty())
}
@@ -24,11 +24,18 @@ pub(crate) struct Shown<V> {
pub(crate) struct ShownState {
pub last_state: (bool, bool),
/// A pointer click on the control, while the pointer has stayed over it since.
#[allow(dead_code)] // P3(ribbon-w2): cv.K45
pub clicked_over: bool,
pub tweens: Option<StateTweens>,
}
impl ShownState {
/// The shown slot under which step 12 leaves the pass's `Hover` report of component `id`, for `Pointer::hover`:
/// the core that answers it cannot name the typed `Shown` record this state lives in.
pub(crate) fn hover_slot(id: Id) -> Id {
crate::runtime::memory::sub(id, "hover")
}
}
impl<V> Clone for Shown<V> {
fn clone(&self) -> Self {
Shown { copy: self.copy.clone(), drawn: self.drawn, state: self.state.clone() }
+10 -3
View File
@@ -73,26 +73,33 @@ fn spec_text(env: &crate::runtime::env::EnvView<'_>, spec: &TooltipSpec, enabled
/// The text the component's own tooltip shows, or `None` when it has none: its validity message when no container
/// shows it (`message`); else the tooltip's text, or its disabled text while disabled, with the bound command's
/// chord; else the full label when the paint cut it, or its own label when the component declares it paints no
/// label (`shows_label`).
/// label (`shows_label`), its face dropped the label (`PaintRecord::label_dropped`) or its command has a hint. A
/// bound command's hint follows on a line of its own.
fn text_of(core: &super::CxCore<'_>, shows_label: bool, message: Option<String>) -> Option<String> {
if message.is_some() {
return message;
}
let hint = core.command.as_deref().and_then(|command| command.hint.as_deref()).filter(|hint| !hint.is_empty());
let base = match core.resolved.tooltip.map(|tooltip| tooltip.spec()) {
Some(spec) => spec_text(&core.env, spec, core.resolved.enabled),
None => {
let paint = core.paint.borrow();
let unpainted = !shows_label || paint.label_dropped || hint.is_some();
match paint.elided.clone() {
Some(full) => full,
None if !shows_label && !core.resolved.label.is_empty() => core.resolved.label.to_owned(),
None if unpainted && !core.resolved.label.is_empty() => core.resolved.label.to_owned(),
None => return None,
}
}
};
let platform = crate::runtime::windows::os_of(&core.ctx);
Some(match core.command.as_deref().and_then(|command| command.chord.as_ref()) {
let text = match core.command.as_deref().and_then(|command| command.chord.as_ref()) {
Some(chord) => with_chord(&base, chord, platform),
None => base,
};
Some(match hint {
Some(hint) => format!("{text}\n{hint}"),
None => text,
})
}
@@ -91,6 +91,19 @@ impl<'a> ContentPainterCx<'a> {
paint(&faded);
}
/// Runs `paint` with a `ContentPainterCx` whose painting is clipped to `rect` (inside the clip it already has).
pub fn clipped(&self, rect: egui::Rect, paint: impl FnOnce(&ContentPainterCx<'_>)) {
let clipped = ContentPainterCx {
painter: self.painter.with_clip_rect(rect.intersect(self.painter.clip_rect())),
tokens: self.tokens,
direction: self.direction,
env: self.env,
ink: self.ink,
data: self.data,
};
paint(&clipped);
}
/// The one sanctioned text layout for content painters: document runs with their own font, size and colour,
/// laid out by the call `TextRun::layout` uses.
pub fn layout(&self, text: &DocText<'_>) -> TextLayout {
+10
View File
@@ -286,6 +286,8 @@ pub struct Access {
pub(crate) required: bool,
pub(crate) url: Option<String>,
pub(crate) shortcut: Option<String>,
/// The node lists no shortcut, not even the bound command's.
pub(crate) no_shortcut: bool,
pub(crate) access_key: Option<char>,
pub(crate) relations: Relations,
pub(crate) custom_actions: Vec<(i32, Label)>,
@@ -384,6 +386,14 @@ impl Access {
/// The keyboard shortcut, over the bound command's.
pub fn shortcut(&mut self, text: impl Into<String>) -> &mut Self {
self.shortcut = Some(text.into());
self.no_shortcut = false;
self
}
/// The node lists no keyboard shortcut, though a command bound to the component has a chord.
pub fn no_shortcut(&mut self) -> &mut Self {
self.shortcut = None;
self.no_shortcut = true;
self
}
@@ -272,7 +272,7 @@ pub(crate) fn report(ctx: &Context, own: &Own<'_>) {
spec.has_popup = access.has_popup.or_else(|| popup.map(|popup| popup.kind));
spec.required = access.required;
spec.url = access.url.clone();
spec.shortcut = access.shortcut.clone().or_else(|| own.shortcut.map(str::to_owned));
spec.shortcut = if access.no_shortcut { None } else { access.shortcut.clone().or_else(|| own.shortcut.map(str::to_owned)) };
spec.access_key = access.access_key;
spec.labelled_by = relations.labelled_by.clone();
spec.described_by = relations.described_by.clone();
+5 -1
View File
@@ -97,7 +97,7 @@ impl ButtonOutput {
(true, Some(activation)) => activation.mods,
_ => Mods::NONE,
};
ButtonOutput { response: cx.response.clone(), clicks, mods, hover: Hover::default() }
ButtonOutput { response: cx.response.clone(), clicks, mods, hover: cx.hover() }
}
/// Whether the button was clicked this pass, by pointer or by key, by the framework's click rule. It stands in
@@ -157,6 +157,7 @@ pub struct Button<'a> {
#[prop]
align: HAlign,
/// How the icon and label are laid out: beside each other, or the icon over the label.
#[style_key]
#[prop]
arrangement: Arrangement,
}
@@ -209,6 +210,9 @@ impl Component for Button<'_> {
Some(tint) => ButtonStyle::tinted(cx, tint),
None => ButtonStyle::of(cx),
};
if key.arrangement == Arrangement::Stacked {
style.metrics = face::stacked_metrics(cx, &cx.variant_look());
}
if let Some(least) = key.least_width {
style.metrics.min_size.x = style.metrics.min_size.x.max(least.points(cx.tokens));
}
+239 -6
View File
@@ -1,8 +1,9 @@
//! What a push or toggle button shows: a leading icon (or spinner), a label and a trailing icon, centred in the
//! button unless it aligns them to an edge, and the look parts the buttons share.
use super::GroupLevel;
use crate::contract::{Component, Cx, MeasureCx, PaintUi, Styled as _};
use crate::primitives::{HAlign, IconSpec, TextRun};
use crate::primitives::{HAlign, IconSpec, TextLayout, TextRun};
use crate::style::{FocusLook, GlyphRole, IconLook, StyleColor, StyleCx, SurfaceKind, SurfaceLook, TextLook, TypeRole, UiTokens, VariantParts};
use craft_behavior::{Flow, Insets, Metrics, Proposal};
use craft_theme::{
@@ -16,15 +17,30 @@ use egui::{Rect, Vec2, pos2};
pub(crate) struct FaceLook {
/// The gap between icon and label.
pub gap: f32,
/// The side of a stacked face's leading icon (`stacked_side`).
pub stacked_icon: f32,
/// How far under a stacked face's leading icon the split button's parts meet.
pub divide_gap: f32,
}
impl FaceLook {
/// The face look of the instance's variant: the control's gap.
/// The face look of the instance's variant: the control's gap and the stacked icon side.
pub(crate) fn of(cx: &StyleCx<'_>) -> FaceLook {
FaceLook { gap: cx.control().gap }
let control = cx.control();
FaceLook { gap: control.gap, stacked_icon: stacked_side(cx.tokens, control.icon), divide_gap: cx.tokens.space.gap.tight }
}
}
/// The side of a stacked face's leading icon: the large icon, or the control's own icon when that is larger. The
/// style and the measure both take it from here, so the painted icon is the measured one.
pub(super) fn stacked_side(tokens: &UiTokens, control_icon: f32) -> f32 {
tokens.size.icon.lg.max(control_icon)
}
/// The most characters a stacked label keeps on one line, as the ribbon's large buttons always kept them: a longer
/// label breaks at the space nearest its middle.
const ONE_LINE_CHARS: usize = 10;
/// The label and icon looks of the instance's variant: the variant's text colours at the control's icon side.
pub(super) fn ink(cx: &StyleCx<'_>) -> (TextLook, IconLook) {
let color = cx.variant_look().text;
@@ -32,7 +48,7 @@ pub(super) fn ink(cx: &StyleCx<'_>) -> (TextLook, IconLook) {
}
/// How a button lays out its icon and label.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum Arrangement {
/// The icon beside the label; no label where the `GroupLevel` is `Compact`.
@@ -43,9 +59,9 @@ pub enum Arrangement {
}
/// What a face shows.
#[derive(Clone, Copy)]
pub(crate) struct FaceSpec<'a> {
/// How the icon and label are laid out.
#[allow(dead_code)] // P3(ribbon-w2): rb.R6
pub arrangement: Arrangement,
pub label: &'a str,
pub role: Option<TypeRole>,
@@ -79,6 +95,131 @@ impl FaceSpec<'_> {
}
}
impl<'a> FaceSpec<'a> {
/// Whether the face drops its label under `level`: an inline face beside a leading icon in a compact group. The
/// icon still shows and the label stays the accessible name and the tooltip. A stacked face keeps its label at
/// every level, and a face without an icon keeps it, since nothing else would show.
fn drops_label(&self, level: GroupLevel) -> bool {
self.arrangement == Arrangement::Inline && level == GroupLevel::Compact && self.lead.is_some() && !self.label.is_empty()
}
/// The spec as the face shows it under `level`, with the label dropped where `drops_label` says.
fn at(self, level: GroupLevel) -> FaceSpec<'a> {
if self.drops_label(level) { FaceSpec { label: "", mnemonic: None, ..self } } else { self }
}
/// One line of a stacked label: `text` with its character `at` marked.
fn line(&self, text: &'a str, at: Option<usize>) -> TextRun<'a> {
let run = TextRun::mnemonic(text, at).elide();
match self.role {
Some(role) => run.role(role),
None => run,
}
}
/// The lines of a stacked label: the label whole, or broken at its middle space when it has more than
/// `ONE_LINE_CHARS` characters. The mnemonic stays on the character it marks.
fn lines(&self) -> Vec<TextRun<'a>> {
if self.label.is_empty() {
return Vec::new();
}
let label = self.label;
let whole = self.line(label, self.mnemonic);
let split = middle_space(label).filter(|_| label.chars().count() > ONE_LINE_CHARS).and_then(|at| label.split_at_checked(at));
let Some((first, rest)) = split else { return vec![whole] };
let (first, second) = (first.trim_end(), rest.trim_start());
// The characters before the second line: the first line and the spaces between.
let skipped = label.chars().count() - second.chars().count();
let (on_first, on_second) = match self.mnemonic {
Some(at) if at < first.chars().count() => (Some(at), None),
Some(at) if at >= skipped => (None, Some(at - skipped)),
_ => (None, None),
};
vec![self.line(first, on_first), self.line(second, on_second)]
}
}
/// The byte offset of the space nearest the middle of `label` by characters, where a two-line label breaks.
fn middle_space(label: &str) -> Option<usize> {
let middle = label.chars().count() / 2;
label.char_indices().enumerate().filter(|(_, (_, c))| *c == ' ').min_by_key(|(n, _)| n.abs_diff(middle)).map(|(_, (at, _))| at)
}
/// The width line `last` or not of a stacked face has in `room`: the last line leaves the trailing icon (a menu
/// button's chevron) its gap and `side`, so the chevron follows it.
fn line_room(spec: &FaceSpec<'_>, last: bool, room: f32, side: f32, gap: f32) -> f32 {
if last && spec.trail.is_some() { (room - side - gap).max(0.0) } else { room.max(0.0) }
}
/// Where a stacked face's parts sit.
struct Stack {
/// The content size: the widest row, and the rows' heights with the gap under the icon.
size: Vec2,
lead: Option<Rect>,
/// Each line's text rect.
lines: Vec<Rect>,
trail: Option<Rect>,
}
/// Lays a stacked face out in `area` from its lines' sizes: the leading icon of `lead_side` centred at the top, a gap,
/// then each line centred under it, the trailing icon of `side` after the last line at its reading end (on a row of
/// its own when there is no line). The block is centred vertically; `size` is what `measure` reports.
fn stack(spec: &FaceSpec<'_>, sides: (f32, f32), gap: f32, lines: &[Vec2], area: Rect, rtl: bool) -> Stack {
let (lead_side, side) = sides;
let trail = spec.trail.is_some();
let last = lines.len().checked_sub(1);
let mut rows: Vec<Vec2> = lines
.iter()
.enumerate()
.map(|(i, line)| if trail && Some(i) == last { Vec2::new(line.x + gap + side, line.y.max(side)) } else { *line })
.collect();
if lines.is_empty() && trail {
rows.push(Vec2::splat(side));
}
let icon = if spec.lead.is_some() { lead_side } else { 0.0 };
let under_icon = if spec.lead.is_some() && !rows.is_empty() { gap } else { 0.0 };
let width = rows.iter().map(|row| row.x).fold(icon, f32::max);
let size = Vec2::new(width, icon + under_icon + rows.iter().map(|row| row.y).sum::<f32>());
let middle = area.center().x;
let mut y = area.top() + (area.height() - size.y).max(0.0) / 2.0;
let lead = spec.lead.map(|_| Rect::from_min_size(pos2(middle - lead_side / 2.0, y), Vec2::splat(lead_side)));
y += icon + under_icon;
let mut placed = Stack { size, lead, lines: Vec::new(), trail: None };
for (i, row) in rows.iter().enumerate() {
let band = Rect::from_min_size(pos2(middle - row.x / 2.0, y), *row);
match lines.get(i) {
Some(line) => {
let (text, rest) = Flow::new(band, rtl).take_start(line.x);
placed.lines.push(Rect::from_min_size(pos2(text.min.x, y + (row.y - line.y) / 2.0), *line));
if trail && Some(i) == last {
let (icon, _) = rest.take_start(gap).1.take_start(side);
placed.trail = Some(Rect::from_center_size(icon.center(), Vec2::splat(side)));
}
}
None => placed.trail = Some(band),
}
y += row.y;
}
placed
}
/// The sizes of a stacked face's `lines` as `measure` takes them: at their readable least for `Proposal::Min`, else
/// laid out in `room` (`line_room`).
fn stacked_sizes<C: Component>(cx: &MeasureCx<'_, C>, spec: &FaceSpec<'_>, lines: &[TextRun<'_>], room: f32, side: f32) -> Vec<Vec2> {
let count = lines.len();
lines
.iter()
.enumerate()
.map(|(i, run)| {
if cx.proposal == Proposal::Min {
Vec2::new(cx.least_width(run), cx.layout_at(run, f32::INFINITY).size().y)
} else {
cx.layout_at(run, line_room(spec, i + 1 == count, room, side, cx.gap())).size()
}
})
.collect()
}
/// The metrics of a button with a face: the control's, with the horizontal padding at least the corner radius plus
/// the gap, so the label and icons of a capsule clear its round ends.
pub(super) fn metrics(cx: &StyleCx<'_>, parts: &VariantParts) -> Metrics {
@@ -87,6 +228,24 @@ pub(super) fn metrics(cx: &StyleCx<'_>, parts: &VariantParts) -> Metrics {
Metrics::new().padding(Insets::horizontal(control.pad_x.max(round + control.gap))).min_size(Vec2::new(0.0, control.height)).gap(control.gap)
}
/// The metrics of a stacked face: `metrics`, with the control's gap above and below the stack, so its height is the
/// icon, the label lines and that padding, and never less than the control's height.
pub(super) fn stacked_metrics(cx: &StyleCx<'_>, parts: &VariantParts) -> Metrics {
let gap = cx.control().gap;
let mut metrics = metrics(cx, parts);
metrics.padding.top = gap;
metrics.padding.bottom = gap;
metrics
}
/// `metrics` or `stacked_metrics`, by `arrangement`.
pub(super) fn metrics_of(cx: &StyleCx<'_>, parts: &VariantParts, arrangement: Arrangement) -> Metrics {
match arrangement {
Arrangement::Stacked => stacked_metrics(cx, parts),
_ => metrics(cx, parts),
}
}
/// The surface of a button from its variant: raised unless flat (ghost, or a custom look with no fill or edge at
/// rest), the variant's fill and edge.
pub(super) fn surface(cx: &StyleCx<'_>, parts: &VariantParts) -> SurfaceLook {
@@ -167,8 +326,16 @@ pub(crate) fn focus(cx: &StyleCx<'_>) -> FocusLook {
/// The size of the face: its parts and the gaps between them.
/// The label elides in the room the icons and gaps leave, so a squeezed face is as wide as its room; at its least
/// the label is at its readable least.
/// the label is at its readable least. The group level comes from the env (`GroupLevel` is a style value, so the
/// measurement is keyed on it): a compact group's inline face measures without its label.
pub(crate) fn measure<C: Component>(cx: &MeasureCx<'_, C>, spec: &FaceSpec<'_>) -> Vec2 {
let spec = &spec.at(cx.env.get::<GroupLevel>());
if spec.arrangement == Arrangement::Stacked {
let (side, lead_side) = (cx.icon(), stacked_side(cx.tokens, cx.icon()));
let lines = spec.lines();
let sizes = stacked_sizes(cx, spec, &lines, cx.room.unwrap_or(f32::INFINITY), side);
return stack(spec, (lead_side, side), cx.gap(), &sizes, Rect::ZERO, false).size;
}
let icon = cx.icon();
let fixed = icon * spec.icons() as f32 + cx.gap() * spec.gaps() as f32;
let text = if spec.label.is_empty() {
@@ -246,7 +413,17 @@ fn text_top(draw: &crate::primitives::Draw<'_>, area: Rect, text: &crate::primit
}
/// Paints the face in `area`, placed by `spec.align`: the leading icon at the reading start, the trailing icon at the reading end.
/// A face that drops its label (`FaceSpec::drops_label`) says so in the paint record, so the tooltip shows the label.
pub(crate) fn paint<C: Component>(ui: &PaintUi<'_>, cx: &Cx<'_, C>, ink: (&TextLook, &IconLook), look: &FaceLook, spec: &FaceSpec<'_>, area: Rect) {
let level = cx.env.get::<GroupLevel>();
if spec.drops_label(level) {
ui.draw().drop_label();
}
let spec = &spec.at(level);
if spec.arrangement == Arrangement::Stacked {
paint_stacked(ui, cx, ink, look, spec, area);
return;
}
let (text_look, icon_look) = ink;
let (text_color, icon_color, side) = (cx.resolve(&text_look.color), cx.resolve(&icon_look.color), icon_look.side);
let draw = ui.draw();
@@ -270,6 +447,54 @@ pub(crate) fn paint<C: Component>(ui: &PaintUi<'_>, cx: &Cx<'_, C>, ink: (&TextL
}
}
/// Paints a stacked face in `area` (`stack`): the leading icon over the label's lines, the trailing icon after the
/// last line. A loading face leaves the leading icon's slot (the label's, without an icon) to the spinner.
fn paint_stacked<C: Component>(ui: &PaintUi<'_>, cx: &Cx<'_, C>, ink: (&TextLook, &IconLook), look: &FaceLook, spec: &FaceSpec<'_>, area: Rect) {
let (text_look, icon_look) = ink;
let (text_color, icon_color, side) = (cx.resolve(&text_look.color), cx.resolve(&icon_look.color), icon_look.side);
let draw = ui.draw();
let lines = spec.lines();
let colored: Vec<TextRun<'_>> = lines.into_iter().map(|run| run.color(text_color)).collect();
let count = colored.len();
let layouts: Vec<TextLayout> =
colored.iter().enumerate().map(|(i, run)| draw.layout(run, line_room(spec, i + 1 == count, area.width(), side, look.gap))).collect();
let sizes: Vec<Vec2> = layouts.iter().map(TextLayout::size).collect();
let placed = stack(spec, (look.stacked_icon, side), look.gap, &sizes, area, cx.flow.is_rtl());
if let (Some(lead), Some(slot)) = (spec.lead, placed.lead)
&& !spec.loading
{
draw.icon(slot, &tinted(lead, icon_color));
}
if !(spec.loading && spec.lead.is_none()) {
for (text, slot) in layouts.iter().zip(&placed.lines) {
draw.galley(slot.min, text);
}
}
if let (Some(trail), Some(slot)) = (spec.trail, placed.trail) {
draw.icon(slot, &tinted(trail, icon_color));
}
}
/// A stacked face placed in `area` as `paint_stacked` places it, its lines laid out for `area`'s width.
fn stacked_in<C: Component>(cx: &MeasureCx<'_, C>, spec: &FaceSpec<'_>, look: &FaceLook, side: f32, area: Rect, rtl: bool) -> Stack {
let lines = spec.lines();
let count = lines.len();
let sizes: Vec<Vec2> =
lines.iter().enumerate().map(|(i, run)| cx.layout_at(run, line_room(spec, i + 1 == count, area.width(), side, look.gap)).size()).collect();
stack(spec, (look.stacked_icon, side), look.gap, &sizes, area, rtl)
}
/// Where a stacked split button's parts meet in `area`: halfway down the gap under the face's leading icon, so the
/// icon is the main part and the label and its chevron are the arrow part. Without an icon the parts meet at the
/// content's top: the whole face is the arrow part.
pub(super) fn stacked_divide<C: Component>(cx: &MeasureCx<'_, C>, spec: &FaceSpec<'_>, look: &FaceLook, side: f32, area: Rect) -> f32 {
let spec = &spec.at(cx.env.get::<GroupLevel>());
match stacked_in(cx, spec, look, side, area, false).lead {
Some(lead) => lead.bottom() + look.divide_gap,
None => area.top(),
}
}
/// Where the busy spinner of a loading face goes: the square of the icon side in the leading icon's slot, or in the
/// label's slot when there is no leading icon. `None` when the face has neither.
pub(super) fn spinner_rect<C: Component>(
@@ -280,6 +505,14 @@ pub(super) fn spinner_rect<C: Component>(
area: Rect,
rtl: bool,
) -> Option<Rect> {
let spec = &spec.at(cx.env.get::<GroupLevel>());
if spec.arrangement == Arrangement::Stacked {
let placed = stacked_in(cx, spec, look, side, area, rtl);
return match placed.lead {
Some(lead) => Some(lead),
None => placed.lines.first().map(|line| Rect::from_center_size(line.center(), Vec2::splat(side))),
};
}
let fixed = side * spec.icons() as f32 + look.gap * spec.gaps() as f32;
let text_width = if spec.label.is_empty() { 0.0 } else { cx.layout_at(&spec.run(), (area.width() - fixed).max(0.0)).size().x };
let slots = slots(spec, side, look.gap, text_width, area, rtl);
+84 -35
View File
@@ -3,7 +3,7 @@
use super::face::{self, Arrangement, FaceLook, FaceSpec};
use crate::contract::{
Access, BodyCx, Common, Component, Cx, Entry, Focus as _, Hover, MeasureCx, Name, Outcome, OverlayUi, Overlays as _, PaintUi, PartsCx,
Props as _, Role, ShowContainer as _, Styled as _, WordSetCx as _,
Pointer as _, Props, Role, ShowContainer as _, Styled as _, WordSetCx as _,
};
use crate::menu::{self, Menu};
use crate::primitives::{IconSpec, PaintShape, RuleKind};
@@ -96,7 +96,9 @@ pub struct SplitButton<'a, T: Value + 'static> {
/// A leading icon on the main part.
#[prop(into)]
icon: Option<IconSpec<'a>>,
/// How the icon and label are laid out: beside each other, or the icon over the label.
/// How the icon and label are laid out: beside each other with the arrow part at the end, or the icon over the
/// label with the arrow part (the label and its chevron) under the icon.
#[style_key]
#[prop]
arrangement: Arrangement,
chosen: Option<T>,
@@ -105,36 +107,33 @@ pub struct SplitButton<'a, T: Value + 'static> {
impl<'a, T: Value + 'static> SplitButton<'a, T> {
/// A split button showing `label` whose arrow opens `entries`.
pub fn new(label: impl Into<Label>, entries: &'a [Entry<T>]) -> Self {
SplitButton {
common: Common::new(),
menu: SplitMenu::Entries(entries),
arrow_label: None,
icon: None,
arrangement: Arrangement::default(),
chosen: None,
}
.label(label)
SplitButton::with_menu(SplitMenu::Entries(entries)).label(label)
}
/// A split button showing `label` whose arrow opens a menu with `body` as its content.
/// A split button showing `label` whose arrow opens a menu with `body` as its content. A body reports no
/// `chosen` entry: its rows run their own commands.
pub fn body(label: impl Into<Label>, body: impl FnMut(&mut Ui, &mut BodyCx<'_>) + 'a) -> Self {
let _ = (label.into(), body);
todo!("rb.R7")
SplitButton::with_menu(SplitMenu::Body(Box::new(body))).label(label)
}
/// A split button bound to `command`: its main part fires the command, its arrow opens `menu`.
/// A split button bound to `command`: its label, enabled state and main part follow the command, which a click
/// on the main part fires; its arrow opens `menu`.
pub fn command(command: impl Into<CommandRef>, menu: SplitMenu<'a, T>) -> Self {
let _ = (command.into(), menu);
todo!("rb.R7")
<SplitButton<'a, T> as Props>::command(SplitButton::with_menu(menu).label(Label::Empty), command)
}
fn spec<'s>(&'s self, label: &'s str) -> FaceSpec<'s> {
fn with_menu(menu: SplitMenu<'a, T>) -> Self {
SplitButton { common: Common::new(), menu, arrow_label: None, icon: None, arrangement: Arrangement::default(), chosen: None }
}
/// The face: a stacked face shows the chevron after its label, so the arrow part holds both.
fn spec<'s>(&'s self, label: &'s str, chevron: &'s IconSpec<'s>) -> FaceSpec<'s> {
FaceSpec {
arrangement: self.arrangement,
label,
role: None,
lead: self.icon.as_ref(),
trail: None,
trail: (self.arrangement == Arrangement::Stacked).then_some(chevron),
loading: false,
mnemonic: None,
align: crate::primitives::HAlign::Center,
@@ -142,15 +141,20 @@ impl<'a, T: Value + 'static> SplitButton<'a, T> {
}
}
/// The chevron the arrow part shows.
fn chevron() -> IconSpec<'static> {
crate::controls::disclosure::DisclosureGlyph::menu_button()
}
impl<T: Value + 'static> Component for SplitButton<'_, T> {
const ROLE: Role = Role::BUTTON;
const KEYS: crate::runtime::focus::KeyUse = crate::runtime::focus::KeyUse::of(crate::contract::Input::Pointer).with_moves();
type Style = SplitButtonStyle;
type Output = SplitOutput<T>;
fn style(cx: &StyleCx<'_>, _: SplitButtonStyleKey<T>) -> SplitButtonStyle {
fn style(cx: &StyleCx<'_>, key: SplitButtonStyleKey<T>) -> SplitButtonStyle {
let parts = cx.variant_look();
let metrics = face::metrics(cx, &parts);
let metrics = face::metrics_of(cx, &parts, key.arrangement);
let mut surface = face::surface(cx, &parts);
let (fill, clear) = (parts.fill.off, cx.color(craft_theme::Rgba::TRANSPARENT));
surface.fill = Stateful::new(fill.rest).off(States::new(fill.rest, fill.rest, fill.rest, fill.disabled));
@@ -173,10 +177,15 @@ impl<T: Value + 'static> Component for SplitButton<'_, T> {
}
}
/// The face and the arrow part, which sits in the end padding.
/// Inline: the face and the arrow part, which sits in the end padding. Stacked: the face, whose chevron follows
/// the label inside the arrow part.
fn measure(&mut self, cx: &MeasureCx<'_, Self>) -> Vec2 {
let face = face::measure(cx, &self.spec(cx.resolved.label));
Vec2::new(face.x + cx.icon(), face.y)
let chevron = chevron();
let face = face::measure(cx, &self.spec(cx.resolved.label, &chevron));
match self.arrangement {
Arrangement::Stacked => face,
_ => Vec2::new(face.x + cx.icon(), face.y),
}
}
fn sense(&self) -> Sense {
@@ -184,7 +193,15 @@ impl<T: Value + 'static> Component for SplitButton<'_, T> {
}
fn parts(&mut self, rect: Rect, cx: &mut PartsCx<'_, Self>) {
let (arrow, _) = Flow::new(rect, cx.flow.is_rtl()).take_end(cx.icon());
let arrow = match self.arrangement {
Arrangement::Stacked => {
let chevron = chevron();
let (look, side) = (&cx.style.face, cx.style.icon.side);
let y = face::stacked_divide(cx, &self.spec(cx.resolved.label, &chevron), look, side, cx.content_rect);
Rect::from_min_max(egui::pos2(rect.left(), y.clamp(rect.top(), rect.bottom())), rect.max)
}
_ => Flow::new(rect, cx.flow.is_rtl()).take_end(cx.icon()).0,
};
let part = cx
.part(ARROW, arrow)
.sense(Sense::CLICK)
@@ -210,15 +227,21 @@ impl<T: Value + 'static> Component for SplitButton<'_, T> {
}
}
/// The menu: one `MenuItem` row per entry, a rule for a separator. Running a row reports its value and closes the
/// menu; a disabled entry takes neither focus-run nor a pick.
/// The menu: one `MenuItem` row per entry, a rule for a separator, or the caller's body. Running an entry's row
/// reports its value and closes the menu; a disabled entry takes neither focus-run nor a pick. A body's rows run
/// their own commands, which close the layer as any row's run does.
fn overlay(&mut self, ui: &mut OverlayUi<'_>, cx: &mut Cx<'_, Self>) {
let popup = cx.popup("menu");
let entries = match &self.menu {
SplitMenu::Entries(entries) => *entries,
SplitMenu::Body(_) => todo!("rb.R7"),
};
let name = cx.label();
let entries = match &mut self.menu {
SplitMenu::Entries(entries) => *entries,
SplitMenu::Body(body) => {
ui.show(popup, menu::layer(false), |ui, _| {
let _ = Menu::inline(name.clone()).show(ui, |ui, cx| body(ui, cx));
});
return;
}
};
let ran = ui.show(popup, menu::layer(false), |ui, _| {
Menu::inline(name.clone()).values().show(ui, |ui, _| menu::entry_rows(ui, entries)).inner.flatten()
});
@@ -237,6 +260,10 @@ impl<T: Value + 'static> Component for SplitButton<'_, T> {
}
fn paint(&mut self, ui: &mut PaintUi<'_>, cx: &Cx<'_, Self>) {
if self.arrangement == Arrangement::Stacked {
self.paint_stacked(ui, cx);
return;
}
let (rtl, direction) = (cx.flow.is_rtl(), cx.env.direction());
let (arrow, main) = Flow::new(cx.rect, rtl).take_end(cx.style.icon.side);
let main = main.rect();
@@ -245,11 +272,11 @@ impl<T: Value + 'static> Component for SplitButton<'_, T> {
draw.fill(&PaintShape::Rect(main, Corners::Start.apply(cx.style.radius, direction)), main_fill);
draw.fill(&PaintShape::Rect(arrow, Corners::End.apply(cx.style.radius, direction)), cx.resolve_part(ARROW, &cx.style.part_fill));
let area = Flow::new(main, rtl).inset(cx.style.metrics.padding);
face::paint(ui, cx, (&cx.style.text, &cx.style.icon), &cx.style.face, &self.spec(cx.resolved.label), area);
let chevron = chevron().color(cx.resolve(&cx.style.chevron));
face::paint(ui, cx, (&cx.style.text, &cx.style.icon), &cx.style.face, &self.spec(cx.resolved.label, &chevron), area);
let draw = ui.draw();
let side = cx.style.icon.side;
let chevron = Rect::from_center_size(arrow.center(), Vec2::splat(side));
draw.icon(chevron, &crate::controls::disclosure::DisclosureGlyph::menu_button().color(cx.resolve(&cx.style.chevron)));
draw.icon(Rect::from_center_size(arrow.center(), Vec2::splat(side)), &chevron);
let x = if rtl { arrow.right() } else { arrow.left() };
let inset = cx.style.divider_inset;
let divider = RuleLook { color: cx.resolve(&cx.style.divider).egui(), width: cx.style.divider_width };
@@ -257,6 +284,28 @@ impl<T: Value + 'static> Component for SplitButton<'_, T> {
}
fn finish(self, cx: Cx<'_, Self>) -> SplitOutput<T> {
SplitOutput { response: cx.response.clone(), chosen: self.chosen, hover: Hover::default() }
SplitOutput { response: cx.response.clone(), chosen: self.chosen, hover: cx.hover() }
}
}
impl<T: Value + 'static> SplitButton<'_, T> {
/// Paints a stacked split button: the main part (the icon) over the arrow part (the label and its chevron), each
/// with its own state fill, and the divider across the button where they meet. The arrow part is the one `parts`
/// declared; a face, which declares none, shows the whole button as the arrow part.
fn paint_stacked(&self, ui: &mut PaintUi<'_>, cx: &Cx<'_, Self>) {
let rect = cx.rect;
let arrow = cx.part_if_declared(ARROW).map_or(rect, |part| part.rect);
let main = Rect::from_min_max(rect.min, Pos2::new(rect.right(), arrow.top().max(rect.top())));
let radius = cx.style.radius;
let draw = ui.draw();
draw.fill(&PaintShape::Rect(main, CornerRadius { sw: 0, se: 0, ..radius }), cx.root_state().resolve(&cx.style.part_fill));
draw.fill(&PaintShape::Rect(arrow, CornerRadius { nw: 0, ne: 0, ..radius }), cx.resolve_part(ARROW, &cx.style.part_fill));
let chevron = chevron().color(cx.resolve(&cx.style.chevron));
face::paint(ui, cx, (&cx.style.text, &cx.style.icon), &cx.style.face, &self.spec(cx.resolved.label, &chevron), cx.content_rect);
if main.height() > 0.0 {
let inset = cx.style.divider_inset;
let divider = RuleLook { color: cx.resolve(&cx.style.divider).egui(), width: cx.style.divider_width };
ui.draw().rule_with(&divider, Pos2::new(rect.left() + inset, arrow.top()), Pos2::new(rect.right() - inset, arrow.top()));
}
}
}
+148 -4
View File
@@ -1,11 +1,13 @@
//! Stories of the buttons.
use super::{Button, IconButton, Link, SplitButton, ToggleButton};
use crate::contract::{Bind, Entry, Props as _, Show as _, ShowContainer as _, Validity};
use super::{Arrangement, Button, GroupLevel, IconButton, Link, SplitButton, SplitMenu, ToggleButton};
use crate::contract::{Bind, BodyCx, Entry, Props as _, Show as _, ShowContainer as _, Validity};
use crate::display::{Shade, Text};
use crate::layout_components::{Grid, Row};
use crate::primitives::IconSpec;
use crate::runtime::env::Message;
use crate::menu::MenuItem;
use crate::primitives::{AppIcons, IconMark, IconSpec, register_app_icons};
use crate::runtime::commands::EditCommands;
use crate::runtime::env::{Message, with_env};
use crate::style::DataColor;
use crate::testing::{Drive, Fixture, StoryData, StoryOutput, story};
use craft_behavior::{ColumnWidth, IconId, Mixed, Proposal};
@@ -107,6 +109,78 @@ fn icon_button_badge(ui: &mut Ui, _: &mut StoryData) -> StoryOutput {
shown.into()
}
/// Icon buttons with a data-colour bar across the bottom of the icon: the default thickness and a weighted one (a
/// pen's width), enabled and then disabled.
#[story(IconButton<'static>, covers = [], drive = Drive::Never, title = "Bar mark")]
fn icon_button_bar_mark(ui: &mut Ui, _: &mut StoryData) -> StoryOutput {
let color = DataColor::new(Color32::from_rgb(230, 180, 30));
let marks = [("Highlight", IconMark::bar(color)), ("Pen", IconMark::weighted_bar(color, 4.0))];
let shown = Row::new().show(ui, |ui, _| {
for enabled in [true, false] {
for (name, mark) in marks {
IconButton::new(IconSpec::svg(IconId::new("eyedropper")).with_mark(mark)).label(name).enabled(enabled).id_salt((name, enabled)).show(ui);
}
}
});
shown.into()
}
/// A pen drawn in the icon ink, with its tip line in the accent ink (`class="accent"`) and a cap dot in its own colour
/// (`class="fixed"`).
const TWO_INK_PEN: &[u8] = br##"<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><path d="M5 15 L14 6 L18 10 L9 19 L5 19 Z" fill="black"/><rect class="accent" x="3" y="21" width="18" height="2" fill="black"/><circle class="fixed" cx="18" cy="5" r="2" fill="#d04848"/></svg>"##;
/// The stories' own app icon set, under a name no other story or app uses.
static STORY_ICONS: AppIcons = AppIcons::new("ui-widgets-stories", None, &[("story_two_ink_pen", TWO_INK_PEN)]);
/// An app icon in two inks and a fixed colour, enabled and then disabled: a disabled button takes the disabled ink in
/// every layer.
#[story(IconButton<'static>, covers = [], drive = Drive::Never, title = "Two-ink icon")]
fn icon_button_two_ink(ui: &mut Ui, _: &mut StoryData) -> StoryOutput {
// A second registration of the same set is a no-op, so the story registers it on every run.
register_app_icons(&STORY_ICONS);
let shown = Row::new().show(ui, |ui, _| {
for enabled in [true, false] {
IconButton::new(IconId::new("story_two_ink_pen")).label("Pen").enabled(enabled).id_salt(enabled).show(ui);
}
});
shown.into()
}
/// Stacked buttons, the icon over the label, with a one-line and a two-line label at each size.
#[story(Button<'static>, covers = [], drive = Drive::Never, title = "Stacked")]
fn button_stacked(ui: &mut Ui, _: &mut StoryData) -> StoryOutput {
let shown = Row::new().show(ui, |ui, _| {
for (size_name, size) in SIZES {
for label in ["Paste", "Insert page break"] {
Button::new(label).icon(IconId::new("copy")).arrangement(Arrangement::Stacked).size(size).id_salt((size_name, label)).show(ui);
}
}
});
shown.into()
}
/// The same inline buttons at full size and inside a compact group, where they drop their labels and keep them as
/// their names and tooltips.
#[story(Button<'static>, covers = [], drive = Drive::Never, title = "Compact in a group")]
fn button_compact_in_group(ui: &mut Ui, _: &mut StoryData) -> StoryOutput {
let entries = presets();
let shown = Row::new().show(ui, |ui, _| {
Button::new("Save").icon(IconId::new("save")).id_salt("full").show(ui);
SplitButton::new("Trace", &entries).icon(IconId::new("image")).id_salt("full split").show(ui);
with_env(
ui,
|overrides| {
overrides.values.set(GroupLevel::Compact);
},
|ui| {
Button::new("Save").icon(IconId::new("save")).id_salt("compact").show(ui);
SplitButton::new("Trace", &entries).icon(IconId::new("image")).id_salt("compact split").show(ui);
},
);
});
shown.into()
}
/// One toggle off and one on with an icon, as the gallery card shows them.
#[story(ToggleButton<'static>, covers = [], drive = Drive::Never)]
fn toggle_button_on(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
@@ -125,6 +199,40 @@ fn toggle_button(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
ToggleButton::new(label, Bind::bound(data.value("on", false))).icon(IconId::new("eye")).size(size).enabled(!disabled).show(ui).into()
}
/// A stacked toggle, off and on.
#[story(ToggleButton<'static>, covers = [], drive = Drive::Never, title = "Stacked")]
fn toggle_button_stacked(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
let shown = Row::new().show(ui, |ui, _| {
ToggleButton::new("Gridlines", Bind::bound(data.value("grid", false)))
.icon(IconId::new("eye"))
.arrangement(Arrangement::Stacked)
.id_salt("grid")
.show(ui);
ToggleButton::new("Show rulers", Bind::bound(data.value("rulers", true)))
.icon(IconId::new("eye"))
.arrangement(Arrangement::Stacked)
.id_salt("rulers")
.show(ui);
});
shown.into()
}
/// Rests the pointer on the toggle, clicks it and stays: its output reports the click while the pointer stays.
fn click_and_stay(fixture: &mut Fixture) {
if let Some(toggle) = fixture.by_label("Snap to grid") {
fixture.click(&toggle);
}
fixture.idle(2);
}
/// A toggle clicked with the pointer still over it: the output's `hover` is over and clicked until the pointer leaves.
#[story(ToggleButton<'static>, covers = [], drive = Drive::Custom(click_and_stay), title = "Clicked under the pointer")]
fn toggle_button_clicked_under_pointer(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
let shown = ToggleButton::new("Snap to grid", Bind::bound(data.value("snap_hover", false))).icon(IconId::new("eye")).show(ui);
*data.value("clicked_over", false) = shown.hover.clicked;
shown.into()
}
#[story(ToggleButton<'static>, covers = [Mixed], drive = Drive::Never)]
fn toggle_button_mixed(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
ToggleButton::new("Snap to grid", Bind::bound_mixed(data.value("mixed", Mixed::Mixed))).show(ui).into()
@@ -162,6 +270,42 @@ fn split_button_open(ui: &mut Ui, _: &mut StoryData) -> StoryOutput {
SplitButton::new("Trace", &entries).icon(IconId::new("image")).arrow_label("Tracing presets").show(ui).into()
}
/// A stacked split button: the icon is the main part, the label and its chevron the arrow part under it.
#[story(SplitButton<'static, u8>, covers = [], drive = Drive::Never, title = "Stacked")]
fn split_button_stacked(ui: &mut Ui, _: &mut StoryData) -> StoryOutput {
let entries = presets();
SplitButton::new("Trace", &entries)
.icon(IconId::new("image"))
.arrow_label("Tracing presets")
.arrangement(Arrangement::Stacked)
.show(ui)
.into()
}
/// The rows a split button's body shows.
fn paste_rows(ui: &mut Ui, _: &mut BodyCx<'_>) {
MenuItem::new("Keep source formatting").show(ui);
MenuItem::new("Merge formatting").show(ui);
MenuItem::new("Keep text only").show(ui);
}
/// A split button whose arrow opens a menu the caller draws, open.
#[story(SplitButton<'static, u8>, covers = [], drive = Drive::Custom(open_menu), title = "Body")]
fn split_button_body(ui: &mut Ui, _: &mut StoryData) -> StoryOutput {
SplitButton::<u8>::body("Paste", paste_rows).icon(IconId::new("copy")).show(ui).into()
}
/// A split button whose main part is the Paste command, stacked as a ribbon shows it, its menu the paste options.
#[story(SplitButton<'static, u8>, covers = [], drive = Drive::Never, title = "Command")]
fn split_button_command(ui: &mut Ui, _: &mut StoryData) -> StoryOutput {
SplitButton::<u8>::command(EditCommands::Paste, SplitMenu::Body(Box::new(paste_rows)))
.icon(IconId::new("copy"))
.arrow_label("Paste options")
.arrangement(Arrangement::Stacked)
.show(ui)
.into()
}
#[story(Link, covers = [Default])]
fn link(ui: &mut Ui, _: &mut StoryData) -> StoryOutput {
Link::new("Show all your shortcuts").url("https://example.com/shortcuts").show(ui).into()
@@ -70,6 +70,7 @@ pub struct ToggleButton<'a> {
#[prop]
spoken: Option<Label>,
/// How the icon and label are laid out: beside each other, or the icon over the label.
#[style_key]
#[prop]
arrangement: Arrangement,
}
@@ -152,7 +153,7 @@ impl Component for ToggleButton<'_> {
(face.surface, face.metrics)
} else {
icon.color = icon.color.on(on.text.off);
(face::on_surface(cx, &off, &on), face::metrics(cx, &off))
(face::on_surface(cx, &off, &on), face::metrics_of(cx, &off, key.arrangement))
};
// A mixed value shows the off look, as Photoshop's style toggles do; the access state tells it from off.
surface.fill = surface.fill.when(Flags::MIXED, off.fill.off.rest);
+1 -1
View File
@@ -185,7 +185,7 @@ impl Segment {
fn spec<'s>(&'s self, label: &'s str) -> FaceSpec<'s> {
FaceSpec {
arrangement: crate::buttons::Arrangement::Inline, // P3(ribbon-w2): rb.R6
arrangement: crate::buttons::Arrangement::Inline,
label: if self.icon.is_some() { "" } else { label },
role: None,
lead: self.icon.as_ref(),
+2 -2
View File
@@ -115,7 +115,7 @@ impl Component for TitleFace {
face::measure(
cx,
&FaceSpec {
arrangement: Arrangement::Inline,
arrangement: crate::buttons::Arrangement::Inline,
label: cx.resolved.label,
role: None,
lead: None,
@@ -137,7 +137,7 @@ impl Component for TitleFace {
fn paint(&mut self, ui: &mut PaintUi<'_>, cx: &Cx<'_, Self>) {
let spec = FaceSpec {
arrangement: Arrangement::Inline,
arrangement: crate::buttons::Arrangement::Inline,
label: cx.resolved.label,
role: None,
lead: None,
+68 -15
View File
@@ -71,6 +71,8 @@ pub struct MenuItemStyle {
detail: TextLook,
/// The least space between the label and the shortcut: `space.gap.section`.
shortcut_gap: f32,
/// The least width of a row's sample: `size.thumb.lg`.
sample: f32,
/// The gap between a submenu and its parent menu: `space.gap.tight`.
submenu_gap: f32,
}
@@ -125,16 +127,36 @@ struct Columns {
mark: f32,
icon: f32,
trail: f32,
/// The least width of the sample slot; zero for a row without a sample.
sample: f32,
}
/// Where the parts of a row's label line lie.
struct Placed {
mark: Rect,
icon: Rect,
/// The room of the label and the sample, between the icon column and the shortcut.
label: Rect,
trail: Rect,
}
/// The label's and the sample's rects in the room `label` a row leaves them. The sample takes what the label's own
/// width `want` and a `gap` leave, at least `least`, at the reading end beside the shortcut, so it mirrors under
/// right-to-left; a `sample_only` row's sample takes the whole room and the label none. No sample (`least` zero):
/// the label keeps the room.
fn split_sample(label: Rect, rtl: bool, want: f32, least: f32, gap: f32, only: bool) -> (Rect, Option<Rect>) {
if least <= 0.0 {
return (label, None);
}
let flow = Flow::new(label, rtl);
if only {
return (flow.take_start(0.0).0, Some(label));
}
let width = (label.width() - want - gap).max(least).min(label.width());
let (sample, rest) = flow.take_end(width);
(rest.take_end(gap).1.rect(), Some(sample))
}
/// The label line of a row's content `area`: all of it but the detail line of height `detail` under it.
fn label_line(area: Rect, detail: f32) -> Rect {
Rect::from_min_max(area.min, pos2(area.max.x, (area.max.y - detail).max(area.min.y)))
@@ -303,11 +325,16 @@ impl<'a> MenuItem<'a> {
}
}
/// The shortcut as the `Kbd` that shows it.
/// The shortcut as the `Kbd` that shows it: the caller's text, even on a row whose command has a chord; nothing
/// when hidden; else the bound command's chord, and nothing for a row with no command or no chord.
fn keys(&self, command: Option<&ResolvedCommand>) -> Option<Kbd> {
match (&self.command_ref, command) {
(Some(reference), Some(resolved)) if resolved.chord.is_some() => Some(Kbd::command(reference.clone())),
_ => self.shortcut_text().cloned().map(Kbd::new), // P3(ribbon-w2): rb.R22
match &self.shortcut {
MenuShortcut::Text(text) => Some(Kbd::new(text.clone())),
MenuShortcut::Hidden => None,
MenuShortcut::Command => match (&self.command_ref, command) {
(Some(reference), Some(resolved)) if resolved.chord.is_some() => Some(Kbd::command(reference.clone())),
_ => None,
},
}
}
@@ -328,9 +355,14 @@ impl<'a> MenuItem<'a> {
/// Shows no shortcut on the row, whatever the bound command's chord is.
#[must_use]
pub fn hide_shortcut(self) -> Self {
let _ = self;
todo!("rb.R22")
pub fn hide_shortcut(mut self) -> Self {
self.shortcut = MenuShortcut::Hidden;
self
}
/// Whether the sample takes the label's place: a `sample_only` row that has a sample.
fn sample_replaces_label(&self) -> bool {
self.sample_only && self.sample.is_some()
}
/// The parts of the label line `line`.
@@ -363,7 +395,12 @@ impl<'a> MenuItem<'a> {
let command = cx.command();
let (mark, icon) = self.lead_columns(cx.ui.ctx(), side, cx.gap(), command, level);
let trail = if self.submenu { side } else { self.keys(command).map_or(0.0, |keys| cx.face(keys).x) };
Columns { mark, icon, trail }
Columns { mark, icon, trail, sample: self.sample_least(cx.style) }
}
/// The least width of the row's sample slot; zero without a sample.
fn sample_least(&self, style: &MenuItemStyle) -> f32 {
if self.sample.is_some() { style.sample } else { 0.0 }
}
/// The size of the detail line; zero without one.
@@ -408,6 +445,7 @@ impl Component for MenuItem<'_> {
icon: IconLook::new(control.icon, ink(normal)),
detail: TextLook::new(TypeRole::Caption, ink(muted)),
shortcut_gap: tokens.space.gap.section,
sample: tokens.size.thumb.lg,
submenu_gap: tokens.space.gap.tight,
}
}
@@ -425,7 +463,9 @@ impl Component for MenuItem<'_> {
let label = if text.is_empty() { Vec2::ZERO } else { cx.layout_at(&run, f32::INFINITY).size() };
let gap = cx.gap();
let step = |width: f32, gap: f32| if width > 0.0 { width + gap } else { 0.0 };
let rest = label.x.max(detail.x) + step(columns.trail, cx.style.shortcut_gap.max(gap));
// The sample follows the label at its least width, or stands in its place.
let shown = if self.sample_replaces_label() { columns.sample } else { label.x + step(columns.sample, gap) };
let rest = shown.max(detail.x) + step(columns.trail, cx.style.shortcut_gap.max(gap));
let padding = cx.style.metrics.padding;
// A row measured before the level's widest mark or icon read narrower columns: the body's group adds the
// widest columns to what the rows reach past them.
@@ -575,7 +615,7 @@ impl Component for MenuItem<'_> {
detail.as_ref().map(|detail| TextRun::new(detail.as_str()).role(cx.style.detail.role).color(cx.resolve(&cx.style.detail.color)));
let detail_height = detail_run.as_ref().map_or(0.0, |run| draw.layout(run, f32::INFINITY).size().y);
let trail = if self.submenu { side } else { cx.part_if_declared(SHORTCUT).map_or(0.0, |part| part.rect.width()) };
let columns = Columns { mark: mark_column, icon: icon_column, trail };
let columns = Columns { mark: mark_column, icon: icon_column, trail, sample: self.sample_least(cx.style) };
let line = label_line(cx.content_rect, detail_height);
let placed = self.place(&columns, line, rtl, cx.style.shortcut_gap.max(gap));
let ink = cx.resolve(&cx.style.icon.color);
@@ -598,11 +638,22 @@ impl Component for MenuItem<'_> {
let mnemonic = if level.keyboard() || cx.modifiers().alt { level.mnemonic_of(cx.id).map(|(_, at)| at) } else { None };
let look = self.label_look(cx.style);
let run = TextRun::mnemonic(text.as_str(), mnemonic).elide().role(look.role).color(cx.resolve(&look.color));
let layout = draw.layout(&run, placed.label.width());
let size = layout.size();
let x = if rtl { placed.label.max.x - size.x } else { placed.label.min.x };
let y = placed.label.center().y - size.y / 2.0;
draw.galley(pos2(x, y), &layout);
let only = self.sample_replaces_label();
let want = if only { 0.0 } else { draw.layout(&run, f32::INFINITY).size().x };
let (label_room, sample_slot) = split_sample(placed.label, rtl, want, columns.sample, gap, only);
// A sample-only row draws no label: the label stays its accessible name and its mnemonic source.
if !only {
let layout = draw.layout(&run, label_room.width());
let size = layout.size();
let x = if rtl { label_room.max.x - size.x } else { label_room.min.x };
let y = label_room.center().y - size.y / 2.0;
draw.galley(pos2(x, y), &layout);
}
if let (Some(slot), Some(paint)) = (sample_slot, self.sample.take()) {
// The sample paints through the content painter, clipped to its slot; its data paths fade while the row
// is disabled (the `States` look).
ui.content_painter(cx).clipped(slot, |painter| paint(painter, slot));
}
// The detail starts where the label starts, under the label line.
if let Some(run) = &detail_run {
let layout = draw.layout(&run.clone().elide(), placed.label.width());
@@ -644,6 +695,8 @@ impl Component for MenuItem<'_> {
}
if let Some(text) = self.shortcut_text() {
access.shortcut(cx.env.resolve(text).as_str().to_owned());
} else if self.shortcut == MenuShortcut::Hidden {
access.no_shortcut();
}
if cx.resolved.tooltip.is_none()
&& let Some(detail) = &self.detail
+86 -4
View File
@@ -1,14 +1,68 @@
//! Stories of the menu rows and the menu.
use super::{Menu, MenuItem};
use crate::buttons::Button;
use crate::buttons::{Button, IconButton};
use crate::contract::{Bind, Entry, Props as _, Show as _, ShowContainer as _, Trigger};
use crate::display::Divider;
use crate::layout_components::Stack;
use crate::layout_components::{Row, Stack};
use crate::primitives::ContentPainterCx;
use crate::runtime::commands::EditCommands;
use crate::style::DataColor;
use crate::testing::{Drive, StoryData, StoryOutput, story};
use craft_behavior::IconId;
use craft_behavior::{Axis, IconId};
use craft_theme::ControlSize;
use egui::Ui;
use egui::{Color32, CornerRadius, Rect, Ui};
/// A sample that paints a colour ramp from `from` to `to` across its slot, as a style or colour preset row previews
/// its look.
fn ramp_sample(from: Color32, to: Color32) -> impl FnOnce(&ContentPainterCx<'_>, Rect) {
move |cx, rect| {
cx.ramp(rect, CornerRadius::ZERO, &[(0.0, DataColor::new(from)), (1.0, DataColor::new(to))], Axis::X);
}
}
const WARM: (Color32, Color32) = (Color32::from_rgb(250, 200, 60), Color32::from_rgb(220, 60, 40));
const COOL: (Color32, Color32) = (Color32::from_rgb(80, 200, 220), Color32::from_rgb(40, 60, 200));
/// Rows with a sample between the label and the shortcut; the disabled row fades its sample.
#[story(MenuItem<'static>, covers = [], drive = Drive::Never)]
fn menu_item_samples(ui: &mut Ui, _: &mut StoryData) -> StoryOutput {
Stack::new()
.show(ui, |ui, _| {
MenuItem::new("Sunset").sample(ramp_sample(WARM.0, WARM.1)).shortcut("Ctrl+Alt+1").show(ui);
MenuItem::new("Ocean").sample(ramp_sample(COOL.0, COOL.1)).shortcut("Ctrl+Alt+2").show(ui);
MenuItem::new("Ember").sample(ramp_sample(WARM.1, WARM.0)).enabled(false).show(ui)
})
.inner
.map(StoryOutput::from)
.unwrap_or_default()
}
/// Rows whose sample stands in for the label; the label stays each row's name.
#[story(MenuItem<'static>, covers = [], drive = Drive::Never)]
fn menu_item_sample_only(ui: &mut Ui, _: &mut StoryData) -> StoryOutput {
Stack::new()
.show(ui, |ui, _| {
MenuItem::new("Warm").sample(ramp_sample(WARM.0, WARM.1)).sample_only().show(ui);
MenuItem::new("Cool").sample(ramp_sample(COOL.0, COOL.1)).sample_only().show(ui)
})
.inner
.map(StoryOutput::from)
.unwrap_or_default()
}
/// A command row that hides its command's chord, under one that shows it.
#[story(MenuItem<'static>, covers = [], drive = Drive::Never)]
fn menu_item_hidden_shortcut(ui: &mut Ui, _: &mut StoryData) -> StoryOutput {
Stack::new()
.show(ui, |ui, _| {
MenuItem::command(EditCommands::Paste).show(ui);
MenuItem::command(EditCommands::Copy).hide_shortcut().show(ui)
})
.inner
.map(StoryOutput::from)
.unwrap_or_default()
}
#[story(MenuItem<'static>, covers = [Default], drive = Drive::Activate)]
fn menu_item(ui: &mut Ui, _: &mut StoryData) -> StoryOutput {
@@ -157,6 +211,34 @@ fn menu_of_values(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
})
}
/// A menu opened from a button with a formatting bar above it in its own layer, its list open.
#[story(Menu<'static>, covers = [], drive = Drive::Never)]
fn menu_with_companion(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
in_row(ui, |ui| {
let opener = Button::new("Format").show(ui);
let mut bar = |ui: &mut Ui| {
Row::new().show(ui, |ui, _| {
for (icon, label) in [("bold", "Bold"), ("italic", "Italic"), ("underline", "Underline")] {
IconButton::new(IconId::new(icon)).label(label).id_salt(icon).show(ui);
}
});
};
let mut ran = false;
let shown = Menu::new("Format").open(Bind::bound(data.value("open", true))).opened_by(&opener, Trigger::Click).companion(&mut bar).show(
ui,
|ui, _| {
ran |= MenuItem::new("Copy").shortcut("Ctrl+C").show(ui).ran;
ran |= MenuItem::new("Paste").shortcut("Ctrl+V").show(ui).ran;
Divider::horizontal().show(ui);
ran |= MenuItem::new("Clear formatting").show(ui).ran;
},
);
let mut output = StoryOutput::from(shown.output);
output.clicked |= ran;
output
})
}
/// The Edit menu of a context menu: shortcuts, icons, a disabled row, check and radio rows and submenus two deep.
#[story(Menu<'static>, covers = [], drive = Drive::Never)]
fn context_menu(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
+76 -9
View File
@@ -34,12 +34,16 @@ fn text_key() -> TextKey<String> {
TextKey::new(TEXT)
}
/// What the combo box keeps between passes: the draft the list was last filtered for, and what the keys in the open
/// list put in.
/// What the combo box keeps between passes: the draft the list was last filtered for, what the keys in the open
/// list put in, and the option text the open list previews.
#[derive(Clone, Default)]
struct Typing {
draft: Option<String>,
keyed: Option<Keyed>,
/// The option text the preview shows; a pass reports a preview only when this changes.
lead: Option<String>,
/// The pointer proposed the lead, so it ends when the pointer leaves the rows (a keyed row keeps its preview).
lead_by_pointer: bool,
}
/// The option text the keys in the open list put in the field, and the draft from before the keys (`None` when the keys
@@ -92,13 +96,44 @@ pub struct ComboBox<'a> {
#[prop(func = "Fn(&String, ListRow<'a>) -> ListRow<'a>")]
decorate: Option<RowDress<'a, String>>,
empty: String,
/// What this pass did to the preview, reported in [`ComboBoxOutput::preview`].
preview: Preview<String>,
}
impl<'a> ComboBox<'a> {
/// A combo box named `label` over the text `value`, offering `options`; an option's value is the text it puts in
/// the field.
pub fn new(label: impl Into<Label>, value: Bind<'a, String>, options: &'a [Entry<String>]) -> Self {
ComboBox { common: Common::new(), value, options, placeholder: None, decorate: None, empty: String::new() }.label(label)
ComboBox {
common: Common::new(),
value,
options,
placeholder: None,
decorate: None,
empty: String::new(),
preview: Preview::Unchanged,
}
.label(label)
}
/// Previews `text`, led by the pointer or by the keys. The pass reports it only when the previewed text changes,
/// so a second pass of a frame, which sees the lead its first pass stored, reports nothing.
fn show_preview(&mut self, cx: &mut Cx<'_, Self>, text: String, by_pointer: bool) {
let typing = cx.memory::<Typing>();
typing.lead_by_pointer = by_pointer;
if typing.lead.as_ref() != Some(&text) {
typing.lead = Some(text.clone());
self.preview = Preview::Shows(text);
}
}
/// Ends the preview, if one runs; the pass reports the end once.
fn end_preview(&mut self, cx: &mut Cx<'_, Self>) {
let typing = cx.memory::<Typing>();
typing.lead_by_pointer = false;
if typing.lead.take().is_some() {
self.preview = Preview::Ended;
}
}
fn text_options(&self) -> TextOptions {
@@ -195,6 +230,8 @@ impl Component for ComboBox<'_> {
if list.is_open(cx) {
return;
}
// A list closed by any path (a pick, Escape, a click outside, the draft ending) ends its preview.
self.end_preview(cx);
let text = cx.value().cloned().unwrap_or_default();
while let Some((step, mods)) = cx.intents().take_move() {
let forward = match step {
@@ -217,7 +254,9 @@ impl Component for ComboBox<'_> {
/// The list: one option row per match, the row of the field's text checked and active when the list opens. The
/// row the keys make active puts its text in the field as a change of the typing run; the list's Escape puts back
/// the text from before the keys. A pick comes back as `Activate` (Enter or a click) and puts the option's text
/// in the field.
/// in the field. The row under the pointer or the keys is previewed (the field's value stays); the preview ends
/// when the pointer leaves the rows, a row is picked or the list closes. Each pass reports only its own input's
/// events, so a rerun pass with no new lead reports `Unchanged`.
fn overlay(&mut self, ui: &mut OverlayUi<'_>, cx: &mut Cx<'_, Self>) {
crate::menu::text_menu(ui, cx, &self.text_options());
let popup = cx.popup("options");
@@ -228,25 +267,31 @@ impl Component for ComboBox<'_> {
let name = cx.label();
let decorate = self.decorate.as_ref();
let rows = EntryRows::new(options, &labels);
let mut over_rows = false;
let mut under_pointer: Option<usize> = None;
let events = ui.show(popup, Overlay::dropdown(), |ui, _| {
let selection = current.filter(|_| query.trim().is_empty()).map_or_else(Selection::default, Selection::single);
List::<usize>::options(name.clone())
let shown = List::<usize>::options(name.clone())
.selection(Bind::given(selection))
.filter(&query, |key| labels[*key].clone())
.ranked(true)
.show_items(ui, &rows, &mut |key, _| rows.row(*key, current, decorate, None))
.events
.show_items(ui, &rows, &mut |key, _| rows.row(*key, current, decorate, None));
under_pointer = shown.shown.iter().find(|row| row.hovered).map(|row| row.key);
over_rows = under_pointer.is_some();
shown.events
});
let (mut picked, mut keyed_to) = (None, None);
let (mut picked, mut keyed_to, mut pointed_to) = (None, None, None);
for event in events.into_iter().flatten() {
match event {
CollectionEvent::Activate(key) => picked = Some(key),
CollectionEvent::LeadMoved { key, by: LeadSource::Keys, .. } => keyed_to = Some(key),
CollectionEvent::LeadMoved { key, by: LeadSource::Pointer, .. } => pointed_to = Some(key),
_ => {}
}
}
if let Some(value) = picked.and_then(|key| options.get(key)).and_then(Entry::value) {
cx.memory::<Typing>().keyed = None;
self.end_preview(cx);
cx.set(value.clone());
popup.close(cx);
} else if let Some(text) = keyed_to.and_then(|key| options.get(key)).and_then(Entry::value) {
@@ -255,6 +300,28 @@ impl Component for ComboBox<'_> {
let before = typing.keyed.take().map_or(draft, |keyed| keyed.before);
typing.keyed = Some(Keyed { shown: text.clone(), before });
cx.set_draft(Some(text.clone()));
self.show_preview(cx, text.clone(), false);
} else if let Some(text) = pointed_to.and_then(|key| options.get(key)).and_then(Entry::value) {
self.show_preview(cx, text.clone(), true);
}
// A preview the pointer proposed ends when the pointer leaves the rows. The list keeps its lead on the row, so
// the pointer coming back to that row reports no move: the row under it proposes again.
let (by_pointer, led) = {
let typing = cx.memory::<Typing>();
(typing.lead_by_pointer, typing.lead.is_some())
};
if picked.is_none() {
if by_pointer && !over_rows {
self.end_preview(cx);
} else if over_rows
&& !led
&& let Some(text) = under_pointer.and_then(|key| options.get(key)).and_then(Entry::value)
{
self.show_preview(cx, text.clone(), true);
}
}
if ui.closing(popup).is_some() {
self.end_preview(cx);
}
match ui.closing(popup) {
Some(CloseReason::Escape) => {
@@ -273,6 +340,6 @@ impl Component for ComboBox<'_> {
}
fn finish(self, cx: Cx<'_, Self>) -> ComboBoxOutput {
ComboBoxOutput { edit: cx.edit_response(), preview: Preview::default() } // P3(ribbon-w2): rb.R24
ComboBoxOutput { edit: cx.edit_response(), preview: self.preview }
}
}
@@ -3,8 +3,9 @@
use super::ComboBox;
use crate::contract::{Bind, Entry, Show as _, Validity};
use crate::runtime::env::Message;
use crate::testing::pointer::moved;
use crate::testing::{Drive, Fixture, StoryData, StoryOutput, story};
use craft_behavior::Mixed;
use craft_behavior::{Mixed, Preview};
use egui::{Key, Modifiers, Ui};
const FAMILIES: [&str; 5] = ["Arial", "Charter", "Garamond", "Verdana", "Zapfino"];
@@ -16,20 +17,20 @@ fn options() -> Vec<Entry<String>> {
#[story(ComboBox<'static>, covers = [Default], drive = Drive::Type("Garamond"))]
fn combo_box(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
let options = options();
ComboBox::new("Font", Bind::bound(data.value("font", "Charter".to_owned())), &options).placeholder("Choose a font").show(ui).into()
ComboBox::new("Font", Bind::bound(data.value("font", "Charter".to_owned())), &options).placeholder("Choose a font").show(ui).edit.into()
}
#[story(ComboBox<'static>, covers = [LongText], drive = Drive::Never)]
fn combo_box_long(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
let options = options();
let long = "A family name that runs far past the room the field has left beside its chevron".to_owned();
ComboBox::new("Font", Bind::bound(data.value("long", long)), &options).show(ui).into()
ComboBox::new("Font", Bind::bound(data.value("long", long)), &options).show(ui).edit.into()
}
#[story(ComboBox<'static>, covers = [Mixed], drive = Drive::Never)]
fn combo_box_mixed(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
let options = options();
ComboBox::new("Font", Bind::bound_mixed(data.value("mixed", Mixed::<String>::Mixed)), &options).show(ui).into()
ComboBox::new("Font", Bind::bound_mixed(data.value("mixed", Mixed::<String>::Mixed)), &options).show(ui).edit.into()
}
#[story(ComboBox<'static>, covers = [Invalid], drive = Drive::Never)]
@@ -37,7 +38,7 @@ fn combo_box_invalid(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
let options = options();
let refuse_zapfino =
|family: &String| if family == "Zapfino" { Validity::Refuse(Message::new("Zapfino is not installed")) } else { Validity::Ok };
ComboBox::new("Font", Bind::bound(data.value("invalid", "Zapfino".to_owned())).check(refuse_zapfino), &options).show(ui).into()
ComboBox::new("Font", Bind::bound(data.value("invalid", "Zapfino".to_owned())).check(refuse_zapfino), &options).show(ui).edit.into()
}
/// Focuses the field and opens the list on every option with Alt+Down.
@@ -51,5 +52,25 @@ fn open_list(fixture: &mut Fixture) {
fn combo_box_open(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
let mut options = options();
options.insert(2, Entry::separator());
ComboBox::new("Font", Bind::bound(data.value("open", "Charter".to_owned())), &options).show(ui).into()
ComboBox::new("Font", Bind::bound(data.value("open", "Charter".to_owned())), &options).show(ui).edit.into()
}
/// Opens the list and rests the pointer on the Garamond row, which the list previews.
fn hover_option(fixture: &mut Fixture) {
open_list(fixture);
if let Some(row) = fixture.by_label("Garamond") {
fixture.frame(vec![moved(row.center())]);
}
fixture.idle(4);
}
#[story(ComboBox<'static>, covers = [Open], drive = Drive::Custom(hover_option))]
fn combo_box_preview(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
let options = options();
let shown = ComboBox::new("Font", Bind::bound(data.value("preview_font", "Charter".to_owned())), &options).show(ui);
// The field keeps "Charter" while the hovered option is previewed; the story keeps what the preview shows.
if shown.preview != Preview::Unchanged {
*data.value("previewed", Preview::<String>::Unchanged) = shown.preview.clone();
}
shown.edit.into()
}
+267
View File
@@ -0,0 +1,267 @@
//! Buttons: the stacked arrangement's height, the hover report of a click the pointer stays on, and the compact
//! group level, under which an inline button drops its label and keeps it as its name and tooltip.
use craft_behavior::IconId;
use craft_theme::ControlSize;
use craft_ui::buttons::{Arrangement, Button, GroupLevel, SplitButton, SplitMenu, ToggleButton};
use craft_ui::contract::tooltip::DELAY;
use craft_ui::contract::{Bind, CommandSet, Entry, Hover, Props as _, Show as _};
use craft_ui::runtime::commands::CommandState;
use craft_ui::runtime::env::with_env;
use craft_ui::testing::pointer::{moved, press, release};
use craft_ui::testing::{Fixture, trial};
use egui::{Event, Id, Pos2, Rect, Response, Ui};
use std::cell::{Cell, RefCell};
use std::rc::Rc;
/// The button kinds that take an arrangement.
#[derive(Clone, Copy, Debug)]
enum Kind {
Button,
Toggle,
Split,
}
/// One stacked control of `kind` with `label` at `size`, shown alone: its rect and the rects of the label lines it
/// paints, in paint order.
fn stacked(kind: Kind, label: &'static str, size: ControlSize) -> (Rect, Vec<Rect>) {
let at = Rc::new(Cell::new(Id::NULL));
let seen = Rc::clone(&at);
let mut fixture = Fixture::new(move |ui| {
let icon = IconId::new("copy");
let id = match kind {
Kind::Button => Button::new(label).icon(icon).arrangement(Arrangement::Stacked).size(size).show(ui).response.id,
Kind::Toggle => {
let mut on = false;
ToggleButton::new(label, Bind::bound(&mut on)).icon(icon).arrangement(Arrangement::Stacked).size(size).show(ui).response.id
}
Kind::Split => {
let entries = [Entry::new(0u8, "Keep source formatting"), Entry::new(1u8, "Keep text only")];
SplitButton::new(label, &entries)
.icon(icon)
.arrow_label("Paste options")
.arrangement(Arrangement::Stacked)
.size(size)
.show(ui)
.response
.id
}
};
seen.set(id);
});
fixture.settle();
// The control's node bounds both of a split button's parts.
let control = fixture.node_of(at.get()).expect("the control is in the access tree").rect;
let lines = fixture.texts().iter().filter(|run| !run.text.trim().is_empty()).map(|run| (run.text.clone(), run.rect));
let lines: Vec<(String, Rect)> = lines.collect();
for (text, _) in &lines {
assert!(label.contains(text.as_str()), "{kind:?} paints only its label's lines: {text:?} is not part of {label:?}");
}
(control, lines.into_iter().map(|(_, rect)| rect).collect())
}
#[trial]
fn a_stacked_label_stays_inside_the_stacked_height_in_every_density() {
for kind in [Kind::Button, Kind::Toggle, Kind::Split] {
for size in [ControlSize::Sm, ControlSize::Md] {
let (one, one_lines) = stacked(kind, "Paste", size);
let (two, two_lines) = stacked(kind, "Insert page break", size);
assert_eq!(one_lines.len(), 1, "{kind:?} at {size:?}: a short label keeps one line");
assert_eq!(two_lines.len(), 2, "{kind:?} at {size:?}: a long label breaks into two lines");
for (control, lines) in [(one, &one_lines), (two, &two_lines)] {
for line in lines.iter() {
assert!(control.expand(0.5).contains_rect(*line), "{kind:?} at {size:?}: the line {line:?} lies inside {control:?}");
}
// The icon sits above the label: at least a line's height of the control lies over the first line.
let first = lines[0];
assert!(
first.min.y - control.min.y >= first.height(),
"{kind:?} at {size:?}: the icon is above the label ({first:?} in {control:?})"
);
}
assert!(two_lines[1].min.y >= two_lines[0].max.y - 0.5, "{kind:?} at {size:?}: the second line is under the first");
assert!(two.height() > one.height() + 0.5, "{kind:?} at {size:?}: two lines make a taller control ({two:?} against {one:?})");
}
}
}
/// A fixture showing one toggle, the hover reports of each pass of a frame, and a switch that reruns the next
/// frame's pass.
struct HoverTrial {
fixture: Fixture,
reports: Rc<RefCell<Vec<Hover>>>,
rerun: Rc<Cell<bool>>,
}
impl HoverTrial {
fn new() -> Self {
let reports = Rc::new(RefCell::new(Vec::new()));
let rerun = Rc::new(Cell::new(false));
let on = Rc::new(Cell::new(false));
let (seen, again) = (Rc::clone(&reports), Rc::clone(&rerun));
let mut fixture = Fixture::new(move |ui| {
let mut value = on.get();
let shown = ToggleButton::new("Snap to grid", Bind::bound(&mut value)).icon(IconId::new("eye")).show(ui);
on.set(value);
seen.borrow_mut().push(shown.hover);
if again.get() && ui.ctx().current_pass_index() == 0 {
ui.ctx().request_discard("the trial reruns the pass");
}
});
fixture.settle();
HoverTrial { fixture, reports, rerun }
}
/// One frame with `events`; the reports of its passes, first pass first.
fn frame(&mut self, events: Vec<Event>) -> Vec<Hover> {
self.reports.borrow_mut().clear();
self.fixture.frame(events);
self.reports.borrow().clone()
}
/// [`HoverTrial::frame`], its pass run twice.
fn frame_twice(&mut self, events: Vec<Event>) -> Vec<Hover> {
self.rerun.set(true);
let reports = self.frame(events);
self.rerun.set(false);
assert_eq!(self.fixture.passes(), 2, "the frame ran a second pass");
reports
}
}
#[trial]
fn a_click_holds_until_the_pointer_leaves() {
let mut trial = HoverTrial::new();
let toggle = trial.fixture.by_label("Snap to grid").expect("the toggle is in the access tree").center();
let away = Pos2::new(390.0, 290.0);
let entered = trial.frame_twice(vec![moved(toggle)]);
assert!(entered[0].over && entered[0].entered && !entered[0].clicked, "the pointer enters the toggle: {:?}", entered[0]);
assert!(entered[1].over && !entered[1].entered, "a second pass applies no input of its own: {:?}", entered[1]);
let pressed = trial.frame(vec![press(toggle)]);
assert!(pressed.iter().all(|hover| hover.over && !hover.clicked), "a press is not a click yet: {pressed:?}");
let clicked = trial.frame_twice(vec![release(toggle)]);
assert!(clicked.iter().all(|hover| hover.over && hover.clicked), "the click shows in both passes of its frame: {clicked:?}");
let staying = trial.frame(Vec::new());
assert!(staying.iter().all(|hover| hover.over && hover.clicked && !hover.entered), "the click holds while the pointer stays: {staying:?}");
let left = trial.frame(vec![moved(away)]);
assert!(!left[0].over && left[0].left && !left[0].clicked, "leaving drops the click: {:?}", left[0]);
let back = trial.frame(vec![moved(toggle)]);
assert!(back[0].over && back[0].entered && !back[0].clicked, "coming back is an entry, not the old click: {:?}", back[0]);
}
/// The command the compact split button's main part is bound to.
#[derive(Clone, Copy, Debug, PartialEq, Eq, CommandSet)]
#[command(prefix = "buttonsTrial")]
#[non_exhaustive]
enum TraceCommand {
#[command(label = "Trace", default = "Cmd+Alt+T", modal = "always")]
Trace,
}
/// The labelled inline button the compact trial shows.
fn save(ui: &mut Ui) -> Response {
Button::new("Save").icon(IconId::new("save")).show(ui).response
}
/// The labelled split button the compact trial shows: its main part runs `TraceCommand::Trace`.
fn trace(ui: &mut Ui) -> Response {
let entries = [Entry::new(0u8, "Black and white"), Entry::new(1u8, "Colour")];
SplitButton::command(TraceCommand::Trace, SplitMenu::Entries(&entries))
.icon(IconId::new("image"))
.arrow_label("Tracing presets")
.show(ui)
.response
}
/// Shows `show` under `level`.
fn at_level(ui: &mut Ui, level: GroupLevel, show: fn(&mut Ui) -> Response) -> Response {
with_env(
ui,
|overrides| {
overrides.values.set(level);
},
|ui| show(ui),
)
}
/// What a control named `name` shows alone, inside a compact group or not.
struct Shown {
width: f32,
/// Whether its label is painted.
painted: bool,
/// Whether its name is in the access tree.
named: bool,
/// The lines the pointer's rest on its main part adds.
tooltip: Vec<String>,
}
fn shown(name: &str, show: fn(&mut Ui) -> Response, compact: bool) -> Shown {
let at = Rc::new(Cell::new(Id::NULL));
let seen = Rc::clone(&at);
let mut fixture = Fixture::new(move |ui| {
let response = if compact { at_level(ui, GroupLevel::Compact, show) } else { show(ui) };
seen.set(response.id);
});
fixture.command_state(TraceCommand::Trace, CommandState::new());
fixture.settle();
let painted = fixture.texts().iter().any(|run| run.text == name);
let named = fixture.by_label(name).is_some();
// The control's node bounds both of a split button's parts.
let rect = fixture.node_of(at.get()).expect("the control is in the access tree").rect;
let before: Vec<String> = fixture.texts().iter().map(|run| run.text.clone()).collect();
// The main part is at the start, the arrow at the end.
fixture.frame(vec![moved(Pos2::new(rect.min.x + rect.width() * 0.25, rect.center().y))]);
fixture.advance(DELAY);
fixture.settle();
let added = fixture.texts().iter().map(|run| run.text.clone()).filter(|text| !before.contains(text));
let tooltip = added.flat_map(|text| text.lines().map(str::to_owned).collect::<Vec<_>>()).filter(|line| !line.is_empty()).collect();
Shown { width: rect.width(), painted, named, tooltip }
}
#[trial]
fn an_inline_button_drops_its_label_under_a_compact_group_and_names_itself_by_tooltip() {
let cases: [(&str, fn(&mut Ui) -> Response); 2] = [("Save", save), ("Trace", trace)];
for (name, show) in cases {
let full = shown(name, show, false);
let compact = shown(name, show, true);
assert!(full.painted, "{name} paints its label at full size");
assert!(!compact.painted, "{name} paints no label in a compact group");
assert!(compact.width < full.width - 0.5, "{name} is narrower in a compact group: {} against {}", compact.width, full.width);
assert!(compact.named, "{name} keeps its label as its accessible name");
assert!(
compact.tooltip.iter().any(|line| line.starts_with(name)),
"{name} shows its label as its tooltip in a compact group: {:?}",
compact.tooltip
);
}
// The level changes between two passes of one frame: the second pass measures at the new level.
let compact = Rc::new(Cell::new(false));
let switch = Rc::new(Cell::new(false));
let widths = Rc::new(RefCell::new(Vec::new()));
let (level, flip, seen) = (Rc::clone(&compact), Rc::clone(&switch), Rc::clone(&widths));
let mut fixture = Fixture::new(move |ui| {
let at = if level.get() { GroupLevel::Compact } else { GroupLevel::Full };
seen.borrow_mut().push(at_level(ui, at, save).rect.width());
if flip.get() && ui.ctx().current_pass_index() == 0 {
flip.set(false);
level.set(true);
ui.ctx().request_discard("the trial changes the level between passes");
}
});
fixture.settle();
widths.borrow_mut().clear();
switch.set(true);
fixture.frame(Vec::new());
assert_eq!(fixture.passes(), 2, "the frame ran a second pass");
let passes = widths.borrow().clone();
let settled = shown("Save", save, true).width;
assert!(passes[1] < passes[0] - 0.5, "the full-size measurement is not reused at the compact level: {passes:?}");
assert!((passes[1] - settled).abs() < 0.5, "the second pass measures as a settled compact button does: {passes:?} against {settled}");
}
+94 -3
View File
@@ -1,16 +1,21 @@
//! The tooltip of a control that paints no label: its own label shows there, inside a field or not; a control named
//! only by its field label shows none, and the field's label stays where it was.
//! only by its field label shows none, and the field's label stays where it was. A bound command's hint is the
//! tooltip's second line, and makes a disabled control a focus stop that shows it.
use super::kit::PlainStyle;
use craft_behavior::Sense;
use craft_ui::buttons::Button;
use craft_ui::contract::tooltip::DELAY;
use craft_ui::contract::{Common, Component, Cx, GlyphLabel, LabelKind, MeasureCx, Props as _, Role, Show as _, ShowContainer as _, SideLabel};
use craft_ui::contract::{
CommandSet, Common, Component, Cx, GlyphLabel, LabelKind, MeasureCx, Props as _, Role, Show as _, ShowContainer as _, SideLabel,
};
use craft_ui::form::Field;
use craft_ui::runtime::commands::CommandState;
use craft_ui::style::StyleCx;
use craft_ui::testing::pointer::moved;
use craft_ui::testing::{Fixture, trial};
use craft_ui::tile_grid::{CaptionPlace, Tile};
use egui::{Pos2, Rect, Response, Ui, Vec2};
use egui::{Id, Key, Modifiers, Pos2, Rect, Response, Ui, Vec2};
use std::cell::Cell;
use std::rc::Rc;
@@ -46,9 +51,15 @@ impl Component for Mark {
/// The texts the pointer's rest on what `show` shows (it returns its rect) adds after the tooltip delay.
fn texts_added_by_hover(show: impl Fn(&mut Ui) -> Rect + 'static) -> Vec<String> {
texts_added_by_hover_in(show, |_| {})
}
/// [`texts_added_by_hover`] in a fixture `prepare` sets up first (the state of a command).
fn texts_added_by_hover_in(show: impl Fn(&mut Ui) -> Rect + 'static, prepare: impl FnOnce(&mut Fixture)) -> Vec<String> {
let at = Rc::new(Cell::new(Rect::NOTHING));
let seen = Rc::clone(&at);
let mut fixture = Fixture::new(move |ui| seen.set(show(ui)));
prepare(&mut fixture);
fixture.settle();
// A cut run carries its full text too: runs are told apart by whether they are cut.
let before: Vec<(String, bool)> = fixture.texts().iter().map(|run| (run.text.clone(), run.elided)).collect();
@@ -121,3 +132,83 @@ fn a_control_that_paints_no_label_shows_its_own_label_as_tooltip() {
assert_eq!(glyph_label(None), ["Leading"], "a glyph label shows its name");
assert_eq!(glyph_label(Some("Leading (1/1000 em)")), ["Leading (1/1000 em)"], "a glyph label's tooltip replaces its name");
}
/// The command the hint trials bind: an app command with a chord.
#[derive(Clone, Copy, Debug, PartialEq, Eq, CommandSet)]
#[command(prefix = "tooltipHintTrial")]
#[non_exhaustive]
enum HintCommand {
#[command(label = "Bold", default = "Cmd+B", modal = "always")]
Bold,
}
const HINT: &str = "Make the selected text heavier";
/// The lines of the texts `added` holds, in order: a run with a line break counts as its lines.
fn lines(added: &[String]) -> Vec<String> {
added.iter().flat_map(|text| text.lines().map(str::to_owned)).filter(|line| !line.is_empty()).collect()
}
#[trial]
fn a_command_hint_is_the_tooltips_second_line() {
let button = || {
|ui: &mut Ui| {
ui.add_space(20.0);
Button::command(HintCommand::Bold).show(ui).rect
}
};
let hinted = texts_added_by_hover_in(button(), |fixture| {
fixture.command_state(HintCommand::Bold, CommandState::new().hint(HINT));
});
let shown = lines(&hinted);
assert_eq!(shown.len(), 2, "the tooltip has two lines: {shown:?}");
assert!(shown[0].contains("Bold") && shown[0] != "Bold", "the first is the label with its chord added: {shown:?}");
assert!(shown[1].contains(HINT), "the second is the hint: {shown:?}");
let plain = texts_added_by_hover_in(button(), |fixture| {
fixture.command_state(HintCommand::Bold, CommandState::new());
});
assert!(plain.is_empty(), "with no hint a button that paints its label shows no tooltip: {plain:?}");
}
/// The stops Tab reaches, in order, among the buttons Before, Bold (disabled, bound to `HintCommand::Bold`) and After,
/// and the texts the tooltip adds once the keyboard rests on Bold.
fn tab_through_disabled(hint: Option<&'static str>) -> (Vec<&'static str>, Vec<String>) {
let ids = Rc::new(Cell::new([Id::NULL; 3]));
let seen = Rc::clone(&ids);
let mut fixture = Fixture::new(move |ui| {
let before = Button::new("Before").show(ui).id;
let bold = Button::command(HintCommand::Bold).show(ui).id;
let after = Button::new("After").show(ui).id;
seen.set([before, bold, after]);
});
let state = CommandState::new().enabled(false);
fixture.command_state(HintCommand::Bold, hint.map_or(state.clone(), |hint| state.hint(hint)));
fixture.settle();
let names = ["Before", "Bold", "After"];
let mut reached = Vec::new();
let mut added = Vec::new();
for _ in 0..3 {
fixture.key(Key::Tab, Modifiers::NONE);
fixture.settle();
let Some(at) = fixture.focused().and_then(|focused| ids.get().iter().position(|id| *id == focused)) else { continue };
reached.push(names[at]);
if at == 1 {
let before: Vec<String> = fixture.texts().iter().map(|run| run.text.clone()).collect();
fixture.advance(DELAY);
fixture.settle();
added = fixture.texts().iter().map(|run| run.text.clone()).filter(|text| !before.contains(text)).collect();
}
}
(reached, added)
}
#[trial]
fn a_disabled_command_with_a_hint_is_a_tab_stop_that_shows_its_reason() {
let (reached, added) = tab_through_disabled(Some(HINT));
assert_eq!(reached, ["Before", "Bold", "After"], "Tab reaches the disabled button with a hint");
assert!(lines(&added).iter().any(|line| line == HINT), "and its tooltip shows the hint on keyboard focus: {added:?}");
let (reached, _) = tab_through_disabled(None);
assert_eq!(&reached[..2], ["Before", "After"], "without a hint Tab skips the disabled button");
}
+1
View File
@@ -6,6 +6,7 @@ extern crate craft_ui_widgets as craft_ui;
mod access;
mod bars;
pub(crate) mod body;
mod buttons;
mod commands;
mod contract;
mod disabled_fade;
+123 -2
View File
@@ -1,10 +1,131 @@
//! Menu rows: the detail line under the label and the row's own tooltip.
//! Menu rows: the detail line under the label, the row's own tooltip, the sample slot and which shortcut a row shows.
use craft_i18n::Direction;
use craft_ui::buttons::Button;
use craft_ui::contract::tooltip::DELAY;
use craft_ui::contract::{Props as _, Show as _, ShowContainer as _, Trigger};
use craft_ui::contract::{CommandSet, Props as _, Show as _, ShowContainer as _, Trigger};
use craft_ui::menu::{Menu, MenuItem};
use craft_ui::primitives::ContentPainterCx;
use craft_ui::runtime::commands::CommandState;
use craft_ui::testing::{Fixture, pointer, trial};
use egui::Rect;
use std::cell::Cell;
use std::rc::Rc;
/// The texts painted inside `row` other than `label`.
fn other_runs(fixture: &Fixture, row: Rect, label: &str) -> Vec<(String, Rect)> {
let runs = fixture.texts().iter().filter(|run| row.contains(run.rect.center()) && run.text != label);
runs.map(|run| (run.text.clone(), run.rect)).collect()
}
/// The painted run `text`.
fn run(fixture: &Fixture, text: &str) -> Option<Rect> {
fixture.texts().iter().find(|run| run.text == text).map(|run| run.rect)
}
/// Where the label, the sample and the shortcut of a row with all three lie under `direction`, and, for a
/// `sample_only` row: whether its label text is painted, whether its name is in the access tree, and its sample.
struct SampleRows {
label: Rect,
sample: Rect,
shortcut: Rect,
only_label_painted: bool,
only_named: bool,
only_sample: Rect,
}
fn sample_rows(direction: Direction) -> SampleRows {
let sample = Rc::new(Cell::new(Rect::NOTHING));
let only = Rc::new(Cell::new(Rect::NOTHING));
let (seen, seen_only) = (Rc::clone(&sample), Rc::clone(&only));
let mut fixture = Fixture::new(move |ui| {
Menu::inline("Swatches").show(ui, |ui, _| {
let (seen, seen_only) = (Rc::clone(&seen), Rc::clone(&seen_only));
MenuItem::new("Shade").sample(move |_: &ContentPainterCx, rect: Rect| seen.set(rect)).shortcut("F5").show(ui);
MenuItem::new("Ocean").sample(move |_: &ContentPainterCx, rect: Rect| seen_only.set(rect)).sample_only().show(ui);
});
});
fixture.direction(direction);
fixture.settle();
SampleRows {
label: run(&fixture, "Shade").expect("the label is painted"),
sample: sample.get(),
shortcut: run(&fixture, "F5").expect("the shortcut is painted"),
only_label_painted: run(&fixture, "Ocean").is_some(),
only_named: fixture.by_label("Ocean").is_some(),
only_sample: only.get(),
}
}
#[trial]
fn a_row_sample_sits_between_the_label_and_the_shortcut_and_mirrors() {
let ltr = sample_rows(Direction::Ltr);
assert!(ltr.sample.width() > 0.0, "the sample is painted into a slot: {:?}", ltr.sample);
assert!(ltr.label.max.x <= ltr.sample.min.x + 0.5, "the sample follows the label: {:?} then {:?}", ltr.label, ltr.sample);
assert!(ltr.sample.max.x <= ltr.shortcut.min.x + 0.5, "and comes before the shortcut: {:?} then {:?}", ltr.sample, ltr.shortcut);
let rtl = sample_rows(Direction::Rtl);
assert!(rtl.sample.width() > 0.0, "the sample is painted under right-to-left too");
assert!(rtl.sample.max.x <= rtl.label.min.x + 0.5, "right to left, the sample lies left of the label: {:?} {:?}", rtl.sample, rtl.label);
assert!(rtl.shortcut.max.x <= rtl.sample.min.x + 0.5, "and the shortcut left of the sample: {:?} {:?}", rtl.shortcut, rtl.sample);
for (rows, direction) in [(&ltr, "left to right"), (&rtl, "right to left")] {
assert!(!rows.only_label_painted, "a sample-only row paints no label text ({direction})");
assert!(rows.only_named, "and keeps its label as its name in the access tree ({direction})");
assert!(rows.only_sample.width() > 0.0, "its sample takes the label's place ({direction})");
}
}
/// The app commands the shortcut trial's rows bind, each with a chord.
#[derive(Clone, Copy, Debug, PartialEq, Eq, CommandSet)]
#[command(prefix = "menuRowsTrial")]
#[non_exhaustive]
enum RowCommand {
#[command(label = "Find", default = "Cmd+K", modal = "always")]
Find,
#[command(label = "Replace", default = "Cmd+J", modal = "always")]
Replace,
#[command(label = "Jump", default = "Cmd+L", modal = "always")]
Jump,
}
#[trial]
fn a_caller_shortcut_wins_over_the_bound_commands_chord_and_hide_shortcut_shows_none() {
let mut fixture = Fixture::new(|ui| {
Menu::inline("Search").show(ui, |ui, _| {
MenuItem::command(RowCommand::Find).show(ui);
MenuItem::command(RowCommand::Replace).shortcut("X").show(ui);
MenuItem::command(RowCommand::Jump).hide_shortcut().show(ui);
MenuItem::new("Plain").show(ui);
});
});
for command in [RowCommand::Find, RowCommand::Replace, RowCommand::Jump] {
fixture.command_state(command, CommandState::new());
}
fixture.settle();
let row = |fixture: &Fixture, label: &str| fixture.by_label(label).expect("each row is in the access tree");
let listed = |fixture: &Fixture, label: &str| {
let node = row(fixture, label).node;
fixture.tree().shortcut_of(node).map(str::to_owned)
};
let find = row(&fixture, "Find");
assert!(!other_runs(&fixture, find.rect, "Find").is_empty(), "a command row shows its command's chord");
assert!(listed(&fixture, "Find").is_some(), "and lists it as its shortcut");
let replace = row(&fixture, "Replace");
let shown: Vec<String> = other_runs(&fixture, replace.rect, "Replace").into_iter().map(|(text, _)| text).collect();
assert_eq!(shown, ["X"], "the caller's shortcut text wins over the chord");
assert_eq!(listed(&fixture, "Replace").as_deref(), Some("X"), "and is the row's listed shortcut");
let jump = row(&fixture, "Jump");
assert!(other_runs(&fixture, jump.rect, "Jump").is_empty(), "a hidden shortcut paints none");
assert_eq!(listed(&fixture, "Jump"), None, "and lists none");
let plain = row(&fixture, "Plain");
assert!(other_runs(&fixture, plain.rect, "Plain").is_empty(), "a row with no command and no text shows no shortcut");
assert_eq!(listed(&fixture, "Plain"), None, "and lists none");
}
#[trial]
fn a_detail_shows_as_a_second_line_under_the_label() {
@@ -1,16 +1,81 @@
//! The keys in a ComboBox's open list put the active option's text in the field at once, and the list's Escape puts
//! back what was typed.
//! back what was typed. The option under the pointer is previewed without changing the field.
use craft_behavior::Preview;
use craft_ui::contract::{Bind, Entry, Role, Show as _};
use craft_ui::pickers::ComboBox;
use craft_ui::testing::pointer::moved;
use craft_ui::testing::{Fixture, Story, StoryData, StoryOutput, trial};
use egui::{Key, Modifiers, Ui};
use egui::{Key, Modifiers, Pos2, Ui};
const FAMILIES: [&str; 3] = ["Garamond", "Georgia", "Arial"];
fn combo(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
let options: Vec<Entry<String>> = FAMILIES.iter().map(|family| Entry::new((*family).to_owned(), *family)).collect();
ComboBox::new("Font", Bind::bound(data.value("font", "Arial".to_owned())), &options).show(ui).into()
ComboBox::new("Font", Bind::bound(data.value("font", "Arial".to_owned())), &options).show(ui).edit.into()
}
/// The combo box that stores the last preview change it reported and how many passes reported one; with `twice` set,
/// every frame runs two passes.
fn previewing(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
let options: Vec<Entry<String>> = FAMILIES.iter().map(|family| Entry::new((*family).to_owned(), *family)).collect();
let shown = ComboBox::new("Font", Bind::bound(data.value("font", "Arial".to_owned())), &options).show(ui);
if shown.preview != Preview::Unchanged {
*data.value("reports", 0_u32) += 1;
*data.value("preview", Preview::<String>::Unchanged) = shown.preview.clone();
}
if *data.value("twice", false) && ui.ctx().current_pass_index() == 0 {
ui.ctx().request_discard("the trial runs the frame twice");
}
shown.edit.into()
}
fn preview(fixture: &mut Fixture) -> Preview<String> {
fixture.data().value("preview", Preview::<String>::Unchanged).clone()
}
fn reports(fixture: &mut Fixture) -> u32 {
*fixture.data().value("reports", 0_u32)
}
#[trial]
fn the_hovered_option_is_previewed_until_the_pointer_leaves_the_list() {
let mut fixture = Fixture::story(&Story::new("combo_preview", previewing));
fixture.settle();
fixture.key(Key::Tab, Modifiers::NONE);
fixture.key(Key::ArrowDown, Modifiers::ALT);
fixture.settle();
assert!(list_open(&mut fixture), "Alt+Down opens the list");
let garamond = fixture.by_label("Garamond").expect("the Garamond row").center();
fixture.frame(vec![moved(garamond)]);
fixture.settle();
assert_eq!(preview(&mut fixture), Preview::Shows("Garamond".to_owned()), "the row under the pointer is previewed");
assert_eq!(font(&mut fixture), "Arial", "and the field's value stays");
// A frame that runs two passes reports the move once: the second pass has no input of its own.
*fixture.data().value("twice", false) = true;
let before = reports(&mut fixture);
let georgia = fixture.by_label("Georgia").expect("the Georgia row").center();
fixture.frame(vec![moved(georgia)]);
assert!(fixture.passes() > 1, "the frame ran twice");
fixture.settle();
assert_eq!(preview(&mut fixture), Preview::Shows("Georgia".to_owned()), "another row previews its text");
assert_eq!(reports(&mut fixture), before + 1, "one report for one move, and none for passes that change nothing");
*fixture.data().value("twice", false) = false;
let list = fixture.by_role(Role::LIST_BOX).first().copied().expect("the open list").rect;
fixture.frame(vec![moved(Pos2::new(list.center().x, list.max.y + 40.0))]);
fixture.settle();
assert!(list_open(&mut fixture), "leaving the rows keeps the list open");
assert_eq!(preview(&mut fixture), Preview::Ended, "and ends the preview");
assert_eq!(font(&mut fixture), "Arial", "the field's value never followed the preview");
let georgia = fixture.by_label("Georgia").expect("the Georgia row");
fixture.click(&georgia);
fixture.settle();
assert_eq!(font(&mut fixture), "Georgia", "a click picks the row");
assert_eq!(preview(&mut fixture), Preview::Ended, "and the pick ends the preview the hover started");
}
fn font(fixture: &mut Fixture) -> String {