Skip to main content

fc_ui/capabilities/controls/
rating.rs

1use crate::capabilities::foundation::theme::use_theme;
2use crate::capabilities::primitives::icon::{Icon, IconSize as IconSizeEnum};
3use gpui::{prelude::*, *};
4use std::rc::Rc;
5
6#[derive(Copy, Clone, Debug, PartialEq, Eq)]
7pub enum RatingSize {
8    Sm,
9    Md,
10    Lg,
11}
12
13impl RatingSize {
14    pub fn icon_size(&self) -> Pixels {
15        match self {
16            RatingSize::Sm => px(16.0),
17            RatingSize::Md => px(24.0),
18            RatingSize::Lg => px(32.0),
19        }
20    }
21
22    pub fn gap(&self) -> Pixels {
23        match self {
24            RatingSize::Sm => px(2.0),
25            RatingSize::Md => px(4.0),
26            RatingSize::Lg => px(6.0),
27        }
28    }
29}
30
31pub struct RatingState {
32    value: f32,
33    max_rating: u8,
34    allows_half: bool,
35    focus_handle: FocusHandle,
36    hover_value: Option<f32>,
37}
38
39impl RatingState {
40    pub fn new(cx: &mut Context<Self>) -> Self {
41        Self {
42            value: 0.0,
43            max_rating: 5,
44            allows_half: false,
45            focus_handle: cx.focus_handle(),
46            hover_value: None,
47        }
48    }
49
50    pub fn value(&self) -> f32 {
51        self.value
52    }
53
54    pub fn set_value(&mut self, value: f32, cx: &mut Context<Self>) {
55        let max = self.max_rating as f32;
56        let clamped = value.clamp(0.0, max);
57        let stepped = if self.allows_half {
58            (clamped * 2.0).round() / 2.0
59        } else {
60            clamped.round()
61        };
62        if (self.value - stepped).abs() > f32::EPSILON {
63            self.value = stepped;
64            cx.notify();
65        }
66    }
67
68    pub fn max_rating(&self) -> u8 {
69        self.max_rating
70    }
71
72    pub fn set_max_rating(&mut self, max: u8, cx: &mut Context<Self>) {
73        let max = max.max(1);
74        self.max_rating = max;
75        self.value = self.value.min(max as f32);
76        cx.notify();
77    }
78
79    pub fn allows_half(&self) -> bool {
80        self.allows_half
81    }
82
83    pub fn set_allows_half(&mut self, allows: bool, cx: &mut Context<Self>) {
84        self.allows_half = allows;
85        if !allows {
86            self.value = self.value.round();
87        }
88        cx.notify();
89    }
90
91    fn set_hover_value(&mut self, value: Option<f32>, cx: &mut Context<Self>) {
92        if self.hover_value != value {
93            self.hover_value = value;
94            cx.notify();
95        }
96    }
97
98    fn display_value(&self) -> f32 {
99        self.hover_value.unwrap_or(self.value)
100    }
101
102    fn increment(&mut self, cx: &mut Context<Self>) {
103        let step = if self.allows_half { 0.5 } else { 1.0 };
104        let new_value = (self.value + step).min(self.max_rating as f32);
105        self.set_value(new_value, cx);
106    }
107
108    fn decrement(&mut self, cx: &mut Context<Self>) {
109        let step = if self.allows_half { 0.5 } else { 1.0 };
110        let new_value = (self.value - step).max(0.0);
111        self.set_value(new_value, cx);
112    }
113}
114
115impl Focusable for RatingState {
116    fn focus_handle(&self, _: &App) -> FocusHandle {
117        self.focus_handle.clone()
118    }
119}
120
121impl Render for RatingState {
122    fn render(&mut self, _: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
123        div()
124    }
125}
126
127#[derive(IntoElement)]
128pub struct Rating {
129    state: Entity<RatingState>,
130    size: RatingSize,
131    read_only: bool,
132    filled_icon: SharedString,
133    empty_icon: SharedString,
134    half_icon: SharedString,
135    active_color: Option<Hsla>,
136    inactive_color: Option<Hsla>,
137    on_change: Option<Rc<dyn Fn(f32, &mut Window, &mut App) + 'static>>,
138    style: StyleRefinement,
139}
140
141impl Rating {
142    pub fn new(state: Entity<RatingState>) -> Self {
143        Self {
144            state,
145            size: RatingSize::Md,
146            read_only: false,
147            filled_icon: "star".into(),
148            empty_icon: "star".into(),
149            half_icon: "star-half".into(),
150            active_color: None,
151            inactive_color: None,
152            on_change: None,
153            style: StyleRefinement::default(),
154        }
155    }
156
157    pub fn size(mut self, size: RatingSize) -> Self {
158        self.size = size;
159        self
160    }
161
162    pub fn read_only(mut self, read_only: bool) -> Self {
163        self.read_only = read_only;
164        self
165    }
166
167    pub fn filled_icon(mut self, icon: impl Into<SharedString>) -> Self {
168        self.filled_icon = icon.into();
169        self
170    }
171
172    pub fn empty_icon(mut self, icon: impl Into<SharedString>) -> Self {
173        self.empty_icon = icon.into();
174        self
175    }
176
177    pub fn half_icon(mut self, icon: impl Into<SharedString>) -> Self {
178        self.half_icon = icon.into();
179        self
180    }
181
182    pub fn active_color(mut self, color: Hsla) -> Self {
183        self.active_color = Some(color);
184        self
185    }
186
187    pub fn inactive_color(mut self, color: Hsla) -> Self {
188        self.inactive_color = Some(color);
189        self
190    }
191
192    pub fn on_change(mut self, handler: impl Fn(f32, &mut Window, &mut App) + 'static) -> Self {
193        self.on_change = Some(Rc::new(handler));
194        self
195    }
196}
197
198impl Styled for Rating {
199    fn style(&mut self) -> &mut StyleRefinement {
200        &mut self.style
201    }
202}
203
204impl RenderOnce for Rating {
205    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
206        let theme = use_theme(cx);
207        let state = self.state.read(cx);
208        let focus_handle = state.focus_handle(cx);
209        let is_focused = focus_handle.is_focused(window);
210        let max_rating = state.max_rating;
211        let allows_half = state.allows_half;
212        let display_value = state.display_value();
213
214        let icon_size = self.size.icon_size();
215        let gap = self.size.gap();
216
217        let active_color = self.active_color.unwrap_or(hsla(0.12, 0.9, 0.55, 1.0));
218        let inactive_color = self
219            .inactive_color
220            .unwrap_or(theme.tokens.muted_foreground.opacity(0.4));
221
222        let focus_ring = theme.tokens.focus_ring_light();
223        let user_style = self.style.clone();
224
225        div()
226            .flex()
227            .items_center()
228            .gap(gap)
229            .when(!self.read_only, |this| {
230                this.track_focus(&focus_handle.tab_index(0).tab_stop(true))
231            })
232            .when(is_focused && !self.read_only, |this| {
233                this.rounded(theme.tokens.radius_sm)
234                    .shadow(smallvec::smallvec![focus_ring])
235            })
236            .when(!self.read_only, |this| {
237                let state_for_key = self.state.clone();
238                let on_change_for_key = self.on_change.clone();
239                this.on_key_down(window.listener_for(
240                    &state_for_key,
241                    move |state, e: &KeyDownEvent, window, cx| {
242                        let key = e.keystroke.key.as_str();
243                        match key {
244                            "left" | "down" => {
245                                state.decrement(cx);
246                                if let Some(ref handler) = on_change_for_key {
247                                    handler(state.value, window, cx);
248                                }
249                            }
250                            "right" | "up" => {
251                                state.increment(cx);
252                                if let Some(ref handler) = on_change_for_key {
253                                    handler(state.value, window, cx);
254                                }
255                            }
256                            "home" => {
257                                state.set_value(0.0, cx);
258                                if let Some(ref handler) = on_change_for_key {
259                                    handler(state.value, window, cx);
260                                }
261                            }
262                            "end" => {
263                                state.set_value(state.max_rating as f32, cx);
264                                if let Some(ref handler) = on_change_for_key {
265                                    handler(state.value, window, cx);
266                                }
267                            }
268                            _ => {}
269                        }
270                    },
271                ))
272            })
273            .when(!self.read_only, |this| {
274                let state_for_leave = self.state.clone();
275                let mut this = this;
276                this.interactivity().on_hover(window.listener_for(
277                    &state_for_leave,
278                    move |state, hovered: &bool, _, cx| {
279                        if !*hovered {
280                            state.set_hover_value(None, cx);
281                        }
282                    },
283                ));
284                this
285            })
286            .children((0..max_rating).map(|index| {
287                let position = index as f32 + 1.0;
288                let fill_state = get_star_fill_state(display_value, position, allows_half);
289
290                let icon_name = match fill_state {
291                    StarFillState::Full => self.filled_icon.clone(),
292                    StarFillState::Half => self.half_icon.clone(),
293                    StarFillState::Empty => self.empty_icon.clone(),
294                };
295
296                let color = match fill_state {
297                    StarFillState::Full | StarFillState::Half => active_color,
298                    StarFillState::Empty => inactive_color,
299                };
300
301                let state_for_star = self.state.clone();
302                let state_for_star_right = self.state.clone();
303                let state_for_hover = self.state.clone();
304                let state_for_hover_right = self.state.clone();
305                let on_change_for_star = self.on_change.clone();
306                let on_change_for_star_right = self.on_change.clone();
307                let on_change_no_half = self.on_change.clone();
308                let read_only = self.read_only;
309
310                div()
311                    .relative()
312                    .w(icon_size)
313                    .h(icon_size)
314                    .cursor(if read_only {
315                        CursorStyle::Arrow
316                    } else {
317                        CursorStyle::PointingHand
318                    })
319                    .when(!read_only && !allows_half, |this| {
320                        this.on_mouse_down(
321                            MouseButton::Left,
322                            window.listener_for(
323                                &state_for_star,
324                                move |state, _: &MouseDownEvent, window, cx| {
325                                    state.set_value(position, cx);
326                                    state.set_hover_value(None, cx);
327                                    if let Some(ref handler) = on_change_no_half {
328                                        handler(state.value, window, cx);
329                                    }
330                                },
331                            ),
332                        )
333                        .on_mouse_move(window.listener_for(
334                            &state_for_hover,
335                            move |state, _: &MouseMoveEvent, _, cx| {
336                                state.set_hover_value(Some(position), cx);
337                            },
338                        ))
339                    })
340                    .child(
341                        Icon::new(icon_name.as_ref())
342                            .size(IconSizeEnum::Custom(icon_size))
343                            .color(color),
344                    )
345                    .when(!read_only && allows_half, |this| {
346                        this.child(
347                            div()
348                                .absolute()
349                                .left_0()
350                                .top_0()
351                                .h_full()
352                                .w(icon_size / 2.0)
353                                .cursor(CursorStyle::PointingHand)
354                                .on_mouse_move(window.listener_for(
355                                    &state_for_hover,
356                                    move |state, _: &MouseMoveEvent, _, cx| {
357                                        state.set_hover_value(Some(position - 0.5), cx);
358                                    },
359                                ))
360                                .on_mouse_down(
361                                    MouseButton::Left,
362                                    window.listener_for(
363                                        &state_for_star,
364                                        move |state, _: &MouseDownEvent, window, cx| {
365                                            state.set_value(position - 0.5, cx);
366                                            state.set_hover_value(None, cx);
367                                            if let Some(ref handler) = on_change_for_star {
368                                                handler(state.value, window, cx);
369                                            }
370                                        },
371                                    ),
372                                ),
373                        )
374                        .child(
375                            div()
376                                .absolute()
377                                .right_0()
378                                .top_0()
379                                .h_full()
380                                .w(icon_size / 2.0)
381                                .cursor(CursorStyle::PointingHand)
382                                .on_mouse_move(window.listener_for(
383                                    &state_for_hover_right,
384                                    move |state, _: &MouseMoveEvent, _, cx| {
385                                        state.set_hover_value(Some(position), cx);
386                                    },
387                                ))
388                                .on_mouse_down(
389                                    MouseButton::Left,
390                                    window.listener_for(
391                                        &state_for_star_right,
392                                        move |state, _: &MouseDownEvent, window, cx| {
393                                            state.set_value(position, cx);
394                                            state.set_hover_value(None, cx);
395                                            if let Some(ref handler) = on_change_for_star_right {
396                                                handler(state.value, window, cx);
397                                            }
398                                        },
399                                    ),
400                                ),
401                        )
402                    })
403            }))
404            .map(|this| {
405                let mut div = this;
406                div.style().refine(&user_style);
407                div
408            })
409    }
410}
411
412#[derive(Copy, Clone, Debug, PartialEq)]
413enum StarFillState {
414    Full,
415    Half,
416    Empty,
417}
418
419fn get_star_fill_state(value: f32, position: f32, allows_half: bool) -> StarFillState {
420    if value >= position {
421        StarFillState::Full
422    } else if allows_half && value >= position - 0.5 {
423        StarFillState::Half
424    } else {
425        StarFillState::Empty
426    }
427}