1use std::{cell::RefCell, collections::HashMap, rc::Rc, time::Duration};
23
24use arc_motion::{
25 BlurFallback, CubicBezier, arc_spring, arc_spring_with_options, arc_transition,
26 is_reduced_motion, motion_now, spring::SpringOptions,
27};
28use arc_tokens::{
29 ActiveArcTheme as _, ControlHeights, Radii, Shadows, Spacing, SpringSpec, Typography, oklab_mix,
30};
31use gpui_kit::{
32 App, Bounds, ElementId, Entity, FocusHandle, Hsla, IntoElement, KeyDownEvent, MouseDownEvent,
33 ParentElement, PathBuilder, Pixels, RenderOnce, Role, SharedString, Styled,
34 TestSupportExt as _, Window,
35 assets::IconName,
36 base::StyledExt as _,
37 canvas,
38 component::{
39 Icon,
40 input::{Input as KitInput, InputState},
41 },
42 deferred, div, point,
43 prelude::*,
44 px,
45};
46
47type MorphSelectChangeHandler = Rc<dyn Fn(&SharedString, &mut Window, &mut App)>;
48
49pub const MORPH_SELECT_DEFAULT_PANEL_W: f32 = 248.0;
51pub const MORPH_SELECT_DEFAULT_MAX_LIST_H: f32 = 260.0;
53pub const MORPH_SELECT_LID_H: f32 = 36.0;
55pub const MORPH_SELECT_OPTION_H: f32 = 32.0;
57pub const MORPH_SELECT_GROUP_HEADER_H: f32 = 24.0;
59
60pub const fn morph_select_grow_spring() -> SpringSpec {
62 SpringSpec::visual(0.40, 0.0)
63}
64
65pub const fn morph_select_shrink_spring() -> SpringSpec {
67 SpringSpec::visual(0.34, 0.0)
68}
69
70pub const fn morph_select_glide_spring() -> SpringSpec {
72 SpringSpec::visual(0.28, 0.0)
73}
74
75pub const fn morph_select_width_spring() -> SpringSpec {
77 SpringSpec::visual(0.42, 0.0)
78}
79
80pub const fn morph_select_fly_spring() -> SpringSpec {
82 SpringSpec::visual(0.30, 0.0)
83}
84
85pub fn estimate_morph_trigger_width(label: &str, has_icon: bool) -> f32 {
88 let text_w: f32 = label
89 .chars()
90 .map(|ch| if ch.is_ascii() { 7.6 } else { 14.0 })
91 .sum();
92 let icon_w = if has_icon { 28.0 } else { 0.0 };
93 (14.0 + icon_w + text_w + 38.0).ceil().clamp(88.0, 320.0)
94}
95
96pub fn morph_select_list_face_sample(elapsed: f64, opening: bool, reduced: bool) -> (f32, f32) {
99 if reduced {
100 return (if opening { 1.0 } else { 0.0 }, 0.0);
101 }
102 if opening {
103 if elapsed <= 0.04 {
104 return (0.0, -6.0);
105 }
106 let t = ((elapsed - 0.04) / 0.20).clamp(0.0, 1.0) as f32;
107 let e = CubicBezier::new(0.16, 1.0, 0.3, 1.0).sample(t);
108 let blur = BlurFallback::evaluate(px(2.0 * (1.0 - e)), false);
109 let op = (e * blur.opacity_multiplier).clamp(0.0, 1.0);
110 let y = -6.0 * (1.0 - e);
111 (op, y)
112 } else {
113 let t = (elapsed / 0.10).clamp(0.0, 1.0) as f32;
114 let e = CubicBezier::new(0.22, 1.0, 0.36, 1.0).sample(t);
115 let blur = BlurFallback::evaluate(px(2.0 * e), false);
116 let op = ((1.0 - e) * blur.opacity_multiplier).clamp(0.0, 1.0);
117 let y = -6.0 * e;
118 (op, y)
119 }
120}
121
122#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
124pub enum MorphSelectAlign {
125 #[default]
126 Start,
127 End,
128}
129
130#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
132pub enum MorphSearchable {
133 #[default]
135 Auto,
136 Enabled,
137 Disabled,
138}
139
140#[derive(Clone, Debug, PartialEq, Eq)]
142pub struct MorphSelectOption {
143 pub value: SharedString,
144 pub label: SharedString,
145 pub icon: Option<IconName>,
146 pub meta: Option<SharedString>,
147 pub keywords: Option<SharedString>,
148 pub disabled: bool,
149}
150
151impl MorphSelectOption {
152 pub fn new(value: impl Into<SharedString>, label: impl Into<SharedString>) -> Self {
153 Self {
154 value: value.into(),
155 label: label.into(),
156 icon: None,
157 meta: None,
158 keywords: None,
159 disabled: false,
160 }
161 }
162
163 pub fn icon(mut self, icon: IconName) -> Self {
164 self.icon = Some(icon);
165 self
166 }
167
168 pub fn meta(mut self, meta: impl Into<SharedString>) -> Self {
169 self.meta = Some(meta.into());
170 self
171 }
172
173 pub fn keywords(mut self, keywords: impl Into<SharedString>) -> Self {
174 self.keywords = Some(keywords.into());
175 self
176 }
177
178 pub fn disabled(mut self, disabled: bool) -> Self {
179 self.disabled = disabled;
180 self
181 }
182
183 pub fn matches_query(&self, needle_lower: &str) -> bool {
184 if needle_lower.is_empty() {
185 return true;
186 }
187 if self.label.to_lowercase().contains(needle_lower) {
188 return true;
189 }
190 if self
191 .meta
192 .as_ref()
193 .is_some_and(|m| m.to_lowercase().contains(needle_lower))
194 {
195 return true;
196 }
197 self.keywords
198 .as_ref()
199 .is_some_and(|k| k.to_lowercase().contains(needle_lower))
200 }
201}
202
203#[derive(Clone, Debug, PartialEq, Eq)]
205pub struct MorphSelectGroup {
206 pub label: SharedString,
207 pub options: Vec<MorphSelectOption>,
208}
209
210impl MorphSelectGroup {
211 pub fn new(
212 label: impl Into<SharedString>,
213 options: impl IntoIterator<Item = MorphSelectOption>,
214 ) -> Self {
215 Self {
216 label: label.into(),
217 options: options.into_iter().collect(),
218 }
219 }
220}
221
222#[derive(Clone, Debug, PartialEq, Eq)]
224pub enum MorphSelectItem {
225 Option(MorphSelectOption),
226 Group(MorphSelectGroup),
227}
228
229impl From<MorphSelectOption> for MorphSelectItem {
230 fn from(opt: MorphSelectOption) -> Self {
231 Self::Option(opt)
232 }
233}
234
235impl From<MorphSelectGroup> for MorphSelectItem {
236 fn from(group: MorphSelectGroup) -> Self {
237 Self::Group(group)
238 }
239}
240
241#[derive(Clone, Debug, PartialEq, Eq)]
243pub struct MorphSelectSection {
244 pub key: SharedString,
245 pub label: Option<SharedString>,
246 pub options: Vec<MorphSelectOption>,
247}
248
249pub fn normalize_morph_select_items(items: &[MorphSelectItem]) -> Vec<MorphSelectSection> {
251 let mut out: Vec<MorphSelectSection> = Vec::new();
252 for (idx, item) in items.iter().enumerate() {
253 match item {
254 MorphSelectItem::Group(g) => {
255 out.push(MorphSelectSection {
256 key: SharedString::from(format!("group-{idx}")),
257 label: Some(g.label.clone()),
258 options: g.options.clone(),
259 });
260 }
261 MorphSelectItem::Option(opt) => {
262 if let Some(last) = out.last_mut()
263 && last.label.is_none()
264 {
265 last.options.push(opt.clone());
266 } else {
267 out.push(MorphSelectSection {
268 key: SharedString::from(format!("loose-{idx}")),
269 label: None,
270 options: vec![opt.clone()],
271 });
272 }
273 }
274 }
275 }
276 out
277}
278
279#[derive(Clone)]
280struct MorphSelectInternal {
281 open: bool,
282 toggled_at_secs: f64,
283 uncontrolled_value: Option<SharedString>,
284 active_value: Option<SharedString>,
285 highlight_seeded: bool,
286 last_selected: Option<SharedString>,
287 fly_epoch: u64,
288 fly_from_y: f32,
289 fly_from_x: f32,
290 fly_started_at_secs: f64,
291 fly_used_lift: bool,
292 fly_dir: i8,
293 previous_label: Option<SharedString>,
294 measured_trigger_w: Rc<RefCell<f32>>,
295 option_y_offsets: Rc<RefCell<HashMap<SharedString, (f32, f32)>>>,
296 shape_bounds: Rc<RefCell<Option<Bounds<Pixels>>>>,
297 last_query: SharedString,
298 query_input: Entity<InputState>,
299 trigger_hovered: bool,
300 focus_handle: FocusHandle,
301}
302
303impl MorphSelectInternal {
304 fn new(
305 default_value: Option<SharedString>,
306 now: f64,
307 window: &mut Window,
308 cx: &mut App,
309 ) -> Self {
310 let query_input = cx.new(|cx| InputState::new(window, cx).placeholder("Search"));
311 Self {
312 open: false,
313 toggled_at_secs: now - 10.0,
314 uncontrolled_value: default_value.clone(),
315 active_value: default_value.clone(),
316 highlight_seeded: false,
317 last_selected: default_value,
318 fly_epoch: 0,
319 fly_from_y: 0.0,
320 fly_from_x: 0.0,
321 fly_started_at_secs: now - 10.0,
322 fly_used_lift: false,
323 fly_dir: 1,
324 previous_label: None,
325 measured_trigger_w: Rc::new(RefCell::new(0.0)),
326 option_y_offsets: Rc::new(RefCell::new(HashMap::new())),
327 shape_bounds: Rc::new(RefCell::new(None)),
328 last_query: "".into(),
329 query_input,
330 trigger_hovered: false,
331 focus_handle: cx.focus_handle(),
332 }
333 }
334}
335
336fn paint_rotated_chevron(cx: f32, cy: f32, angle_deg: f32, color: Hsla, window: &mut Window) {
337 let rad = angle_deg.to_radians();
338 let cos_a = rad.cos();
339 let sin_a = rad.sin();
340 let pts = [(-4.0_f32, -2.0_f32), (0.0, 2.0), (4.0, -2.0)];
341 let mut builder = PathBuilder::stroke(px(1.75));
342 for (i, (lx, ly)) in pts.iter().enumerate() {
343 let rx = cx + lx * cos_a - ly * sin_a;
344 let ry = cy + lx * sin_a + ly * cos_a;
345 let p = point(px(rx), px(ry));
346 if i == 0 {
347 builder.move_to(p);
348 } else {
349 builder.line_to(p);
350 }
351 }
352 if let Ok(path) = builder.build() {
353 window.paint_path(path, color);
354 }
355}
356
357fn paint_scaled_check(
358 cx: f32,
359 cy: f32,
360 scale: f32,
361 opacity: f32,
362 color: Hsla,
363 window: &mut Window,
364) {
365 if opacity <= 0.01 {
366 return;
367 }
368 let pts = [(-4.5_f32, 0.2_f32), (-1.4, 3.3), (4.8, -3.2)];
369 let mut builder = PathBuilder::stroke(px(1.75));
370 for (i, (lx, ly)) in pts.iter().enumerate() {
371 let p = point(px(cx + lx * scale), px(cy + ly * scale));
372 if i == 0 {
373 builder.move_to(p);
374 } else {
375 builder.line_to(p);
376 }
377 }
378 let c = Hsla {
379 a: color.a * opacity.clamp(0.0, 1.0),
380 ..color
381 };
382 if let Ok(path) = builder.build() {
383 window.paint_path(path, c);
384 }
385}
386
387#[derive(IntoElement)]
391pub struct MorphSelect {
392 id: ElementId,
393 label: SharedString,
394 hide_label: bool,
395 items: Vec<MorphSelectItem>,
396 value: Option<SharedString>,
397 default_value: Option<SharedString>,
398 placeholder: SharedString,
399 searchable: MorphSearchable,
400 search_placeholder: Option<SharedString>,
401 panel_width: f32,
402 max_list_height: f32,
403 align: MorphSelectAlign,
404 disabled: bool,
405 on_value_change: Option<MorphSelectChangeHandler>,
406}
407
408impl MorphSelect {
409 pub fn new(id: impl Into<ElementId>, label: impl Into<SharedString>) -> Self {
410 Self {
411 id: id.into(),
412 label: label.into(),
413 hide_label: false,
414 items: Vec::new(),
415 value: None,
416 default_value: None,
417 placeholder: "Select".into(),
418 searchable: MorphSearchable::Auto,
419 search_placeholder: None,
420 panel_width: MORPH_SELECT_DEFAULT_PANEL_W,
421 max_list_height: MORPH_SELECT_DEFAULT_MAX_LIST_H,
422 align: MorphSelectAlign::Start,
423 disabled: false,
424 on_value_change: None,
425 }
426 }
427
428 pub fn hide_label(mut self, hide: bool) -> Self {
429 self.hide_label = hide;
430 self
431 }
432
433 pub fn option(mut self, option: MorphSelectOption) -> Self {
434 self.items.push(MorphSelectItem::Option(option));
435 self
436 }
437
438 pub fn options(mut self, options: impl IntoIterator<Item = MorphSelectOption>) -> Self {
439 self.items
440 .extend(options.into_iter().map(MorphSelectItem::Option));
441 self
442 }
443
444 pub fn group(mut self, group: MorphSelectGroup) -> Self {
445 self.items.push(MorphSelectItem::Group(group));
446 self
447 }
448
449 pub fn items(mut self, items: impl IntoIterator<Item = impl Into<MorphSelectItem>>) -> Self {
450 self.items.extend(items.into_iter().map(Into::into));
451 self
452 }
453
454 pub fn value(mut self, value: impl Into<SharedString>) -> Self {
455 self.value = Some(value.into());
456 self
457 }
458
459 pub fn default_value(mut self, value: impl Into<SharedString>) -> Self {
460 self.default_value = Some(value.into());
461 self
462 }
463
464 pub fn placeholder(mut self, placeholder: impl Into<SharedString>) -> Self {
465 self.placeholder = placeholder.into();
466 self
467 }
468
469 pub fn searchable(mut self, searchable: MorphSearchable) -> Self {
470 self.searchable = searchable;
471 self
472 }
473
474 pub fn search_placeholder(mut self, placeholder: impl Into<SharedString>) -> Self {
475 self.search_placeholder = Some(placeholder.into());
476 self
477 }
478
479 pub fn panel_width(mut self, width: f32) -> Self {
480 self.panel_width = width.max(140.0);
481 self
482 }
483
484 pub fn max_list_height(mut self, height: f32) -> Self {
485 self.max_list_height = height.max(120.0);
486 self
487 }
488
489 pub fn align(mut self, align: MorphSelectAlign) -> Self {
490 self.align = align;
491 self
492 }
493
494 pub fn disabled(mut self, disabled: bool) -> Self {
495 self.disabled = disabled;
496 self
497 }
498
499 pub fn on_value_change(
500 mut self,
501 handler: impl Fn(&SharedString, &mut Window, &mut App) + 'static,
502 ) -> Self {
503 self.on_value_change = Some(Rc::new(handler));
504 self
505 }
506}
507
508impl RenderOnce for MorphSelect {
509 fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
510 let theme = cx.arc_theme().clone();
511 let colors = theme.colors;
512 let motion = theme.motion;
513 let reduced = is_reduced_motion(cx);
514 let now = motion_now(cx);
515
516 let sections = normalize_morph_select_items(&self.items);
517 let all_options: Vec<MorphSelectOption> = sections
518 .iter()
519 .flat_map(|sec| sec.options.iter().cloned())
520 .collect();
521 let can_search = match self.searchable {
522 MorphSearchable::Auto => all_options.len() > 8,
523 MorphSearchable::Enabled => true,
524 MorphSearchable::Disabled => false,
525 };
526
527 let initial_val = self.value.clone().or_else(|| self.default_value.clone());
528 let state_id =
529 ElementId::NamedChild(self.id.clone().into(), "__arc-morph-select-state".into());
530 let internal = window.use_keyed_state(state_id, cx, |window, cx| {
531 MorphSelectInternal::new(initial_val.clone(), now, window, cx)
532 });
533
534 let selected_val: Option<SharedString> = self
535 .value
536 .clone()
537 .or_else(|| internal.read(cx).uncontrolled_value.clone())
538 .filter(|v| !v.is_empty());
539 let selected_index = selected_val
540 .as_ref()
541 .and_then(|v| all_options.iter().position(|opt| &opt.value == v));
542 let selected_option = selected_index.and_then(|idx| all_options.get(idx)).cloned();
543
544 let effective_search_ph = self
546 .search_placeholder
547 .clone()
548 .or_else(|| selected_option.as_ref().map(|opt| opt.label.clone()))
549 .unwrap_or_else(|| "Search".into());
550 {
551 let q_in = internal.read(cx).query_input.clone();
552 q_in.update(cx, |s, cx| {
553 s.set_placeholder(effective_search_ph.clone(), window, cx);
554 });
555 }
556
557 {
559 let prev_sel = internal.read(cx).last_selected.clone();
560 if prev_sel != selected_val {
561 let prev_idx = prev_sel
562 .as_ref()
563 .and_then(|v| all_options.iter().position(|opt| &opt.value == v));
564 let dir = match (selected_index, prev_idx) {
565 (Some(to), Some(from)) if to < from => -1,
566 _ => 1,
567 };
568 let prev_lbl = prev_idx
569 .and_then(|i| all_options.get(i))
570 .map(|opt| opt.label.clone());
571 internal.update(cx, |s, _| {
572 s.last_selected = selected_val.clone();
573 s.previous_label = prev_lbl;
574 s.fly_dir = dir;
575 s.fly_used_lift = false;
576 s.fly_from_x = 0.0;
577 s.fly_from_y = (dir as f32) * 7.0;
578 s.fly_epoch = s.fly_epoch.wrapping_add(1);
579 s.fly_started_at_secs = now;
580 });
581 }
582 }
583
584 {
586 let q_in = internal.read(cx).query_input.clone();
587 let q_val: SharedString = q_in.read(cx).value().clone();
588 let last_q = internal.read(cx).last_query.clone();
589 if q_val != last_q {
590 internal.update(cx, |s, _| {
591 s.last_query = q_val;
592 s.active_value = None;
593 });
594 }
595 }
596
597 let snap = internal.read(cx).clone();
598 let is_open = snap.open && !self.disabled;
599 let show_search = is_open && can_search;
600
601 let needle = if is_open && can_search {
602 snap.query_input.read(cx).value().trim().to_lowercase()
603 } else {
604 String::new()
605 };
606
607 let visible_sections: Vec<MorphSelectSection> = if needle.is_empty() {
608 sections
609 } else {
610 sections
611 .into_iter()
612 .filter_map(|mut sec| {
613 sec.options.retain(|opt| opt.matches_query(&needle));
614 (!sec.options.is_empty()).then_some(sec)
615 })
616 .collect()
617 };
618 let enabled_options: Vec<MorphSelectOption> = visible_sections
619 .iter()
620 .flat_map(|sec| sec.options.iter())
621 .filter(|opt| !opt.disabled)
622 .cloned()
623 .collect();
624 let current_active: Option<SharedString> = snap
625 .active_value
626 .clone()
627 .filter(|act| enabled_options.iter().any(|opt| &opt.value == act))
628 .or_else(|| enabled_options.first().map(|opt| opt.value.clone()));
629
630 let display_label = selected_option
632 .as_ref()
633 .map(|opt| opt.label.clone())
634 .unwrap_or_else(|| self.placeholder.clone());
635 let has_icon = selected_option
636 .as_ref()
637 .is_some_and(|opt| opt.icon.is_some());
638 let measured_w = *snap.measured_trigger_w.borrow();
639 let trigger_w = if measured_w > 40.0 {
640 measured_w
641 } else {
642 estimate_morph_trigger_width(&display_label, has_icon)
643 };
644
645 let raw_list_content_h: f32 = if visible_sections.is_empty() {
647 46.0
648 } else {
649 let mut h = 0.0_f32;
650 for (sec_idx, sec) in visible_sections.iter().enumerate() {
651 if sec_idx > 0 {
652 h += 4.0;
653 }
654 if sec.label.is_some() {
655 h += MORPH_SELECT_GROUP_HEADER_H + 2.0;
656 }
657 let n = sec.options.len();
658 h += n as f32 * MORPH_SELECT_OPTION_H + n.saturating_sub(1) as f32 * 2.0;
659 }
660 h
661 };
662 let list_scroll_h = (raw_list_content_h + 6.0).min(self.max_list_height);
663 let list_face_h = list_scroll_h + 7.0;
665 let open_w = trigger_w.max(self.panel_width);
666 let open_h = MORPH_SELECT_LID_H + list_face_h;
667
668 let target_shape_w = if is_open { open_w } else { trigger_w };
669 let target_shape_h = if is_open { open_h } else { MORPH_SELECT_LID_H };
670 let shape_spec = if is_open {
671 morph_select_grow_spring()
672 } else {
673 morph_select_shrink_spring()
674 };
675 let width_spec = morph_select_width_spring();
676
677 let anchor_w = if reduced {
678 trigger_w
679 } else {
680 arc_spring(
681 (self.id.clone(), "anchor-w"),
682 trigger_w,
683 width_spec,
684 window,
685 cx,
686 )
687 };
688 let shape_w = if reduced {
689 target_shape_w
690 } else {
691 arc_spring(
692 (self.id.clone(), "shape-w"),
693 target_shape_w,
694 if is_open { shape_spec } else { width_spec },
695 window,
696 cx,
697 )
698 };
699 let shape_h = if reduced {
700 target_shape_h
701 } else {
702 arc_spring(
703 (self.id.clone(), "shape-h"),
704 target_shape_h,
705 shape_spec,
706 window,
707 cx,
708 )
709 };
710
711 let fly_spec = if snap.fly_used_lift {
713 morph_select_fly_spring()
714 } else {
715 morph_select_glide_spring()
716 };
717 let lid_val_x = if reduced {
718 0.0
719 } else {
720 arc_spring_with_options(
721 (self.id.clone(), format!("fly-x-{}", snap.fly_epoch)),
722 0.0,
723 SpringOptions::new(fly_spec).with_initial_value(snap.fly_from_x),
724 window,
725 cx,
726 )
727 .value
728 };
729 let lid_val_y = if reduced {
730 0.0
731 } else {
732 arc_spring_with_options(
733 (self.id.clone(), format!("fly-y-{}", snap.fly_epoch)),
734 0.0,
735 SpringOptions::new(fly_spec).with_initial_value(snap.fly_from_y),
736 window,
737 cx,
738 )
739 .value
740 };
741 let fly_elapsed = (now - snap.fly_started_at_secs).max(0.0);
742 let lid_val_op = if snap.fly_used_lift {
743 1.0
744 } else if fly_elapsed < 0.22 {
745 window.request_animation_frame();
746 let t = (fly_elapsed / 0.20).clamp(0.0, 1.0) as f32;
747 let e = if reduced {
748 t
749 } else {
750 CubicBezier::new(0.16, 1.0, 0.3, 1.0).sample(t)
751 };
752 let blur = BlurFallback::evaluate(px(4.0 * (1.0 - e)), reduced);
753 (e * blur.opacity_multiplier).clamp(0.0, 1.0)
754 } else {
755 1.0
756 };
757 let exit_op = if !snap.fly_used_lift && fly_elapsed < 0.12 {
758 window.request_animation_frame();
759 let t = (fly_elapsed / 0.12).clamp(0.0, 1.0) as f32;
760 1.0 - t
761 } else {
762 0.0
763 };
764
765 let glide_spec = morph_select_glide_spring();
767 let chevron_deg = if reduced {
768 if is_open { 180.0 } else { 0.0 }
769 } else {
770 arc_spring(
771 (self.id.clone(), "chevron-deg"),
772 if is_open { 180.0 } else { 0.0 },
773 glide_spec,
774 window,
775 cx,
776 )
777 };
778
779 let toggle_elapsed = (now - snap.toggled_at_secs).max(0.0);
781 let (list_face_op, list_face_y) =
782 morph_select_list_face_sample(toggle_elapsed, is_open, reduced);
783 if (is_open && toggle_elapsed < 0.26) || (!is_open && toggle_elapsed < 0.12) {
784 window.request_animation_frame();
785 }
786 let render_list_face = is_open || shape_h > MORPH_SELECT_LID_H + 1.0 || list_face_op > 0.01;
787
788 let mut computed_offsets: HashMap<SharedString, (f32, f32)> = HashMap::new();
791 {
792 let mut cur_y = 0.0_f32;
793 for (sec_idx, sec) in visible_sections.iter().enumerate() {
794 if sec_idx > 0 {
795 cur_y += 4.0;
796 }
797 if sec.label.is_some() {
798 cur_y += MORPH_SELECT_GROUP_HEADER_H + 2.0;
799 }
800 for (opt_idx, opt) in sec.options.iter().enumerate() {
801 if opt_idx > 0 {
802 cur_y += 2.0;
803 }
804 computed_offsets.insert(opt.value.clone(), (cur_y, MORPH_SELECT_OPTION_H));
805 cur_y += MORPH_SELECT_OPTION_H;
806 }
807 }
808 *snap.option_y_offsets.borrow_mut() = computed_offsets.clone();
809 }
810
811 let active_geom = current_active
813 .as_ref()
814 .and_then(|val| computed_offsets.get(val).copied());
815 let hi_op = arc_transition(
816 (self.id.clone(), "hi-op"),
817 if is_open && active_geom.is_some() {
818 1.0
819 } else {
820 0.0
821 },
822 if reduced || !is_open {
823 Duration::ZERO
824 } else {
825 Duration::from_millis(120)
826 },
827 if is_open {
828 motion.ease.enter
829 } else {
830 motion.ease.standard
831 },
832 window,
833 cx,
834 );
835 let (target_hy, target_hh) = active_geom.unwrap_or((0.0, MORPH_SELECT_OPTION_H));
836 let (pill_y, pill_h) = if reduced || !snap.highlight_seeded || hi_op < 0.05 {
837 let _ = arc_spring_with_options(
838 (self.id.clone(), "hi-y"),
839 target_hy,
840 SpringOptions::new(glide_spec).with_initial_value(target_hy),
841 window,
842 cx,
843 );
844 let _ = arc_spring_with_options(
845 (self.id.clone(), "hi-h"),
846 target_hh,
847 SpringOptions::new(glide_spec).with_initial_value(target_hh),
848 window,
849 cx,
850 );
851 if is_open && active_geom.is_some() && !snap.highlight_seeded {
852 internal.update(cx, |s, _| s.highlight_seeded = true);
853 }
854 (target_hy, target_hh)
855 } else {
856 (
857 arc_spring((self.id.clone(), "hi-y"), target_hy, glide_spec, window, cx),
858 arc_spring((self.id.clone(), "hi-h"), target_hh, glide_spec, window, cx),
859 )
860 };
861
862 let hover_p = arc_transition(
864 (self.id.clone(), "shape-hover"),
865 if !self.disabled && !is_open && snap.trigger_hovered {
866 1.0
867 } else {
868 0.0
869 },
870 if reduced {
871 Duration::ZERO
872 } else {
873 motion.duration.fast
874 },
875 motion.ease.standard,
876 window,
877 cx,
878 );
879 let open_p = arc_transition(
880 (self.id.clone(), "shape-open-bg"),
881 if is_open { 1.0 } else { 0.0 },
882 if reduced {
883 Duration::ZERO
884 } else {
885 motion.duration.fast
886 },
887 motion.ease.standard,
888 window,
889 cx,
890 );
891 let closed_bg = oklab_mix(colors.surface_muted, colors.surface, hover_p);
892 let shape_bg = oklab_mix(colors.surface_raised, closed_bg, open_p);
893 let shape_border = oklab_mix(
894 colors.border_strong,
895 colors.border,
896 hover_p * (1.0 - open_p),
897 );
898 let shape_shadow = if is_open || shape_h > MORPH_SELECT_LID_H + 4.0 {
899 Shadows::floating(theme.mode)
900 } else {
901 Shadows::resting(theme.mode)
902 };
903
904 let measure_w_ref = snap.measured_trigger_w.clone();
906 let measure_probe = canvas(
907 move |rect, window, _| {
908 let w = (f32::from(rect.size.width) + 1.0).ceil();
909 if w > 40.0 {
910 let prev = *measure_w_ref.borrow();
911 *measure_w_ref.borrow_mut() = w;
912 if (prev - w).abs() > 0.5 && prev > 0.0 {
913 window.request_animation_frame();
914 }
915 }
916 },
917 |_, _, _, _| {},
918 )
919 .absolute()
920 .inset_0();
921
922 let measure_el = div()
923 .absolute()
924 .top_0()
925 .left_0()
926 .h(ControlHeights::MD)
927 .pl(px(14.0))
928 .pr(px(36.0))
929 .flex()
930 .flex_row()
931 .items_center()
932 .gap(Spacing::S2)
933 .opacity(0.0)
934 .child(measure_probe)
935 .when_some(selected_option.as_ref().and_then(|o| o.icon), |this, ic| {
936 this.child(Icon::new(ic).text_size(px(16.0)))
937 })
938 .child(
939 div()
940 .text_size(Typography::TEXT_SM)
941 .font_medium()
942 .child(display_label.clone()),
943 );
944
945 let shape_bounds_ref = snap.shape_bounds.clone();
947 let shape_bounds_outside = snap.shape_bounds.clone();
948 let internal_outside = internal.clone();
949 let shape_probe = canvas(
950 move |rect, _, _| {
951 *shape_bounds_ref.borrow_mut() = Some(rect);
952 },
953 move |_, _, window, _| {
954 if is_open {
955 let s_ref = shape_bounds_outside.clone();
956 let st = internal_outside.clone();
957 window.on_mouse_event(move |event: &MouseDownEvent, phase, window, cx| {
958 if !phase.bubble() {
959 return;
960 }
961 let in_shape = s_ref.borrow().is_some_and(|b| b.contains(&event.position));
962 if !in_shape {
963 let t_now = motion_now(cx);
964 let q_in = st.read(cx).query_input.clone();
965 q_in.update(cx, |s, cx| s.set_value("", window, cx));
966 st.update(cx, |s, _| {
967 s.open = false;
968 s.toggled_at_secs = t_now;
969 s.highlight_seeded = false;
970 s.last_query = "".into();
971 });
972 window.refresh();
973 }
974 });
975 }
976 },
977 )
978 .absolute()
979 .inset_0();
980
981 let slot_op = arc_transition(
983 (self.id.clone(), "slot-hidden-op"),
984 if show_search { 0.0 } else { 1.0 },
985 motion.duration.instant,
986 motion.ease.standard,
987 window,
988 cx,
989 );
990 let value_fg = if selected_option.is_some() {
991 colors.foreground
992 } else {
993 colors.text_muted
994 };
995
996 let mut lid_slot = div()
997 .relative()
998 .flex_1()
999 .min_w_0()
1000 .h_full()
1001 .overflow_hidden()
1002 .opacity(slot_op)
1003 .child(
1004 div()
1005 .absolute()
1006 .inset_0()
1007 .ml(px(lid_val_x))
1008 .mt(px(lid_val_y))
1009 .opacity(lid_val_op)
1010 .flex()
1011 .flex_row()
1012 .items_center()
1013 .gap(Spacing::S2)
1014 .when_some(selected_option.as_ref().and_then(|o| o.icon), |this, ic| {
1015 this.child(
1016 div()
1017 .size(px(20.0))
1018 .flex_none()
1019 .flex()
1020 .items_center()
1021 .justify_center()
1022 .text_color(colors.text_secondary)
1023 .child(Icon::new(ic).text_size(px(16.0))),
1024 )
1025 })
1026 .child(
1027 div()
1028 .flex_1()
1029 .min_w_0()
1030 .text_size(Typography::TEXT_SM)
1031 .when(selected_option.is_some(), |this| this.font_medium())
1032 .text_color(value_fg)
1033 .truncate()
1034 .child(display_label),
1035 ),
1036 );
1037
1038 if exit_op > 0.01
1039 && let Some(prev_lbl) = snap.previous_label.clone()
1040 {
1041 lid_slot = lid_slot.child(
1042 div()
1043 .absolute()
1044 .inset_0()
1045 .mt(px(-(snap.fly_dir as f32) * 5.0 * (1.0 - exit_op)))
1046 .opacity(exit_op)
1047 .flex()
1048 .items_center()
1049 .text_size(Typography::TEXT_SM)
1050 .font_medium()
1051 .text_color(colors.text_secondary)
1052 .truncate()
1053 .child(prev_lbl),
1054 );
1055 }
1056
1057 let trigger_id = ElementId::NamedChild(self.id.clone().into(), "trigger".into());
1058 let int_hover = internal.clone();
1059 let int_click = internal.clone();
1060 let focus_for_open = snap.focus_handle.clone();
1061 let selected_for_open = selected_val.clone();
1062 let disabled = self.disabled;
1063
1064 let chevron_color = colors.text_muted;
1065 let lid_trigger = div()
1066 .id(trigger_id)
1067 .test_support()
1068 .role(Role::Button)
1069 .aria_label(self.label.clone())
1070 .on_click(move |_, window, cx| {
1071 if disabled {
1072 return;
1073 }
1074 let t_now = motion_now(cx);
1075 let mut became_open = false;
1076 let q_in = int_click.read(cx).query_input.clone();
1077 int_click.update(cx, |s, _| {
1078 s.open = !s.open;
1079 s.toggled_at_secs = t_now;
1080 became_open = s.open;
1081 if s.open {
1082 s.active_value = selected_for_open.clone();
1083 s.highlight_seeded = false;
1084 s.last_query = "".into();
1085 } else {
1086 s.highlight_seeded = false;
1087 }
1088 });
1089 if became_open {
1090 q_in.update(cx, |s, cx| {
1091 s.set_value("", window, cx);
1092 if can_search {
1093 s.focus(window, cx);
1094 }
1095 });
1096 if !can_search {
1097 window.focus(&focus_for_open, cx);
1098 }
1099 }
1100 window.refresh();
1101 })
1102 .absolute()
1103 .inset_0()
1104 .w_full()
1105 .h(ControlHeights::MD)
1106 .pl(px(14.0))
1107 .pr(px(36.0))
1108 .flex()
1109 .flex_row()
1110 .items_center()
1111 .gap(Spacing::S2)
1112 .when(!disabled, |this| this.cursor_pointer())
1113 .on_hover(move |hovered, window, cx| {
1114 int_hover.update(cx, |s, _| {
1115 s.trigger_hovered = *hovered;
1116 });
1117 window.refresh();
1118 })
1119 .child(lid_slot)
1120 .child(
1121 div()
1122 .absolute()
1123 .top(px(14.0))
1124 .right(px(12.0))
1125 .size(px(16.0))
1126 .child(
1127 canvas(
1128 |_, _, _| {},
1129 move |rect, _, window, _| {
1130 let cx_pt = f32::from(rect.origin.x + rect.size.width * 0.5);
1131 let cy_pt = f32::from(rect.origin.y + rect.size.height * 0.5);
1132 paint_rotated_chevron(
1133 cx_pt,
1134 cy_pt,
1135 chevron_deg,
1136 chevron_color,
1137 window,
1138 );
1139 },
1140 )
1141 .size_full(),
1142 ),
1143 );
1144
1145 let search_row_el = if show_search {
1147 let has_query = !needle.is_empty();
1148 let int_clear_q = internal.clone();
1149 let int_close_hit = internal.clone();
1150 let int_close_icon = internal.clone();
1151 let hover_tint = oklab_mix(colors.foreground, colors.surface_raised, 0.08);
1152 Some(
1153 div()
1154 .absolute()
1155 .inset_0()
1156 .pl(px(10.0))
1157 .pr(px(4.0))
1158 .flex()
1159 .flex_row()
1160 .items_center()
1161 .gap(Spacing::S2)
1162 .child(
1163 div()
1164 .id(ElementId::NamedChild(
1165 self.id.clone().into(),
1166 "search-icon-close".into(),
1167 ))
1168 .test_support()
1169 .role(Role::Button)
1170 .aria_label("Close")
1171 .on_click(move |_, window, cx| {
1172 let t_now = motion_now(cx);
1173 let q_in = int_close_icon.read(cx).query_input.clone();
1174 q_in.update(cx, |s, cx| s.set_value("", window, cx));
1175 int_close_icon.update(cx, |s, _| {
1176 s.open = false;
1177 s.toggled_at_secs = t_now;
1178 s.highlight_seeded = false;
1179 s.last_query = "".into();
1180 });
1181 window.refresh();
1182 })
1183 .size(px(24.0))
1184 .flex_none()
1185 .flex()
1186 .items_center()
1187 .justify_center()
1188 .rounded(Radii::PILL)
1189 .cursor_pointer()
1190 .hover(move |s| s.bg(hover_tint))
1191 .child(
1192 Icon::new(IconName::Search)
1193 .text_size(px(16.0))
1194 .text_color(colors.text_muted),
1195 ),
1196 )
1197 .child(
1198 div()
1199 .flex_1()
1200 .min_w_0()
1201 .text_size(Typography::TEXT_SM)
1202 .text_color(colors.foreground)
1203 .child(KitInput::new(&snap.query_input).appearance(false).w_full()),
1204 )
1205 .when(has_query, |this| {
1206 this.child(
1207 div()
1208 .id(ElementId::NamedChild(
1209 self.id.clone().into(),
1210 "clear-search".into(),
1211 ))
1212 .test_support()
1213 .role(Role::Button)
1214 .aria_label("Clear search")
1215 .on_click(move |_, window, cx| {
1216 let q_in = int_clear_q.read(cx).query_input.clone();
1217 q_in.update(cx, |s, cx| {
1218 s.set_value("", window, cx);
1219 s.focus(window, cx);
1220 });
1221 int_clear_q.update(cx, |s, _| {
1222 s.last_query = "".into();
1223 s.active_value = None;
1224 });
1225 window.refresh();
1226 })
1227 .size(px(24.0))
1228 .flex_none()
1229 .flex()
1230 .items_center()
1231 .justify_center()
1232 .rounded(Radii::PILL)
1233 .bg(hover_tint)
1234 .text_color(colors.text_secondary)
1235 .cursor_pointer()
1236 .child(Icon::new(IconName::X).text_size(px(13.0))),
1237 )
1238 })
1239 .child(
1240 div()
1241 .id(ElementId::NamedChild(
1242 self.id.clone().into(),
1243 "close-hit".into(),
1244 ))
1245 .test_support()
1246 .role(Role::Button)
1247 .aria_label("Close")
1248 .on_click(move |_, window, cx| {
1249 let t_now = motion_now(cx);
1250 let q_in = int_close_hit.read(cx).query_input.clone();
1251 q_in.update(cx, |s, cx| s.set_value("", window, cx));
1252 int_close_hit.update(cx, |s, _| {
1253 s.open = false;
1254 s.toggled_at_secs = t_now;
1255 s.highlight_seeded = false;
1256 s.last_query = "".into();
1257 });
1258 window.refresh();
1259 })
1260 .size(px(36.0))
1261 .flex_none()
1262 .flex()
1263 .items_center()
1264 .justify_center()
1265 .rounded(Radii::PILL)
1266 .cursor_pointer()
1267 .hover(move |s| s.bg(hover_tint))
1268 .child(
1269 div().size(px(16.0)).child(
1270 canvas(
1271 |_, _, _| {},
1272 move |rect, _, window, _| {
1273 let cx_pt =
1274 f32::from(rect.origin.x + rect.size.width * 0.5);
1275 let cy_pt =
1276 f32::from(rect.origin.y + rect.size.height * 0.5);
1277 paint_rotated_chevron(
1278 cx_pt,
1279 cy_pt,
1280 chevron_deg,
1281 chevron_color,
1282 window,
1283 );
1284 },
1285 )
1286 .size_full(),
1287 ),
1288 ),
1289 ),
1290 )
1291 } else {
1292 None
1293 };
1294
1295 let lid_el = div()
1296 .relative()
1297 .w_full()
1298 .h(ControlHeights::MD)
1299 .flex_none()
1300 .when(!show_search, |this| this.child(lid_trigger))
1301 .when_some(search_row_el, |this, sr| this.child(sr));
1302
1303 let list_face_el = if render_list_face {
1305 let hi_bg = oklab_mix(colors.foreground, colors.surface_raised, 0.065);
1306 let mut section_els = Vec::with_capacity(visible_sections.len());
1307
1308 for (sec_idx, sec) in visible_sections.iter().enumerate() {
1309 let mut group_div = div()
1310 .w_full()
1311 .flex_none()
1312 .flex()
1313 .flex_col()
1314 .gap(px(2.0))
1315 .when(sec_idx > 0, |this| this.mt(px(4.0)));
1316
1317 if let Some(sec_label) = &sec.label {
1318 group_div = group_div.child(
1319 div()
1320 .flex_none()
1321 .h(px(MORPH_SELECT_GROUP_HEADER_H))
1322 .px(px(10.0))
1323 .pt(px(8.0))
1324 .pb(px(4.0))
1325 .flex()
1326 .items_center()
1327 .text_size(Typography::TEXT_XS)
1328 .text_color(colors.text_muted)
1329 .child(sec_label.clone()),
1330 );
1331 }
1332
1333 for opt in &sec.options {
1334 let is_selected = selected_val.as_ref() == Some(&opt.value);
1335 let is_active = current_active.as_ref() == Some(&opt.value) && !opt.disabled;
1336 let check_op = arc_transition(
1337 (self.id.clone(), format!("check-op-{}", opt.value)),
1338 if is_selected { 1.0 } else { 0.0 },
1339 if reduced {
1340 Duration::ZERO
1341 } else {
1342 motion.duration.fast
1343 },
1344 motion.ease.standard,
1345 window,
1346 cx,
1347 );
1348 let check_scale = if reduced {
1349 if is_selected { 1.0 } else { 0.6 }
1350 } else {
1351 arc_spring(
1352 (self.id.clone(), format!("check-sc-{}", opt.value)),
1353 if is_selected { 1.0 } else { 0.6 },
1354 glide_spec,
1355 window,
1356 cx,
1357 )
1358 };
1359
1360 let row_fg = if opt.disabled {
1361 colors.text_muted
1362 } else if is_active || is_selected {
1363 colors.foreground
1364 } else {
1365 colors.text_secondary
1366 };
1367 let check_color = colors.foreground;
1368 let int_hi = internal.clone();
1369 let int_commit = internal.clone();
1370 let on_change = self.on_value_change.clone();
1371 let opt_val = opt.value.clone();
1372 let opt_val_for_hi = opt.value.clone();
1373 let opt_label = opt.label.clone();
1374 let opt_icon = opt.icon;
1375 let opt_meta = opt.meta.clone();
1376 let opt_disabled = opt.disabled;
1377 let row_y = computed_offsets
1378 .get(&opt.value)
1379 .map(|(y, _)| *y)
1380 .unwrap_or(0.0);
1381
1382 group_div = group_div.child(
1383 div()
1384 .id(ElementId::NamedChild(
1385 self.id.clone().into(),
1386 SharedString::from(format!("option-{}", opt.value)),
1387 ))
1388 .test_support()
1389 .role(Role::ListBoxOption)
1390 .aria_label(opt_label.clone())
1391 .relative()
1392 .flex_none()
1393 .w_full()
1394 .h(px(MORPH_SELECT_OPTION_H))
1395 .min_h(px(MORPH_SELECT_OPTION_H))
1396 .pl(px(8.0))
1397 .pr(px(10.0))
1398 .flex()
1399 .flex_row()
1400 .items_center()
1401 .gap(Spacing::S2)
1402 .rounded(px(6.0))
1403 .text_size(Typography::TEXT_SM)
1404 .text_color(row_fg)
1405 .opacity(if opt_disabled { 0.6 } else { 1.0 })
1406 .when(!opt_disabled, |this| this.cursor_pointer())
1407 .on_hover(move |hovered, window, cx| {
1408 if opt_disabled || !*hovered {
1409 return;
1410 }
1411 int_hi.update(cx, |s, _| {
1412 s.active_value = Some(opt_val_for_hi.clone());
1413 });
1414 window.refresh();
1415 })
1416 .on_click(move |_, window, cx| {
1417 if opt_disabled {
1418 return;
1419 }
1420 let t_now = motion_now(cx);
1421 let lift_y = MORPH_SELECT_LID_H + 6.0 + row_y;
1424 let q_in = int_commit.read(cx).query_input.clone();
1425 q_in.update(cx, |s, cx| s.set_value("", window, cx));
1426 int_commit.update(cx, |s, _| {
1427 let changed = s.last_selected.as_ref() != Some(&opt_val);
1428 s.uncontrolled_value = Some(opt_val.clone());
1429 s.last_selected = Some(opt_val.clone());
1430 s.open = false;
1431 s.toggled_at_secs = t_now;
1432 s.highlight_seeded = false;
1433 s.last_query = "".into();
1434 if changed {
1435 s.fly_used_lift = true;
1436 s.fly_from_x = 0.0;
1437 s.fly_from_y = lift_y;
1438 s.fly_epoch = s.fly_epoch.wrapping_add(1);
1439 s.fly_started_at_secs = t_now;
1440 }
1441 });
1442 if let Some(cb) = &on_change {
1443 cb(&opt_val, window, cx);
1444 }
1445 window.refresh();
1446 })
1447 .child(
1448 div()
1449 .flex_1()
1450 .min_w_0()
1451 .flex()
1452 .flex_row()
1453 .items_center()
1454 .gap(Spacing::S2)
1455 .font_medium()
1456 .when_some(opt_icon, |this, ic| {
1457 this.child(
1458 div()
1459 .size(px(20.0))
1460 .flex_none()
1461 .flex()
1462 .items_center()
1463 .justify_center()
1464 .text_color(colors.text_secondary)
1465 .child(Icon::new(ic).text_size(px(16.0))),
1466 )
1467 })
1468 .child(div().flex_1().min_w_0().truncate().child(opt_label)),
1469 )
1470 .when_some(opt_meta, |this, m| {
1471 this.child(
1472 div()
1473 .flex_none()
1474 .text_size(Typography::TEXT_XS)
1475 .text_color(colors.text_muted)
1476 .child(m),
1477 )
1478 })
1479 .child(
1480 div().size(px(16.0)).flex_none().child(
1481 canvas(
1482 |_, _, _| {},
1483 move |rect, _, window, _| {
1484 let cx_pt =
1485 f32::from(rect.origin.x + rect.size.width * 0.5);
1486 let cy_pt =
1487 f32::from(rect.origin.y + rect.size.height * 0.5);
1488 paint_scaled_check(
1489 cx_pt,
1490 cy_pt,
1491 check_scale,
1492 check_op,
1493 check_color,
1494 window,
1495 );
1496 },
1497 )
1498 .size_full(),
1499 ),
1500 ),
1501 );
1502 }
1503
1504 section_els.push(group_div.into_any_element());
1505 }
1506
1507 let options_box = if visible_sections.is_empty() {
1508 div()
1509 .w_full()
1510 .px(px(10.0))
1511 .pt(px(12.0))
1512 .pb(px(14.0))
1513 .text_size(Typography::TEXT_SM)
1514 .text_color(colors.text_muted)
1515 .child(SharedString::from(format!("No matches for “{needle}”")))
1516 .into_any_element()
1517 } else {
1518 div()
1519 .id(ElementId::NamedChild(
1520 self.id.clone().into(),
1521 "listbox".into(),
1522 ))
1523 .role(Role::ListBox)
1524 .relative()
1525 .w_full()
1526 .flex()
1527 .flex_col()
1528 .when(hi_op > 0.01, |this| {
1529 this.child(
1530 div()
1531 .absolute()
1532 .left_0()
1533 .right_0()
1534 .top(px(pill_y))
1535 .h(px(pill_h))
1536 .rounded(px(6.0))
1537 .bg(hi_bg)
1538 .opacity(hi_op),
1539 )
1540 })
1541 .children(section_els)
1542 .into_any_element()
1543 };
1544
1545 Some(
1546 div()
1547 .w(px(open_w))
1548 .px(px(6.0))
1549 .pb(px(6.0))
1550 .mt(px(list_face_y))
1551 .opacity(list_face_op)
1552 .flex()
1553 .flex_col()
1554 .child(
1555 div()
1557 .flex_none()
1558 .mx(px(8.0))
1559 .h(px(1.0))
1560 .bg(colors.border_subtle),
1561 )
1562 .child(
1563 div()
1564 .id(ElementId::NamedChild(
1565 self.id.clone().into(),
1566 "scroll".into(),
1567 ))
1568 .w_full()
1569 .h(px(list_scroll_h))
1570 .max_h(px(self.max_list_height))
1571 .pt(px(6.0))
1572 .overflow_y_scroll()
1573 .on_scroll(|_, _, cx| cx.stop_propagation())
1574 .child(options_box),
1575 ),
1576 )
1577 } else {
1578 None
1579 };
1580
1581 let int_key = internal.clone();
1582 let enabled_for_key = enabled_options.clone();
1583 let current_for_key = current_active.clone();
1584 let offsets_for_key = computed_offsets;
1585 let on_change_key = self.on_value_change.clone();
1586 let focus_handle = snap.focus_handle.clone();
1587 let align_end = self.align == MorphSelectAlign::End;
1588
1589 let shape_el = div()
1590 .id(ElementId::NamedChild(
1591 self.id.clone().into(),
1592 "shape".into(),
1593 ))
1594 .test_support()
1595 .track_focus(&focus_handle)
1596 .on_key_down(move |event: &KeyDownEvent, window, cx| {
1597 let currently_open = int_key.read(cx).open;
1598 if !currently_open {
1599 return;
1600 }
1601 let cur_pos = current_for_key
1602 .as_ref()
1603 .and_then(|c| enabled_for_key.iter().position(|o| &o.value == c));
1604 match event.keystroke.key.as_str() {
1605 "escape" => {
1606 let t_now = motion_now(cx);
1607 let q_in = int_key.read(cx).query_input.clone();
1608 q_in.update(cx, |s, cx| s.set_value("", window, cx));
1609 int_key.update(cx, |s, _| {
1610 s.open = false;
1611 s.toggled_at_secs = t_now;
1612 s.highlight_seeded = false;
1613 s.last_query = "".into();
1614 });
1615 window.refresh();
1616 }
1617 "down" | "arrowdown" => {
1618 if !enabled_for_key.is_empty() {
1619 let next_idx = match cur_pos {
1620 Some(i) => (i + 1).min(enabled_for_key.len() - 1),
1621 None => 0,
1622 };
1623 let next_val = enabled_for_key[next_idx].value.clone();
1624 int_key.update(cx, |s, _| s.active_value = Some(next_val));
1625 window.refresh();
1626 }
1627 }
1628 "up" | "arrowup" => {
1629 if !enabled_for_key.is_empty() {
1630 let prev_idx = match cur_pos {
1631 Some(i) => i.saturating_sub(1),
1632 None => 0,
1633 };
1634 let prev_val = enabled_for_key[prev_idx].value.clone();
1635 int_key.update(cx, |s, _| s.active_value = Some(prev_val));
1636 window.refresh();
1637 }
1638 }
1639 "home" => {
1640 if let Some(first) = enabled_for_key.first() {
1641 let v = first.value.clone();
1642 int_key.update(cx, |s, _| s.active_value = Some(v));
1643 window.refresh();
1644 }
1645 }
1646 "end" => {
1647 if let Some(last) = enabled_for_key.last() {
1648 let v = last.value.clone();
1649 int_key.update(cx, |s, _| s.active_value = Some(v));
1650 window.refresh();
1651 }
1652 }
1653 "enter" => {
1654 if let Some(idx) = cur_pos
1655 && let Some(opt) = enabled_for_key.get(idx)
1656 {
1657 let chosen = opt.value.clone();
1658 let row_y =
1659 offsets_for_key.get(&chosen).map(|(y, _)| *y).unwrap_or(0.0);
1660 let lift_y = MORPH_SELECT_LID_H + 6.0 + row_y;
1661 let t_now = motion_now(cx);
1662 let q_in = int_key.read(cx).query_input.clone();
1663 q_in.update(cx, |s, cx| s.set_value("", window, cx));
1664 int_key.update(cx, |s, _| {
1665 let changed = s.last_selected.as_ref() != Some(&chosen);
1666 s.uncontrolled_value = Some(chosen.clone());
1667 s.last_selected = Some(chosen.clone());
1668 s.open = false;
1669 s.toggled_at_secs = t_now;
1670 s.highlight_seeded = false;
1671 s.last_query = "".into();
1672 if changed {
1673 s.fly_used_lift = true;
1674 s.fly_from_x = 0.0;
1675 s.fly_from_y = lift_y;
1676 s.fly_epoch = s.fly_epoch.wrapping_add(1);
1677 s.fly_started_at_secs = t_now;
1678 }
1679 });
1680 if let Some(cb) = &on_change_key {
1681 cb(&chosen, window, cx);
1682 }
1683 window.refresh();
1684 }
1685 }
1686 _ => {}
1687 }
1688 })
1689 .absolute()
1690 .top_0()
1691 .when(!align_end, |this| this.left_0())
1692 .when(align_end, |this| this.right_0())
1693 .w(px(shape_w))
1694 .h(px(shape_h))
1695 .rounded(Radii::PANEL)
1696 .border_1()
1697 .border_color(shape_border)
1698 .bg(shape_bg)
1699 .shadow(shape_shadow)
1700 .opacity(if disabled { 0.55 } else { 1.0 })
1701 .overflow_hidden()
1702 .flex()
1703 .flex_col()
1704 .child(shape_probe)
1705 .child(lid_el)
1706 .when_some(list_face_el, |this, lf| this.child(lf));
1707
1708 let elevated = is_open || shape_h > MORPH_SELECT_LID_H + 0.5;
1709 let anchor = div()
1710 .relative()
1711 .w(px(anchor_w))
1712 .h(ControlHeights::MD)
1713 .child(measure_el)
1714 .child(if elevated {
1715 deferred(shape_el).with_priority(25).into_any_element()
1716 } else {
1717 shape_el.into_any_element()
1718 });
1719
1720 div()
1721 .id(self.id)
1722 .test_support()
1723 .flex()
1724 .flex_col()
1725 .when(!align_end, |this| this.items_start())
1726 .when(align_end, |this| this.items_end())
1727 .gap(Spacing::S2)
1728 .when(!self.hide_label, |this| {
1729 this.child(
1730 div()
1731 .text_size(Typography::TEXT_SM)
1732 .font_medium()
1733 .text_color(colors.text_secondary)
1734 .child(self.label),
1735 )
1736 })
1737 .child(anchor)
1738 }
1739}
1740
1741#[cfg(test)]
1742mod tests {
1743 use super::*;
1744
1745 #[test]
1746 fn normalize_morph_select_items_gathers_consecutive_loose_options() {
1747 let items = vec![
1748 MorphSelectItem::Option(MorphSelectOption::new("a", "Alpha")),
1749 MorphSelectItem::Option(MorphSelectOption::new("b", "Beta")),
1750 MorphSelectItem::Group(MorphSelectGroup::new(
1751 "Group 1",
1752 [MorphSelectOption::new("c", "Charlie")],
1753 )),
1754 MorphSelectItem::Option(MorphSelectOption::new("d", "Delta")),
1755 ];
1756 let sections = normalize_morph_select_items(&items);
1757 assert_eq!(sections.len(), 3);
1758 assert!(sections[0].label.is_none());
1759 assert_eq!(sections[0].options.len(), 2);
1760 assert_eq!(sections[1].label, Some("Group 1".into()));
1761 assert_eq!(sections[2].options.len(), 1);
1762 }
1763
1764 #[test]
1765 fn morph_select_option_matches_label_meta_and_keywords() {
1766 let opt = MorphSelectOption::new("tokyo", "Tokyo")
1767 .meta("UTC+9")
1768 .keywords("japan asia");
1769 assert!(opt.matches_query("tokyo"));
1770 assert!(opt.matches_query("utc+9"));
1771 assert!(opt.matches_query("japan"));
1772 assert!(!opt.matches_query("zurich"));
1773 }
1774
1775 #[test]
1776 fn morph_select_list_face_sample_respects_40ms_open_delay() {
1777 let (op_early, y_early) = morph_select_list_face_sample(0.02, true, false);
1778 assert!(op_early < 1e-4);
1779 assert!((y_early - (-6.0)).abs() < 1e-4);
1780
1781 let (op_settled, y_settled) = morph_select_list_face_sample(0.28, true, false);
1782 assert!((op_settled - 1.0).abs() < 1e-4);
1783 assert!(y_settled.abs() < 1e-4);
1784 }
1785}