LightCraft: An open-source non-destructive photo editor written by scratch in pure Rust
LR-LIB-RATING: keep arrow keys on a focused star, draw its ring
Nathaniel Ledford0e04000f60d1
diff --git a/crates/ui-egui/src/panels/mask_effects.rs b/crates/ui-egui/src/panels/mask_effects.rsindex 6062d241c..ef17bfba0 100644--- a/crates/ui-egui/src/panels/mask_effects.rs+++ b/crates/ui-egui/src/panels/mask_effects.rs@@ -237,7 +237,12 @@ fn menu(app: &mut LightcraftApp, ui: &mut egui::Ui, mask: &Mask, current: Optionlet elided = g.elided;ui.painter().galley(rect.left_center() + vec2(18.0, -g.size().y / 2.0), g, t.text);if fav {- ui.painter().text(rect.right_center() - vec2(4.0, 0.0), egui::Align2::RIGHT_CENTER, "★", t.font(11.0), t.text_dim);+ crate::rating::paint_star(+ ui.painter(),+ egui::Rect::from_center_size(rect.right_center() - vec2(10.0, 0.0), vec2(11.0, 11.0)),+ true,+ t.text_dim,+ );}if moved && st.highlight == Some(i) {resp.scroll_to_me(None);@@ -522,10 +527,7 @@ pub fn manage_body(for e in list {let sel = selected.contains(&e.name);ui.horizontal(|ui| {- let star = ui.add(egui::Button::new(if e.favorite { "★" } else { "☆" }).frame(false)).on_hover_text(crate::i18n::tr("Favorite"));- if ui.is_rect_visible(star.rect) {- register(ui.ctx(), format!("effectStar:{}", e.name), star.rect);- }+ let star = crate::rating::favorite_button(ui, format!("effectStar:{}", e.name), e.favorite, crate::i18n::tr("Favorite"));if star.clicked() {toggle_star = Some((e.name.clone(), !e.favorite));}diff --git a/crates/ui-egui/src/rating.rs b/crates/ui-egui/src/rating.rsindex 50fa00fda..f8b3c3a19 100644--- a/crates/ui-egui/src/rating.rs+++ b/crates/ui-egui/src/rating.rs@@ -13,6 +13,7 @@use egui::{Color32, Key, Modifiers, Painter, Pos2, Rect, Sense, Ui, pos2, vec2};+use crate::button::Button;use crate::icons::{Icon, paint};use crate::theme::Tokens;use crate::widgets::{announce_selected, register};@@ -27,7 +28,7 @@ pub enum RatingSize {Small,/// Grid badges and compare captions: 12 px stars every 13 px.Medium,- /// The bottom bar, the Info panel and the filter bar: 14 px stars in 19 px cells.+ /// The clickable row (bottom bar, Info panel, filter bar): 14 px stars in 19 px cells.Large,}@@ -52,11 +53,7 @@ impl RatingSize {/// Side of one clickable cell in a [`Rating`] row.fn cell(self) -> f32 {- match self {- Self::Small => 12.0,- Self::Medium => 16.0,- Self::Large => 19.0,- }+ self.step() + 2.0}}@@ -101,34 +98,13 @@ fn nudged_rating(current: u8, left: bool, right: bool) -> Option<u8> {pub struct Rating {id: String,rating: u8,- size: RatingSize,- read_only: bool,- enabled: bool,ids_prefix: Option<String>,}impl Rating {/// A rating of `rating` (0 to 5) whose stars are reachable as `star:{id}:{n}`.pub fn new(id: impl Into<String>, rating: u8) -> Self {- Self { id: id.into(), rating: rating.min(STARS), size: RatingSize::Large, read_only: false, enabled: true, ids_prefix: None }- }-- /// The size the stars are drawn at (default [`RatingSize::Large`]).- pub fn size(mut self, size: RatingSize) -> Self {- self.size = size;- self- }-- /// Show the rating without reacting to hover or clicks.- pub fn read_only(mut self) -> Self {- self.read_only = true;- self- }-- /// Whether the stars react (default true). A disabled row is faded and ignores clicks.- pub fn enabled(mut self, enabled: bool) -> Self {- self.enabled = enabled;- self+ Self { id: id.into(), rating: rating.min(STARS), ids_prefix: None }}/// Register the stars under `{prefix}{n}` instead of `star:{id}:{n}`, for rows that already have@@ -148,24 +124,28 @@ impl Rating {/// Draw the row. Returns the new rating when a click or an arrow key changed it.pub fn show(self, ui: &mut Ui) -> Option<u8> {let t = Tokens::get(ui.ctx());- let interactive = self.enabled && !self.read_only;- let cell = self.size.cell();+ let cell = RatingSize::Large.cell();let mut out = None;let mut hover_n = None;let mut focused = false;let mut cells = [Rect::NOTHING; STARS as usize];for (i, slot) in (0..STARS).zip(cells.iter_mut()) {- let (r, resp) = ui.allocate_exact_size(vec2(cell, cell), if interactive { Sense::click() } else { Sense::hover() });+ let (r, resp) = ui.allocate_exact_size(vec2(cell, cell), Sense::click());announce_selected(&resp, format!("{} ★", i + 1), i < self.rating);register(ui.ctx(), self.widget_id(i + 1), r);- if interactive {- if resp.hovered() {- hover_n = Some(i + 1);- }- if resp.clicked() {- out = Some(clicked_rating(self.rating, i + 1));- }- focused |= resp.has_focus();+ if resp.hovered() {+ hover_n = Some(i + 1);+ }+ if resp.clicked() {+ out = Some(clicked_rating(self.rating, i + 1));+ }+ if resp.has_focus() {+ focused = true;+ // ← and → step the rating instead of moving the focus to the neighbouring widget+ ui.memory_mut(|m| {+ m.set_focus_lock_filter(resp.id, egui::EventFilter { horizontal_arrows: true, ..Default::default() });+ });+ ui.painter().rect_stroke(r.expand(1.0), 6.0, egui::Stroke::new(2.0, t.accent), egui::StrokeKind::Outside);}*slot = r;}@@ -175,20 +155,24 @@ impl Rating {}// The hovered star also gets the icon-button hover square, so hovering the current rating (where// the preview looks the same) still shows feedback.- let fade = if self.enabled { 1.0 } else { 0.4 };- let side = self.size.icon();+ let side = RatingSize::Large.icon();for (i, r) in (0..STARS).zip(cells) {if hover_n == Some(i + 1) {ui.painter().rect_filled(r, 4.0, t.hover.gamma_multiply(0.7));}let filled = star_lit(i, self.rating, hover_n);- let color = if filled { t.star } else { t.icon };- paint_star(ui.painter(), Rect::from_center_size(r.center(), vec2(side, side)), filled, color.gamma_multiply(fade));+ paint_star(ui.painter(), Rect::from_center_size(r.center(), vec2(side, side)), filled, if filled { t.star } else { t.icon });}out}}+/// A frameless star toggle for favourites: filled when `favorite`, named `name` for screen readers,+/// reachable as `widget` (a full automation id).+pub fn favorite_button(ui: &mut Ui, widget: String, favorite: bool, name: &str) -> egui::Response {+ Button::icon_only(if favorite { Icon::StarFilled } else { Icon::Star }, name).ghost().small().widget(widget).show(ui)+}+#[cfg(test)]mod tests {use super::*;diff --git a/crates/ui-egui/src/tests_rating.rs b/crates/ui-egui/src/tests_rating.rsindex a7a8e65f9..15534853b 100644--- a/crates/ui-egui/src/tests_rating.rs+++ b/crates/ui-egui/src/tests_rating.rs@@ -3,7 +3,7 @@use egui::{Pos2, Rect, vec2};-use crate::rating::{Rating, RatingSize};+use crate::rating::Rating;/// Draw `build` for a few frames. After the first, click the centre of star `click` (1 to 5) if given,/// then press `keys`. Returns every value `build` reported and the AccessKit@@ -51,7 +51,7 @@ fn drive(click: Option<u8>, keys: &[egui::Key], build: impl Fn(&mut egui::Ui) ->}fn row(rating: u8) -> Rating {- Rating::new("t", rating).size(RatingSize::Large)+ Rating::new("t", rating)}#[test]@@ -66,18 +66,6 @@ fn clicking_the_current_rating_clears_it() {assert_eq!(got, vec![0]);}-#[test]-fn a_read_only_row_ignores_clicks() {- let (got, _) = drive(Some(4), &[], |ui| row(2).read_only().show(ui));- assert!(got.is_empty(), "{got:?}");-}--#[test]-fn a_disabled_row_ignores_clicks() {- let (got, _) = drive(Some(4), &[], |ui| row(2).enabled(false).show(ui));- assert!(got.is_empty(), "{got:?}");-}-#[test]fn hovering_alone_changes_nothing() {// the preview is only painted; the rating is reported on click@@ -108,3 +96,41 @@ fn arrow_keys_do_nothing_when_no_star_is_focused() {let (got, _) = drive(None, &[egui::Key::ArrowRight], |ui| row(3).show(ui));assert!(got.is_empty(), "{got:?}");}++/// Feed the shown rating back each frame, with other focusable widgets on both sides.+fn step_with_neighbours(start: u8, keys: &[egui::Key]) -> Vec<u8> {+ let ctx = egui::Context::default();+ crate::theme::install_fonts(&ctx);+ let rating = std::cell::Cell::new(start);+ let mut seen = Vec::new();+ // a key every other frame, as a person presses them: the focus lock is set during the frame after a focus change+ for frame in 0..keys.len() * 2 + 3 {+ let mut events = Vec::new();+ if let Some(k) = frame.checked_sub(1).filter(|f| f % 2 == 0).and_then(|f| keys.get(f / 2)) {+ events.push(egui::Event::Key { key: *k, physical_key: Some(*k), pressed: true, repeat: false, modifiers: Default::default() });+ }+ let raw = egui::RawInput { screen_rect: Some(Rect::from_min_size(Pos2::ZERO, vec2(600.0, 200.0))), events, ..Default::default() };+ let mut out = ctx.run_ui(raw, |ui| {+ ui.horizontal(|ui| {+ let _ = ui.button("left neighbour");+ if let Some(r) = row(rating.get()).show(ui) {+ rating.set(r);+ }+ let _ = ui.button("right neighbour");+ });+ });+ out.textures_delta.clear();+ seen.push(rating.get());+ }+ seen+}++#[test]+fn arrows_keep_stepping_between_other_focusable_widgets() {+ use egui::Key::*;+ // Tab, Tab: the left neighbour, then star 1+ let seen = step_with_neighbours(5, &[Tab, Tab, ArrowLeft, ArrowLeft, ArrowLeft, ArrowLeft, ArrowLeft]);+ assert_eq!(seen.last(), Some(&0), "{seen:?}");+ let seen = step_with_neighbours(0, &[Tab, Tab, ArrowRight, ArrowRight, ArrowRight, ArrowRight, ArrowRight, ArrowLeft]);+ assert_eq!(seen.last(), Some(&4), "{seen:?}");+}