arc-ui 0.4.0

Physics-first native Rust desktop UI component library & charts for GPUI (120+ interactive components ported from Arc).
Documentation
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
//! Ported from Arc (MIT) © 2026 Elia Kuratli
//! Reference: `Arc源码/arc-library/registry/components/tag-input/tag-input.tsx` & `.module.css`
//!
//! P4 Component #5: `tag-input`
//!
//! - Multi-tag freeform input (`ControlHeights::MD` 44px minimum height, `7px` inner padding,
//!   `6px` gap, `Radii::CONTROL`, `1px border`, `surface` background):
//!   - Shell height follows wrapped tag rows on `motion.spring.smooth` so opening or closing a
//!     second line never snaps.
//!   - Each tag pill (`min-height: 28px`, `Radii::PILL`, `1px border`, `surface_muted` background,
//!     `22×22px` circular remove button with `scale(0.96)` press) blurs and springs in on
//!     `motion.spring.morph` (`duration.fast` opacity, `BlurFallback::soft`) and collapses cleanly
//!     on removal.
//!   - Two-step keyboard removal & gliding pick ring:
//!     - Pressing `Backspace` at the start of an empty draft (or `ArrowLeft` / `ArrowRight`, or
//!       clicking a tag pill) selects (`picked`) a tag first.
//!     - A pick ring (`1px solid colors.accent`, `colors.accent_subtle` fill, `Radii::PILL`)
//!       glides between picked tags on `motion.spring.morph` (`x, y, width, height`).
//!     - Pressing `Backspace` or `Delete` while a tag is picked removes it; `Escape` clears the
//!       pick.
//!   - Duplicate pulse: committing (`Enter` or `,`) a tag that already exists (case-insensitive)
//!     pulses the existing tag (`scale: 1.0 -> 1.06 -> 1.0` over `360ms`, `ease.inOut`) instead of
//!     adding a duplicate.

use std::{cell::RefCell, collections::HashMap, rc::Rc, time::Duration};

use arc_motion::{
    BlurFallback, CubicBezier, arc_spring, arc_spring_with_options, arc_transition,
    is_reduced_motion, motion_now, spring::SpringOptions,
};
use arc_tokens::{ActiveArcTheme as _, Radii, Spacing, Typography, oklab_mix};
use gpui_kit::{
    App, Bounds, ElementId, Entity, Focusable as _, IntoElement, KeyDownEvent, MouseButton,
    ParentElement, Pixels, RenderOnce, Role, SharedString, Styled, TestSupportExt as _, Window,
    assets::IconName,
    base::StyledExt as _,
    canvas,
    component::{
        Icon,
        input::{Input as KitInput, InputState},
    },
    div,
    prelude::*,
    px,
};

use super::field_message::render_field_message;

type TagInputChangeHandler = Rc<dyn Fn(&[SharedString], &mut Window, &mut App)>;
type TagRectMap = Rc<RefCell<HashMap<SharedString, (f32, f32, f32, f32)>>>;

/// Duration (`360ms` = `duration.standard 240ms + duration.instant 120ms`) of the duplicate tag pulse.
pub const TAG_DUPLICATE_PULSE_SECS: f64 = 0.36;
/// Minimum content height (`34px`, inside `1px` top/bottom border = `36px` control height).
pub const TAG_INPUT_MIN_CONTENT_H_PX: f32 = 34.0;

/// Evaluates the `[1.0 -> 1.06 -> 1.0]` scale pulse at `elapsed` seconds after a duplicate tag
/// commit (`360ms`, `ease.inOut`).
pub fn tag_duplicate_pulse_scale(elapsed: f64, reduced: bool) -> f32 {
    if reduced || !(0.0..TAG_DUPLICATE_PULSE_SECS).contains(&elapsed) {
        return 1.0;
    }
    let norm = (elapsed / TAG_DUPLICATE_PULSE_SECS).clamp(0.0, 1.0) as f32;
    let ease = CubicBezier::new(0.65, 0.0, 0.35, 1.0);
    let wave = if norm < 0.5 {
        ease.sample(norm * 2.0)
    } else {
        1.0 - ease.sample((norm - 0.5) * 2.0)
    };
    1.0 + 0.06 * wave
}

/// Sampled `(opacity, y_offset_px)` for the empty-state placeholder (`240ms`, `ease.enter`,
/// `y: 0.3em (4.2px) -> 0`, `blur.soft 4px -> 0`).
pub fn tag_placeholder_sample(elapsed: f64, reduced: bool) -> (f32, f32) {
    if reduced {
        let t = (elapsed / 0.12).clamp(0.0, 1.0) as f32;
        return (t, 0.0);
    }
    let t = (elapsed / 0.24).clamp(0.0, 1.0) as f32;
    let e = CubicBezier::new(0.16, 1.0, 0.3, 1.0).sample(t);
    let blur = BlurFallback::evaluate(px(4.0 * (1.0 - e)), false);
    (
        (e * blur.opacity_multiplier).clamp(0.0, 1.0),
        4.2 * (1.0 - e),
    )
}

/// Attempts to commit `draft` into `tags`:
/// - Returns `None` if `draft.trim()` is empty.
/// - Returns `Some(Err(existing_tag))` if a case-insensitive match already exists in `tags`.
/// - Returns `Some(Ok(updated_tags))` with the trimmed tag appended otherwise.
pub fn try_add_tag(
    tags: &[SharedString],
    draft: &str,
) -> Option<Result<Vec<SharedString>, SharedString>> {
    let trimmed = draft.trim();
    if trimmed.is_empty() {
        return None;
    }
    let lower = trimmed.to_lowercase();
    if let Some(existing) = tags.iter().find(|t| t.to_lowercase() == lower) {
        return Some(Err(existing.clone()));
    }
    let mut next = tags.to_vec();
    next.push(SharedString::from(trimmed.to_string()));
    Some(Ok(next))
}

#[derive(Clone)]
struct TagInputInternal {
    uncontrolled_tags: Vec<SharedString>,
    picked: Option<SharedString>,
    ring_seeded: bool,
    last_ring_rect: Option<(f32, f32, f32, f32)>,
    pulsed_tag: Option<(SharedString, f64)>,
    empty_entered_at_secs: f64,
    was_empty: bool,
    last_draft: SharedString,
    control_hovered: bool,
    pressed_remove: Option<SharedString>,
    measured_content_h: Rc<RefCell<Option<f32>>>,
    content_bounds: Rc<RefCell<Option<Bounds<Pixels>>>>,
    tag_rects: TagRectMap,
    draft_input: Entity<InputState>,
}

impl TagInputInternal {
    fn new(default_tags: Vec<SharedString>, now: f64, window: &mut Window, cx: &mut App) -> Self {
        let draft_input = cx.new(|cx| InputState::new(window, cx));
        let is_empty = default_tags.is_empty();
        Self {
            uncontrolled_tags: default_tags,
            picked: None,
            ring_seeded: false,
            last_ring_rect: None,
            pulsed_tag: None,
            empty_entered_at_secs: now - 10.0,
            was_empty: is_empty,
            last_draft: "".into(),
            control_hovered: false,
            pressed_remove: None,
            measured_content_h: Rc::new(RefCell::new(None)),
            content_bounds: Rc::new(RefCell::new(None)),
            tag_rects: Rc::new(RefCell::new(HashMap::new())),
            draft_input,
        }
    }
}

/// Arc `TagInput` — freeform tag pill field with spring height wrapping, gliding selection ring,
/// two-step Backspace/Arrow removal, and duplicate-tag pulse feedback.
#[derive(IntoElement)]
pub struct TagInput {
    id: ElementId,
    label: SharedString,
    value: Option<Vec<SharedString>>,
    default_value: Vec<SharedString>,
    placeholder: SharedString,
    description: Option<SharedString>,
    disabled: bool,
    width: Option<Pixels>,
    on_value_change: Option<TagInputChangeHandler>,
}

impl TagInput {
    pub fn new(id: impl Into<ElementId>, label: impl Into<SharedString>) -> Self {
        Self {
            id: id.into(),
            label: label.into(),
            value: None,
            default_value: Vec::new(),
            placeholder: "Add a tag".into(),
            description: None,
            disabled: false,
            width: None,
            on_value_change: None,
        }
    }

    pub fn value<I, S>(mut self, value: I) -> Self
    where
        I: IntoIterator<Item = S>,
        S: Into<SharedString>,
    {
        self.value = Some(value.into_iter().map(Into::into).collect());
        self
    }

    pub fn default_value<I, S>(mut self, value: I) -> Self
    where
        I: IntoIterator<Item = S>,
        S: Into<SharedString>,
    {
        self.default_value = value.into_iter().map(Into::into).collect();
        self
    }

    pub fn placeholder(mut self, placeholder: impl Into<SharedString>) -> Self {
        self.placeholder = placeholder.into();
        self
    }

    pub fn description(mut self, description: impl Into<SharedString>) -> Self {
        self.description = Some(description.into());
        self
    }

    pub fn disabled(mut self, disabled: bool) -> Self {
        self.disabled = disabled;
        self
    }

    pub fn width(mut self, width: impl Into<Pixels>) -> Self {
        self.width = Some(width.into());
        self
    }

    pub fn on_value_change(
        mut self,
        handler: impl Fn(&[SharedString], &mut Window, &mut App) + 'static,
    ) -> Self {
        self.on_value_change = Some(Rc::new(handler));
        self
    }
}

impl RenderOnce for TagInput {
    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 initial_tags = self
            .value
            .clone()
            .unwrap_or_else(|| self.default_value.clone());

        let state_id =
            ElementId::NamedChild(self.id.clone().into(), "__arc-tag-input-state".into());
        let internal = window.use_keyed_state(state_id, cx, |window, cx| {
            TagInputInternal::new(initial_tags.clone(), now, window, cx)
        });

        let tags: Vec<SharedString> = self
            .value
            .clone()
            .unwrap_or_else(|| internal.read(cx).uncontrolled_tags.clone());

        // Check draft input for trailing comma `,` (auto-commits tag) or draft edits (clears `picked`).
        {
            let d_in = internal.read(cx).draft_input.clone();
            let raw_draft = d_in.read(cx).value().to_string();
            let last_d = internal.read(cx).last_draft.clone();
            if raw_draft.as_str() != last_d.as_ref() {
                if raw_draft.ends_with(',') {
                    let candidate = raw_draft.trim_end_matches(',');
                    match try_add_tag(&tags, candidate) {
                        Some(Ok(next_tags)) => {
                            d_in.update(cx, |s, cx| s.set_value("", window, cx));
                            internal.update(cx, |s, _| {
                                s.uncontrolled_tags = next_tags.clone();
                                s.picked = None;
                                s.last_draft = "".into();
                            });
                            if let Some(cb) = &self.on_value_change {
                                cb(&next_tags, window, cx);
                            }
                        }
                        Some(Err(dup)) => {
                            d_in.update(cx, |s, cx| {
                                s.set_value(candidate.to_string(), window, cx);
                            });
                            internal.update(cx, |s, _| {
                                s.pulsed_tag = Some((dup, now));
                                s.last_draft = SharedString::from(candidate.to_string());
                            });
                        }
                        None => {
                            d_in.update(cx, |s, cx| s.set_value("", window, cx));
                            internal.update(cx, |s, _| {
                                s.last_draft = "".into();
                            });
                        }
                    }
                } else {
                    internal.update(cx, |s, _| {
                        s.last_draft = SharedString::from(raw_draft);
                        s.picked = None;
                    });
                }
            }
        }

        let tags: Vec<SharedString> = self
            .value
            .clone()
            .unwrap_or_else(|| internal.read(cx).uncontrolled_tags.clone());
        let draft_str = internal.read(cx).draft_input.read(cx).value().to_string();
        let is_empty = tags.is_empty() && draft_str.is_empty();

        // Keep the native `KitInput` placeholder synced so the placeholder text sits inside the
        // exact same inline text run as the caret (never offset from the cursor).
        {
            let target_ph = if tags.is_empty() {
                self.placeholder.clone()
            } else {
                SharedString::default()
            };
            let d_in = internal.read(cx).draft_input.clone();
            d_in.update(cx, |s, cx| {
                s.set_placeholder(target_ph, window, cx);
            });
        }

        // Track when the field becomes completely empty so the placeholder rises in.
        {
            let was_empty = internal.read(cx).was_empty;
            if is_empty != was_empty {
                internal.update(cx, |s, _| {
                    s.was_empty = is_empty;
                    if is_empty {
                        s.empty_entered_at_secs = now;
                    }
                });
            }
        }

        let snap = internal.read(cx).clone();
        let active_pick: Option<SharedString> = snap.picked.clone().filter(|p| tags.contains(p));
        let is_focused = snap
            .draft_input
            .read(cx)
            .focus_handle(cx)
            .is_focused(window);

        // Shell height spring (`motion.spring.smooth`).
        let measured_h = snap
            .measured_content_h
            .borrow()
            .map(|h| h.max(TAG_INPUT_MIN_CONTENT_H_PX));
        let shell_h = arc_motion::arc_measured_spring(
            (self.id.clone(), "control-h"),
            measured_h,
            TAG_INPUT_MIN_CONTENT_H_PX,
            motion.spring.smooth,
            window,
            cx,
        )
        .max(TAG_INPUT_MIN_CONTENT_H_PX);

        // Pick ring geometry & spring glide (`motion.spring.morph`).
        let active_rect = active_pick
            .as_ref()
            .and_then(|t| snap.tag_rects.borrow().get(t).copied())
            .or(snap.last_ring_rect);
        let has_ring = active_pick.is_some() && active_rect.is_some();
        let ring_op = arc_transition(
            (self.id.clone(), "ring-op"),
            if has_ring { 1.0 } else { 0.0 },
            if reduced {
                motion.duration.instant
            } else if has_ring {
                motion.duration.fast
            } else {
                motion.duration.instant
            },
            motion.ease.standard,
            window,
            cx,
        );

        let (rx_t, ry_t, rw_t, rh_t) = active_rect.unwrap_or((7.0, 7.0, 64.0, 28.0));
        let (ring_x, ring_y, ring_w, ring_h) = if reduced || !snap.ring_seeded || ring_op < 0.02 {
            let _ = arc_spring_with_options(
                (self.id.clone(), "ring-x"),
                rx_t,
                SpringOptions::new(motion.spring.morph).with_initial_value(rx_t),
                window,
                cx,
            );
            let _ = arc_spring_with_options(
                (self.id.clone(), "ring-y"),
                ry_t,
                SpringOptions::new(motion.spring.morph).with_initial_value(ry_t),
                window,
                cx,
            );
            let _ = arc_spring_with_options(
                (self.id.clone(), "ring-w"),
                rw_t,
                SpringOptions::new(motion.spring.morph).with_initial_value(rw_t),
                window,
                cx,
            );
            let _ = arc_spring_with_options(
                (self.id.clone(), "ring-h"),
                rh_t,
                SpringOptions::new(motion.spring.morph).with_initial_value(rh_t),
                window,
                cx,
            );
            if has_ring && !snap.ring_seeded {
                internal.update(cx, |s, _| {
                    s.ring_seeded = true;
                    s.last_ring_rect = Some((rx_t, ry_t, rw_t, rh_t));
                });
            } else if !has_ring && ring_op < 0.02 && snap.ring_seeded {
                internal.update(cx, |s, _| s.ring_seeded = false);
            }
            (rx_t, ry_t, rw_t, rh_t)
        } else {
            internal.update(cx, |s, _| {
                s.last_ring_rect = Some((rx_t, ry_t, rw_t, rh_t));
            });
            (
                arc_spring(
                    (self.id.clone(), "ring-x"),
                    rx_t,
                    motion.spring.morph,
                    window,
                    cx,
                ),
                arc_spring(
                    (self.id.clone(), "ring-y"),
                    ry_t,
                    motion.spring.morph,
                    window,
                    cx,
                ),
                arc_spring(
                    (self.id.clone(), "ring-w"),
                    rw_t,
                    motion.spring.morph,
                    window,
                    cx,
                ),
                arc_spring(
                    (self.id.clone(), "ring-h"),
                    rh_t,
                    motion.spring.morph,
                    window,
                    cx,
                ),
            )
        };

        // Placeholder rise sample when field is empty.
        let empty_elapsed = (now - snap.empty_entered_at_secs).max(0.0);
        let (ph_op, ph_y) = if is_empty {
            if empty_elapsed < 0.25 {
                window.request_animation_frame();
            }
            tag_placeholder_sample(empty_elapsed, reduced)
        } else {
            (0.0, 0.0)
        };

        // Control border & hover transition.
        let hover_p = arc_transition(
            (self.id.clone(), "control-hover"),
            if !self.disabled && !is_focused && snap.control_hovered {
                1.0
            } else {
                0.0
            },
            if reduced {
                Duration::ZERO
            } else {
                motion.duration.fast
            },
            motion.ease.standard,
            window,
            cx,
        );
        let border_color = if !self.disabled && is_focused {
            colors.foreground
        } else {
            oklab_mix(colors.border_strong, colors.border, hover_p)
        };

        // Content measurement probe (measures wrapped height and origin for relative tag coordinates).
        let content_h_ref = snap.measured_content_h.clone();
        let content_b_ref = snap.content_bounds.clone();
        let content_probe = canvas(
            move |rect, window, _| {
                *content_b_ref.borrow_mut() = Some(rect);
                let h = f32::from(rect.size.height).max(TAG_INPUT_MIN_CONTENT_H_PX);
                let prev = *content_h_ref.borrow();
                *content_h_ref.borrow_mut() = Some(h);
                if prev.is_none_or(|prev| (prev - h).abs() > 0.5) {
                    window.request_animation_frame();
                }
            },
            |_, _, _, _| {},
        )
        .absolute()
        .inset_0();

        let disabled = self.disabled;
        let tag_els = tags
            .iter()
            .map(|tag| {
                let is_picked = active_pick.as_ref() == Some(tag);
                let tag_op = arc_transition(
                    (self.id.clone(), format!("tag-op-{tag}")),
                    1.0,
                    if reduced {
                        motion.duration.instant
                    } else {
                        motion.duration.fast
                    },
                    motion.ease.enter,
                    window,
                    cx,
                );
                let blur = BlurFallback::evaluate(motion.blur.soft * (1.0 - tag_op), reduced);

                // Duplicate pulse (`1.0 -> 1.06 -> 1.0` over `360ms`).
                let pulse_scale = if let Some((ref p_tag, started_at)) = snap.pulsed_tag
                    && p_tag == tag
                {
                    let el = (now - started_at).max(0.0);
                    if el < TAG_DUPLICATE_PULSE_SECS {
                        window.request_animation_frame();
                    }
                    tag_duplicate_pulse_scale(el, reduced)
                } else {
                    1.0
                };
                let extra_px = ((pulse_scale - 1.0) * 18.0).max(0.0);

                let rects_map = snap.tag_rects.clone();
                let content_b_for_tag = snap.content_bounds.clone();
                let tag_key = tag.clone();
                let tag_probe = canvas(
                    move |rect, _, _| {
                        if let Some(cb) = *content_b_for_tag.borrow() {
                            let rel_x = f32::from(rect.origin.x - cb.origin.x);
                            let rel_y = f32::from(rect.origin.y - cb.origin.y);
                            let w = f32::from(rect.size.width);
                            let h = f32::from(rect.size.height);
                            rects_map
                                .borrow_mut()
                                .insert(tag_key.clone(), (rel_x, rel_y, w, h));
                        }
                    },
                    |_, _, _, _| {},
                )
                .absolute()
                .inset_0();

                let int_pick = internal.clone();
                let int_rem = internal.clone();
                let int_down = internal.clone();
                let int_up = internal.clone();
                let int_out = internal.clone();
                let on_change = self.on_value_change.clone();
                let cur_tags = tags.clone();
                let tag_for_pick = tag.clone();
                let tag_for_rem = tag.clone();
                let tag_for_down = tag.clone();
                let is_rem_pressed = snap.pressed_remove.as_ref() == Some(tag);
                let rem_sz = if is_rem_pressed && !reduced {
                    21.0
                } else {
                    22.0
                };
                let rem_hover_bg = colors.surface;
                let rem_hover_fg = colors.foreground;
                let rem_fg = if is_picked {
                    colors.foreground
                } else {
                    colors.text_secondary
                };

                div()
                    .id(ElementId::NamedChild(
                        self.id.clone().into(),
                        SharedString::from(format!("tag-{tag}")),
                    ))
                    .test_support()
                    .relative()
                    .flex_none()
                    .h(px(28.0 + extra_px))
                    .pl(px(9.0 + extra_px * 0.5))
                    .pr(px(4.0 + extra_px * 0.5))
                    .flex()
                    .flex_row()
                    .items_center()
                    .gap(px(3.0))
                    .rounded(Radii::PILL)
                    .border_1()
                    .border_color(if is_picked {
                        colors.accent
                    } else {
                        colors.border
                    })
                    .bg(if is_picked {
                        colors.accent_subtle
                    } else {
                        colors.surface_muted
                    })
                    .opacity((tag_op * blur.opacity_multiplier).clamp(0.0, 1.0))
                    .text_size(Typography::TEXT_SM)
                    .text_color(colors.foreground)
                    .when(!disabled, |this| this.cursor_pointer())
                    .on_click(move |_, window, cx| {
                        if disabled {
                            return;
                        }
                        let d_in = int_pick.read(cx).draft_input.clone();
                        d_in.update(cx, |s, cx| s.focus(window, cx));
                        int_pick.update(cx, |s, _| {
                            if s.picked.as_ref() == Some(&tag_for_pick) {
                                s.picked = None;
                            } else {
                                s.picked = Some(tag_for_pick.clone());
                            }
                        });
                        window.refresh();
                    })
                    .child(tag_probe)
                    .child(div().flex_none().whitespace_nowrap().child(tag.clone()))
                    .child(
                        div()
                            .id(ElementId::NamedChild(
                                self.id.clone().into(),
                                SharedString::from(format!("remove-{tag}")),
                            ))
                            .test_support()
                            .role(Role::Button)
                            .aria_label(SharedString::from(format!("Remove {tag}")))
                            .on_click(move |_, window, cx| {
                                if disabled {
                                    return;
                                }
                                let next_tags: Vec<SharedString> = cur_tags
                                    .iter()
                                    .filter(|&item| item != &tag_for_rem)
                                    .cloned()
                                    .collect();
                                let d_in = int_rem.read(cx).draft_input.clone();
                                d_in.update(cx, |s, cx| s.focus(window, cx));
                                int_rem.update(cx, |s, _| {
                                    s.uncontrolled_tags = next_tags.clone();
                                    s.picked = None;
                                    s.pressed_remove = None;
                                });
                                if let Some(cb) = &on_change {
                                    cb(&next_tags, window, cx);
                                }
                                window.refresh();
                            })
                            .w(px(rem_sz))
                            .h(px(rem_sz))
                            .flex_none()
                            .flex()
                            .items_center()
                            .justify_center()
                            .rounded(Radii::PILL)
                            .text_color(rem_fg)
                            .when(!disabled, |this| {
                                this.cursor_pointer()
                                    .hover(move |s| s.bg(rem_hover_bg).text_color(rem_hover_fg))
                            })
                            .on_mouse_down(MouseButton::Left, move |_, window, cx| {
                                int_down.update(cx, |s, _| {
                                    s.pressed_remove = Some(tag_for_down.clone());
                                });
                                window.refresh();
                            })
                            .on_mouse_up(MouseButton::Left, move |_, window, cx| {
                                int_up.update(cx, |s, _| s.pressed_remove = None);
                                window.refresh();
                            })
                            .on_mouse_up_out(MouseButton::Left, move |_, window, cx| {
                                int_out.update(cx, |s, _| s.pressed_remove = None);
                                window.refresh();
                            })
                            .child(Icon::new(IconName::X).text_size(px(13.0))),
                    )
                    .into_any_element()
            })
            .collect::<Vec<_>>();

        let int_hover = internal.clone();
        let int_focus_bg = internal.clone();
        let int_key = internal.clone();
        let tags_for_key = tags.clone();
        let active_for_key = active_pick;
        let on_change_key = self.on_value_change.clone();
        let _ = (ph_op, ph_y);

        let content_el = div()
            .relative()
            .w_full()
            .min_h(px(TAG_INPUT_MIN_CONTENT_H_PX))
            .p(px(7.0))
            .flex()
            .flex_row()
            .flex_wrap()
            .items_center()
            .gap(px(6.0))
            .child(content_probe)
            .when(ring_op > 0.01, |this| {
                this.child(
                    div()
                        .absolute()
                        .left(px(ring_x))
                        .top(px(ring_y))
                        .w(px(ring_w))
                        .h(px(ring_h))
                        .rounded(Radii::PILL)
                        .border_1()
                        .border_color(colors.accent)
                        .bg(colors.accent_subtle)
                        .opacity(ring_op),
                )
            })
            .children(tag_els)
            .child(
                div()
                    .flex_1()
                    .min_w(px(96.0))
                    .h(px(28.0))
                    .flex()
                    .items_center()
                    .text_size(Typography::TEXT_SM)
                    .text_color(colors.foreground)
                    .child(
                        KitInput::new(&snap.draft_input)
                            .appearance(false)
                            .disabled(disabled)
                            .px(px(2.0))
                            .py(px(0.0))
                            .h(px(28.0))
                            .w_full(),
                    ),
            );

        let control = div()
            .id(ElementId::NamedChild(
                self.id.clone().into(),
                "control".into(),
            ))
            .test_support()
            .w_full()
            .h(px(shell_h + 2.0))
            .rounded(Radii::CONTROL)
            .border_1()
            .border_color(border_color)
            .bg(colors.surface)
            .opacity(if disabled { 0.5 } else { 1.0 })
            .overflow_hidden()
            .on_hover(move |hovered, window, cx| {
                int_hover.update(cx, |s, _| s.control_hovered = *hovered);
                window.refresh();
            })
            .on_click(move |_, window, cx| {
                if !disabled {
                    let d_in = int_focus_bg.read(cx).draft_input.clone();
                    d_in.update(cx, |s, cx| s.focus(window, cx));
                }
            })
            .on_key_down(move |event: &KeyDownEvent, window, cx| {
                if disabled {
                    return;
                }
                let d_in = int_key.read(cx).draft_input.clone();
                let cur_draft = d_in.read(cx).value().to_string();
                let active_idx = active_for_key
                    .as_ref()
                    .and_then(|a| tags_for_key.iter().position(|t| t == a))
                    .unwrap_or(tags_for_key.len());

                match event.keystroke.key.as_str() {
                    "enter" => {
                        let t_now = motion_now(cx);
                        match try_add_tag(&tags_for_key, &cur_draft) {
                            Some(Ok(next_tags)) => {
                                d_in.update(cx, |s, cx| s.set_value("", window, cx));
                                int_key.update(cx, |s, _| {
                                    s.uncontrolled_tags = next_tags.clone();
                                    s.picked = None;
                                    s.last_draft = "".into();
                                });
                                if let Some(cb) = &on_change_key {
                                    cb(&next_tags, window, cx);
                                }
                                window.refresh();
                            }
                            Some(Err(existing)) => {
                                int_key.update(cx, |s, _| {
                                    s.pulsed_tag = Some((existing, t_now));
                                });
                                window.refresh();
                            }
                            None => {}
                        }
                    }
                    "backspace" | "delete" => {
                        if let Some(ref picked_tag) = active_for_key {
                            let next_tags: Vec<SharedString> = tags_for_key
                                .iter()
                                .filter(|&t| t != picked_tag)
                                .cloned()
                                .collect();
                            int_key.update(cx, |s, _| {
                                s.uncontrolled_tags = next_tags.clone();
                                s.picked = None;
                            });
                            if let Some(cb) = &on_change_key {
                                cb(&next_tags, window, cx);
                            }
                            window.refresh();
                        } else if event.keystroke.key.as_str() == "backspace"
                            && cur_draft.is_empty()
                            && let Some(last_tag) = tags_for_key.last()
                        {
                            let t = last_tag.clone();
                            int_key.update(cx, |s, _| {
                                s.picked = Some(t);
                            });
                            window.refresh();
                        }
                    }
                    "left" | "arrowleft"
                        if (cur_draft.is_empty() || active_for_key.is_some()) && active_idx > 0 =>
                    {
                        let prev_tag = tags_for_key[active_idx - 1].clone();
                        int_key.update(cx, |s, _| {
                            s.picked = Some(prev_tag);
                        });
                        window.refresh();
                    }
                    "right" | "arrowright" if active_for_key.is_some() => {
                        let next_pick = tags_for_key.get(active_idx + 1).cloned();
                        int_key.update(cx, |s, _| {
                            s.picked = next_pick;
                        });
                        window.refresh();
                    }
                    "escape" if active_for_key.is_some() => {
                        int_key.update(cx, |s, _| {
                            s.picked = None;
                        });
                        window.refresh();
                    }
                    _ => {}
                }
            })
            .child(content_el);

        let desc_id = ElementId::NamedChild(self.id.clone().into(), "description".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()
            .child(
                div()
                    .mb(Spacing::S2)
                    .text_size(Typography::TEXT_SM)
                    .font_medium()
                    .text_color(colors.foreground)
                    .child(self.label),
            )
            .child(control)
            .child(render_field_message(
                desc_id,
                self.description,
                false,
                window,
                cx,
            ))
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn try_add_tag_rejects_empty_and_detects_case_insensitive_duplicates() {
        let existing: Vec<SharedString> = vec!["Rust".into(), "GPUI".into()];
        assert!(try_add_tag(&existing, "   ").is_none());
        assert_eq!(
            try_add_tag(&existing, "rust"),
            Some(Err(SharedString::from("Rust")))
        );
        assert_eq!(
            try_add_tag(&existing, "  Motion "),
            Some(Ok(vec![
                SharedString::from("Rust"),
                SharedString::from("GPUI"),
                SharedString::from("Motion")
            ]))
        );
    }

    #[test]
    fn tag_duplicate_pulse_peaks_at_1_06_and_settles_to_1_0() {
        assert!((tag_duplicate_pulse_scale(0.0, false) - 1.0).abs() < 1e-4);
        let peak = tag_duplicate_pulse_scale(TAG_DUPLICATE_PULSE_SECS * 0.5, false);
        assert!((peak - 1.06).abs() < 1e-3);
        assert!((tag_duplicate_pulse_scale(0.40, false) - 1.0).abs() < 1e-4);
        assert!((tag_duplicate_pulse_scale(0.18, true) - 1.0).abs() < 1e-4);
    }

    #[test]
    fn tag_placeholder_sample_rises_from_4_2px_to_zero() {
        let (op0, y0) = tag_placeholder_sample(0.0, false);
        assert!(op0 < 0.01);
        assert!((y0 - 4.2).abs() < 1e-4);

        let (op1, y1) = tag_placeholder_sample(0.26, false);
        assert!((op1 - 1.0).abs() < 1e-4);
        assert!(y1.abs() < 1e-4);
    }
}