Skip to main content

egui_pop_core/
rating.rs

1//! Rating stars: zero to five stars, edited with the pointer (and the
2//! keyboard when focusable) or only shown. One widget for every place a
3//! rating appears: a thumbnail's overlay, a panel, a table's column, a
4//! file's facts. Its behaviour follows the photo applications it is
5//! modelled on (`docs/rating.md`):
6//!
7//! <div class="warning">Experimental: may change in any release
8//! (docs/stability.md).</div>
9//!
10//! - **empty stars** are outlines, shown always or only while the item
11//!   they rate (or the stars) is under the pointer ([`EmptyStars`]), so
12//!   an unrated item still says it can be rated;
13//! - **under the pointer** the stars up to the pointer light in a
14//!   preview look (`hover`), the rest stay outlines; the current value
15//!   past the preview stays visible as a ghost (`selected` in the
16//!   `muted` tone);
17//! - **a click** gives the star's value; on the star of the current
18//!   value it clears the rating (its preview: every star a ghost). Each
19//!   star's tooltip and accessible name say it: "Set 3 of 5", "Clear
20//!   rating";
21//! - **read-only**, the stars are drawn by `rating-star-display` and
22//!   read as "3 of 5".
23//!
24//! The application owns the value: the widget takes the current one and
25//! says what the user asked for ([`RatingResponse::changed`]).
26//!
27//! ```
28//! use egui_pop_core::rating::{EmptyStars, RatingStars};
29//!
30//! fn ui(ui: &mut egui::Ui, rating: &mut u8) {
31//!     if let Some(r) = RatingStars::new(*rating).show(ui).changed {
32//!         *rating = r;
33//!     }
34//!     // In a table's cell: shown, not edited.
35//!     let _ = RatingStars::new(*rating).read_only(true).show(ui);
36//!     // Over a thumbnail: outlines only while the cell is hovered.
37//!     let _ = RatingStars::new(*rating).empty(EmptyStars::OnHover);
38//! }
39//! ```
40
41use egui::{Id, Key as EKey, Rect, Response, Role, Sense, Ui, WidgetInfo, vec2};
42
43use crate::kit::{Kit, KitCx, Part, State, Tone};
44use crate::strings::{self, tr};
45use crate::theme::Tokens;
46
47/// The highest rating.
48pub const MAX_RATING: u8 = 5;
49
50/// When empty stars (outlines) show.
51#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
52pub enum EmptyStars {
53    /// Always: a panel, a row or a cell with room for them.
54    #[default]
55    Always,
56    /// While the item they rate is hovered ([`RatingStars::item_hovered`])
57    /// or the pointer is on the stars: a thumbnail's overlay.
58    OnHover,
59}
60
61/// What a star shows.
62#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
63pub enum StarLook {
64    /// Past the value (and the preview): an outline, the kit's `rest`.
65    Empty,
66    /// A star of the value: `selected`.
67    Given,
68    /// A star of the value under the pointer: `hover`.
69    Preview,
70    /// A star of the current value past the preview: `selected` in the
71    /// `muted` tone.
72    Ghost,
73}
74
75impl StarLook {
76    /// The look of star `star` (1 to 5) for a value and, while the
77    /// pointer is on the stars, the value a click would give.
78    pub fn of(star: u8, value: u8, preview: Option<u8>) -> StarLook {
79        match preview {
80            Some(p) if star <= p => StarLook::Preview,
81            Some(_) if star <= value => StarLook::Ghost,
82            None if star <= value => StarLook::Given,
83            _ => StarLook::Empty,
84        }
85    }
86
87    /// The kit state it is painted in.
88    pub fn state(self) -> State {
89        match self {
90            StarLook::Empty => State::REST,
91            StarLook::Given => State::SELECTED,
92            StarLook::Preview => State::HOVER,
93            StarLook::Ghost => State::SELECTED.toned(Tone::Muted),
94        }
95    }
96}
97
98/// What a click on star `star` (1 to 5) gives: its value, or 0 on the
99/// star of the current value (it clears the rating).
100pub fn click_value(star: u8, value: u8) -> u8 {
101    if star == value { 0 } else { star }
102}
103
104/// What [`RatingStars`] returns.
105#[derive(Debug)]
106pub struct RatingResponse {
107    /// The stars' row as a whole.
108    pub response: Response,
109    /// The value the user asked for, if any (never the current one).
110    pub changed: Option<u8>,
111    /// The value a click would give, while the pointer is on the stars.
112    pub preview: Option<u8>,
113    /// Whether the pointer is on the stars.
114    pub hovered: bool,
115}
116
117/// Five stars (see the [module](self)).
118///
119/// Need (input): a star rating.
120#[derive(Clone, Debug)]
121#[must_use = "show it with `show` or `show_at`"]
122pub struct RatingStars {
123    value: u8,
124    label: Option<String>,
125    size: Option<f32>,
126    read_only: bool,
127    empty: EmptyStars,
128    item_hovered: bool,
129    focusable: bool,
130    id: Option<Id>,
131}
132
133impl RatingStars {
134    pub fn new(value: u8) -> RatingStars {
135        RatingStars {
136            value: value.min(MAX_RATING),
137            label: None,
138            size: None,
139            read_only: false,
140            empty: EmptyStars::Always,
141            item_hovered: false,
142            focusable: true,
143            id: None,
144        }
145    }
146
147    /// Its accessible name ("Rating" by default); a read-only rating is
148    /// named by its value ("3 of 5").
149    pub fn label(mut self, label: impl Into<String>) -> RatingStars {
150        self.label = Some(label.into());
151        self
152    }
153
154    /// One star's size in points (default: the inline icon size, at
155    /// least 12, plus 4).
156    pub fn size(mut self, size: f32) -> RatingStars {
157        self.size = Some(size);
158        self
159    }
160
161    /// Shown, not edited: no preview, no click, no focus, drawn by the
162    /// kit's `rating-star-display`. A disabled `Ui` gives the same.
163    pub fn read_only(mut self, read_only: bool) -> RatingStars {
164        self.read_only = read_only;
165        self
166    }
167
168    /// When empty stars show ([`EmptyStars::Always`] by default).
169    pub fn empty(mut self, empty: EmptyStars) -> RatingStars {
170        self.empty = empty;
171        self
172    }
173
174    /// Whether the item the stars rate is under the pointer (a
175    /// thumbnail's cell), for [`EmptyStars::OnHover`].
176    pub fn item_hovered(mut self, hovered: bool) -> RatingStars {
177        self.item_hovered = hovered;
178        self
179    }
180
181    /// Whether the stars take the keyboard focus (true by default): 0 to
182    /// 5 set the rating, the arrows step it, Home and End go to the ends.
183    /// A view with its own keys (a thumbnail grid) turns it off.
184    pub fn focusable(mut self, focusable: bool) -> RatingStars {
185        self.focusable = focusable;
186        self
187    }
188
189    /// The id of the stars' row, for [`RatingStars::show_at`] (default:
190    /// the `Ui`'s next automatic id).
191    pub fn id(mut self, id: Id) -> RatingStars {
192        self.id = Some(id);
193        self
194    }
195
196    /// The size of five stars of `size` points.
197    pub fn size_for(size: f32) -> egui::Vec2 {
198        vec2(size * f32::from(MAX_RATING), size)
199    }
200
201    fn star_size(&self, ui: &Ui) -> f32 {
202        self.size
203            .unwrap_or_else(|| Tokens::of(ui.ctx()).size.icon_inline.max(12.0) + 4.0)
204    }
205
206    fn editable(&self, ui: &Ui) -> bool {
207        !self.read_only && ui.is_enabled()
208    }
209
210    fn row_sense(&self, ui: &Ui) -> Sense {
211        if self.editable(ui) && self.focusable {
212            Sense::FOCUSABLE
213        } else {
214            Sense::hover()
215        }
216    }
217
218    /// Lays the stars out in `ui`, one star's size high.
219    pub fn show(self, ui: &mut Ui) -> RatingResponse {
220        let size = Self::size_for(self.star_size(ui));
221        let (rect, response) = ui.allocate_exact_size(size, self.row_sense(ui));
222        self.run(ui, rect, response)
223    }
224
225    /// Puts the stars in `rect` (laid out by the caller: an overlay),
226    /// five equal slots across it.
227    pub fn show_at(self, ui: &mut Ui, rect: Rect) -> RatingResponse {
228        let id = self.id.unwrap_or_else(|| ui.next_auto_id());
229        let response = ui.interact(rect, id, self.row_sense(ui));
230        self.run(ui, rect, response)
231    }
232
233    fn run(self, ui: &mut Ui, rect: Rect, response: Response) -> RatingResponse {
234        let editable = self.editable(ui);
235        let focusable = editable && self.focusable;
236        let slot = rect.width() / f32::from(MAX_RATING);
237        let star_rect = |i: u8| {
238            Rect::from_min_size(
239                rect.min + vec2(slot * f32::from(i), 0.0),
240                vec2(slot, rect.height()),
241            )
242        };
243        let hovered = ui.rect_contains_pointer(rect);
244        let mut changed = None;
245        let mut preview = None;
246        if editable {
247            // The star under the pointer, gaps and edges included: the
248            // preview never flickers between two stars.
249            if hovered && let Some(p) = ui.ctx().pointer_hover_pos() {
250                let i = (((p.x - rect.left()) / slot).floor() as i32).clamp(0, 4) as u8;
251                preview = Some(click_value(i + 1, self.value));
252            }
253            for i in 0..MAX_RATING {
254                let star = i + 1;
255                let gives = click_value(star, self.value);
256                let r = ui.interact(star_rect(i), response.id.with(star), Sense::CLICK);
257                let name = if gives == 0 {
258                    tr(ui.ctx(), &strings::RATING_CLEAR)
259                } else {
260                    strings::tr_with(ui.ctx(), &strings::RATING_SET, &[("stars", star.into())])
261                };
262                let tip = name.clone();
263                r.widget_info(move || WidgetInfo::labeled(Role::Button, true, &name));
264                let r = r.on_hover_text(tip);
265                if r.clicked() {
266                    changed = Some(gives);
267                    if focusable {
268                        r.ctx.memory_mut(|m| m.request_focus(response.id));
269                    }
270                }
271            }
272        }
273        if focusable {
274            crate::focus::takes_keys(ui.ctx(), response.id);
275        }
276        if focusable && response.has_focus() {
277            changed = changed.or_else(|| self.keys(ui));
278            ui.memory_mut(|m| {
279                m.set_focus_lock_filter(
280                    response.id,
281                    egui::EventFilter {
282                        horizontal_arrows: true,
283                        vertical_arrows: true,
284                        ..Default::default()
285                    },
286                )
287            });
288        }
289        if changed == Some(self.value) {
290            changed = None;
291        }
292        if ui.is_rect_visible(rect) {
293            let kit = Kit::of(ui.ctx());
294            let component = if editable {
295                &kit.rating_star
296            } else {
297                &kit.rating_star_display
298            };
299            let painter = ui.painter();
300            let cx = KitCx {
301                painter,
302                ppp: ui.ctx().pixels_per_point(),
303            };
304            let empty_shown = match self.empty {
305                EmptyStars::Always => true,
306                EmptyStars::OnHover => self.item_hovered || hovered,
307            };
308            for i in 0..MAX_RATING {
309                let look = StarLook::of(i + 1, self.value, preview);
310                if look == StarLook::Empty && !empty_shown {
311                    continue;
312                }
313                let r = star_rect(i);
314                component.paint(
315                    &cx,
316                    &Part {
317                        rect: r,
318                        room: r,
319                        state: look.state(),
320                        label: None,
321                    },
322                );
323            }
324            if focusable && response.has_focus() {
325                crate::focus::own_ring(ui.ctx(), response.id);
326            }
327            if focusable && crate::focus::shows_ring(&response) {
328                let t = Tokens::of(ui.ctx());
329                painter.rect_stroke(
330                    rect.expand(1.0),
331                    t.radius.widget,
332                    egui::Stroke::new(1.0, t.focus_ring),
333                    egui::StrokeKind::Outside,
334                );
335            }
336        }
337        let value = self.value;
338        if focusable {
339            let label = self.label.unwrap_or_else(|| tr(ui.ctx(), &strings::RATING));
340            response.widget_info(move || WidgetInfo::slider(true, f64::from(value), &label));
341            ui.ctx().accesskit_node_builder(response.id, |n| {
342                n.set_min_numeric_value(0.0);
343                n.set_max_numeric_value(f64::from(MAX_RATING));
344                n.set_numeric_value_step(1.0);
345            });
346        } else if !editable {
347            let said =
348                strings::tr_with(ui.ctx(), &strings::RATING_VALUE, &[("stars", value.into())]);
349            response.widget_info(move || WidgetInfo::labeled(Role::Label, true, &said));
350        }
351        RatingResponse {
352            response,
353            changed,
354            preview,
355            hovered,
356        }
357    }
358
359    /// The value the keys pressed this pass ask for.
360    fn keys(&self, ui: &Ui) -> Option<u8> {
361        ui.input(|i| {
362            let mut v = None;
363            for (k, r) in [
364                (EKey::Num0, 0),
365                (EKey::Num1, 1),
366                (EKey::Num2, 2),
367                (EKey::Num3, 3),
368                (EKey::Num4, 4),
369                (EKey::Num5, 5),
370            ] {
371                if i.key_pressed(k) {
372                    v = Some(r);
373                }
374            }
375            if i.key_pressed(EKey::ArrowRight) || i.key_pressed(EKey::ArrowUp) {
376                v = Some((self.value + 1).min(MAX_RATING));
377            }
378            if i.key_pressed(EKey::ArrowLeft) || i.key_pressed(EKey::ArrowDown) {
379                v = Some(self.value.saturating_sub(1));
380            }
381            if i.key_pressed(EKey::Home) {
382                v = Some(0);
383            }
384            if i.key_pressed(EKey::End) {
385                v = Some(MAX_RATING);
386            }
387            v
388        })
389    }
390}
391
392#[cfg(test)]
393mod tests {
394    use super::*;
395
396    #[test]
397    fn a_lower_preview_keeps_the_current_value_as_a_ghost() {
398        let looks: Vec<StarLook> = (1..=5).map(|s| StarLook::of(s, 3, Some(1))).collect();
399        assert_eq!(
400            looks,
401            [
402                StarLook::Preview,
403                StarLook::Ghost,
404                StarLook::Ghost,
405                StarLook::Empty,
406                StarLook::Empty
407            ]
408        );
409    }
410
411    #[test]
412    fn the_current_star_clears_and_its_preview_is_all_ghosts() {
413        assert_eq!(click_value(3, 3), 0);
414        assert_eq!(click_value(4, 3), 4);
415        assert_eq!(click_value(1, 0), 1);
416        let looks: Vec<StarLook> = (1..=5).map(|s| StarLook::of(s, 3, Some(0))).collect();
417        assert_eq!(&looks[..3], [StarLook::Ghost; 3]);
418        assert_eq!(&looks[3..], [StarLook::Empty; 2]);
419        assert_eq!(StarLook::of(2, 3, None), StarLook::Given);
420        assert_eq!(StarLook::of(5, 3, Some(5)), StarLook::Preview);
421    }
422}