Skip to main content

gpui_component/
rating.rs

1use crate::theme::ActiveTheme;
2use crate::{Disableable, Icon, IconName, Sizable, Size, StyledExt, h_flex};
3use gpui_base::LogicalStyledExt as _;
4use std::rc::Rc;
5
6use gpui::{
7    App, ElementId, InteractiveElement, IntoElement, ParentElement, RenderOnce, StyleRefinement,
8    Styled, Window, div, prelude::FluentBuilder as _,
9};
10use gpui::{ClickEvent, Hsla, StatefulInteractiveElement};
11
12/// A simple star Rating element.
13#[derive(IntoElement)]
14pub struct Rating {
15    id: ElementId,
16    style: StyleRefinement,
17    size: Size,
18    disabled: bool,
19    value: usize,
20    max: usize,
21    color: Option<Hsla>,
22    on_click: Option<Rc<dyn Fn(&usize, &mut Window, &mut App) + 'static>>,
23}
24
25impl Rating {
26    /// Create a new Rating with an `ElementId`.
27    pub fn new(id: impl Into<ElementId>) -> Self {
28        Self {
29            id: id.into(),
30            style: StyleRefinement::default(),
31            size: Size::Medium,
32            disabled: false,
33            value: 0,
34            max: 5,
35            color: None,
36            on_click: None,
37        }
38    }
39
40    /// Set the star size.
41    pub fn with_size(mut self, size: impl Into<Size>) -> Self {
42        self.size = size.into();
43        self
44    }
45
46    /// Disable interaction.
47    pub fn disabled(mut self, disabled: bool) -> Self {
48        self.disabled = disabled;
49        self
50    }
51
52    /// Set active color, default will use `yellow` from theme colors.
53    pub fn color(mut self, color: impl Into<Hsla>) -> Self {
54        self.color = Some(color.into());
55        self
56    }
57
58    /// Set initial value (0..=max).
59    pub fn value(mut self, value: usize) -> Self {
60        self.value = value;
61        if self.value > self.max {
62            self.value = self.max;
63        }
64        self
65    }
66
67    /// Set maximum number of stars.
68    pub fn max(mut self, max: usize) -> Self {
69        self.max = max;
70        if self.value > self.max {
71            self.value = self.max;
72        }
73        self
74    }
75
76    /// Add on_click handler when the rating changes.
77    ///
78    /// The `&usize` parameter is the new rating value.
79    pub fn on_click(mut self, handler: impl Fn(&usize, &mut Window, &mut App) + 'static) -> Self {
80        self.on_click = Some(Rc::new(handler));
81        self
82    }
83}
84
85impl Styled for Rating {
86    fn style(&mut self) -> &mut gpui::StyleRefinement {
87        &mut self.style
88    }
89}
90
91impl Sizable for Rating {
92    fn with_size(mut self, size: impl Into<Size>) -> Self {
93        self.size = size.into();
94        self
95    }
96}
97
98impl Disableable for Rating {
99    fn disabled(mut self, disabled: bool) -> Self {
100        self.disabled = disabled;
101        self
102    }
103}
104
105struct RaitingState {
106    /// To save the default value on init state, to detect external value changes.
107    default_value: usize,
108    /// To store the current selected value.
109    value: usize,
110    /// To store the currently hovered value.
111    hovered_value: usize,
112}
113
114impl RenderOnce for Rating {
115    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
116        let id = self.id;
117        let size = self.size;
118        let disabled = self.disabled;
119        let max = self.max;
120        let default_value = self.value;
121        let active_color = self.color.unwrap_or(cx.theme().yellow);
122        let on_click = self.on_click.clone();
123
124        let state = window.use_keyed_state(id.clone(), cx, |_, _| RaitingState {
125            default_value,
126            value: default_value,
127            hovered_value: 0,
128        });
129
130        // Reset state if outside has changed `value` prop.
131        if state.read(cx).default_value != default_value {
132            state.update(cx, |state, _| {
133                state.default_value = default_value;
134                state.value = default_value;
135            });
136        }
137        let value = state.read(cx).value;
138
139        h_flex()
140            .flex_row_dir(cx)
141            .id(id)
142            .flex_nowrap()
143            .refine_style(&self.style)
144            .on_hover(window.listener_for(&state, move |state, hovered, _, cx| {
145                if !hovered && state.hovered_value != 0 {
146                    state.hovered_value = 0;
147                    cx.notify();
148                }
149            }))
150            .map(|mut this| {
151                for ix in 1..=max {
152                    let filled = ix <= value;
153                    let hovered = state.read(cx).hovered_value >= ix;
154
155                    this = this.child(
156                        div()
157                            .id(ix)
158                            .p_0p5()
159                            .flex_none()
160                            .flex_shrink_0()
161                            .when(filled || hovered, |this| this.text_color(active_color))
162                            .child(
163                                Icon::new(if filled {
164                                    IconName::StarFill
165                                } else {
166                                    IconName::Star
167                                })
168                                .with_size(size),
169                            )
170                            .when(!disabled, |this| {
171                                this.on_mouse_move(window.listener_for(
172                                    &state,
173                                    move |state, _, _, cx| {
174                                        if state.hovered_value != ix {
175                                            state.hovered_value = ix;
176                                            cx.notify();
177                                        }
178                                    },
179                                ))
180                                .on_click({
181                                    let state = state.clone();
182                                    let on_click = on_click.clone();
183                                    move |_: &ClickEvent, window, cx| {
184                                        let new = if value >= ix {
185                                            ix.saturating_sub(1)
186                                        } else {
187                                            ix
188                                        };
189
190                                        state.update(cx, |state, cx| {
191                                            state.value = new;
192                                            cx.notify();
193                                        });
194
195                                        if let Some(on_click) = &on_click {
196                                            on_click(&new, window, cx);
197                                        }
198                                    }
199                                })
200                            }),
201                    );
202                }
203
204                this
205            })
206    }
207}