1use std::{cell::RefCell, collections::HashMap, rc::Rc, time::Duration};
26
27use arc_motion::{
28 BlurFallback, CubicBezier, arc_spring, arc_spring_with_options, arc_transition,
29 is_reduced_motion, motion_now, spring::SpringOptions,
30};
31use arc_tokens::{ActiveArcTheme as _, Radii, Spacing, Typography, oklab_mix};
32use gpui_kit::{
33 App, Bounds, ElementId, Entity, Focusable as _, IntoElement, KeyDownEvent, MouseButton,
34 ParentElement, Pixels, RenderOnce, Role, SharedString, Styled, TestSupportExt as _, Window,
35 assets::IconName,
36 base::StyledExt as _,
37 canvas,
38 component::{
39 Icon,
40 input::{Input as KitInput, InputState},
41 },
42 div,
43 prelude::*,
44 px,
45};
46
47use super::field_message::render_field_message;
48
49type TagInputChangeHandler = Rc<dyn Fn(&[SharedString], &mut Window, &mut App)>;
50type TagRectMap = Rc<RefCell<HashMap<SharedString, (f32, f32, f32, f32)>>>;
51
52pub const TAG_DUPLICATE_PULSE_SECS: f64 = 0.36;
54pub const TAG_INPUT_MIN_CONTENT_H_PX: f32 = 34.0;
56
57pub fn tag_duplicate_pulse_scale(elapsed: f64, reduced: bool) -> f32 {
60 if reduced || !(0.0..TAG_DUPLICATE_PULSE_SECS).contains(&elapsed) {
61 return 1.0;
62 }
63 let norm = (elapsed / TAG_DUPLICATE_PULSE_SECS).clamp(0.0, 1.0) as f32;
64 let ease = CubicBezier::new(0.65, 0.0, 0.35, 1.0);
65 let wave = if norm < 0.5 {
66 ease.sample(norm * 2.0)
67 } else {
68 1.0 - ease.sample((norm - 0.5) * 2.0)
69 };
70 1.0 + 0.06 * wave
71}
72
73pub fn tag_placeholder_sample(elapsed: f64, reduced: bool) -> (f32, f32) {
76 if reduced {
77 let t = (elapsed / 0.12).clamp(0.0, 1.0) as f32;
78 return (t, 0.0);
79 }
80 let t = (elapsed / 0.24).clamp(0.0, 1.0) as f32;
81 let e = CubicBezier::new(0.16, 1.0, 0.3, 1.0).sample(t);
82 let blur = BlurFallback::evaluate(px(4.0 * (1.0 - e)), false);
83 (
84 (e * blur.opacity_multiplier).clamp(0.0, 1.0),
85 4.2 * (1.0 - e),
86 )
87}
88
89pub fn try_add_tag(
94 tags: &[SharedString],
95 draft: &str,
96) -> Option<Result<Vec<SharedString>, SharedString>> {
97 let trimmed = draft.trim();
98 if trimmed.is_empty() {
99 return None;
100 }
101 let lower = trimmed.to_lowercase();
102 if let Some(existing) = tags.iter().find(|t| t.to_lowercase() == lower) {
103 return Some(Err(existing.clone()));
104 }
105 let mut next = tags.to_vec();
106 next.push(SharedString::from(trimmed.to_string()));
107 Some(Ok(next))
108}
109
110#[derive(Clone)]
111struct TagInputInternal {
112 uncontrolled_tags: Vec<SharedString>,
113 picked: Option<SharedString>,
114 ring_seeded: bool,
115 last_ring_rect: Option<(f32, f32, f32, f32)>,
116 pulsed_tag: Option<(SharedString, f64)>,
117 empty_entered_at_secs: f64,
118 was_empty: bool,
119 last_draft: SharedString,
120 control_hovered: bool,
121 pressed_remove: Option<SharedString>,
122 measured_content_h: Rc<RefCell<Option<f32>>>,
123 content_bounds: Rc<RefCell<Option<Bounds<Pixels>>>>,
124 tag_rects: TagRectMap,
125 draft_input: Entity<InputState>,
126}
127
128impl TagInputInternal {
129 fn new(default_tags: Vec<SharedString>, now: f64, window: &mut Window, cx: &mut App) -> Self {
130 let draft_input = cx.new(|cx| InputState::new(window, cx));
131 let is_empty = default_tags.is_empty();
132 Self {
133 uncontrolled_tags: default_tags,
134 picked: None,
135 ring_seeded: false,
136 last_ring_rect: None,
137 pulsed_tag: None,
138 empty_entered_at_secs: now - 10.0,
139 was_empty: is_empty,
140 last_draft: "".into(),
141 control_hovered: false,
142 pressed_remove: None,
143 measured_content_h: Rc::new(RefCell::new(None)),
144 content_bounds: Rc::new(RefCell::new(None)),
145 tag_rects: Rc::new(RefCell::new(HashMap::new())),
146 draft_input,
147 }
148 }
149}
150
151#[derive(IntoElement)]
154pub struct TagInput {
155 id: ElementId,
156 label: SharedString,
157 value: Option<Vec<SharedString>>,
158 default_value: Vec<SharedString>,
159 placeholder: SharedString,
160 description: Option<SharedString>,
161 disabled: bool,
162 width: Option<Pixels>,
163 on_value_change: Option<TagInputChangeHandler>,
164}
165
166impl TagInput {
167 pub fn new(id: impl Into<ElementId>, label: impl Into<SharedString>) -> Self {
168 Self {
169 id: id.into(),
170 label: label.into(),
171 value: None,
172 default_value: Vec::new(),
173 placeholder: "Add a tag".into(),
174 description: None,
175 disabled: false,
176 width: None,
177 on_value_change: None,
178 }
179 }
180
181 pub fn value<I, S>(mut self, value: I) -> Self
182 where
183 I: IntoIterator<Item = S>,
184 S: Into<SharedString>,
185 {
186 self.value = Some(value.into_iter().map(Into::into).collect());
187 self
188 }
189
190 pub fn default_value<I, S>(mut self, value: I) -> Self
191 where
192 I: IntoIterator<Item = S>,
193 S: Into<SharedString>,
194 {
195 self.default_value = value.into_iter().map(Into::into).collect();
196 self
197 }
198
199 pub fn placeholder(mut self, placeholder: impl Into<SharedString>) -> Self {
200 self.placeholder = placeholder.into();
201 self
202 }
203
204 pub fn description(mut self, description: impl Into<SharedString>) -> Self {
205 self.description = Some(description.into());
206 self
207 }
208
209 pub fn disabled(mut self, disabled: bool) -> Self {
210 self.disabled = disabled;
211 self
212 }
213
214 pub fn width(mut self, width: impl Into<Pixels>) -> Self {
215 self.width = Some(width.into());
216 self
217 }
218
219 pub fn on_value_change(
220 mut self,
221 handler: impl Fn(&[SharedString], &mut Window, &mut App) + 'static,
222 ) -> Self {
223 self.on_value_change = Some(Rc::new(handler));
224 self
225 }
226}
227
228impl RenderOnce for TagInput {
229 fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
230 let theme = cx.arc_theme().clone();
231 let colors = theme.colors;
232 let motion = theme.motion;
233 let reduced = is_reduced_motion(cx);
234 let now = motion_now(cx);
235
236 let initial_tags = self
237 .value
238 .clone()
239 .unwrap_or_else(|| self.default_value.clone());
240
241 let state_id =
242 ElementId::NamedChild(self.id.clone().into(), "__arc-tag-input-state".into());
243 let internal = window.use_keyed_state(state_id, cx, |window, cx| {
244 TagInputInternal::new(initial_tags.clone(), now, window, cx)
245 });
246
247 let tags: Vec<SharedString> = self
248 .value
249 .clone()
250 .unwrap_or_else(|| internal.read(cx).uncontrolled_tags.clone());
251
252 {
254 let d_in = internal.read(cx).draft_input.clone();
255 let raw_draft = d_in.read(cx).value().to_string();
256 let last_d = internal.read(cx).last_draft.clone();
257 if raw_draft.as_str() != last_d.as_ref() {
258 if raw_draft.ends_with(',') {
259 let candidate = raw_draft.trim_end_matches(',');
260 match try_add_tag(&tags, candidate) {
261 Some(Ok(next_tags)) => {
262 d_in.update(cx, |s, cx| s.set_value("", window, cx));
263 internal.update(cx, |s, _| {
264 s.uncontrolled_tags = next_tags.clone();
265 s.picked = None;
266 s.last_draft = "".into();
267 });
268 if let Some(cb) = &self.on_value_change {
269 cb(&next_tags, window, cx);
270 }
271 }
272 Some(Err(dup)) => {
273 d_in.update(cx, |s, cx| {
274 s.set_value(candidate.to_string(), window, cx);
275 });
276 internal.update(cx, |s, _| {
277 s.pulsed_tag = Some((dup, now));
278 s.last_draft = SharedString::from(candidate.to_string());
279 });
280 }
281 None => {
282 d_in.update(cx, |s, cx| s.set_value("", window, cx));
283 internal.update(cx, |s, _| {
284 s.last_draft = "".into();
285 });
286 }
287 }
288 } else {
289 internal.update(cx, |s, _| {
290 s.last_draft = SharedString::from(raw_draft);
291 s.picked = None;
292 });
293 }
294 }
295 }
296
297 let tags: Vec<SharedString> = self
298 .value
299 .clone()
300 .unwrap_or_else(|| internal.read(cx).uncontrolled_tags.clone());
301 let draft_str = internal.read(cx).draft_input.read(cx).value().to_string();
302 let is_empty = tags.is_empty() && draft_str.is_empty();
303
304 {
307 let target_ph = if tags.is_empty() {
308 self.placeholder.clone()
309 } else {
310 SharedString::default()
311 };
312 let d_in = internal.read(cx).draft_input.clone();
313 d_in.update(cx, |s, cx| {
314 s.set_placeholder(target_ph, window, cx);
315 });
316 }
317
318 {
320 let was_empty = internal.read(cx).was_empty;
321 if is_empty != was_empty {
322 internal.update(cx, |s, _| {
323 s.was_empty = is_empty;
324 if is_empty {
325 s.empty_entered_at_secs = now;
326 }
327 });
328 }
329 }
330
331 let snap = internal.read(cx).clone();
332 let active_pick: Option<SharedString> = snap.picked.clone().filter(|p| tags.contains(p));
333 let is_focused = snap
334 .draft_input
335 .read(cx)
336 .focus_handle(cx)
337 .is_focused(window);
338
339 let measured_h = snap
341 .measured_content_h
342 .borrow()
343 .map(|h| h.max(TAG_INPUT_MIN_CONTENT_H_PX));
344 let shell_h = arc_motion::arc_measured_spring(
345 (self.id.clone(), "control-h"),
346 measured_h,
347 TAG_INPUT_MIN_CONTENT_H_PX,
348 motion.spring.smooth,
349 window,
350 cx,
351 )
352 .max(TAG_INPUT_MIN_CONTENT_H_PX);
353
354 let active_rect = active_pick
356 .as_ref()
357 .and_then(|t| snap.tag_rects.borrow().get(t).copied())
358 .or(snap.last_ring_rect);
359 let has_ring = active_pick.is_some() && active_rect.is_some();
360 let ring_op = arc_transition(
361 (self.id.clone(), "ring-op"),
362 if has_ring { 1.0 } else { 0.0 },
363 if reduced {
364 motion.duration.instant
365 } else if has_ring {
366 motion.duration.fast
367 } else {
368 motion.duration.instant
369 },
370 motion.ease.standard,
371 window,
372 cx,
373 );
374
375 let (rx_t, ry_t, rw_t, rh_t) = active_rect.unwrap_or((7.0, 7.0, 64.0, 28.0));
376 let (ring_x, ring_y, ring_w, ring_h) = if reduced || !snap.ring_seeded || ring_op < 0.02 {
377 let _ = arc_spring_with_options(
378 (self.id.clone(), "ring-x"),
379 rx_t,
380 SpringOptions::new(motion.spring.morph).with_initial_value(rx_t),
381 window,
382 cx,
383 );
384 let _ = arc_spring_with_options(
385 (self.id.clone(), "ring-y"),
386 ry_t,
387 SpringOptions::new(motion.spring.morph).with_initial_value(ry_t),
388 window,
389 cx,
390 );
391 let _ = arc_spring_with_options(
392 (self.id.clone(), "ring-w"),
393 rw_t,
394 SpringOptions::new(motion.spring.morph).with_initial_value(rw_t),
395 window,
396 cx,
397 );
398 let _ = arc_spring_with_options(
399 (self.id.clone(), "ring-h"),
400 rh_t,
401 SpringOptions::new(motion.spring.morph).with_initial_value(rh_t),
402 window,
403 cx,
404 );
405 if has_ring && !snap.ring_seeded {
406 internal.update(cx, |s, _| {
407 s.ring_seeded = true;
408 s.last_ring_rect = Some((rx_t, ry_t, rw_t, rh_t));
409 });
410 } else if !has_ring && ring_op < 0.02 && snap.ring_seeded {
411 internal.update(cx, |s, _| s.ring_seeded = false);
412 }
413 (rx_t, ry_t, rw_t, rh_t)
414 } else {
415 internal.update(cx, |s, _| {
416 s.last_ring_rect = Some((rx_t, ry_t, rw_t, rh_t));
417 });
418 (
419 arc_spring(
420 (self.id.clone(), "ring-x"),
421 rx_t,
422 motion.spring.morph,
423 window,
424 cx,
425 ),
426 arc_spring(
427 (self.id.clone(), "ring-y"),
428 ry_t,
429 motion.spring.morph,
430 window,
431 cx,
432 ),
433 arc_spring(
434 (self.id.clone(), "ring-w"),
435 rw_t,
436 motion.spring.morph,
437 window,
438 cx,
439 ),
440 arc_spring(
441 (self.id.clone(), "ring-h"),
442 rh_t,
443 motion.spring.morph,
444 window,
445 cx,
446 ),
447 )
448 };
449
450 let empty_elapsed = (now - snap.empty_entered_at_secs).max(0.0);
452 let (ph_op, ph_y) = if is_empty {
453 if empty_elapsed < 0.25 {
454 window.request_animation_frame();
455 }
456 tag_placeholder_sample(empty_elapsed, reduced)
457 } else {
458 (0.0, 0.0)
459 };
460
461 let hover_p = arc_transition(
463 (self.id.clone(), "control-hover"),
464 if !self.disabled && !is_focused && snap.control_hovered {
465 1.0
466 } else {
467 0.0
468 },
469 if reduced {
470 Duration::ZERO
471 } else {
472 motion.duration.fast
473 },
474 motion.ease.standard,
475 window,
476 cx,
477 );
478 let border_color = if !self.disabled && is_focused {
479 colors.foreground
480 } else {
481 oklab_mix(colors.border_strong, colors.border, hover_p)
482 };
483
484 let content_h_ref = snap.measured_content_h.clone();
486 let content_b_ref = snap.content_bounds.clone();
487 let content_probe = canvas(
488 move |rect, window, _| {
489 *content_b_ref.borrow_mut() = Some(rect);
490 let h = f32::from(rect.size.height).max(TAG_INPUT_MIN_CONTENT_H_PX);
491 let prev = *content_h_ref.borrow();
492 *content_h_ref.borrow_mut() = Some(h);
493 if prev.is_none_or(|prev| (prev - h).abs() > 0.5) {
494 window.request_animation_frame();
495 }
496 },
497 |_, _, _, _| {},
498 )
499 .absolute()
500 .inset_0();
501
502 let disabled = self.disabled;
503 let tag_els = tags
504 .iter()
505 .map(|tag| {
506 let is_picked = active_pick.as_ref() == Some(tag);
507 let tag_op = arc_transition(
508 (self.id.clone(), format!("tag-op-{tag}")),
509 1.0,
510 if reduced {
511 motion.duration.instant
512 } else {
513 motion.duration.fast
514 },
515 motion.ease.enter,
516 window,
517 cx,
518 );
519 let blur = BlurFallback::evaluate(motion.blur.soft * (1.0 - tag_op), reduced);
520
521 let pulse_scale = if let Some((ref p_tag, started_at)) = snap.pulsed_tag
523 && p_tag == tag
524 {
525 let el = (now - started_at).max(0.0);
526 if el < TAG_DUPLICATE_PULSE_SECS {
527 window.request_animation_frame();
528 }
529 tag_duplicate_pulse_scale(el, reduced)
530 } else {
531 1.0
532 };
533 let extra_px = ((pulse_scale - 1.0) * 18.0).max(0.0);
534
535 let rects_map = snap.tag_rects.clone();
536 let content_b_for_tag = snap.content_bounds.clone();
537 let tag_key = tag.clone();
538 let tag_probe = canvas(
539 move |rect, _, _| {
540 if let Some(cb) = *content_b_for_tag.borrow() {
541 let rel_x = f32::from(rect.origin.x - cb.origin.x);
542 let rel_y = f32::from(rect.origin.y - cb.origin.y);
543 let w = f32::from(rect.size.width);
544 let h = f32::from(rect.size.height);
545 rects_map
546 .borrow_mut()
547 .insert(tag_key.clone(), (rel_x, rel_y, w, h));
548 }
549 },
550 |_, _, _, _| {},
551 )
552 .absolute()
553 .inset_0();
554
555 let int_pick = internal.clone();
556 let int_rem = internal.clone();
557 let int_down = internal.clone();
558 let int_up = internal.clone();
559 let int_out = internal.clone();
560 let on_change = self.on_value_change.clone();
561 let cur_tags = tags.clone();
562 let tag_for_pick = tag.clone();
563 let tag_for_rem = tag.clone();
564 let tag_for_down = tag.clone();
565 let is_rem_pressed = snap.pressed_remove.as_ref() == Some(tag);
566 let rem_sz = if is_rem_pressed && !reduced {
567 21.0
568 } else {
569 22.0
570 };
571 let rem_hover_bg = colors.surface;
572 let rem_hover_fg = colors.foreground;
573 let rem_fg = if is_picked {
574 colors.foreground
575 } else {
576 colors.text_secondary
577 };
578
579 div()
580 .id(ElementId::NamedChild(
581 self.id.clone().into(),
582 SharedString::from(format!("tag-{tag}")),
583 ))
584 .test_support()
585 .relative()
586 .flex_none()
587 .h(px(28.0 + extra_px))
588 .pl(px(9.0 + extra_px * 0.5))
589 .pr(px(4.0 + extra_px * 0.5))
590 .flex()
591 .flex_row()
592 .items_center()
593 .gap(px(3.0))
594 .rounded(Radii::PILL)
595 .border_1()
596 .border_color(if is_picked {
597 colors.accent
598 } else {
599 colors.border
600 })
601 .bg(if is_picked {
602 colors.accent_subtle
603 } else {
604 colors.surface_muted
605 })
606 .opacity((tag_op * blur.opacity_multiplier).clamp(0.0, 1.0))
607 .text_size(Typography::TEXT_SM)
608 .text_color(colors.foreground)
609 .when(!disabled, |this| this.cursor_pointer())
610 .on_click(move |_, window, cx| {
611 if disabled {
612 return;
613 }
614 let d_in = int_pick.read(cx).draft_input.clone();
615 d_in.update(cx, |s, cx| s.focus(window, cx));
616 int_pick.update(cx, |s, _| {
617 if s.picked.as_ref() == Some(&tag_for_pick) {
618 s.picked = None;
619 } else {
620 s.picked = Some(tag_for_pick.clone());
621 }
622 });
623 window.refresh();
624 })
625 .child(tag_probe)
626 .child(div().flex_none().whitespace_nowrap().child(tag.clone()))
627 .child(
628 div()
629 .id(ElementId::NamedChild(
630 self.id.clone().into(),
631 SharedString::from(format!("remove-{tag}")),
632 ))
633 .test_support()
634 .role(Role::Button)
635 .aria_label(SharedString::from(format!("Remove {tag}")))
636 .on_click(move |_, window, cx| {
637 if disabled {
638 return;
639 }
640 let next_tags: Vec<SharedString> = cur_tags
641 .iter()
642 .filter(|&item| item != &tag_for_rem)
643 .cloned()
644 .collect();
645 let d_in = int_rem.read(cx).draft_input.clone();
646 d_in.update(cx, |s, cx| s.focus(window, cx));
647 int_rem.update(cx, |s, _| {
648 s.uncontrolled_tags = next_tags.clone();
649 s.picked = None;
650 s.pressed_remove = None;
651 });
652 if let Some(cb) = &on_change {
653 cb(&next_tags, window, cx);
654 }
655 window.refresh();
656 })
657 .w(px(rem_sz))
658 .h(px(rem_sz))
659 .flex_none()
660 .flex()
661 .items_center()
662 .justify_center()
663 .rounded(Radii::PILL)
664 .text_color(rem_fg)
665 .when(!disabled, |this| {
666 this.cursor_pointer()
667 .hover(move |s| s.bg(rem_hover_bg).text_color(rem_hover_fg))
668 })
669 .on_mouse_down(MouseButton::Left, move |_, window, cx| {
670 int_down.update(cx, |s, _| {
671 s.pressed_remove = Some(tag_for_down.clone());
672 });
673 window.refresh();
674 })
675 .on_mouse_up(MouseButton::Left, move |_, window, cx| {
676 int_up.update(cx, |s, _| s.pressed_remove = None);
677 window.refresh();
678 })
679 .on_mouse_up_out(MouseButton::Left, move |_, window, cx| {
680 int_out.update(cx, |s, _| s.pressed_remove = None);
681 window.refresh();
682 })
683 .child(Icon::new(IconName::X).text_size(px(13.0))),
684 )
685 .into_any_element()
686 })
687 .collect::<Vec<_>>();
688
689 let int_hover = internal.clone();
690 let int_focus_bg = internal.clone();
691 let int_key = internal.clone();
692 let tags_for_key = tags.clone();
693 let active_for_key = active_pick;
694 let on_change_key = self.on_value_change.clone();
695 let _ = (ph_op, ph_y);
696
697 let content_el = div()
698 .relative()
699 .w_full()
700 .min_h(px(TAG_INPUT_MIN_CONTENT_H_PX))
701 .p(px(7.0))
702 .flex()
703 .flex_row()
704 .flex_wrap()
705 .items_center()
706 .gap(px(6.0))
707 .child(content_probe)
708 .when(ring_op > 0.01, |this| {
709 this.child(
710 div()
711 .absolute()
712 .left(px(ring_x))
713 .top(px(ring_y))
714 .w(px(ring_w))
715 .h(px(ring_h))
716 .rounded(Radii::PILL)
717 .border_1()
718 .border_color(colors.accent)
719 .bg(colors.accent_subtle)
720 .opacity(ring_op),
721 )
722 })
723 .children(tag_els)
724 .child(
725 div()
726 .flex_1()
727 .min_w(px(96.0))
728 .h(px(28.0))
729 .flex()
730 .items_center()
731 .text_size(Typography::TEXT_SM)
732 .text_color(colors.foreground)
733 .child(
734 KitInput::new(&snap.draft_input)
735 .appearance(false)
736 .disabled(disabled)
737 .px(px(2.0))
738 .py(px(0.0))
739 .h(px(28.0))
740 .w_full(),
741 ),
742 );
743
744 let control = div()
745 .id(ElementId::NamedChild(
746 self.id.clone().into(),
747 "control".into(),
748 ))
749 .test_support()
750 .w_full()
751 .h(px(shell_h + 2.0))
752 .rounded(Radii::CONTROL)
753 .border_1()
754 .border_color(border_color)
755 .bg(colors.surface)
756 .opacity(if disabled { 0.5 } else { 1.0 })
757 .overflow_hidden()
758 .on_hover(move |hovered, window, cx| {
759 int_hover.update(cx, |s, _| s.control_hovered = *hovered);
760 window.refresh();
761 })
762 .on_click(move |_, window, cx| {
763 if !disabled {
764 let d_in = int_focus_bg.read(cx).draft_input.clone();
765 d_in.update(cx, |s, cx| s.focus(window, cx));
766 }
767 })
768 .on_key_down(move |event: &KeyDownEvent, window, cx| {
769 if disabled {
770 return;
771 }
772 let d_in = int_key.read(cx).draft_input.clone();
773 let cur_draft = d_in.read(cx).value().to_string();
774 let active_idx = active_for_key
775 .as_ref()
776 .and_then(|a| tags_for_key.iter().position(|t| t == a))
777 .unwrap_or(tags_for_key.len());
778
779 match event.keystroke.key.as_str() {
780 "enter" => {
781 let t_now = motion_now(cx);
782 match try_add_tag(&tags_for_key, &cur_draft) {
783 Some(Ok(next_tags)) => {
784 d_in.update(cx, |s, cx| s.set_value("", window, cx));
785 int_key.update(cx, |s, _| {
786 s.uncontrolled_tags = next_tags.clone();
787 s.picked = None;
788 s.last_draft = "".into();
789 });
790 if let Some(cb) = &on_change_key {
791 cb(&next_tags, window, cx);
792 }
793 window.refresh();
794 }
795 Some(Err(existing)) => {
796 int_key.update(cx, |s, _| {
797 s.pulsed_tag = Some((existing, t_now));
798 });
799 window.refresh();
800 }
801 None => {}
802 }
803 }
804 "backspace" | "delete" => {
805 if let Some(ref picked_tag) = active_for_key {
806 let next_tags: Vec<SharedString> = tags_for_key
807 .iter()
808 .filter(|&t| t != picked_tag)
809 .cloned()
810 .collect();
811 int_key.update(cx, |s, _| {
812 s.uncontrolled_tags = next_tags.clone();
813 s.picked = None;
814 });
815 if let Some(cb) = &on_change_key {
816 cb(&next_tags, window, cx);
817 }
818 window.refresh();
819 } else if event.keystroke.key.as_str() == "backspace"
820 && cur_draft.is_empty()
821 && let Some(last_tag) = tags_for_key.last()
822 {
823 let t = last_tag.clone();
824 int_key.update(cx, |s, _| {
825 s.picked = Some(t);
826 });
827 window.refresh();
828 }
829 }
830 "left" | "arrowleft"
831 if (cur_draft.is_empty() || active_for_key.is_some()) && active_idx > 0 =>
832 {
833 let prev_tag = tags_for_key[active_idx - 1].clone();
834 int_key.update(cx, |s, _| {
835 s.picked = Some(prev_tag);
836 });
837 window.refresh();
838 }
839 "right" | "arrowright" if active_for_key.is_some() => {
840 let next_pick = tags_for_key.get(active_idx + 1).cloned();
841 int_key.update(cx, |s, _| {
842 s.picked = next_pick;
843 });
844 window.refresh();
845 }
846 "escape" if active_for_key.is_some() => {
847 int_key.update(cx, |s, _| {
848 s.picked = None;
849 });
850 window.refresh();
851 }
852 _ => {}
853 }
854 })
855 .child(content_el);
856
857 let desc_id = ElementId::NamedChild(self.id.clone().into(), "description".into());
858
859 div()
860 .id(self.id)
861 .test_support()
862 .when_some(self.width, |this, w| this.w(w))
863 .when(self.width.is_none(), |this| this.w_full())
864 .flex()
865 .flex_col()
866 .child(
867 div()
868 .mb(Spacing::S2)
869 .text_size(Typography::TEXT_SM)
870 .font_medium()
871 .text_color(colors.foreground)
872 .child(self.label),
873 )
874 .child(control)
875 .child(render_field_message(
876 desc_id,
877 self.description,
878 false,
879 window,
880 cx,
881 ))
882 }
883}
884
885#[cfg(test)]
886mod tests {
887 use super::*;
888
889 #[test]
890 fn try_add_tag_rejects_empty_and_detects_case_insensitive_duplicates() {
891 let existing: Vec<SharedString> = vec!["Rust".into(), "GPUI".into()];
892 assert!(try_add_tag(&existing, " ").is_none());
893 assert_eq!(
894 try_add_tag(&existing, "rust"),
895 Some(Err(SharedString::from("Rust")))
896 );
897 assert_eq!(
898 try_add_tag(&existing, " Motion "),
899 Some(Ok(vec![
900 SharedString::from("Rust"),
901 SharedString::from("GPUI"),
902 SharedString::from("Motion")
903 ]))
904 );
905 }
906
907 #[test]
908 fn tag_duplicate_pulse_peaks_at_1_06_and_settles_to_1_0() {
909 assert!((tag_duplicate_pulse_scale(0.0, false) - 1.0).abs() < 1e-4);
910 let peak = tag_duplicate_pulse_scale(TAG_DUPLICATE_PULSE_SECS * 0.5, false);
911 assert!((peak - 1.06).abs() < 1e-3);
912 assert!((tag_duplicate_pulse_scale(0.40, false) - 1.0).abs() < 1e-4);
913 assert!((tag_duplicate_pulse_scale(0.18, true) - 1.0).abs() < 1e-4);
914 }
915
916 #[test]
917 fn tag_placeholder_sample_rises_from_4_2px_to_zero() {
918 let (op0, y0) = tag_placeholder_sample(0.0, false);
919 assert!(op0 < 0.01);
920 assert!((y0 - 4.2).abs() < 1e-4);
921
922 let (op1, y1) = tag_placeholder_sample(0.26, false);
923 assert!((op1 - 1.0).abs() < 1e-4);
924 assert!(y1.abs() < 1e-4);
925 }
926}