red round 4 (fw-widgets, Opus): fixes for fw-run-5 (runs/fw-run-5/fw-widgets.md); committed by the lead

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Dylan M. Taylor
2026-11-18 09:35:13 -05:00
co-authored by Claude Opus 5.5
parent 9d326dec44
commit d86a6015a8
16 changed files with 238 additions and 143 deletions
@@ -112,6 +112,9 @@ pub(crate) struct Board {
shown: ShownMap,
/// The scope each child scope is declared inside: an instance of the child is also an instance of the parent.
parents: HashMap<&'static str, &'static str>,
/// The commands fired since the testing kit last took them (`observe_fired`); `None` until it first does.
#[cfg(feature = "testing")]
observed: Option<Vec<CommandRef>>,
}
/// What `set_input` changed for the readers of command states, which each pass of the frame notes before any component
@@ -679,6 +682,13 @@ pub(crate) fn take_fired(ctx: &Context) -> Vec<Fired> {
with(ctx, |board| std::mem::take(&mut board.out))
}
/// The commands fired since the last call, whatever they were routed to, and from now on records them: the testing
/// kit's story observer takes them around each pass of a story. Nothing is recorded before the first call.
#[cfg(feature = "testing")]
pub(crate) fn observe_fired(ctx: &Context) -> Vec<CommandRef> {
with(ctx, |board| board.observed.replace(Vec::new()).unwrap_or_default())
}
/// The app-scope commands a key press fired while only the app's own command state disabled them, since the last
/// call.
pub(crate) fn take_declined(ctx: &Context) -> Vec<Fired> {
@@ -940,6 +950,12 @@ pub(crate) fn resolve_scoped(ctx: &Context, chain: &CommandChain, command: &Comm
}
fn queue(ctx: &Context, fired: Fired) {
#[cfg(feature = "testing")]
with(ctx, |board| {
if let Some(observed) = &mut board.observed {
observed.push(fired.command.clone());
}
});
// An edit command goes to the focused component that lists it; otherwise it goes to the instance that declared
// it or, with none, stays an app command.
if fired.phase != FirePhase::Release
@@ -22,6 +22,8 @@ pub use board::focus_within;
#[cfg(feature = "testing")]
#[doc(hidden)]
pub use board::keymap_builds;
#[cfg(feature = "testing")]
pub(crate) use board::observe_fired;
pub(crate) use board::publish as publish_for;
pub(crate) use board::take as take_for_instance;
pub(crate) use board::{
+11
View File
@@ -207,6 +207,8 @@ pub(crate) struct Pass {
last: Vec<OpenEntry>,
/// The layers whose bodies are running and the tier each shows in, innermost last.
drawing: Vec<(Id, Tier)>,
/// Whether each body of `drawing` is that of a layer fading out, in the same order.
exiting: Vec<bool>,
/// The side of its anchor each anchored layer was placed on this pass, set before its body runs.
sides: Vec<(Id, Side)>,
/// The map from its parent's layer space to screen space of each layer container shown this pass, set by its host
@@ -273,6 +275,7 @@ fn with_pass<R>(ctx: &Context, f: impl FnOnce(&mut Pass) -> R) -> R {
pass.last.clear();
}
pass.drawing.clear();
pass.exiting.clear();
pass.sides.clear();
pass.spaces.clear();
pass.activated.clear();
@@ -473,6 +476,7 @@ pub(crate) fn begin_layer(ctx: &Context, id: Id, tier: Tier, exiting: bool, side
let reopened = reopened(ctx, id, exiting);
with_pass(ctx, |pass| {
pass.drawing.push((id, tier));
pass.exiting.push(exiting);
if let Some(side) = side {
pass.sides.push((id, side));
}
@@ -556,9 +560,16 @@ pub(crate) fn released_inside(ctx: &Context, rect: Rect) -> bool {
pub(crate) fn end_layer(ctx: &Context) {
with_pass(ctx, |pass| {
pass.drawing.pop();
pass.exiting.pop();
});
}
/// Whether the running code is inside the body of a layer that fades out, which takes no input: nor does any layer
/// opened inside it.
pub(crate) fn drawing_exiting(ctx: &Context) -> bool {
with_pass(ctx, |pass| pass.exiting.iter().any(|exiting| *exiting))
}
/// Records that the component `id` was activated: the innermost layer whose body is running around it, other than the
/// one `id` is the container of, and the menus the walk out of that layer crosses (`focus::menus_closed_from`) may
/// close on it (`Dismiss.on_activate`). An activation in a popup opened from a field inside a menu leaves that menu
+5 -10
View File
@@ -145,8 +145,12 @@ impl State {
}
}
/// Registers a taker for next pass's split.
/// Registers a taker for next pass's split. A layer that fades out takes no input, so a taker in its body registers
/// none: it would hold the wheel over what already shows through it.
pub(crate) fn register(ctx: &Context, taker: WheelTaker<Id>) {
if crate::runtime::overlay::drawing_exiting(ctx) {
return;
}
crate::runtime::replay::journal(ctx, || move |ctx: &Context| register(ctx, taker));
PerViewport::<State>::with(ctx, pass::current_viewport(ctx), |state| state.this.push(taker));
}
@@ -195,7 +199,6 @@ pub(crate) fn begin(ctx: &Context) {
.map(|at| pointer::press_winner(ctx, at, pass_pointer.press_targets).map(|(winner, _)| winner.owner));
// A modal layer holds the wheel, except over the canvas it keeps open and inside its own family.
let blocked = hover.is_some_and(|at| !sampler::wheel_allowed(ctx, at));
let had_wheel = wheel_in.is_some();
let wake = PerViewport::<State>::with(ctx, viewport, |state| {
state.last = std::mem::take(&mut state.this);
state.shares.clear();
@@ -276,14 +279,6 @@ pub(crate) fn begin(ctx: &Context) {
}
// A value control that owns the running gesture hears its end without a timer of its own: a pass at the gap.
// An owed ease pays in the passes that follow.
if had_wheel {
eprintln!(
"DIAG popover::popup::the_wheel_over_an_open_popup_list_scrolls_the_list_and_not_the_surface_below: wheel hover {hover:?} blocked {blocked} by_position {by_position} gesture owner {:?} shares {:?} under {:?}",
state.gesture.owner,
state.shares.iter().map(|(owner, share)| (*owner, share.scroll)).collect::<Vec<_>>(),
state.last.iter().filter(|taker| hover.is_some_and(|at| taker.rect.contains(at))).collect::<Vec<_>>()
);
}
state.wake(now)
});
if let Some(seconds) = wake {
+4 -1
View File
@@ -189,11 +189,14 @@ impl Fixture {
let mut fixture = Fixture::new(move |ui| {
let number = shared_pass.get() + 1;
shared_pass.set(number);
let output = if shared_probed.get() {
// What fired before the story's code ran (a shortcut the input hook took) is not the story's.
crate::runtime::commands::observe_fired(ui.ctx());
let mut output = if shared_probed.get() {
probed_pass(ui, number, scope, show, &shared_data, &shared_delivers, &shared_impure)
} else {
shown(ui, scope, show, &shared_data)
};
output.fired = crate::runtime::commands::observe_fired(ui.ctx());
shared_root.set(output.id);
shared_outputs.borrow_mut().push(output);
});
+10 -1
View File
@@ -2,7 +2,7 @@
use super::Fixture;
use crate::contract::{CollectionEvent, Inner, Outcome, TooltipSpec};
use crate::runtime::commands::CommandInput;
use crate::runtime::commands::{CommandInput, CommandRef};
use craft_behavior::{EditEvent, EditEvents, PartKey, PartRef, Value};
use egui::{Id, Response, Ui, Vec2};
use std::any::{Any, TypeId};
@@ -507,6 +507,9 @@ pub struct StoryOutput {
pub edits: Vec<EditKind>,
/// The pass reported a click, by pointer or by keyboard activation.
pub clicked: bool,
/// The commands the story's pass fired, in order; the fixture that shows the story fills it in. A component bound
/// to a command reports its activation as the command it fires, not as a click.
pub fired: Vec<CommandRef>,
/// The collection events' kinds, in drawing order.
pub collection: Vec<CollectionKind>,
/// The positions a collection showed.
@@ -526,6 +529,12 @@ impl StoryOutput {
self
}
/// Whether the pass activated what the story shows: it reported a click, or it fired a command, as a component
/// bound to one does in place of the click.
pub fn activated(&self) -> bool {
self.clicked || !self.fired.is_empty()
}
pub(crate) fn from_response(response: &Response) -> Self {
StoryOutput { id: Some(response.id), clicked: super::contract::clicked(response), ..StoryOutput::default() }
}
@@ -41,7 +41,7 @@ fn each_activation_clicks_once(subject: &Subject) -> Result<(), String> {
let mut fixture = input_fixture(story);
fixture.take_outputs();
run(&mut fixture, plan, variant);
let clicks = fixture.take_outputs().iter().filter(|output| output.clicked).count();
let clicks = fixture.take_outputs().iter().filter(|output| output.activated()).count();
if clicks != 1 {
return Err(format!("{}: {} gave {clicks} clicks", story.name, variant_name(plan, variant)));
}
@@ -97,7 +97,7 @@ fn each_part_activates_once(subject: &Subject) -> Result<(), String> {
}
}
fixture.settle();
let clicks = fixture.take_outputs().iter().filter(|output| output.clicked).count();
let clicks = fixture.take_outputs().iter().filter(|output| output.activated()).count();
if clicks != 1 {
return Err(format!("{}: {name} on the part {part:?} gave {clicks} clicks", story.name));
}
@@ -145,7 +145,7 @@ fn declared_actions_are_handled(subject: &Subject) -> Result<(), String> {
fixture.access(kind, &target);
fixture.settle();
let outputs = fixture.take_outputs();
let acted = outputs.iter().any(|output| output.clicked || !output.edits.is_empty())
let acted = outputs.iter().any(|output| output.activated() || !output.edits.is_empty())
|| signature(fixture.tree()) != before
|| fixture.focused() != focus;
if !acted {
@@ -219,7 +219,7 @@ fn every_intent_has_a_declared_action(subject: &Subject) -> Result<(), String> {
_ => by_key,
});
let could_step = step.is_some_and(|step| if step == Declared::Increment { steps_before.0 } else { steps_before.1 });
let clicked = fixture.take_outputs().iter().any(|output| output.clicked);
let clicked = fixture.take_outputs().iter().any(|output| output.activated());
let changed = !lent && !fixture.data().changed_since(&before).is_empty();
let radios = fixture.tree().with_role(Role::RADIO_BUTTON);
let tree = fixture.tree();
@@ -305,7 +305,7 @@ fn escape_and_blur_cancel_a_press(subject: &Subject) -> Result<(), String> {
fixture.settle();
let outputs = fixture.take_outputs();
let ended = outputs.iter().flat_map(|output| output.edits.iter()).any(|kind| matches!(kind, EditKind::Commit | EditKind::Set));
if outputs.iter().any(|output| output.clicked) || ended || !fixture.data().changed_since(&before).is_empty() {
if outputs.iter().any(|output| output.activated()) || ended || !fixture.data().changed_since(&before).is_empty() {
return Err(format!("{}: a press cancelled by {} still acted", story.name, if escape { "Escape" } else { "blur" }));
}
}
@@ -332,7 +332,9 @@ fn removal_cancels_a_press(subject: &Subject) -> Result<(), String> {
if shared_hidden.get() {
return;
}
let output = show(ui, &mut shared_data.borrow_mut());
crate::runtime::commands::observe_fired(ui.ctx());
let mut output = show(ui, &mut shared_data.borrow_mut());
output.fired = crate::runtime::commands::observe_fired(ui.ctx());
shared_id.set(output.id);
shared_outputs.borrow_mut().push(output);
});
@@ -352,7 +354,7 @@ fn removal_cancels_a_press(subject: &Subject) -> Result<(), String> {
fixture.settle();
let outputs = std::mem::take(&mut *outputs.borrow_mut());
let ended = outputs.iter().flat_map(|output| output.edits.iter()).any(|kind| matches!(kind, EditKind::Commit | EditKind::Set));
if outputs.iter().any(|output| output.clicked) || ended || !data.borrow().changed_since(&before).is_empty() {
if outputs.iter().any(|output| output.activated()) || ended || !data.borrow().changed_since(&before).is_empty() {
return Err(format!("{}: a press whose component was not shown for a pass still acted on release", story.name));
}
}
@@ -47,7 +47,7 @@ fn slop_separates_click_from_drag(subject: &Subject) -> Result<(), String> {
let target = target(&fixture);
fixture.take_outputs();
gesture(&mut fixture, &target, by);
let clicks = fixture.take_outputs().iter().filter(|output| output.clicked).count();
let clicks = fixture.take_outputs().iter().filter(|output| output.activated()).count();
if clicks != expected {
return Err(format!("{}: a press moved {by} points (slop {slop}) gave {clicks} clicks, expected {expected}", story.name));
}
@@ -22,17 +22,17 @@ pub(super) const CASES: &[Case] = &[
Case::new("language", ANY, a_language_change_keeps_the_ids),
];
/// Whether the drive changed a value, reported an edit or reported a click.
/// Whether the drive changed a value, reported an edit or activated the story: a click or a fired command.
fn acted(fixture: &mut Fixture, before: &crate::testing::story::StorySnapshot) -> bool {
let changed = !fixture.data().changed_since(before).is_empty();
let outputs = fixture.take_outputs();
changed || outputs.iter().any(|output| output.clicked || !output.edits.is_empty())
changed || outputs.iter().any(|output| output.activated() || !output.edits.is_empty())
}
/// A disabled component changes no value, fires no command and takes no focus unless it explains itself: a node
/// with a description stands for the tooltip of `disabled_text`, and then its tooltip shows on focus. A description
/// also comes from an invalid state, so a disabled story that takes no focus is not read as lacking `disabled_text`.
/// A story with `disabled_text` is reached by Tab and shows that reason. A story binds no command, so a fired command is read as the pass's click, which a bound command follows.
/// A story with `disabled_text` is reached by Tab and shows that reason.
fn disabled_changes_nothing(subject: &Subject) -> Result<(), String> {
for story in &subject.stories {
let plan = subject.base(story).plan;
+12 -85
View File
@@ -2,16 +2,15 @@
use super::face::{self, FaceLook, FaceSpec};
use crate::contract::{Common, Component, Cx, LeastWidth, MeasureCx, NoValue, Outcome, PaintUi, PartsCx, Pointer as _, Props, Role, Styled as _};
use crate::display::{Kbd, Spinner};
use crate::display::Spinner;
use crate::primitives::{HAlign, IconSpec, PaintShape};
use crate::runtime::commands::CommandRef;
use crate::runtime::env::Label;
use crate::style::{ComponentStyle, DataColor, FocusLook, IconLook, StyleColor, StyleCx, SurfaceLook, TextLook, TypeRole};
use crate::text::FieldStyle;
use craft_behavior::{Flow, IconId, Metrics, PartKey, PressPhase, Sense};
use craft_behavior::{Metrics, PartKey, PressPhase, Sense};
use craft_keymap::Mods;
use craft_theme::{
Rgba, Stateful, States, Variant,
Rgba, Stateful, Variant,
variant::{Emphasis, Tone},
};
use egui::{Color32, Rect, Response, Vec2};
@@ -19,19 +18,6 @@ use std::ops::Deref;
/// The part a loading button shows its spinner in.
const SPINNER: PartKey = PartKey::new("spinner");
/// The part the Search face shows its command's chord in.
const CHORD: PartKey = PartKey::new("chord");
/// The form of a button's face.
#[non_exhaustive]
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub enum ButtonForm {
/// The ordinary push button.
#[default]
Push,
/// The command-search opener: a text field's face with the search glyph, the placeholder and the command's chord.
Search,
}
/// The style of a push button.
#[derive(Clone, Debug, PartialEq, ComponentStyle)]
@@ -70,24 +56,6 @@ impl ButtonStyle {
}
}
/// The style of the command-search opener: a text field's surface, padding and glyph, and the label in the
/// colour a field's placeholder takes.
fn search(cx: &StyleCx<'_>) -> ButtonStyle {
let field = FieldStyle::at(cx);
let text = &cx.tokens.color.text;
let (faint, off) = (cx.color(text.faint), cx.color(text.disabled));
ButtonStyle {
// A button carries no value, so it is never invalid: the well without the field's failure edge.
surface: cx.text_well(),
metrics: field.metrics(),
focus: face::focus(cx),
text: TextLook::new(TypeRole::Body, Stateful::new(faint).off(States::new(faint, faint, faint, off))),
icon: field.glyph().clone(),
face: FaceLook::of(cx),
overlay: cx.state_layer(),
}
}
/// The style of a button whose face is filled with `tint`: the label and icons read on it.
fn tinted(cx: &StyleCx<'_>, tint: Rgba) -> ButtonStyle {
let mut style = ButtonStyle::of(cx);
@@ -184,12 +152,6 @@ pub struct Button<'a> {
/// that names an item at the reading start).
#[prop]
align: HAlign,
/// The face: a push button, or the command-search opener.
#[style_key]
#[prop]
form: ButtonForm,
/// The command whose chord the Search face shows at its end.
chord: Option<CommandRef>,
}
impl<'a> Button<'a> {
@@ -204,39 +166,20 @@ impl<'a> Button<'a> {
tint: None,
least_width: None,
align: HAlign::Center,
form: ButtonForm::Push,
chord: None,
}
.label(label)
}
/// The command-search opener: a search field's face showing `placeholder` and the chord of `command`. The
/// placeholder is the button's name; cut to fit, it shows whole in the tooltip. A click, Enter or Space fires
/// `command`.
pub fn search(command: impl Into<CommandRef>, placeholder: impl Into<Label>) -> Self {
let command = command.into();
let mut button = Button::command(command.clone()).label(placeholder).form(ButtonForm::Search);
button.icon = Some(IconSpec::svg(IconId::new("search")));
button.align = HAlign::Start;
button.chord = Some(command);
button
}
/// A button bound to `command`: its label, enabled state and activation follow the command.
pub fn command(command: impl Into<CommandRef>) -> Self {
<Button as Props>::command(Button::new(Label::Empty), command)
}
/// The room the face's icons and label take: the content less the chord's slot, `chord` wide, and the gap before it.
fn face_area(content: Rect, rtl: bool, chord: f32, gap: f32) -> Rect {
if chord > 0.0 { Flow::new(content, rtl).take_end(chord + gap).1.rect() } else { content }
}
fn spec<'s>(&'s self, label: &'s str) -> FaceSpec<'s> {
let label = self.painted.as_ref().map_or(label, Label::as_str);
FaceSpec {
label,
role: (self.form == ButtonForm::Search).then_some(TypeRole::Body),
role: None,
lead: self.icon.as_ref(),
trail: self.trailing_icon.as_ref(),
loading: self.loading,
@@ -253,10 +196,9 @@ impl Component for Button<'_> {
type Output = ButtonOutput;
fn style(cx: &StyleCx<'_>, key: ButtonStyleKey) -> ButtonStyle {
let mut style = match (key.form, key.tint) {
(ButtonForm::Search, _) => ButtonStyle::search(cx),
(_, Some(tint)) => ButtonStyle::tinted(cx, tint),
(_, None) => ButtonStyle::of(cx),
let mut style = match key.tint {
Some(tint) => ButtonStyle::tinted(cx, tint),
None => ButtonStyle::of(cx),
};
if let Some(least) = key.least_width {
style.metrics.min_size.x = style.metrics.min_size.x.max(least.points(cx.tokens));
@@ -264,31 +206,21 @@ impl Component for Button<'_> {
style
}
/// The Search face adds the chord's room, which it keeps at its least too: the placeholder is cut first.
fn measure(&mut self, cx: &MeasureCx<'_, Self>) -> Vec2 {
let size = face::measure(cx, &self.spec(cx.resolved.label));
let chord = self.chord.as_ref().map_or(0.0, |command| cx.face(Kbd::command(command.clone())).x);
if chord > 0.0 { Vec2::new(size.x + cx.style.face.gap + chord, size.y) } else { size }
face::measure(cx, &self.spec(cx.resolved.label))
}
fn sense(&self) -> Sense {
if self.loading { Sense::FOCUS } else { Sense::CLICK | Sense::FOCUS }
}
/// The Search face declares the slot of its chord at the reading end, taken before the placeholder's room; a
/// loading button declares the slot of its spinner. Each paints as the face of its part.
/// A loading button declares the slot of its spinner, which paints as the face of its part.
fn parts(&mut self, _: Rect, cx: &mut PartsCx<'_, Self>) {
let (content, rtl) = (cx.content_rect, cx.flow.is_rtl());
let chord = self.chord.as_ref().map_or(0.0, |command| cx.face(Kbd::command(command.clone())).x);
if chord > 0.0 {
let (slot, _) = Flow::new(content, rtl).take_end(chord);
cx.part(CHORD, slot);
}
if !self.loading {
return;
}
let area = Self::face_area(content, rtl, chord, cx.style.face.gap);
let spinner = face::spinner_rect(cx, &self.spec(cx.resolved.label), &cx.style.face, cx.style.icon.side, area, rtl);
let (content, rtl) = (cx.content_rect, cx.flow.is_rtl());
let spinner = face::spinner_rect(cx, &self.spec(cx.resolved.label), &cx.style.face, cx.style.icon.side, content, rtl);
if let Some(rect) = spinner {
cx.part(SPINNER, rect);
}
@@ -312,12 +244,7 @@ impl Component for Button<'_> {
ui.draw().data_fill(&shape, DataColor::new(Color32::from(craft_theme::Srgba::from(tint))));
ui.draw().fill(&shape, cx.resolve(&cx.style.overlay));
}
let chord = cx.part_if_declared(CHORD).map_or(0.0, |part| part.rect.width());
let area = Self::face_area(cx.content_rect, cx.flow.is_rtl(), chord, cx.style.face.gap);
face::paint(ui, cx, (&cx.style.text, &cx.style.icon), &cx.style.face, &self.spec(cx.resolved.label), area);
if let (Some(command), true) = (&self.chord, chord > 0.0) {
ui.face(CHORD, Kbd::command(command.clone()));
}
face::paint(ui, cx, (&cx.style.text, &cx.style.icon), &cx.style.face, &self.spec(cx.resolved.label), cx.content_rect);
if cx.part_if_declared(SPINNER).is_some() {
ui.face(SPINNER, Spinner::new().size(cx.resolved.size));
}
@@ -0,0 +1,131 @@
//! `CommandSearch`: the command-search opener, a search field's face that fires its command.
use super::ButtonOutput;
use super::face::{self, FaceLook, FaceSpec};
use crate::contract::{Common, Component, Cx, MeasureCx, PaintUi, PartsCx, Pointer as _, Props as _, Role};
use crate::display::Kbd;
use crate::primitives::{HAlign, IconSpec};
use crate::runtime::commands::CommandRef;
use crate::runtime::env::Label;
use crate::style::{ComponentStyle, FocusLook, IconLook, StyleCx, SurfaceLook, TextLook, TypeRole};
use crate::text::FieldStyle;
use craft_behavior::{Flow, IconId, Metrics, PartKey, Sense};
use craft_theme::{Stateful, States};
use egui::{Rect, Vec2};
/// The part the opener shows its command's chord in.
const CHORD: PartKey = PartKey::new("chord");
/// The style of the command-search opener: a text field's surface, padding and glyph, and the placeholder in the
/// colour a field's placeholder takes.
#[derive(Clone, Debug, PartialEq, ComponentStyle)]
#[non_exhaustive]
pub struct CommandSearchStyle {
#[style(surface)]
surface: SurfaceLook,
#[style(metrics)]
metrics: Metrics,
#[style(focus)]
focus: FocusLook,
/// The placeholder.
#[style(text)]
text: TextLook,
/// The search glyph.
#[style(icon)]
icon: IconLook,
face: FaceLook,
}
/// The command-search opener: a search field's face showing the search glyph, a placeholder and the chord of its
/// command at the reading end. It takes no text: a click, Enter or Space fires the command, which opens the search.
/// The placeholder is its name; cut to fit, it shows whole in the tooltip, and the chord keeps its width.
#[derive(crate::contract::Component, crate::contract::Props)]
pub struct CommandSearch {
#[common]
common: Common,
glyph: IconSpec<'static>,
/// The command whose chord the face shows; the opener is bound to it.
chord: CommandRef,
}
impl CommandSearch {
/// An opener showing `placeholder` that fires `command`.
pub fn new(command: impl Into<CommandRef>, placeholder: impl Into<Label>) -> Self {
let command = command.into();
CommandSearch { common: Common::new(), glyph: IconSpec::svg(IconId::new("search")), chord: command.clone() }
.command(command)
.label(placeholder)
}
/// The room the glyph and placeholder take: the content less the chord's slot, `chord` wide, and the gap before it.
fn face_area(content: Rect, rtl: bool, chord: f32, gap: f32) -> Rect {
if chord > 0.0 { Flow::new(content, rtl).take_end(chord + gap).1.rect() } else { content }
}
fn spec<'s>(&'s self, label: &'s str) -> FaceSpec<'s> {
FaceSpec { label, role: Some(TypeRole::Body), lead: Some(&self.glyph), trail: None, loading: false, mnemonic: None, align: HAlign::Start }
}
}
impl Component for CommandSearch {
const ROLE: Role = Role::BUTTON;
const OVERLAYS: bool = false;
type Style = CommandSearchStyle;
type Output = ButtonOutput;
fn style(cx: &StyleCx<'_>, _: CommandSearchStyleKey) -> CommandSearchStyle {
let field = FieldStyle::at(cx);
let text = &cx.tokens.color.text;
let (faint, off) = (cx.color(text.faint), cx.color(text.disabled));
CommandSearchStyle {
// The opener carries no value, so it is never invalid: the well without the field's failure edge.
surface: cx.text_well(),
metrics: field.metrics(),
focus: face::focus(cx),
text: TextLook::new(TypeRole::Body, Stateful::new(faint).off(States::new(faint, faint, faint, off))),
icon: field.glyph().clone(),
face: FaceLook::of(cx),
}
}
/// The chord's room is kept at the least width too: the placeholder is cut first.
fn measure(&mut self, cx: &MeasureCx<'_, Self>) -> Vec2 {
let size = face::measure(cx, &self.spec(cx.resolved.label));
let chord = cx.face(Kbd::command(self.chord.clone())).x;
if chord > 0.0 { Vec2::new(size.x + cx.style.face.gap + chord, size.y) } else { size }
}
fn sense(&self) -> Sense {
Sense::CLICK | Sense::FOCUS
}
/// The chord's slot at the reading end, taken before the placeholder's room; it paints as the face of its part.
fn parts(&mut self, _: Rect, cx: &mut PartsCx<'_, Self>) {
let chord = cx.face(Kbd::command(self.chord.clone())).x;
if chord > 0.0 {
let (slot, _) = Flow::new(cx.content_rect, cx.flow.is_rtl()).take_end(chord);
cx.part(CHORD, slot);
}
}
fn update(&mut self, cx: &mut Cx<'_, Self>) {
cx.join_roving();
}
fn activated(&self, cx: &Cx<'_, Self>) -> bool {
cx.activation().is_some()
}
fn paint(&mut self, ui: &mut PaintUi<'_>, cx: &Cx<'_, Self>) {
let chord = cx.part_if_declared(CHORD).map_or(0.0, |part| part.rect.width());
let area = Self::face_area(cx.content_rect, cx.flow.is_rtl(), chord, cx.style.face.gap);
face::paint(ui, cx, (&cx.style.text, &cx.style.icon), &cx.style.face, &self.spec(cx.resolved.label), area);
if chord > 0.0 {
ui.face(CHORD, Kbd::command(self.chord.clone()));
}
}
fn finish(self, cx: Cx<'_, Self>) -> ButtonOutput {
ButtonOutput::of(&cx, self.activated(&cx))
}
}
+1 -5
View File
@@ -29,11 +29,7 @@ pub(crate) struct MarkerStyle {
impl MarkerStyle {
/// The marker look from the tokens.
pub(crate) fn of(cx: &StyleCx<'_>) -> MarkerStyle {
MarkerStyle {
side: cx.tokens.size.handle.sm,
color: cx.color(cx.tokens.color.accent.solid),
edge: cx.color(cx.tokens.color.line.mark),
}
MarkerStyle { side: cx.tokens.size.handle.sm, color: cx.color(cx.tokens.color.accent.solid), edge: cx.color(cx.tokens.color.line.mark) }
}
}
+4 -2
View File
@@ -1,6 +1,7 @@
//! `Button`, `IconButton`, `ToggleButton`, `SplitButton` and `Link`.
//! `Button`, `IconButton`, `ToggleButton`, `SplitButton`, `Link` and `CommandSearch`.
pub mod button;
pub mod command_search;
pub(crate) mod face;
pub mod icon_button;
pub mod link;
@@ -10,7 +11,8 @@ mod stories;
pub mod toggle_button;
mod words;
pub use button::{Button, ButtonForm, ButtonOutput, ButtonStyle};
pub use button::{Button, ButtonOutput, ButtonStyle};
pub use command_search::{CommandSearch, CommandSearchStyle};
pub use icon_button::{IconButton, IconButtonStyle, PopupMark};
pub use link::{Link, LinkStyle};
pub use split_button::{SplitButton, SplitButtonStyle, SplitOutput};
+14 -15
View File
@@ -1,6 +1,6 @@
//! Stories of the buttons.
use super::{Button, IconButton, Link, SplitButton, ToggleButton};
use super::{Button, CommandSearch, IconButton, Link, SplitButton, ToggleButton};
use crate::contract::{Bind, Entry, Props as _, Show as _, ShowContainer as _, Validity};
use crate::display::{Shade, Text};
use crate::layout_components::{Grid, Row};
@@ -78,30 +78,29 @@ enum SearchStoryCommand {
Open,
}
/// The command-search opener: the search glyph, the placeholder and the chord of its command at the end. A command-bound
/// button reports no click (the command fires instead), so the click-counting drive does not apply.
#[story(Button<'static>, covers = [], drive = Drive::Never, group = "Playground", title = "Search")]
fn button_search(ui: &mut Ui, _: &mut StoryData) -> StoryOutput {
Button::search(SearchStoryCommand::Open, "Search commands and settings").show(ui).into()
/// The command-search opener: the search glyph, the placeholder and the chord of its command at the end.
#[story(CommandSearch, covers = [Default])]
fn command_search(ui: &mut Ui, _: &mut StoryData) -> StoryOutput {
CommandSearch::new(SearchStoryCommand::Open, "Search commands and settings").show(ui).into()
}
/// In a narrow room the chord keeps its width and the placeholder is cut; the tooltip shows it whole.
#[story(Button<'static>, covers = [], drive = Drive::Never, group = "Playground", title = "Search, narrow")]
fn button_search_narrow(ui: &mut Ui, _: &mut StoryData) -> StoryOutput {
#[story(CommandSearch, covers = [LongText], drive = Drive::Never, title = "Narrow")]
fn command_search_narrow(ui: &mut Ui, _: &mut StoryData) -> StoryOutput {
ui.set_max_width(ui.available_width() * 0.3);
Button::search(SearchStoryCommand::Open, "Search commands and settings").show(ui).into()
CommandSearch::new(SearchStoryCommand::Open, "Search commands and settings").show(ui).into()
}
#[story(Button<'static>, covers = [], drive = Drive::Never, group = "Playground", title = "Search, disabled")]
fn button_search_disabled(ui: &mut Ui, _: &mut StoryData) -> StoryOutput {
Button::search(SearchStoryCommand::Open, "Search commands and settings").enabled(false).show(ui).into()
#[story(CommandSearch, covers = [], drive = Drive::Never, title = "Disabled")]
fn command_search_disabled(ui: &mut Ui, _: &mut StoryData) -> StoryOutput {
CommandSearch::new(SearchStoryCommand::Open, "Search commands and settings").enabled(false).show(ui).into()
}
/// A right-to-left placeholder: the glyph at the reading start and the chord, which keeps its left-to-right order, at
/// the reading end.
#[story(Button<'static>, covers = [], drive = Drive::Never, group = "Right to left", title = "Search")]
fn button_search_rtl(ui: &mut Ui, _: &mut StoryData) -> StoryOutput {
Button::search(SearchStoryCommand::Open, "חיפוש פקודות והגדרות").show(ui).into()
#[story(CommandSearch, covers = [], drive = Drive::Never, group = "Right to left", title = "Right to left")]
fn command_search_rtl(ui: &mut Ui, _: &mut StoryData) -> StoryOutput {
CommandSearch::new(SearchStoryCommand::Open, "חיפוש פקודות והגדרות").show(ui).into()
}
#[story(IconButton<'static>, covers = [Default])]
+12 -6
View File
@@ -152,6 +152,10 @@ fn the_wheel_over_an_open_popup_list_scrolls_the_list_and_not_the_surface_below(
open.set(false);
fixture.settle();
let on_page = fixture.by_label("Page 4").expect("the page shows its buttons").rect.center();
eprintln!(
"DIAG popover::popup::the_wheel_over_an_open_popup_list_scrolls_the_list_and_not_the_surface_below: after the close still animating {}",
fixture.repaint_requested()
);
fixture.frame(vec![pointer::moved(on_page)]);
fixture.frame(vec![pointer::wheel(-60.0)]);
eprintln!(
@@ -170,19 +174,21 @@ fn the_wheel_over_an_open_popup_list_scrolls_the_list_and_not_the_surface_below(
}
/// A pointer resting on the list keeps no hold on the lead: End scrolls another row under it, and Enter picks the row
/// End went to.
/// End went to. The list keys reach the list through its opener's key focus; a click gives a button none, so the
/// opener is reached by Tab.
#[trial]
fn a_resting_pointer_leaves_the_lead_where_the_keys_moved_it() {
let open = Rc::new(Cell::new(false));
let activated = Rc::new(RefCell::new(Vec::new()));
let mut fixture = page(Rc::clone(&open), Rc::clone(&activated));
let opener = fixture.by_label("Open").expect("the opener shows");
fixture.click(&opener).settle();
assert!(open.get(), "a click on the opener opens the list");
fixture.key(Key::Tab, Modifiers::NONE).settle();
fixture.key(Key::Space, Modifiers::NONE).settle();
assert!(open.get(), "Space on the focused opener opens the list");
eprintln!(
"DIAG popover::popup::a_resting_pointer_leaves_the_lead_where_the_keys_moved_it: after the click focused {:?} stop {:?}",
"DIAG popover::popup::a_resting_pointer_leaves_the_lead_where_the_keys_moved_it: after Space focused {:?} stop {:?} opener {:?}",
fixture.focused(),
fixture.focused_stop()
fixture.focused_stop(),
fixture.by_label("Open").map(|shown| shown.node)
);
let rest = fixture.by_label(&row(3)).expect("the list shows its fourth row").rect.center();
fixture.frame(vec![pointer::moved(rest)]).settle();
@@ -88,14 +88,10 @@ fn wrapped_right_to_left_lines_align_to_the_right_edge() {
})
.collect();
let right = spans.iter().map(|(_, right)| *right).fold(f32::NEG_INFINITY, f32::max);
for ((left, end), (top, text, glyphs)) in spans.iter().zip(&rows) {
let outer = glyphs.iter().filter(|(chr, ..)| !chr.is_whitespace()).max_by(|a, b| (a.1 + a.2).total_cmp(&(b.1 + b.2)));
eprintln!(
"DIAG text::rtl_paragraph::wrapped_right_to_left_lines_align_to_the_right_edge: top {top} span {left}..{end} rightmost ink glyph {outer:?} text {text:?}"
);
}
// Glyphs are placed on whole device pixels and their advances are not, so line ends differ by under a pixel.
let pixel = 1.0 / fixture.ctx().pixels_per_point();
for ((left, end), (_, text, _)) in spans.iter().zip(&rows) {
assert!((end - right).abs() < 0.5, "{text:?} ends at the right edge {right}: {end}");
assert!((end - right).abs() <= pixel, "{text:?} ends at the right edge {right}: {end}");
assert!(*left >= -0.5, "{text:?} stays inside the column: {left}");
}
assert!(right <= WIDTH + 0.5, "the lines stay inside the column: {right}");