BlueGit

ict rusty-teams

Files

rusty-teams / crates / app / src / views / card_input.rs

card_input.rs

card_input.rs 13.7 KiB Download Raw
1use crate::views::image_memory::bounded;
2use gpui_kit::assets::IconName;
3use gpui_kit::component::checkbox::Checkbox;
4use gpui_kit::component::date_picker::DatePicker;
5use gpui_kit::component::input::{Input, Textarea};
6use gpui_kit::component::radio::{Radio, RadioGroup};
7use gpui_kit::component::select::Select;
8use gpui_kit::component::time_field::TimeField;
9use gpui_kit::component::{h_flex, v_flex};
10use gpui_kit::prelude::FluentBuilder as _;
11use gpui_kit::*;
12use teams_core::{
13 CardActionKind, CardInput, CardInputKind, ChoiceInput, DATE_PLACEHOLDER, InlineAction,
14 RatingColor, RatingDisplay, RatingInput, RatingSize, RatingStyle, ToggleInput,
15};
16
17use super::widgets::{icon, symbol};
18use crate::app_state::AppHandle;
19use crate::card_inputs::{InputField, inline_action_key, uses_select};
20use crate::card_state::{ActionPhase, CardScope, CardState};
21use crate::theme;
22
23const INPUT_GAP: f32 = 4.;
24const LABEL_SIZE: f32 = 12.5;
25const ERROR_SIZE: f32 = 12.;
26const FIELD_RADIUS: f32 = 6.;
27const CHOICE_GAP: f32 = 6.;
28const STAR_GAP: f32 = 2.;
29const STAR_MEDIUM: f32 = 20.;
30const STAR_LARGE: f32 = 28.;
31const RATING_TEXT_SIZE: f32 = 13.;
32const RATING_TEXT_GAP: f32 = 6.;
33const HALF: f64 = 0.5;
34const INLINE_ICON_SIZE: f32 = 16.;
35const INLINE_BUTTON_PADDING: f32 = 4.;
36const INLINE_BUSY_OPACITY: f32 = 0.5;
37
38pub fn input_view(
39 input: &CardInput,
40 scope: &CardScope,
41 state: &CardState,
42 inputs: &[CardInput],
43) -> AnyElement {
44 let key = scope.input_key(&input.id);
45 let error = state.input_error(&key).map(str::to_owned);
46 let label = input
47 .label
48 .as_deref()
49 .filter(|label| !label.trim().is_empty());
50 v_flex()
51 .id(ElementId::Name(format!("{key}-input").into()))
52 .w_full()
53 .gap(px(INPUT_GAP))
54 .on_click(|_, _, cx| cx.stop_propagation())
55 .when_some(label, |column, label| {
56 column.child(
57 div()
58 .text_size(px(LABEL_SIZE))
59 .font_weight(FontWeight::SEMIBOLD)
60 .text_color(theme::text_strong())
61 .child(if input.required {
62 format!("{label} *")
63 } else {
64 label.to_owned()
65 }),
66 )
67 })
68 .child(
69 div()
70 .w_full()
71 .rounded(px(FIELD_RADIUS))
72 .border_1()
73 .border_color(if error.is_some() {
74 theme::red()
75 } else {
76 transparent_black()
77 })
78 .child(control_view(input, &key, scope, state, inputs)),
79 )
80 .when_some(error, |column, error| {
81 column.child(
82 div()
83 .text_size(px(ERROR_SIZE))
84 .text_color(theme::red_soft())
85 .child(error),
86 )
87 })
88 .into_any_element()
89}
90
91fn control_view(
92 input: &CardInput,
93 key: &str,
94 scope: &CardScope,
95 state: &CardState,
96 inputs: &[CardInput],
97) -> AnyElement {
98 let current = state.input_value(key).to_owned();
99 match &input.kind {
100 CardInputKind::Toggle(toggle) => toggle_view(toggle, key, &current, scope),
101 CardInputKind::Rating(rating) => rating_input_view(rating, key, &current, scope),
102 CardInputKind::Choice(choice) if !uses_select(choice) => {
103 choices_view(choice, key, &current, scope)
104 }
105 _ => match state.input_field(key) {
106 Some(InputField::Line(field)) => {
107 let inline = match &input.kind {
108 CardInputKind::Text(text) => text.inline_action.as_ref(),
109 _ => None,
110 };
111 Input::new(field)
112 .when_some(inline, |line, inline| {
113 line.suffix(inline_action_view(inline, key, scope, state, inputs))
114 })
115 .into_any_element()
116 }
117 Some(InputField::Area(field)) => Textarea::new(field).into_any_element(),
118 Some(InputField::Date(field)) => DatePicker::new(field)
119 .placeholder(DATE_PLACEHOLDER)
120 .cleanable(!input.required)
121 .into_any_element(),
122 Some(InputField::Time(field)) => TimeField::new(field)
123 .invalid(state.input_error(key).is_some())
124 .into_any_element(),
125 Some(InputField::Select(field)) => {
126 let placeholder = match &input.kind {
127 CardInputKind::Choice(choice) => choice.placeholder.clone(),
128 _ => None,
129 };
130 Select::new(field)
131 .w_full()
132 .when_some(placeholder, |select, placeholder| {
133 select.placeholder(placeholder)
134 })
135 .into_any_element()
136 }
137 None => div().into_any_element(),
138 },
139 }
140}
141
142fn inline_action_view(
143 inline: &InlineAction,
144 key: &str,
145 scope: &CardScope,
146 state: &CardState,
147 inputs: &[CardInput],
148) -> AnyElement {
149 let action_key = inline_action_key(key);
150 let phase = state.phase(&action_key).cloned();
151 let glyph = match (&phase, &inline.icon_url) {
152 (Some(ActionPhase::Done), _) => {
153 symbol("done", INLINE_ICON_SIZE, theme::green()).into_any_element()
154 }
155 (_, Some(url)) if url.starts_with("https://") => img(bounded(url.clone()))
156 .size(px(INLINE_ICON_SIZE))
157 .into_any_element(),
158 _ => {
159 let name = match inline.action.kind {
160 CardActionKind::OpenUrl(_) => IconName::ExternalLink,
161 _ => IconName::SendHorizontal,
162 };
163 icon(name, INLINE_ICON_SIZE, theme::accent_text()).into_any_element()
164 }
165 };
166 let (scope, action, inputs) = (scope.clone(), inline.action.clone(), inputs.to_vec());
167 div()
168 .id(ElementId::Name(action_key.clone().into()))
169 .p(px(INLINE_BUTTON_PADDING))
170 .rounded(px(FIELD_RADIUS))
171 .cursor_pointer()
172 .hover(|button| button.bg(theme::row_hover()))
173 .when(phase == Some(ActionPhase::Busy), |button| {
174 button.opacity(INLINE_BUSY_OPACITY)
175 })
176 .child(glyph)
177 .on_click(move |_, _, cx| {
178 cx.stop_propagation();
179 let (scope, action, action_key, inputs) = (
180 scope.clone(),
181 action.clone(),
182 action_key.clone(),
183 inputs.clone(),
184 );
185 cx.global::<AppHandle>().0.clone().update(cx, |state, cx| {
186 state.run_inline_action(&scope, action_key, &action, &inputs, cx)
187 });
188 })
189 .into_any_element()
190}
191
192fn star_pixels(size: RatingSize) -> f32 {
193 match size {
194 RatingSize::Medium => STAR_MEDIUM,
195 RatingSize::Large => STAR_LARGE,
196 }
197}
198
199fn star_color(color: RatingColor) -> Hsla {
200 match color {
201 RatingColor::Neutral => theme::text_strong(),
202 RatingColor::Marigold => theme::amber(),
203 }
204}
205
206fn star_icon(rating: f64, position: u32, pixels: f32, color: Hsla) -> AnyElement {
207 let position = f64::from(position);
208 if rating >= position {
209 icon(IconName::StarFill, pixels, color).into_any_element()
210 } else if rating >= position - HALF {
211 div()
212 .relative()
213 .size(px(pixels))
214 .child(icon(IconName::Star, pixels, theme::text_muted()))
215 .child(
216 div()
217 .absolute()
218 .top_0()
219 .left_0()
220 .w(px(pixels / 2.))
221 .h(px(pixels))
222 .overflow_hidden()
223 .child(icon(IconName::StarFill, pixels, color)),
224 )
225 .into_any_element()
226 } else {
227 icon(IconName::Star, pixels, theme::text_muted()).into_any_element()
228 }
229}
230
231fn rating_input_view(
232 rating: &RatingInput,
233 key: &str,
234 current: &str,
235 scope: &CardScope,
236) -> AnyElement {
237 let value = rating.rating(current);
238 let pixels = star_pixels(rating.size);
239 let color = star_color(rating.color);
240 h_flex()
241 .gap(px(STAR_GAP))
242 .children((1..=rating.max).map(|position| {
243 let zones: Vec<f64> = if rating.allow_half {
244 vec![f64::from(position) - HALF, f64::from(position)]
245 } else {
246 vec![f64::from(position)]
247 };
248 div()
249 .relative()
250 .flex_none()
251 .size(px(pixels))
252 .child(star_icon(value, position, pixels, color))
253 .child(
254 h_flex()
255 .absolute()
256 .inset_0()
257 .children(
258 zones
259 .into_iter()
260 .enumerate()
261 .map(|(zone_index, zone_value)| {
262 let (scope, input_key, rating) =
263 (scope.clone(), key.to_owned(), rating.clone());
264 div()
265 .id(ElementId::Name(
266 format!("{key}-star-{position}-{zone_index}").into(),
267 ))
268 .flex_1()
269 .h_full()
270 .cursor_pointer()
271 .on_click(move |_, _, cx| {
272 cx.stop_propagation();
273 pick(
274 &scope,
275 &input_key,
276 rating.value_text(zone_value),
277 cx,
278 );
279 })
280 }),
281 ),
282 )
283 }))
284 .into_any_element()
285}
286
287pub fn rating_display_view(display: &RatingDisplay) -> AnyElement {
288 let pixels = star_pixels(display.size);
289 let color = star_color(RatingColor::Marigold);
290 let count = display.count.map(|count| format!("({count})"));
291 let row = match display.style {
292 RatingStyle::Compact => h_flex()
293 .gap(px(RATING_TEXT_GAP))
294 .child(star_icon(display.value, 1, pixels, color))
295 .child(format!("{:.1}", display.value)),
296 RatingStyle::Default => h_flex().gap(px(STAR_GAP)).children(
297 (1..=display.max).map(|position| star_icon(display.value, position, pixels, color)),
298 ),
299 };
300 row.items_center()
301 .text_size(px(RATING_TEXT_SIZE))
302 .text_color(theme::text_strong())
303 .when_some(count, |row, count| {
304 row.child(
305 div()
306 .ml(px(RATING_TEXT_GAP - STAR_GAP))
307 .text_color(theme::text_muted())
308 .child(count),
309 )
310 })
311 .into_any_element()
312}
313
314fn toggle_view(toggle: &ToggleInput, key: &str, current: &str, scope: &CardScope) -> AnyElement {
315 let (value_on, value_off) = (toggle.value_on.clone(), toggle.value_off.clone());
316 let (scope, input_key) = (scope.clone(), key.to_owned());
317 Checkbox::new(ElementId::Name(format!("{key}-toggle").into()))
318 .label(toggle.title.clone())
319 .checked(toggle.is_on(current))
320 .when(!toggle.wrap, |checkbox| {
321 checkbox.whitespace_nowrap().text_ellipsis()
322 })
323 .on_click(move |checked, _, cx| {
324 let value = if *checked { &value_on } else { &value_off };
325 pick(&scope, &input_key, value.clone(), cx);
326 })
327 .into_any_element()
328}
329
330fn choices_view(choice: &ChoiceInput, key: &str, current: &str, scope: &CardScope) -> AnyElement {
331 let (scope, input_key) = (scope.clone(), key.to_owned());
332 if choice.multi {
333 return v_flex()
334 .gap(px(CHOICE_GAP))
335 .children(choice.choices.iter().enumerate().map(|(index, candidate)| {
336 let (choice, scope, input_key, current, value) = (
337 choice.clone(),
338 scope.clone(),
339 input_key.clone(),
340 current.to_owned(),
341 candidate.value.clone(),
342 );
343 Checkbox::new(ElementId::Name(format!("{key}-choice-{index}").into()))
344 .label(candidate.title.clone())
345 .checked(choice.is_selected(&current, &value))
346 .on_click(move |_, _, cx| {
347 pick(&scope, &input_key, choice.toggled(&current, &value), cx)
348 })
349 }))
350 .into_any_element();
351 }
352 let selected = choice
353 .choices
354 .iter()
355 .position(|candidate| candidate.value == current);
356 let values: Vec<String> = choice
357 .choices
358 .iter()
359 .map(|candidate| candidate.value.clone())
360 .collect();
361 RadioGroup::new(ElementId::Name(format!("{key}-choices").into()))
362 .selected_index(selected)
363 .children(choice.choices.iter().enumerate().map(|(index, candidate)| {
364 Radio::new(ElementId::Name(format!("{key}-choice-{index}").into()))
365 .label(candidate.title.clone())
366 }))
367 .on_click(move |index, _, cx| {
368 if let Some(value) = values.get(*index) {
369 pick(&scope, &input_key, value.clone(), cx);
370 }
371 })
372 .into_any_element()
373}
374
375fn pick(scope: &CardScope, key: &str, value: String, cx: &mut App) {
376 cx.global::<AppHandle>()
377 .0
378 .clone()
379 .update(cx, |state, cx| state.pick_card_input(scope, key, value, cx));
380}