1use std::{cell::RefCell, rc::Rc};
25
26use arc_motion::{
27 arc_spring, arc_spring_with_options, is_reduced_motion, motion_now, spring::SpringOptions,
28};
29use arc_tokens::{ActiveArcTheme as _, Spacing, SpringSpec, Typography, oklab_mix};
30use gpui_kit::{
31 AnyElement, App, Bounds, ElementId, FocusHandle, Hsla, IntoElement, KeyDownEvent, MouseButton,
32 MouseDownEvent, MouseMoveEvent, MouseUpEvent, ParentElement, PathBuilder, Pixels, RenderOnce,
33 Role, SharedString, Styled, TestSupportExt as _, Window, base::StyledExt as _, canvas, div,
34 point, prelude::*, px,
35};
36
37use super::field_message::render_field_message;
38
39type RatingHandler = Rc<dyn Fn(&f32, &mut Window, &mut App)>;
40
41pub const RATING_POP_VELOCITY: f32 = 9.0;
43pub const RATING_WAVE_GAP_SECS: f64 = 0.26;
45
46pub const fn rating_pop_spring() -> SpringSpec {
48 let root = std::f64::consts::TAU / (0.26 * 1.2);
49 SpringSpec::physics((root * root) as f32, (2.0 * root) as f32)
50}
51
52const DEFAULT_WORDS: [&str; 5] = ["Poor", "Fair", "Good", "Great", "Excellent"];
53
54#[derive(Clone)]
55struct RatingInternal {
56 uncontrolled: f32,
57 sweep_from: f32,
59 last_commit_secs: f64,
60 pop_key: u64,
61 pop_value: f32,
62 pop_wave: bool,
63 pressed_star: Option<usize>,
64 preview: Option<f32>,
65 fill_targets: Rc<RefCell<Vec<f32>>>,
67 pop_impulses: Rc<RefCell<Vec<Option<f32>>>>,
69 stars_bounds: Rc<RefCell<Option<Bounds<Pixels>>>>,
70 focus_handle: FocusHandle,
71}
72
73impl RatingInternal {
74 fn new(initial: f32, cx: &mut App) -> Self {
75 Self {
76 uncontrolled: initial,
77 sweep_from: initial,
78 last_commit_secs: f64::NEG_INFINITY,
79 pop_key: 0,
80 pop_value: 0.0,
81 pop_wave: false,
82 pressed_star: None,
83 preview: None,
84 fill_targets: Rc::new(RefCell::new(Vec::new())),
85 pop_impulses: Rc::new(RefCell::new(Vec::new())),
86 stars_bounds: Rc::new(RefCell::new(None)),
87 focus_handle: cx.focus_handle(),
88 }
89 }
90}
91
92fn paint_star(rect: Bounds<Pixels>, color: Hsla, clip_fraction: f32, window: &mut Window) {
94 if clip_fraction <= 0.0 {
95 return;
96 }
97 let w = f32::from(rect.size.width);
98 let h = f32::from(rect.size.height);
99 let cx = f32::from(rect.origin.x) + w / 2.0;
100 let cy = f32::from(rect.origin.y) + h / 2.0;
101 let outer = w.min(h) / 2.0;
102 let inner = outer * 0.42;
103 let mut builder = PathBuilder::fill();
104 for i in 0..10 {
105 let angle = -std::f32::consts::FRAC_PI_2 + i as f32 * std::f32::consts::PI / 5.0;
106 let radius = if i % 2 == 0 { outer } else { inner };
107 let x = cx + angle.cos() * radius;
108 let y = cy + angle.sin() * radius;
109 let p = point(px(x), px(y));
110 if i == 0 {
111 builder.move_to(p);
112 } else {
113 builder.line_to(p);
114 }
115 }
116 builder.close();
117 if let Ok(path) = builder.build() {
118 if clip_fraction >= 1.0 {
121 window.paint_path(path, color);
122 } else {
123 let _ = path;
125 let faded = Hsla {
128 a: color.a * clip_fraction,
129 ..color
130 };
131 window.paint_path(path, faded);
132 }
133 }
134}
135
136#[derive(IntoElement)]
138pub struct Rating {
139 id: ElementId,
140 label: SharedString,
141 value: Option<f32>,
142 default_value: f32,
143 max: usize,
144 read_only: bool,
145 disabled: bool,
146 description: Option<SharedString>,
147 size: RatingSize,
148 allow_half: bool,
149 allow_clear: bool,
150 show_value: bool,
151 value_labels: Option<Vec<SharedString>>,
152 empty_label: SharedString,
153 width: Option<Pixels>,
154 on_change: Option<RatingHandler>,
155}
156
157#[derive(Clone, Copy, Debug, PartialEq, Eq)]
159pub enum RatingSize {
160 Sm,
161 Md,
162 Lg,
163}
164
165impl RatingSize {
166 pub const fn glyph_px(self) -> f32 {
167 match self {
168 Self::Sm => 16.0,
169 Self::Md => 22.0,
170 Self::Lg => 28.0,
171 }
172 }
173}
174
175impl Rating {
176 pub fn new(id: impl Into<ElementId>, label: impl Into<SharedString>) -> Self {
177 Self {
178 id: id.into(),
179 label: label.into(),
180 value: None,
181 default_value: 0.0,
182 max: 5,
183 read_only: false,
184 disabled: false,
185 description: None,
186 size: RatingSize::Md,
187 allow_half: false,
188 allow_clear: true,
189 show_value: true,
190 value_labels: None,
191 empty_label: "Not rated".into(),
192 width: None,
193 on_change: None,
194 }
195 }
196
197 pub fn value(mut self, value: f32) -> Self {
198 self.value = Some(value);
199 self
200 }
201
202 pub fn default_value(mut self, value: f32) -> Self {
203 self.default_value = value;
204 self
205 }
206
207 pub fn max(mut self, max: usize) -> Self {
208 self.max = max.max(1);
209 self
210 }
211
212 pub fn read_only(mut self, read_only: bool) -> Self {
213 self.read_only = read_only;
214 self
215 }
216
217 pub fn disabled(mut self, disabled: bool) -> Self {
218 self.disabled = disabled;
219 self
220 }
221
222 pub fn description(mut self, description: impl Into<SharedString>) -> Self {
223 self.description = Some(description.into());
224 self
225 }
226
227 pub fn size(mut self, size: RatingSize) -> Self {
228 self.size = size;
229 self
230 }
231
232 pub fn allow_half(mut self, allow: bool) -> Self {
234 self.allow_half = allow;
235 self
236 }
237
238 pub fn allow_clear(mut self, allow: bool) -> Self {
240 self.allow_clear = allow;
241 self
242 }
243
244 pub fn show_value(mut self, show: bool) -> Self {
245 self.show_value = show;
246 self
247 }
248
249 pub fn value_labels<I, S>(mut self, labels: I) -> Self
251 where
252 I: IntoIterator<Item = S>,
253 S: Into<SharedString>,
254 {
255 self.value_labels = Some(labels.into_iter().map(Into::into).collect());
256 self
257 }
258
259 pub fn empty_label(mut self, label: impl Into<SharedString>) -> Self {
261 self.empty_label = label.into();
262 self
263 }
264
265 pub fn width(mut self, width: impl Into<Pixels>) -> Self {
266 self.width = Some(width.into());
267 self
268 }
269
270 pub fn on_change(mut self, handler: impl Fn(&f32, &mut Window, &mut App) + 'static) -> Self {
272 self.on_change = Some(Rc::new(handler));
273 self
274 }
275}
276
277impl RenderOnce for Rating {
278 fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
279 let theme = cx.arc_theme().clone();
280 let colors = theme.colors;
281 let motion = theme.motion;
282 let reduced = is_reduced_motion(cx);
283 let now = motion_now(cx);
284
285 let max = self.max;
286 let step = if self.allow_half { 0.5 } else { 1.0 };
287 let normalize = |next: f32| (next / step).round() * step;
288 let interactive = !self.read_only && !self.disabled;
289
290 let state_id = ElementId::NamedChild(self.id.clone().into(), "__arc-rating-state".into());
291 let internal = window.use_keyed_state(state_id, cx, |_, cx| {
292 RatingInternal::new(self.default_value, cx)
293 });
294
295 if let Some(ext) = self.value {
296 let snapped = normalize(ext.clamp(0.0, max as f32));
297 let cur = internal.read(cx).uncontrolled;
298 if (snapped - cur).abs() > f32::EPSILON {
299 internal.update(cx, |s, _| {
300 s.uncontrolled = snapped;
301 s.fill_targets.borrow_mut().clear();
302 });
303 }
304 }
305
306 let snap_state = internal.read(cx).clone();
307 let current = self.value.map_or(snap_state.uncontrolled, |v| {
308 normalize(v.clamp(0.0, max as f32))
309 });
310 let display_value = snap_state.preview.unwrap_or(current);
311 let direction = if display_value >= snap_state.sweep_from {
312 1
313 } else {
314 -1
315 };
316
317 let words = self.value_labels.clone().or_else(|| {
318 if max == 5 && !self.allow_half {
319 Some(
320 DEFAULT_WORDS
321 .iter()
322 .map(|w| SharedString::from(*w))
323 .collect(),
324 )
325 } else {
326 None
327 }
328 });
329 let word_for = |next: f32| -> Option<SharedString> {
330 if next.fract() == 0.0 && next >= 1.0 {
331 words
332 .as_ref()
333 .and_then(|w| w.get(next as usize - 1).cloned())
334 } else {
335 None
336 }
337 };
338 let text_for = |next: f32| -> SharedString {
339 if next <= 0.0 {
340 self.empty_label.clone()
341 } else {
342 word_for(next).unwrap_or_else(|| SharedString::from(format!("{next} out of {max}")))
343 }
344 };
345
346 let pop_spring = rating_pop_spring();
348 let pop_value = if snap_state.pop_value == current && current > 0.0 {
349 Some((snap_state.pop_key, snap_state.pop_wave))
350 } else {
351 None
352 };
353 let pulsing = pop_value;
354 let mut star_els: Vec<AnyElement> = Vec::with_capacity(max);
355 for index in 0..max {
356 let fill = (display_value - index as f32).clamp(0.0, 1.0);
357 let kept = (current - index as f32).clamp(0.0, 1.0);
358 let star_size = self.size.glyph_px();
359 let order = if display_value > snap_state.sweep_from {
360 index as f32 - snap_state.sweep_from.floor()
361 } else {
362 snap_state.sweep_from.ceil() - 1.0 - index as f32
363 };
364 let delay = order.max(0.0) * 0.035;
365 let delay_elapsed = (now - snap_state.last_commit_secs).max(0.0);
366 let fill_target = if delay_elapsed >= f64::from(delay) {
367 fill
368 } else {
369 window.request_animation_frame();
370 snap_state
373 .fill_targets
374 .borrow()
375 .get(index)
376 .copied()
377 .unwrap_or(kept)
378 };
379 let fill_sample = arc_spring_with_options(
382 (self.id.clone(), SharedString::from(format!("fill-{index}"))),
383 fill_target,
384 SpringOptions::new(motion.spring.snappy.as_physical()),
385 window,
386 cx,
387 );
388 let kept_sample = arc_spring(
389 (self.id.clone(), SharedString::from(format!("kept-{index}"))),
390 kept,
391 motion.spring.smooth,
392 window,
393 cx,
394 );
395 let popping = pulsing
397 .map(|(key, wave)| {
398 key != 0
399 && index < (pulsing.map(|_| current).unwrap_or(0.0)).ceil() as usize
400 && (wave || index == current.ceil() as usize - 1)
401 })
402 .unwrap_or(false);
403 let impulse_ready = popping
404 && snap_state
405 .pop_impulses
406 .borrow()
407 .get(index)
408 .copied()
409 .flatten()
410 .is_some();
411 let mut pop_opts = SpringOptions::new(pop_spring);
412 if impulse_ready {
413 pop_opts = pop_opts.with_initial_velocity(RATING_POP_VELOCITY);
414 internal.update(cx, |s, _| {
415 let mut impulses = s.pop_impulses.borrow_mut();
416 if let Some(slot) = impulses.get_mut(index) {
417 *slot = None;
418 }
419 });
420 }
421 let scale_sample = arc_spring_with_options(
422 (
423 self.id.clone(),
424 SharedString::from(format!("scale-{index}")),
425 ),
426 1.0,
427 pop_opts,
428 window,
429 cx,
430 );
431 let pressed_scale = arc_spring(
432 (
433 self.id.clone(),
434 SharedString::from(format!("press-{index}")),
435 ),
436 if snap_state.pressed_star == Some(index) && !reduced {
437 0.86
438 } else if display_value > 0.0 && fill == 0.0 {
439 0.9
440 } else {
441 1.0
442 },
443 motion.spring.snappy,
444 window,
445 cx,
446 );
447 let scale = scale_sample.value * pressed_scale;
448 let fill_now = fill_sample.value;
449 let kept_now = kept_sample;
450 let empty_color = oklab_mix(colors.foreground, colors.surface, 0.22);
451 let glyph_color = colors.control_fill;
452 let kept_color = oklab_mix(colors.control_fill, colors.surface, 0.42);
453
454 star_els.push(
455 div()
456 .id(ElementId::NamedChild(
457 self.id.clone().into(),
458 SharedString::from(format!("star-{index}")),
459 ))
460 .test_support()
461 .aria_label(SharedString::from(format!(
462 "{} {}",
463 index + 1,
464 text_for(index as f32 + 1.0)
465 )))
466 .flex_none()
467 .w(px(star_size * scale))
468 .h(px(star_size * scale))
469 .ml(px((star_size * (scale - 1.0)) / -2.0))
470 .child(
471 canvas(
472 |_, _, _| {},
473 move |rect, _, window, _| {
474 paint_star(rect, empty_color, 1.0, window);
476 paint_star(rect, kept_color, kept_now, window);
477 paint_star(rect, glyph_color, fill_now, window);
478 },
479 )
480 .size_full(),
481 )
482 .into_any_element(),
483 );
484 }
485
486 let is_ctrl = self.value.is_some();
488 let st_pointer = internal.clone();
489 let ch_pointer = self.on_change.clone();
490 let max_pointer = max;
491 let step_pointer = step;
492 let allow_clear_pointer = self.allow_clear;
493 let stars_bounds_ref = snap_state.stars_bounds.clone();
494
495 let value_at = move |x: f32, bounds: Bounds<Pixels>| -> f32 {
496 let star_w = f32::from(bounds.size.width) / max as f32;
497 let rel = x - f32::from(bounds.origin.x);
498 let idx = (rel / star_w).floor().max(0.0) as usize;
499 if rel < 0.0 {
500 return if allow_clear_pointer {
501 0.0
502 } else {
503 step_pointer
504 };
505 }
506 let idx = idx.min(max_pointer - 1);
507 if rel <= (idx + 1) as f32 * star_w + 1.0 {
508 if step_pointer < 1.0 && rel < (idx as f32 + 0.5) * star_w {
509 idx as f32 + 0.5
510 } else {
511 idx as f32 + 1.0
512 }
513 } else {
514 max_pointer as f32
515 }
516 };
517
518 let stars_group = div()
519 .id(ElementId::NamedChild(
520 self.id.clone().into(),
521 "stars".into(),
522 ))
523 .test_support()
524 .role(if self.read_only {
525 Role::Image
526 } else {
527 Role::RadioGroup
528 })
529 .aria_label(self.label.clone())
530 .relative()
531 .flex()
532 .flex_row()
533 .items_center()
534 .gap(px(2.0))
535 .when(interactive, |this| this.cursor_pointer())
536 .on_mouse_down(MouseButton::Left, {
537 let st_pointer = st_pointer.clone();
538 move |event: &MouseDownEvent, window, cx| {
539 if !interactive {
540 return;
541 }
542 let Some(bounds) = *st_pointer.read(cx).stars_bounds.borrow() else {
543 return;
544 };
545 let at = value_at(f32::from(event.position.x), bounds);
546 st_pointer.update(cx, |s, _| {
547 s.pressed_star = if at > 0.0 {
548 Some((at.ceil() as usize).saturating_sub(1))
549 } else {
550 None
551 };
552 s.preview = Some(at);
553 });
554 window.refresh();
555 }
556 })
557 .child(
558 canvas(
559 {
560 let bounds_ref = stars_bounds_ref;
561 move |rect, _, _| {
562 *bounds_ref.borrow_mut() = Some(rect);
563 }
564 },
565 {
566 let st_pointer = st_pointer.clone();
567 let ch_pointer = ch_pointer.clone();
568 move |_, _, window, cx| {
569 let st = st_pointer.clone();
570 let _ = ch_pointer.clone();
571 if st.read(cx).pressed_star.is_some() || st.read(cx).preview.is_some() {
573 window.on_mouse_event(
574 move |event: &MouseMoveEvent, phase, window, cx| {
575 if !phase.bubble() || st.read(cx).pressed_star.is_none() {
576 return;
577 }
578 let Some(bounds) = *st.read(cx).stars_bounds.borrow()
579 else {
580 return;
581 };
582 let at = value_at(f32::from(event.position.x), bounds);
583 st.update(cx, |s, _| {
584 s.pressed_star = if at > 0.0 {
585 Some((at.ceil() as usize).saturating_sub(1))
586 } else {
587 None
588 };
589 s.preview = Some(at);
590 });
591 window.refresh();
592 },
593 );
594 let st_up = st_pointer.clone();
595 let ch_up = ch_pointer.clone();
596 window.on_mouse_event(
597 move |event: &MouseUpEvent, phase, window, cx| {
598 if !phase.bubble()
599 || event.button != gpui_kit::MouseButton::Left
600 || st_up.read(cx).pressed_star.is_none()
601 {
602 return;
603 }
604 let Some(bounds) = *st_up.read(cx).stars_bounds.borrow()
605 else {
606 return;
607 };
608 let now_u = motion_now(cx);
609 let at = value_at(f32::from(event.position.x), bounds);
610 let cur = st_up.read(cx).uncontrolled;
611 let mut chosen =
612 normalize_generic(at, step_pointer, max_pointer);
613 if chosen == cur && allow_clear_pointer {
614 chosen = 0.0;
615 }
616 if !allow_clear_pointer {
617 chosen = chosen.max(step_pointer);
618 }
619 st_up.update(cx, |s, _| {
620 s.pressed_star = None;
621 s.preview = None;
622 s.sweep_from = s.uncontrolled;
623 s.pop_key += 1;
624 s.pop_value = chosen;
625 s.pop_wave =
626 now_u - s.last_commit_secs > RATING_WAVE_GAP_SECS;
627 s.last_commit_secs = now_u;
628 let count = chosen.ceil() as usize;
630 let mut impulses = s.pop_impulses.borrow_mut();
631 impulses.clear();
632 for i in 0..max_pointer {
633 impulses.push(if i < count {
634 Some(0.0)
635 } else {
636 None
637 });
638 }
639 if !is_ctrl {
640 s.uncontrolled = chosen;
641 }
642 s.fill_targets.borrow_mut().clear();
643 });
644 if (chosen - cur).abs() > f32::EPSILON
645 && let Some(handler) = &ch_up
646 {
647 handler(&chosen, window, cx);
648 }
649 window.refresh();
650 },
651 );
652 }
653 }
654 },
655 )
656 .absolute()
657 .inset_0(),
658 )
659 .children(star_els);
660
661 let st_key = internal.clone();
663 let ch_key = self.on_change.clone();
664 let focus_key = snap_state.focus_handle.clone();
665 let is_ctrl_k = self.value.is_some();
666
667 let keyboard_commit = move |next_raw: f32,
668 st: &gpui_kit::Entity<RatingInternal>,
669 window: &mut Window,
670 cx: &mut App| {
671 let now_k = motion_now(cx);
672 let cur = st.read(cx).uncontrolled;
673 let mut chosen = normalize_generic(next_raw, step, max);
674 if !self.allow_clear {
675 chosen = chosen.max(step);
676 }
677 st.update(cx, |s, _| {
678 s.sweep_from = s.uncontrolled;
679 s.pop_key += 1;
680 s.pop_value = chosen;
681 s.pop_wave = now_k - s.last_commit_secs > RATING_WAVE_GAP_SECS;
682 s.last_commit_secs = now_k;
683 let count = chosen.ceil() as usize;
684 let mut impulses = s.pop_impulses.borrow_mut();
685 impulses.clear();
686 for i in 0..max {
687 impulses.push(if i < count && (chosen > 0.0) {
688 Some(0.0)
689 } else {
690 None
691 });
692 }
693 if !is_ctrl_k {
694 s.uncontrolled = chosen;
695 }
696 s.fill_targets.borrow_mut().clear();
697 });
698 if (chosen - cur).abs() > f32::EPSILON
699 && let Some(handler) = &ch_key
700 {
701 handler(&chosen, window, cx);
702 }
703 window.refresh();
704 };
705
706 let stars_focus_wrap =
707 div()
708 .track_focus(&focus_key)
709 .on_key_down(move |event: &KeyDownEvent, window, cx| {
710 if !interactive {
711 return;
712 }
713 let now_v = st_key.read(cx).uncontrolled;
714 let key = event.keystroke.key.as_str();
715 let shift = event.keystroke.modifiers.shift;
716 let _ = shift;
717 let wanted: Option<f32> = match key {
718 "right" | "arrowright" | "up" | "arrowup" => Some(now_v + step),
719 "left" | "arrowleft" | "down" | "arrowdown" => Some(now_v - step),
720 "home" => Some(step),
721 "end" => Some(max as f32),
722 "enter" | " " | "space" => {
723 Some(if now_v > 0.0 && self.allow_clear {
725 0.0
726 } else {
727 now_v
728 })
729 }
730 "backspace" | "delete" => {
731 if self.allow_clear {
732 Some(0.0)
733 } else {
734 None
735 }
736 }
737 k if k.len() == 1
738 && k.chars().next().is_some_and(|c| c.is_ascii_digit())
739 && !k.starts_with('0')
740 && ((k.chars().next().unwrap() as u8 - b'0') as usize) <= max =>
741 {
742 Some((k.chars().next().unwrap() as u8 - b'0') as f32)
743 }
744 _ => None,
745 };
746 if let Some(wanted) = wanted {
747 keyboard_commit(wanted, &st_key, window, cx);
748 }
749 });
750
751 let value_text = text_for(display_value);
753 let src_elapsed_value = (now - snap_state.last_commit_secs).max(0.0);
754 let (word_op, word_y) = if src_elapsed_value >= 0.24 {
755 (1.0_f32, 0.0_f32)
756 } else {
757 window.request_animation_frame();
758 let t = (src_elapsed_value / 0.24).clamp(0.0, 1.0) as f32;
759 let e = if reduced {
760 t
761 } else {
762 arc_motion::CubicBezier::new(0.16, 1.0, 0.3, 1.0).sample(t)
763 };
764 let y = if reduced {
765 0.0
766 } else {
767 direction as f32 * 0.3 * f32::from(Typography::TEXT_SM) * (1.0 - e)
768 };
769 ((e).clamp(0.0, 1.0), y)
770 };
771
772 let msg_id = ElementId::NamedChild(self.id.clone().into(), "message".into());
773
774 div()
775 .id(self.id)
776 .test_support()
777 .when_some(self.width, |this, w| this.w(w))
778 .when(self.width.is_none(), |this| this.w_full())
779 .flex()
780 .flex_col()
781 .gap(Spacing::S2)
782 .when(self.disabled, |this| this.opacity(0.5))
783 .child(
784 div()
785 .text_size(Typography::TEXT_SM)
786 .font_medium()
787 .text_color(colors.foreground)
788 .child(self.label.clone()),
789 )
790 .child(
791 div()
792 .flex()
793 .flex_row()
794 .items_center()
795 .gap(Spacing::S3)
796 .child(stars_focus_wrap.child(stars_group))
797 .when(self.show_value, |this| {
798 this.child(
799 div()
800 .mt(px(word_y))
801 .opacity(word_op)
802 .text_size(Typography::TEXT_SM)
803 .text_color(if display_value > 0.0 {
804 colors.text_secondary
805 } else {
806 colors.text_muted
807 })
808 .child(value_text),
809 )
810 }),
811 )
812 .child(render_field_message(
813 msg_id,
814 self.description,
815 false,
816 window,
817 cx,
818 ))
819 }
820}
821
822fn normalize_generic(next: f32, step: f32, max: usize) -> f32 {
823 ((next / step).round() * step).clamp(0.0, max as f32)
824}
825
826#[cfg(test)]
827mod tests {
828 use arc_tokens::{Accent, ThemeMode, install_arc_theme};
829 use gpui_kit::{Context, Render, TestAppContext, test::TestWindowExt as _};
830
831 use super::*;
832
833 #[test]
834 fn rating_normalize_rounds_to_half_steps() {
835 assert!((normalize_generic(1.24, 1.0, 5) - 1.0).abs() < 1e-4);
836 assert!((normalize_generic(1.26, 0.5, 5) - 1.5).abs() < 1e-4);
837 assert!((normalize_generic(7.0, 1.0, 5) - 5.0).abs() < 1e-4);
838 assert!((normalize_generic(-2.0, 0.5, 5) - 0.0).abs() < 1e-4);
839 }
840
841 #[test]
842 fn rating_constants_match_upstream() {
843 assert!((RATING_POP_VELOCITY - 9.0).abs() < 1e-5);
844 assert!((RATING_WAVE_GAP_SECS - 0.26).abs() < 1e-5);
845 assert!((RatingSize::Sm.glyph_px() - 16.0).abs() < 1e-5);
846 assert!((RatingSize::Lg.glyph_px() - 28.0).abs() < 1e-5);
847 }
848
849 struct RatingHost {
850 value: f32,
851 events: Rc<RefCell<Vec<String>>>,
852 disabled: bool,
853 }
854
855 impl Render for RatingHost {
856 fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
857 let events = self.events.clone();
858 div().w(px(480.0)).p(px(16.0)).child(
859 Rating::new("rating-test", "Satisfaction")
860 .value(self.value)
861 .allow_half(false)
862 .show_value(true)
863 .disabled(self.disabled)
864 .on_change(cx.listener({
865 let events = events.clone();
866 move |this, v: &f32, _, cx| {
867 events.borrow_mut().push(format!("{v}"));
868 this.value = *v;
869 cx.notify();
870 }
871 })),
872 )
873 }
874 }
875
876 fn rating_element(name: &str) -> ElementId {
877 ElementId::NamedChild(ElementId::Name("rating-test".into()).into(), name.into())
878 }
879
880 #[gpui_kit::test]
881 fn rating_keyboard_digits_arrows_and_clear(cx: &mut TestAppContext) {
882 cx.update(|cx| {
883 gpui_kit::init(cx);
884 install_arc_theme(ThemeMode::Light, Accent::Violet, cx);
885 });
886
887 let host = RatingHost {
888 value: 0.0,
889 events: Rc::new(RefCell::new(Vec::new())),
890 disabled: false,
891 };
892 let events = host.events.clone();
893 let (view, cx) = cx.add_window_view(|_, _| host);
894
895 cx.update(|window, cx| {
896 window.render_frame(cx);
897 let group = window.find(rating_element("stars"));
898 assert_eq!(group.role(), Some(Role::RadioGroup));
899
900 window.click(rating_element("stars"), cx);
902 window.press("4", cx);
903 });
904 assert_eq!(events.borrow().last().map(String::as_str), Some("4"));
905
906 cx.update(|window, cx| {
907 window.press("up", cx);
908 });
909 assert_eq!(events.borrow().last().map(String::as_str), Some("5"));
910
911 cx.update(|window, cx| {
912 window.press("left", cx);
913 });
914 assert_eq!(events.borrow().last().map(String::as_str), Some("4"));
915
916 cx.update(|window, cx| {
918 window.press("enter", cx);
919 });
920 assert_eq!(events.borrow().last().map(String::as_str), Some("0"));
921
922 view.update(cx, |host, cx| {
924 host.disabled = true;
925 cx.notify();
926 });
927 cx.update(|window, cx| {
928 window.render_frame(cx);
929 window.press("4", cx);
930 });
931 assert_eq!(events.borrow().last().map(String::as_str), Some("0"));
932 }
933
934 #[gpui_kit::test]
935 fn rating_reduced_motion_still_commits(cx: &mut TestAppContext) {
936 cx.update(|cx| {
937 gpui_kit::init(cx);
938 install_arc_theme(ThemeMode::Light, Accent::Violet, cx);
939 arc_motion::set_reduced_motion(arc_motion::ReducedMotionChoice::Reduce, cx);
940 });
941
942 let host = RatingHost {
943 value: 2.0,
944 events: Rc::new(RefCell::new(Vec::new())),
945 disabled: false,
946 };
947 let events = host.events.clone();
948 let (_view, cx) = cx.add_window_view(|_, _| host);
949
950 cx.update(|window, cx| {
951 window.render_frame(cx);
952 window.click(rating_element("stars"), cx);
954 window.press("left", cx);
955 });
956 assert_eq!(events.borrow().last().map(String::as_str), Some("2"));
957 }
958}