Merge pull request #3479 from dotCooCoo/fix/widgets-focus-ring

ui-widgets: focused notice, bar, row, chip, tile, slider, tab strip end and table header parts show the focus ring
This commit is contained in:
BFlat
2026-11-26 09:55:55 +07:00
committed by GitHub
15 changed files with 143 additions and 23 deletions
+1 -1
View File
@@ -1266,7 +1266,7 @@ fn paint_step(p: &mut Pass<'_, '_, '_>, ui: &mut Ui, env: &Env, h: &mut HostStep
e.content_env(&mut h.values);
steps::unfade(ui, e.core(), fade);
ui.set_clip_rect(h.outer_clip);
steps::paint_focus(ui, e.core_ref(), p.style);
steps::paint_focus(ui, e.core_ref(), p.style, e.shape() != ShapeKind::Item);
// A rule a bar's view shows waits for the member after it.
if let Some((line, from)) = rule_from {
hold_rule(ui, line, from);
@@ -114,8 +114,8 @@ pub(crate) fn paint_part_layers(ui: &Ui, env: &Env, core: &CxCore<'_>) {
/// Step 13, paint, after `C::paint`: the focus ring of the focused component or its active part, when focus is
/// keyboard-visible. An active part's ring takes the shape the part declared (`focus_shape`), else its rect; the
/// component's own ring takes the shape it declared (`Cx::focus_shape`), else its rect with its surface's corners. Never
/// on `Well` surfaces.
pub(crate) fn paint_focus(ui: &Ui, core: &CxCore<'_>, style: &dyn StyleView) {
/// on `Well` surfaces, and never around a collection (`whole` false), whose lead item shows the focus.
pub(crate) fn paint_focus(ui: &Ui, core: &CxCore<'_>, style: &dyn StyleView, whole: bool) {
let Some(look) = style.focus() else { return };
let ppp = ui.ctx().pixels_per_point();
let flags = core.state.flags;
@@ -125,7 +125,7 @@ pub(crate) fn paint_focus(ui: &Ui, core: &CxCore<'_>, style: &dyn StyleView) {
let declared = core.focus_shapes.iter().find(|((key, index), _)| craft_behavior::PartRef { key: *key, index: *index } == part);
let outline = declared.map_or(PaintShape::Rect(rect, egui::CornerRadius::ZERO), |(_, shape)| FocusRing::outline(shape, rect));
ui.painter().extend(FocusRing::shapes(look, FocusKind::Ring, &outline, ppp));
} else if FocusRing::visible(flags) && !well {
} else if whole && FocusRing::visible(flags) && !well {
let outline = match &core.focus_shape {
Some(shape) => FocusRing::outline(shape, core.rect),
None => PaintShape::Rect(core.rect, style.surface().map_or(egui::CornerRadius::ZERO, |surface| surface.radius)),
+5 -2
View File
@@ -11,7 +11,7 @@ use crate::menu::{Menu, MenuItem};
use crate::primitives::IconSpec;
use crate::runtime::commands::{CommandRef, ResolvedCommand};
use crate::runtime::env::Label;
use crate::style::{ComponentStyle, GlyphRole, StyleCx};
use crate::style::{ComponentStyle, FocusLook, GlyphRole, StyleCx};
use craft_behavior::fit::{FitItem, FitKeep, fit_items};
use craft_behavior::{Axis, IconId, Metrics, NavShape, PartKey, PartRef, Proposal, Roving, Sense};
use craft_theme::Variant;
@@ -89,11 +89,13 @@ impl BarItem {
/// The style of a bar item strip: the gap between items, the space around the rule of a section change and the
/// space between the groups of a vertical strip.
#[derive(Clone, Debug, Default, PartialEq, ComponentStyle)]
#[derive(Clone, Debug, PartialEq, ComponentStyle)]
#[non_exhaustive]
pub struct BarItemsStyle {
#[style(metrics)]
metrics: Metrics,
#[style(focus)]
focus: FocusLook,
/// Between an item and the rule of a section change.
joint: f32,
/// The clear space of a section change, on both sides of its rule together.
@@ -305,6 +307,7 @@ impl Component for BarItems {
let gap = cx.tokens.space.gap.inline;
BarItemsStyle {
metrics: Metrics::new().gap(gap),
focus: cx.focus_look(),
joint: gap,
section_gap: gap * 2.0,
stack_gap: gap + cx.tokens.space.gap.stack,
+1
View File
@@ -90,6 +90,7 @@ impl Component for ListRow<'_> {
surface,
// A separator is as high as its rule and the room around it.
metrics: Metrics::new().min_size(Vec2::new(0.0, if key.separator { 0.0 } else { sizes.row })).gap(sizes.gap),
focus: cx.focus_look(),
text: TextLook::new(role, ink(base)),
icon: IconLook::new(
sizes.icon,
+3 -1
View File
@@ -2,7 +2,7 @@
use super::placement::Sizes;
use crate::display::divider::SeparatorRule;
use crate::style::{ComponentStyle, DataColor, Flags, IconLook, StyleColor, StyleCx, SurfaceLook, TextLook};
use crate::style::{ComponentStyle, DataColor, Flags, FocusLook, IconLook, StyleColor, StyleCx, SurfaceLook, TextLook};
use craft_behavior::Metrics;
use craft_theme::{Contrast, Rgba, Stateful, States, contrast_ratio, identifiable_outline, over};
@@ -17,6 +17,8 @@ pub struct ListRowStyle {
pub(super) surface: SurfaceLook,
#[style(metrics)]
pub(super) metrics: Metrics,
#[style(focus)]
pub(super) focus: FocusLook,
/// The label.
#[style(text)]
pub(super) text: TextLook,
+4 -1
View File
@@ -11,7 +11,7 @@ use crate::contract::{
use crate::primitives::{HAlign, IconSpec, TextRun, Wrap};
use crate::runtime::commands::CommandRef;
use crate::runtime::env::{EnvView, Label};
use crate::style::{ComponentStyle, IconLook, Insets, StyleColor, StyleCx, SurfaceKind, SurfaceLook, TextLook, TypeRole, UiTokens};
use crate::style::{ComponentStyle, FocusLook, IconLook, Insets, StyleColor, StyleCx, SurfaceKind, SurfaceLook, TextLook, TypeRole, UiTokens};
use craft_behavior::{Flow, IconId, Metrics, NavShape, PartKey, Proposal, Roving, Sense};
use craft_i18n::Format;
use craft_theme::{Rgba, Stateful, States, Variant, variant::Tone};
@@ -135,6 +135,8 @@ pub struct NoticeStyle {
surface: SurfaceLook,
#[style(metrics)]
metrics: Metrics,
#[style(focus)]
focus: FocusLook,
/// The title's role and colour.
#[style(text)]
title: TextLook,
@@ -581,6 +583,7 @@ impl Component for Notice<'_> {
NoticeStyle {
surface,
metrics: Metrics::new().padding(padding).gap(control.gap),
focus: cx.focus_look(),
title,
brand,
byline,
+7 -5
View File
@@ -13,7 +13,7 @@ use crate::display::Divider;
use crate::list::{DropTest, ListRow, RowEvent, RowTest, RowText};
use crate::menu::{Menu, MenuItem};
use crate::runtime::env::Label;
use crate::style::{ComponentStyle, StyleCx};
use crate::style::{ComponentStyle, FocusLook, StyleCx};
use craft_behavior::{ColumnKey, ItemSource, Metrics, Selection, SpanLayout};
use egui::{Rect, Ui};
use std::hash::Hash;
@@ -21,12 +21,14 @@ use std::hash::Hash;
/// The header menu's popup.
const HEADER_MENU: &str = "header_menu";
/// The style of the table: it has no look of its own beyond its container's surface.
#[derive(Clone, Debug, Default, PartialEq, ComponentStyle)]
/// The style of the table: the focus ring of its header cells, and no other look beyond its container's surface.
#[derive(Clone, Debug, PartialEq, ComponentStyle)]
#[non_exhaustive]
pub struct TableStyle {
#[style(metrics)]
metrics: Metrics,
#[style(focus)]
focus: FocusLook,
}
/// A table: one Tab stop, a header row over the columns, the selection rules of the collection contract, type-ahead on
@@ -134,8 +136,8 @@ impl<K: Clone + Eq + Hash + Send + Sync + 'static> Component for Table<'_, K> {
type Style = TableStyle;
type Output = CollectionResponse<K, RowEvent>;
fn style(_: &StyleCx<'_>, _: TableStyleKey<K>) -> TableStyle {
TableStyle::default()
fn style(cx: &StyleCx<'_>, _: TableStyleKey<K>) -> TableStyle {
TableStyle { metrics: Metrics::default(), focus: cx.focus_look() }
}
fn update(&mut self, cx: &mut Cx<'_, Self>) {
+5 -2
View File
@@ -29,7 +29,7 @@ use crate::menu::Menu;
use crate::primitives::{PaintShape, StrokeWidth};
use crate::runtime::commands::FireSource;
use crate::runtime::env::Label;
use crate::style::{ComponentStyle, StyleColor, StyleCx};
use crate::style::{ComponentStyle, FocusLook, StyleColor, StyleCx};
use craft_behavior::fit::{FitItem, fit_items};
use craft_behavior::{
Flow, HitLevel, HitPriority, IconId, Insets, ItemLayout, ItemSource, Metrics, NavShape, PartKey, PressPhase, ScrollPos, Selection,
@@ -122,12 +122,14 @@ fn strip_lead(kind: TabKind, tokens: &crate::style::UiTokens) -> f32 {
if kind == TabKind::Ribbon { tokens.space.pad.regular } else { 0.0 }
}
/// The look of a strip: it has none of its own; its row is as high as its tabs.
/// The look of a strip: the focus ring of its end items; its row is as high as its tabs.
#[derive(Clone, Debug, PartialEq, ComponentStyle)]
#[non_exhaustive]
pub struct TabStripStyle {
#[style(metrics)]
metrics: Metrics,
#[style(focus)]
focus: FocusLook,
/// The text line a wheel notch given in lines counts.
line: f32,
/// The colour of the one underline a ribbon strip slides under its shown tab.
@@ -827,6 +829,7 @@ impl<K: Clone + Eq + Hash + Send + Sync + std::fmt::Debug + 'static> Component f
let (lead, side) = (strip_lead(key.kind, tokens), if ribbon { super::tab::ribbon_pad(tokens) - tokens.stroke.thick / 2.0 } else { 0.0 });
TabStripStyle {
metrics: Metrics::new().padding(Insets::new(lead, 0.0, 0.0, 0.0)),
focus: cx.focus_look(),
line: tokens.typography.body.line_height,
underline: cx.color(tokens.color.accent.solid),
underline_inset: tokens.stroke.thick / 2.0,
+4 -2
View File
@@ -10,7 +10,7 @@ use crate::contract::{
};
use crate::primitives::{TextOptions, TextRun};
use crate::runtime::env::Label;
use crate::style::{ComponentStyle, Flags, StyleCx, SurfaceLook};
use crate::style::{ComponentStyle, Flags, FocusLook, StyleCx, SurfaceLook};
use craft_behavior::{Codec, Metrics, Mixed, NotAValue, PartKey, Proposal, Sense};
use egui::{Rect, Vec2, pos2, vec2};
use std::borrow::Cow;
@@ -104,6 +104,8 @@ pub struct AltTextFieldStyle {
surface: SurfaceLook,
#[style(metrics)]
metrics: Metrics,
#[style(focus)]
focus: FocusLook,
}
/// An alt text editor: a multi-line description box and a Mark as decorative check. While the check is on, the box
@@ -148,7 +150,7 @@ impl Component for AltTextField<'_> {
fn style(cx: &StyleCx<'_>, _: AltTextFieldStyleKey) -> AltTextFieldStyle {
let field = FieldStyle::at(cx);
AltTextFieldStyle { surface: field.surface, metrics: field.metrics.gap(cx.control().gap) }
AltTextFieldStyle { surface: field.surface, metrics: field.metrics.gap(cx.control().gap), focus: cx.focus_look() }
}
fn sense(&self) -> Sense {
+9 -2
View File
@@ -14,7 +14,7 @@ use crate::display::Badge;
use crate::menu::Menu;
use crate::primitives::TextOptions;
use crate::runtime::env::Label;
use crate::style::{ComponentStyle, StyleCx, SurfaceLook};
use crate::style::{ComponentStyle, FocusLook, StyleCx, SurfaceLook};
use craft_behavior::{Caret, Codec, Flow, Granularity, IconId, Intent, Metrics, NavShape, NotAValue, PartKey, Proposal, Roving, Sense};
use craft_theme::Variant;
use egui::{Rect, Response, Vec2, pos2, vec2};
@@ -105,6 +105,8 @@ pub struct ChipFieldStyle {
surface: SurfaceLook,
#[style(metrics)]
metrics: Metrics,
#[style(focus)]
focus: FocusLook,
/// The least width of the draft, so a full line of chips still leaves room to type.
draft_min: f32,
}
@@ -334,7 +336,12 @@ impl Component for ChipField<'_> {
fn style(cx: &StyleCx<'_>, _: ChipFieldStyleKey) -> ChipFieldStyle {
let field = FieldStyle::at(cx);
ChipFieldStyle { surface: field.surface, metrics: field.metrics.gap(cx.control().gap), draft_min: cx.tokens.size.length.short }
ChipFieldStyle {
surface: field.surface,
metrics: field.metrics.gap(cx.control().gap),
focus: cx.focus_look(),
draft_min: cx.tokens.size.length.short,
}
}
fn sense(&self) -> Sense {
+4 -1
View File
@@ -24,7 +24,7 @@ use crate::primitives::{IconSpec, PaintShape, RectSide, StrokeWidth};
use crate::runtime::access::Name;
use crate::runtime::commands::FireSource;
use crate::runtime::env::Label;
use crate::style::{ComponentStyle, RuleKind, StyleColor, StyleCx};
use crate::style::{ComponentStyle, FocusLook, RuleKind, StyleColor, StyleCx};
use craft_behavior::{
ColumnKey, ColumnWidth, EditEvent, HitLevel, HitPriority, Intent, ItemLayout as _, ItemSource, Metrics, Mixed, NavShape, PartKey, PointerButton,
PressPhase, Roving, Selection, Sense,
@@ -154,6 +154,8 @@ impl<K> Outcome for TileGridOutput<K> {
pub struct TileGridStyle {
#[style(metrics)]
metrics: Metrics,
#[style(focus)]
focus: FocusLook,
/// A header pinned over its group's tiles.
pinned: StyleColor,
/// The look of a group header: a heading row, which places the disclosure the grid declares.
@@ -668,6 +670,7 @@ impl<K: Clone + Eq + Hash + Send + Sync + 'static> Component for TileGrid<'_, K>
fn style(cx: &StyleCx<'_>, _: TileGridStyleKey<K>) -> TileGridStyle {
TileGridStyle {
metrics: Metrics::new(),
focus: cx.focus_look(),
pinned: cx.color(cx.tokens.color.surface.panel),
header: ListRow::style(cx, ListRow::new(Label::default()).heading().style_key()),
insert: cx.color(cx.tokens.color.accent.solid),
+4 -2
View File
@@ -6,7 +6,7 @@ use crate::contract::{
Access, Bind, Common, Component, Cx, Edit as _, EditResponse, MeasureCx, Name, PaintUi, PartsCx, Props as _, Role, WordSetCx as _,
};
use crate::runtime::env::Label;
use crate::style::{ComponentStyle, StyleCx};
use crate::style::{ComponentStyle, FocusLook, StyleCx};
use craft_behavior::{IconId, Metrics, Mixed, NavShape, PartKey, Roving, Sense};
use egui::{Rect, Vec2};
use std::ops::RangeInclusive;
@@ -106,6 +106,8 @@ const LARGER_ICON: &str = "grid";
pub struct ThumbnailSliderStyle {
#[style(metrics)]
metrics: Metrics,
#[style(focus)]
focus: FocusLook,
}
/// Where the thumbnail slider's three controls lie.
@@ -152,7 +154,7 @@ impl Component for ThumbnailSlider<'_> {
type Output = EditResponse<f64>;
fn style(cx: &StyleCx<'_>, _: ThumbnailSliderStyleKey) -> ThumbnailSliderStyle {
ThumbnailSliderStyle { metrics: Metrics::new().gap(cx.control().gap) }
ThumbnailSliderStyle { metrics: Metrics::new().gap(cx.control().gap), focus: cx.focus_look() }
}
fn sense(&self) -> Sense {
+5 -1
View File
@@ -21,7 +21,8 @@ use crate::primitives::{ContentPainterCx, HAlign, IconSpec, PaintShape, StrokeWi
use crate::runtime::commands::CommandRef;
use crate::runtime::env::{Label, Units};
use crate::style::{
ComponentStyle, Corners, DataColor, Flags, IconLook, StyleColor, StyleCx, SurfaceEdge, SurfaceKind, SurfaceLook, SurfaceStyle, TextLook, UiTokens,
ComponentStyle, Corners, DataColor, Flags, FocusLook, IconLook, StyleColor, StyleCx, SurfaceEdge, SurfaceKind, SurfaceLook, SurfaceStyle,
TextLook, UiTokens,
};
use craft_behavior::{AccessAction, AccessData, Flow, IconId, Insets, Metrics, Mixed, NavShape, PartKey, PressPhase, Proposal, Roving, Sense};
use craft_keymap::Mods;
@@ -243,6 +244,8 @@ pub struct TileStyle {
surface: SurfaceLook,
#[style(metrics)]
metrics: Metrics,
#[style(focus)]
focus: FocusLook,
/// The name.
#[style(text)]
name: TextLook,
@@ -896,6 +899,7 @@ impl Component for Tile<'_> {
sizes.inset,
))
.gap(sizes.tight),
focus: cx.focus_look(),
name: if key.card {
TextLook::new(key.card_text.name_role(), ink(c(text.normal)))
} else {
+1
View File
@@ -22,6 +22,7 @@ pub(crate) mod list;
pub(crate) mod menu;
pub(crate) mod notices;
pub(crate) mod overlay;
pub(crate) mod part_rings;
pub(crate) mod pickers;
pub(crate) mod picture;
pub(crate) mod popover;
+87
View File
@@ -0,0 +1,87 @@
//! The focus ring of focusable parts: Tab to each part of a story and the paint step rings it, as it rings a button.
//! A collection rings its focused parts but not itself, since its lead item shows the focus.
use craft_behavior::PartKey;
use craft_ui::testing::{Fixture, Registry, trial};
use egui::{Key, Modifiers, Rect, Shape};
/// The story named `name`, settled.
fn story(name: &str) -> Fixture {
let registry = Registry::of(&[crate::register, craft_ui::testing::register]);
let _ = registry.install_story_sets();
let entry = registry.stories().iter().find(|entry| entry.story.name == name).unwrap_or_else(|| panic!("a story named {name}"));
let mut fixture = Fixture::story(&entry.story);
fixture.settle();
fixture
}
/// Presses Tab until the stop `part` (`None` for a component's own stop) holds the focus, and returns its rect.
fn tab_to(fixture: &mut Fixture, part: Option<&'static str>) -> Option<Rect> {
let wanted = part.map(PartKey::new);
for _ in 0..24 {
fixture.key(Key::Tab, Modifiers::NONE).settle();
let Some((owner, focused)) = fixture.focused_stop() else { continue };
if focused.map(|focused| focused.key) != wanted {
continue;
}
return match focused {
Some(focused) => fixture.part_rect(owner, focused),
None => fixture.node_of(owner).map(|target| target.rect),
};
}
None
}
/// Whether the latest frame paints a focus ring (a rectangle stroke at least two points wide) around `target`.
fn ringed(fixture: &mut Fixture, target: Rect) -> bool {
fixture.frame_shapes().iter().any(|shape| match shape {
Shape::Rect(rect) if rect.stroke.width >= 2.0 => rect.rect.expand(1.0).contains_rect(target),
_ => false,
})
}
/// Each focusable part, and each control that is its own stop, is ringed when Tab reaches it.
#[trial]
fn focused_parts_show_the_focus_ring() {
const STOPS: &[(&str, Option<&str>)] = &[
("notice", Some("action")),
("toast_stack", Some("dismiss")),
("bar_items", Some("item")),
("list_row", None),
("list_row_trailing_items", Some("trailing")),
("list_row_status_cell", Some("status-action")),
("list_row_thumbnails_only", Some("link")),
("chip_field", Some("chip")),
("alt_text_field", Some("decorative")),
("tile", None),
("tile_actions", Some("action")),
("tile_grid_insert_gaps", Some("insert_gap")),
("thumbnail_slider", Some("out")),
("tab_strip_ribbon_end_items", Some("end")),
("table_one", Some("header")),
("table_editable_grid", Some("header_remove")),
];
let mut unringed = Vec::new();
for &(name, part) in STOPS {
let mut fixture = story(name);
let rect = tab_to(&mut fixture, part).unwrap_or_else(|| panic!("Tab reaches {part:?} in {name}"));
if !ringed(&mut fixture, rect) {
unringed.push(format!("{name} {part:?}"));
}
}
assert!(unringed.is_empty(), "these focused stops show no ring: {unringed:?}");
}
/// A focused collection draws no ring around itself: its lead item shows the focus.
#[trial]
fn a_focused_collection_draws_no_ring_around_itself() {
let mut ringed_whole = Vec::new();
for name in ["tab_strip_ribbon_end_items", "table_one", "tile_grid_insert_gaps"] {
let mut fixture = story(name);
let rect = tab_to(&mut fixture, None).unwrap_or_else(|| panic!("Tab reaches the collection in {name}"));
if ringed(&mut fixture, rect) {
ringed_whole.push(name);
}
}
assert!(ringed_whole.is_empty(), "these collections ring themselves: {ringed_whole:?}");
}