1use 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
47pub const MAX_RATING: u8 = 5;
49
50#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
52pub enum EmptyStars {
53 #[default]
55 Always,
56 OnHover,
59}
60
61#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
63pub enum StarLook {
64 Empty,
66 Given,
68 Preview,
70 Ghost,
73}
74
75impl StarLook {
76 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 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
98pub fn click_value(star: u8, value: u8) -> u8 {
101 if star == value { 0 } else { star }
102}
103
104#[derive(Debug)]
106pub struct RatingResponse {
107 pub response: Response,
109 pub changed: Option<u8>,
111 pub preview: Option<u8>,
113 pub hovered: bool,
115}
116
117#[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 pub fn label(mut self, label: impl Into<String>) -> RatingStars {
150 self.label = Some(label.into());
151 self
152 }
153
154 pub fn size(mut self, size: f32) -> RatingStars {
157 self.size = Some(size);
158 self
159 }
160
161 pub fn read_only(mut self, read_only: bool) -> RatingStars {
164 self.read_only = read_only;
165 self
166 }
167
168 pub fn empty(mut self, empty: EmptyStars) -> RatingStars {
170 self.empty = empty;
171 self
172 }
173
174 pub fn item_hovered(mut self, hovered: bool) -> RatingStars {
177 self.item_hovered = hovered;
178 self
179 }
180
181 pub fn focusable(mut self, focusable: bool) -> RatingStars {
185 self.focusable = focusable;
186 self
187 }
188
189 pub fn id(mut self, id: Id) -> RatingStars {
192 self.id = Some(id);
193 self
194 }
195
196 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 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 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 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 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}