1use std::{cell::RefCell, rc::Rc, time::Duration};
23
24use arc_motion::{
25 BlurFallback, CubicBezier, PathPoint, PolylinePath, arc_spring, arc_transition,
26 is_reduced_motion, motion_now,
27};
28use arc_tokens::{ActiveArcTheme as _, ControlHeights, Radii, Spacing, Typography, oklab_mix};
29use gpui_kit::{
30 App, ElementId, FocusHandle, Hsla, IntoElement, KeyDownEvent, MouseButton, ParentElement,
31 Pixels, RenderOnce, Role, SharedString, Styled, TestSupportExt as _, Window,
32 base::{Button as BaseButton, StyledExt as _},
33 canvas, div,
34 prelude::*,
35 px,
36};
37
38type ChipGroupChangeHandler = Rc<dyn Fn(&[SharedString], &mut Window, &mut App)>;
39
40pub const CHIP_CHECK_SLOT_PX: f32 = 18.0;
42pub const CHIP_REVEAL_STAGGER_SECS: f64 = 0.035;
44pub const CHIP_REVEAL_MAX_DELAY_SECS: f64 = 0.30;
46
47pub fn chip_check_metrics(grown: f32, reduced: bool) -> (f32, f32, f32, f32) {
50 let g = grown.clamp(0.0, 1.15);
51 let slot_w = (g * CHIP_CHECK_SLOT_PX).clamp(0.0, CHIP_CHECK_SLOT_PX);
52 let scale = g.min(1.1);
53 let raw_op = (g * 1.4).clamp(0.0, 1.0);
54 let blur = BlurFallback::evaluate(px(((1.0 - g).max(0.0)) * 2.0), reduced);
55 let opacity = (raw_op * blur.opacity_multiplier).clamp(0.0, 1.0);
56 let path_len = g.clamp(0.0, 1.0);
57 (slot_w, scale, opacity, path_len)
58}
59
60pub fn chip_reveal_progress(elapsed: f64, index: usize, max_visible: usize, reduced: bool) -> f32 {
63 if reduced || index < max_visible {
64 return 1.0;
65 }
66 let delay =
67 ((index - max_visible) as f64 * CHIP_REVEAL_STAGGER_SECS).min(CHIP_REVEAL_MAX_DELAY_SECS);
68 if elapsed <= delay {
69 return 0.0;
70 }
71 let t = ((elapsed - delay) / 0.16).clamp(0.0, 1.0) as f32;
72 CubicBezier::new(0.22, 1.0, 0.36, 1.0).sample(t)
73}
74
75pub fn chip_more_swap_sample(elapsed: f64, reduced: bool) -> (f32, f32, f32, f32) {
78 if reduced {
79 let t = (elapsed / 0.15).clamp(0.0, 1.0) as f32;
80 return (t, 0.0, 1.0 - t, 0.0);
81 }
82 let t_in = (elapsed / 0.24).clamp(0.0, 1.0) as f32;
83 let e_in = CubicBezier::new(0.16, 1.0, 0.3, 1.0).sample(t_in);
84 let blur_in = BlurFallback::evaluate(px(4.0 * (1.0 - e_in)), false);
85 let enter_op = (e_in * blur_in.opacity_multiplier).clamp(0.0, 1.0);
86 let enter_y = 4.2 * (1.0 - e_in);
87
88 let t_out = (elapsed / 0.16).clamp(0.0, 1.0) as f32;
89 let e_out = CubicBezier::new(0.22, 1.0, 0.36, 1.0).sample(t_out);
90 let blur_out = BlurFallback::evaluate(px(2.0 * e_out), false);
91 let exit_op = ((1.0 - e_out) * blur_out.opacity_multiplier).clamp(0.0, 1.0);
92 let exit_y = -4.2 * e_out;
93
94 (enter_op, enter_y, exit_op, exit_y)
95}
96
97pub fn toggle_chip_group_value(
99 options: &[ChipOption],
100 selected: &[SharedString],
101 target: &SharedString,
102 multiple: bool,
103) -> Vec<SharedString> {
104 let is_on = selected.iter().any(|v| v == target);
105 if !multiple {
106 return if is_on {
107 Vec::new()
108 } else {
109 vec![target.clone()]
110 };
111 }
112 options
113 .iter()
114 .filter(|opt| {
115 if &opt.value == target {
116 !is_on
117 } else {
118 selected.iter().any(|v| v == &opt.value)
119 }
120 })
121 .map(|opt| opt.value.clone())
122 .collect()
123}
124
125#[derive(Clone, Debug, PartialEq, Eq)]
127pub struct ChipOption {
128 pub value: SharedString,
129 pub label: SharedString,
130}
131
132impl ChipOption {
133 pub fn new(value: impl Into<SharedString>, label: impl Into<SharedString>) -> Self {
134 Self {
135 value: value.into(),
136 label: label.into(),
137 }
138 }
139}
140
141#[derive(Clone)]
142struct ChipGroupInternal {
143 uncontrolled_value: Vec<SharedString>,
144 expanded: bool,
145 expanded_changed_at_secs: f64,
146 previous_more_text: Option<SharedString>,
147 pinned: Vec<SharedString>,
148 active_focus_key: Option<SharedString>,
149 hovered_chip: Option<SharedString>,
150 pressed_chip: Option<SharedString>,
151 measured_frame_h: Rc<RefCell<Option<f32>>>,
152 focus_handle: FocusHandle,
153}
154
155impl ChipGroupInternal {
156 fn new(default_value: Vec<SharedString>, now: f64, focus_handle: FocusHandle) -> Self {
157 Self {
158 pinned: default_value.clone(),
159 uncontrolled_value: default_value,
160 expanded: false,
161 expanded_changed_at_secs: now - 10.0,
162 previous_more_text: None,
163 active_focus_key: None,
164 hovered_chip: None,
165 pressed_chip: None,
166 measured_frame_h: Rc::new(RefCell::new(None)),
167 focus_handle,
168 }
169 }
170}
171
172fn paint_chip_check(
173 origin_x: Pixels,
174 origin_y: Pixels,
175 scale: f32,
176 path_length: f32,
177 opacity: f32,
178 color: Hsla,
179 window: &mut Window,
180) {
181 let len = path_length.clamp(0.0, 1.0);
182 let alpha = opacity.clamp(0.0, 1.0);
183 if len <= 0.01 || alpha <= 0.01 || scale <= 0.05 {
184 return;
185 }
186 let s = 14.0 / 24.0;
188 let cy = 7.0_f32;
189 let transform_pt = |vx: f32, vy: f32| -> PathPoint {
190 let bx = vx * s;
191 let by = vy * s;
192 PathPoint::new(bx * scale, cy + (by - cy) * scale)
193 };
194 let poly = PolylinePath::new(vec![
195 transform_pt(4.0, 12.5),
196 transform_pt(9.5, 18.0),
197 transform_pt(20.0, 6.5),
198 ]);
199 let sliced = poly.slice(0.0, len);
200 let stroke_color = Hsla {
201 a: color.a * alpha,
202 ..color
203 };
204 if let Some(b) = sliced.to_stroke_builder(origin_x, origin_y, px(2.1))
205 && let Ok(path) = b.build()
206 {
207 window.paint_path(path, stroke_color);
208 }
209}
210
211#[derive(IntoElement)]
215pub struct ChipGroup {
216 id: ElementId,
217 label: SharedString,
218 show_label: bool,
219 options: Vec<ChipOption>,
220 value: Option<Vec<SharedString>>,
221 default_value: Vec<SharedString>,
222 multiple: bool,
223 max_visible: Option<usize>,
224 disabled: bool,
225 width: Option<Pixels>,
226 on_value_change: Option<ChipGroupChangeHandler>,
227}
228
229impl ChipGroup {
230 pub fn new(id: impl Into<ElementId>, label: impl Into<SharedString>) -> Self {
231 Self {
232 id: id.into(),
233 label: label.into(),
234 show_label: false,
235 options: Vec::new(),
236 value: None,
237 default_value: Vec::new(),
238 multiple: true,
239 max_visible: None,
240 disabled: false,
241 width: None,
242 on_value_change: None,
243 }
244 }
245
246 pub fn show_label(mut self, show: bool) -> Self {
247 self.show_label = show;
248 self
249 }
250
251 pub fn option(mut self, option: ChipOption) -> Self {
252 self.options.push(option);
253 self
254 }
255
256 pub fn options(mut self, options: impl IntoIterator<Item = ChipOption>) -> Self {
257 self.options.extend(options);
258 self
259 }
260
261 pub fn value<I, S>(mut self, value: I) -> Self
262 where
263 I: IntoIterator<Item = S>,
264 S: Into<SharedString>,
265 {
266 self.value = Some(value.into_iter().map(Into::into).collect());
267 self
268 }
269
270 pub fn default_value<I, S>(mut self, value: I) -> Self
271 where
272 I: IntoIterator<Item = S>,
273 S: Into<SharedString>,
274 {
275 self.default_value = value.into_iter().map(Into::into).collect();
276 self
277 }
278
279 pub fn multiple(mut self, multiple: bool) -> Self {
280 self.multiple = multiple;
281 self
282 }
283
284 pub fn max_visible(mut self, max_visible: usize) -> Self {
285 self.max_visible = Some(max_visible.max(1));
286 self
287 }
288
289 pub fn disabled(mut self, disabled: bool) -> Self {
290 self.disabled = disabled;
291 self
292 }
293
294 pub fn width(mut self, width: impl Into<Pixels>) -> Self {
295 self.width = Some(width.into());
296 self
297 }
298
299 pub fn on_value_change(
300 mut self,
301 handler: impl Fn(&[SharedString], &mut Window, &mut App) + 'static,
302 ) -> Self {
303 self.on_value_change = Some(Rc::new(handler));
304 self
305 }
306}
307
308impl RenderOnce for ChipGroup {
309 fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
310 let theme = cx.arc_theme().clone();
311 let colors = theme.colors;
312 let motion = theme.motion;
313 let reduced = is_reduced_motion(cx);
314 let now = motion_now(cx);
315
316 let initial_vals = self
317 .value
318 .clone()
319 .unwrap_or_else(|| self.default_value.clone());
320
321 let state_id =
322 ElementId::NamedChild(self.id.clone().into(), "__arc-chip-group-state".into());
323 let internal = window.use_keyed_state(state_id, cx, |_, cx| {
324 ChipGroupInternal::new(initial_vals.clone(), now, cx.focus_handle())
325 });
326
327 let selected: Vec<SharedString> = self
328 .value
329 .clone()
330 .unwrap_or_else(|| internal.read(cx).uncontrolled_value.clone());
331 let snap = internal.read(cx).clone();
332
333 let max_vis = self.max_visible.unwrap_or(usize::MAX);
334 let foldable = self.options.len() > max_vis;
335 let visible_options: Vec<(usize, ChipOption)> = if !foldable || snap.expanded {
336 self.options.iter().cloned().enumerate().collect()
337 } else {
338 self.options
339 .iter()
340 .cloned()
341 .enumerate()
342 .filter(|(idx, opt)| {
343 *idx < max_vis
344 || snap.pinned.contains(&opt.value)
345 || selected.contains(&opt.value)
346 })
347 .collect()
348 };
349 let hidden_count = self.options.len().saturating_sub(visible_options.len());
350 let show_more = foldable && (snap.expanded || hidden_count > 0);
351
352 let measured_h = snap.measured_frame_h.borrow().map(|h| h.max(36.0));
354 let frame_h = arc_motion::arc_measured_spring(
355 (self.id.clone(), "frame-h"),
356 measured_h,
357 36.0,
358 motion.spring.smooth,
359 window,
360 cx,
361 )
362 .max(36.0);
363
364 let frame_h_ref = snap.measured_frame_h.clone();
365 let frame_probe = canvas(
366 move |rect, window, _| {
367 let h = f32::from(rect.size.height).max(36.0);
368 let prev = *frame_h_ref.borrow();
369 *frame_h_ref.borrow_mut() = Some(h);
370 if prev.is_none_or(|prev| (prev - h).abs() > 0.5) {
371 window.request_animation_frame();
372 }
373 },
374 |_, _, _, _| {},
375 )
376 .absolute()
377 .inset_0();
378
379 let expand_elapsed = (now - snap.expanded_changed_at_secs).max(0.0);
380 let disabled = self.disabled;
381 let multiple = self.multiple;
382
383 let mut chip_els = Vec::with_capacity(visible_options.len() + 1);
384 for (orig_idx, option) in &visible_options {
385 let is_selected = selected.contains(&option.value);
386 let is_hovered = snap.hovered_chip.as_ref() == Some(&option.value) && !disabled;
387 let is_pressed = snap.pressed_chip.as_ref() == Some(&option.value) && !disabled;
388 let is_focused = snap.active_focus_key.as_ref() == Some(&option.value);
389
390 let grown = if reduced {
392 if is_selected { 1.0 } else { 0.0 }
393 } else {
394 arc_spring(
395 (self.id.clone(), format!("grown-{}", option.value)),
396 if is_selected { 1.0 } else { 0.0 },
397 motion.spring.morph,
398 window,
399 cx,
400 )
401 };
402 let (slot_w, check_scale, check_op, check_path_len) =
403 chip_check_metrics(grown, reduced);
404
405 let reveal_p = if snap.expanded && foldable && *orig_idx >= max_vis {
407 let rp = chip_reveal_progress(expand_elapsed, *orig_idx, max_vis, reduced);
408 if rp < 0.999 {
409 window.request_animation_frame();
410 }
411 rp
412 } else {
413 1.0
414 };
415
416 let hover_p = arc_transition(
417 (self.id.clone(), format!("hover-{}", option.value)),
418 if is_hovered || is_focused { 1.0 } else { 0.0 },
419 if reduced {
420 Duration::ZERO
421 } else {
422 motion.duration.fast
423 },
424 motion.ease.standard,
425 window,
426 cx,
427 );
428 let sel_p = grown.clamp(0.0, 1.0);
429
430 let resting_unsel_bg = colors.surface;
431 let resting_sel_bg = oklab_mix(colors.accent, colors.surface, 0.11);
432 let hover_sel_bg = oklab_mix(colors.accent, colors.surface, 0.16);
433 let sel_bg = oklab_mix(hover_sel_bg, resting_sel_bg, hover_p);
434 let chip_bg = oklab_mix(sel_bg, resting_unsel_bg, sel_p);
435
436 let resting_unsel_border = oklab_mix(colors.border_strong, colors.border, hover_p);
437 let resting_sel_border = oklab_mix(colors.accent, colors.border, 0.42);
438 let hover_sel_border = oklab_mix(colors.accent, colors.border, 0.60);
439 let sel_border = oklab_mix(hover_sel_border, resting_sel_border, hover_p);
440 let chip_border = oklab_mix(sel_border, resting_unsel_border, sel_p);
441
442 let text_fg = if is_selected || is_hovered || is_focused {
443 colors.foreground
444 } else {
445 colors.text_secondary
446 };
447 let check_color = colors.accent_strong;
448 let body_h = if is_pressed && !reduced { 35.0 } else { 36.0 };
449
450 let int_hover = internal.clone();
451 let int_down = internal.clone();
452 let int_up = internal.clone();
453 let int_out = internal.clone();
454 let int_click = internal.clone();
455 let all_opts = self.options.clone();
456 let cur_selected = selected.clone();
457 let on_change = self.on_value_change.clone();
458 let val_hover = option.value.clone();
459 let val_down = option.value.clone();
460 let val_up = option.value.clone();
461 let val_out = option.value.clone();
462 let val_click = option.value.clone();
463 let focus_for_click = snap.focus_handle.clone();
464
465 chip_els.push(
466 BaseButton::new(ElementId::NamedChild(
467 self.id.clone().into(),
468 SharedString::from(format!("chip-{}", option.value)),
469 ))
470 .accessibility_label(option.label.clone())
471 .disabled(disabled)
472 .on_click(move |_, window, cx| {
473 if disabled {
474 return;
475 }
476 window.focus(&focus_for_click, cx);
477 let next_vals =
478 toggle_chip_group_value(&all_opts, &cur_selected, &val_click, multiple);
479 int_click.update(cx, |s, _| {
480 s.uncontrolled_value = next_vals.clone();
481 s.active_focus_key = Some(val_click.clone());
482 s.pressed_chip = None;
483 });
484 if let Some(cb) = &on_change {
485 cb(&next_vals, window, cx);
486 }
487 window.refresh();
488 })
489 .relative()
490 .h(px(body_h))
491 .px(px(14.0))
492 .flex()
493 .flex_row()
494 .items_center()
495 .rounded(Radii::PILL)
496 .border_1()
497 .border_color(chip_border)
498 .bg(chip_bg)
499 .opacity(if disabled { 0.5 } else { reveal_p })
500 .text_size(Typography::TEXT_SM)
501 .font_medium()
502 .text_color(text_fg)
503 .when(!disabled, |this| this.cursor_pointer())
504 .on_hover(move |hovered, window, cx| {
505 int_hover.update(cx, |s, _| {
506 if *hovered {
507 s.hovered_chip = Some(val_hover.clone());
508 } else if s.hovered_chip.as_ref() == Some(&val_hover) {
509 s.hovered_chip = None;
510 }
511 });
512 window.refresh();
513 })
514 .on_mouse_down(MouseButton::Left, move |_, window, cx| {
515 if !disabled {
516 int_down.update(cx, |s, _| s.pressed_chip = Some(val_down.clone()));
517 window.refresh();
518 }
519 })
520 .on_mouse_up(MouseButton::Left, move |_, window, cx| {
521 if int_up.read(cx).pressed_chip.as_ref() == Some(&val_up) {
522 int_up.update(cx, |s, _| s.pressed_chip = None);
523 window.refresh();
524 }
525 })
526 .on_mouse_up_out(MouseButton::Left, move |_, window, cx| {
527 if int_out.read(cx).pressed_chip.as_ref() == Some(&val_out) {
528 int_out.update(cx, |s, _| s.pressed_chip = None);
529 window.refresh();
530 }
531 })
532 .when(check_op > 0.01, |this| {
533 this.child(
534 div()
535 .absolute()
536 .left(px(12.0))
537 .top(px((body_h - 14.0) * 0.5))
538 .size(px(14.0))
539 .child(
540 canvas(
541 |_, _, _| {},
542 move |rect, _, window, _| {
543 paint_chip_check(
544 rect.origin.x,
545 rect.origin.y,
546 check_scale,
547 check_path_len,
548 check_op,
549 check_color,
550 window,
551 );
552 },
553 )
554 .size_full(),
555 ),
556 )
557 })
558 .child(div().w(px(slot_w)).flex_none())
559 .child(div().truncate().child(option.label.clone()))
560 .into_any_element(),
561 );
562 }
563
564 if show_more {
566 let more_key: SharedString = "__more__".into();
567 let more_text: SharedString = if snap.expanded {
568 "Show less".into()
569 } else {
570 SharedString::from(format!("+{hidden_count} more"))
571 };
572 let is_more_hovered = snap.hovered_chip.as_ref() == Some(&more_key) && !disabled;
573 let is_more_focused = snap.active_focus_key.as_ref() == Some(&more_key);
574 let more_border = if is_more_hovered || is_more_focused {
575 colors.border_strong
576 } else {
577 colors.border
578 };
579 let more_fg = if is_more_hovered || is_more_focused {
580 colors.foreground
581 } else {
582 colors.text_muted
583 };
584
585 let (in_op, in_y, out_op, out_y) = if expand_elapsed < 0.25 {
586 window.request_animation_frame();
587 chip_more_swap_sample(expand_elapsed, reduced)
588 } else {
589 (1.0, 0.0, 0.0, 0.0)
590 };
591
592 let mut more_label_slot = div()
593 .relative()
594 .h(px(20.0))
595 .overflow_hidden()
596 .flex()
597 .items_center()
598 .justify_center()
599 .child(div().mt(px(in_y)).opacity(in_op).child(more_text.clone()));
600 if out_op > 0.01
601 && let Some(prev_txt) = snap.previous_more_text.clone()
602 {
603 more_label_slot = more_label_slot.child(
604 div()
605 .absolute()
606 .top_0()
607 .left_0()
608 .mt(px(out_y))
609 .opacity(out_op)
610 .child(prev_txt),
611 );
612 }
613
614 let int_more_hover = internal.clone();
615 let int_more_click = internal.clone();
616 let cur_selected_for_pin = selected.clone();
617 let cur_more_text = more_text.clone();
618 let focus_for_more = snap.focus_handle.clone();
619
620 chip_els.push(
621 BaseButton::new(ElementId::NamedChild(self.id.clone().into(), "more".into()))
622 .accessibility_label(more_text)
623 .disabled(disabled)
624 .on_click(move |_, window, cx| {
625 if disabled {
626 return;
627 }
628 window.focus(&focus_for_more, cx);
629 let t_now = motion_now(cx);
630 int_more_click.update(cx, |s, _| {
631 if s.expanded {
632 s.pinned = cur_selected_for_pin.clone();
633 }
634 s.expanded = !s.expanded;
635 s.expanded_changed_at_secs = t_now;
636 s.previous_more_text = Some(cur_more_text.clone());
637 s.active_focus_key = Some("__more__".into());
638 });
639 window.refresh();
640 })
641 .h(ControlHeights::SM)
642 .px(px(14.0))
643 .flex()
644 .flex_row()
645 .items_center()
646 .rounded(Radii::PILL)
647 .border_1()
648 .border_color(more_border)
649 .bg(colors.surface_muted)
650 .text_size(Typography::TEXT_SM)
651 .font_medium()
652 .text_color(more_fg)
653 .when(!disabled, |this| this.cursor_pointer())
654 .on_hover(move |hovered, window, cx| {
655 int_more_hover.update(cx, |s, _| {
656 if *hovered {
657 s.hovered_chip = Some("__more__".into());
658 } else if s.hovered_chip.as_deref() == Some("__more__") {
659 s.hovered_chip = None;
660 }
661 });
662 window.refresh();
663 })
664 .child(more_label_slot)
665 .into_any_element(),
666 );
667 }
668
669 let mut focus_keys: Vec<SharedString> = visible_options
672 .iter()
673 .map(|(_, o)| o.value.clone())
674 .collect();
675 if show_more {
676 focus_keys.push("__more__".into());
677 }
678 let int_key = internal.clone();
679 let all_opts_key = self.options.clone();
680 let selected_for_key = selected;
681 let on_change_key = self.on_value_change.clone();
682 let focus_handle = snap.focus_handle.clone();
683
684 let group_box = div()
685 .id(ElementId::NamedChild(
686 self.id.clone().into(),
687 "group".into(),
688 ))
689 .test_support()
690 .role(Role::Group)
691 .aria_label(self.label.clone())
692 .track_focus(&focus_handle)
693 .on_key_down(move |event: &KeyDownEvent, window, cx| {
694 if disabled || focus_keys.is_empty() {
695 return;
696 }
697 let cur_key = int_key.read(cx).active_focus_key.clone();
698 let cur_idx = cur_key
699 .as_ref()
700 .and_then(|k| focus_keys.iter().position(|fk| fk == k))
701 .unwrap_or(0);
702 let len = focus_keys.len();
703
704 match event.keystroke.key.as_str() {
705 "right" | "arrowright" | "down" | "arrowdown" => {
706 let next_k = focus_keys[(cur_idx + 1) % len].clone();
707 int_key.update(cx, |s, _| s.active_focus_key = Some(next_k));
708 window.refresh();
709 }
710 "left" | "arrowleft" | "up" | "arrowup" => {
711 let prev_k = focus_keys[(cur_idx + len - 1) % len].clone();
712 int_key.update(cx, |s, _| s.active_focus_key = Some(prev_k));
713 window.refresh();
714 }
715 "home" => {
716 let first_k = focus_keys[0].clone();
717 int_key.update(cx, |s, _| s.active_focus_key = Some(first_k));
718 window.refresh();
719 }
720 "end" => {
721 let last_k = focus_keys[len - 1].clone();
722 int_key.update(cx, |s, _| s.active_focus_key = Some(last_k));
723 window.refresh();
724 }
725 "enter" | " " | "space" => {
726 let target_k = focus_keys[cur_idx].clone();
727 if target_k.as_ref() == "__more__" {
728 let t_now = motion_now(cx);
729 int_key.update(cx, |s, _| {
730 if s.expanded {
731 s.pinned = selected_for_key.clone();
732 }
733 s.expanded = !s.expanded;
734 s.expanded_changed_at_secs = t_now;
735 });
736 } else {
737 let next_vals = toggle_chip_group_value(
738 &all_opts_key,
739 &selected_for_key,
740 &target_k,
741 multiple,
742 );
743 int_key.update(cx, |s, _| {
744 s.uncontrolled_value = next_vals.clone();
745 });
746 if let Some(cb) = &on_change_key {
747 cb(&next_vals, window, cx);
748 }
749 }
750 window.refresh();
751 }
752 _ => {}
753 }
754 })
755 .w_full()
756 .h(px(frame_h))
757 .overflow_hidden()
758 .child(
759 div()
760 .relative()
761 .w_full()
762 .flex()
763 .flex_row()
764 .flex_wrap()
765 .gap(Spacing::S2)
766 .child(frame_probe)
767 .children(chip_els),
768 );
769
770 div()
771 .id(self.id)
772 .test_support()
773 .when_some(self.width, |this, w| this.w(w))
774 .when(self.width.is_none(), |this| this.w_full())
775 .flex()
776 .flex_col()
777 .gap(Spacing::S2)
778 .when(self.show_label, |this| {
779 this.child(
780 div()
781 .text_size(Typography::TEXT_SM)
782 .font_medium()
783 .text_color(colors.foreground)
784 .child(self.label),
785 )
786 })
787 .child(group_box)
788 }
789}
790
791#[cfg(test)]
792mod tests {
793 use super::*;
794
795 #[test]
796 fn chip_check_metrics_coordinate_slot_width_and_path_length() {
797 let (w0, sc0, op0, len0) = chip_check_metrics(0.0, false);
798 assert!(w0.abs() < 1e-4);
799 assert!(sc0.abs() < 1e-4);
800 assert!(op0.abs() < 1e-4);
801 assert!(len0.abs() < 1e-4);
802
803 let (w1, sc1, op1, len1) = chip_check_metrics(1.0, false);
804 assert!((w1 - CHIP_CHECK_SLOT_PX).abs() < 1e-4);
805 assert!((sc1 - 1.0).abs() < 1e-4);
806 assert!((op1 - 1.0).abs() < 1e-4);
807 assert!((len1 - 1.0).abs() < 1e-4);
808 }
809
810 #[test]
811 fn toggle_chip_group_value_handles_multi_and_single_modes() {
812 let opts = vec![
813 ChipOption::new("a", "Alpha"),
814 ChipOption::new("b", "Beta"),
815 ChipOption::new("c", "Gamma"),
816 ];
817 let sel: Vec<SharedString> = vec!["c".into()];
819 let next_multi = toggle_chip_group_value(&opts, &sel, &"a".into(), true);
820 assert_eq!(
821 next_multi,
822 vec![SharedString::from("a"), SharedString::from("c")]
823 );
824
825 let next_single = toggle_chip_group_value(&opts, &sel, &"a".into(), false);
827 assert_eq!(next_single, vec![SharedString::from("a")]);
828 let cleared = toggle_chip_group_value(&opts, &next_single, &"a".into(), false);
829 assert!(cleared.is_empty());
830 }
831
832 #[test]
833 fn chip_reveal_progress_staggers_items_beyond_max_visible() {
834 assert!((chip_reveal_progress(0.0, 2, 4, false) - 1.0).abs() < 1e-4);
835 assert!(chip_reveal_progress(0.02, 5, 4, false) < 1e-4);
836 assert!((chip_reveal_progress(0.50, 5, 4, false) - 1.0).abs() < 1e-4);
837 }
838}