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