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_motion::arc_measured_spring(
681 (self.id.clone(), "anchor-w"),
682 (measured_w > 40.0).then_some(trigger_w),
683 trigger_w,
684 width_spec,
685 window,
686 cx,
687 )
688 };
689 let shape_w = if reduced {
690 target_shape_w
691 } else {
692 arc_motion::arc_measured_spring(
693 (self.id.clone(), "shape-w"),
694 (measured_w > 40.0 || is_open).then_some(target_shape_w),
695 target_shape_w,
696 if is_open { shape_spec } else { width_spec },
697 window,
698 cx,
699 )
700 };
701 let shape_h = if reduced {
702 target_shape_h
703 } else {
704 arc_spring(
705 (self.id.clone(), "shape-h"),
706 target_shape_h,
707 shape_spec,
708 window,
709 cx,
710 )
711 };
712
713 let fly_spec = if snap.fly_used_lift {
715 morph_select_fly_spring()
716 } else {
717 morph_select_glide_spring()
718 };
719 let lid_val_x = if reduced {
720 0.0
721 } else {
722 arc_spring_with_options(
723 (self.id.clone(), format!("fly-x-{}", snap.fly_epoch)),
724 0.0,
725 SpringOptions::new(fly_spec).with_initial_value(snap.fly_from_x),
726 window,
727 cx,
728 )
729 .value
730 };
731 let lid_val_y = if reduced {
732 0.0
733 } else {
734 arc_spring_with_options(
735 (self.id.clone(), format!("fly-y-{}", snap.fly_epoch)),
736 0.0,
737 SpringOptions::new(fly_spec).with_initial_value(snap.fly_from_y),
738 window,
739 cx,
740 )
741 .value
742 };
743 let fly_elapsed = (now - snap.fly_started_at_secs).max(0.0);
744 let lid_val_op = if snap.fly_used_lift {
745 1.0
746 } else if fly_elapsed < 0.22 {
747 window.request_animation_frame();
748 let t = (fly_elapsed / 0.20).clamp(0.0, 1.0) as f32;
749 let e = if reduced {
750 t
751 } else {
752 CubicBezier::new(0.16, 1.0, 0.3, 1.0).sample(t)
753 };
754 let blur = BlurFallback::evaluate(px(4.0 * (1.0 - e)), reduced);
755 (e * blur.opacity_multiplier).clamp(0.0, 1.0)
756 } else {
757 1.0
758 };
759 let exit_op = if !snap.fly_used_lift && fly_elapsed < 0.12 {
760 window.request_animation_frame();
761 let t = (fly_elapsed / 0.12).clamp(0.0, 1.0) as f32;
762 1.0 - t
763 } else {
764 0.0
765 };
766
767 let glide_spec = morph_select_glide_spring();
769 let chevron_deg = if reduced {
770 if is_open { 180.0 } else { 0.0 }
771 } else {
772 arc_spring(
773 (self.id.clone(), "chevron-deg"),
774 if is_open { 180.0 } else { 0.0 },
775 glide_spec,
776 window,
777 cx,
778 )
779 };
780
781 let toggle_elapsed = (now - snap.toggled_at_secs).max(0.0);
783 let (list_face_op, list_face_y) =
784 morph_select_list_face_sample(toggle_elapsed, is_open, reduced);
785 if (is_open && toggle_elapsed < 0.26) || (!is_open && toggle_elapsed < 0.12) {
786 window.request_animation_frame();
787 }
788 let render_list_face = is_open || shape_h > MORPH_SELECT_LID_H + 1.0 || list_face_op > 0.01;
789
790 let mut computed_offsets: HashMap<SharedString, (f32, f32)> = HashMap::new();
793 {
794 let mut cur_y = 0.0_f32;
795 for (sec_idx, sec) in visible_sections.iter().enumerate() {
796 if sec_idx > 0 {
797 cur_y += 4.0;
798 }
799 if sec.label.is_some() {
800 cur_y += MORPH_SELECT_GROUP_HEADER_H + 2.0;
801 }
802 for (opt_idx, opt) in sec.options.iter().enumerate() {
803 if opt_idx > 0 {
804 cur_y += 2.0;
805 }
806 computed_offsets.insert(opt.value.clone(), (cur_y, MORPH_SELECT_OPTION_H));
807 cur_y += MORPH_SELECT_OPTION_H;
808 }
809 }
810 *snap.option_y_offsets.borrow_mut() = computed_offsets.clone();
811 }
812
813 let active_geom = current_active
815 .as_ref()
816 .and_then(|val| computed_offsets.get(val).copied());
817 let hi_op = arc_transition(
818 (self.id.clone(), "hi-op"),
819 if is_open && active_geom.is_some() {
820 1.0
821 } else {
822 0.0
823 },
824 if reduced || !is_open {
825 Duration::ZERO
826 } else {
827 Duration::from_millis(120)
828 },
829 if is_open {
830 motion.ease.enter
831 } else {
832 motion.ease.standard
833 },
834 window,
835 cx,
836 );
837 let (target_hy, target_hh) = active_geom.unwrap_or((0.0, MORPH_SELECT_OPTION_H));
838 let (pill_y, pill_h) = if reduced || !snap.highlight_seeded || hi_op < 0.05 {
839 let _ = arc_spring_with_options(
840 (self.id.clone(), "hi-y"),
841 target_hy,
842 SpringOptions::new(glide_spec).with_initial_value(target_hy),
843 window,
844 cx,
845 );
846 let _ = arc_spring_with_options(
847 (self.id.clone(), "hi-h"),
848 target_hh,
849 SpringOptions::new(glide_spec).with_initial_value(target_hh),
850 window,
851 cx,
852 );
853 if is_open && active_geom.is_some() && !snap.highlight_seeded {
854 internal.update(cx, |s, _| s.highlight_seeded = true);
855 }
856 (target_hy, target_hh)
857 } else {
858 (
859 arc_spring((self.id.clone(), "hi-y"), target_hy, glide_spec, window, cx),
860 arc_spring((self.id.clone(), "hi-h"), target_hh, glide_spec, window, cx),
861 )
862 };
863
864 let hover_p = arc_transition(
866 (self.id.clone(), "shape-hover"),
867 if !self.disabled && !is_open && snap.trigger_hovered {
868 1.0
869 } else {
870 0.0
871 },
872 if reduced {
873 Duration::ZERO
874 } else {
875 motion.duration.fast
876 },
877 motion.ease.standard,
878 window,
879 cx,
880 );
881 let open_p = arc_transition(
882 (self.id.clone(), "shape-open-bg"),
883 if is_open { 1.0 } else { 0.0 },
884 if reduced {
885 Duration::ZERO
886 } else {
887 motion.duration.fast
888 },
889 motion.ease.standard,
890 window,
891 cx,
892 );
893 let closed_bg = oklab_mix(colors.surface_muted, colors.surface, hover_p);
894 let shape_bg = oklab_mix(colors.surface_raised, closed_bg, open_p);
895 let shape_border = oklab_mix(
896 colors.border_strong,
897 colors.border,
898 hover_p * (1.0 - open_p),
899 );
900 let shape_shadow = if is_open || shape_h > MORPH_SELECT_LID_H + 4.0 {
901 Shadows::floating(theme.mode)
902 } else {
903 Shadows::resting(theme.mode)
904 };
905
906 let measure_w_ref = snap.measured_trigger_w.clone();
908 let measure_probe = canvas(
909 move |rect, window, _| {
910 let w = (f32::from(rect.size.width) + 1.0).ceil();
911 if w > 40.0 {
912 let prev = *measure_w_ref.borrow();
913 *measure_w_ref.borrow_mut() = w;
914 if (prev - w).abs() > 0.5 {
915 window.request_animation_frame();
916 }
917 }
918 },
919 |_, _, _, _| {},
920 )
921 .absolute()
922 .inset_0();
923
924 let measure_el = div()
925 .absolute()
926 .top_0()
927 .left_0()
928 .h(ControlHeights::MD)
929 .pl(px(14.0))
930 .pr(px(36.0))
931 .flex()
932 .flex_row()
933 .items_center()
934 .gap(Spacing::S2)
935 .opacity(0.0)
936 .child(measure_probe)
937 .when_some(selected_option.as_ref().and_then(|o| o.icon), |this, ic| {
938 this.child(Icon::new(ic).text_size(px(16.0)))
939 })
940 .child(
941 div()
942 .text_size(Typography::TEXT_SM)
943 .font_medium()
944 .child(display_label.clone()),
945 );
946
947 let shape_bounds_ref = snap.shape_bounds.clone();
949 let shape_bounds_outside = snap.shape_bounds.clone();
950 let internal_outside = internal.clone();
951 let shape_probe = canvas(
952 move |rect, _, _| {
953 *shape_bounds_ref.borrow_mut() = Some(rect);
954 },
955 move |_, _, window, _| {
956 if is_open {
957 let s_ref = shape_bounds_outside.clone();
958 let st = internal_outside.clone();
959 window.on_mouse_event(move |event: &MouseDownEvent, phase, window, cx| {
960 if !phase.bubble() {
961 return;
962 }
963 let in_shape = s_ref.borrow().is_some_and(|b| b.contains(&event.position));
964 if !in_shape {
965 let t_now = motion_now(cx);
966 let q_in = st.read(cx).query_input.clone();
967 q_in.update(cx, |s, cx| s.set_value("", window, cx));
968 st.update(cx, |s, _| {
969 s.open = false;
970 s.toggled_at_secs = t_now;
971 s.highlight_seeded = false;
972 s.last_query = "".into();
973 });
974 window.refresh();
975 }
976 });
977 }
978 },
979 )
980 .absolute()
981 .inset_0();
982
983 let slot_op = arc_transition(
985 (self.id.clone(), "slot-hidden-op"),
986 if show_search { 0.0 } else { 1.0 },
987 motion.duration.instant,
988 motion.ease.standard,
989 window,
990 cx,
991 );
992 let value_fg = if selected_option.is_some() {
993 colors.foreground
994 } else {
995 colors.text_muted
996 };
997
998 let mut lid_slot = div()
999 .relative()
1000 .flex_1()
1001 .min_w_0()
1002 .h_full()
1003 .overflow_hidden()
1004 .opacity(slot_op)
1005 .child(
1006 div()
1007 .absolute()
1008 .inset_0()
1009 .ml(px(lid_val_x))
1010 .mt(px(lid_val_y))
1011 .opacity(lid_val_op)
1012 .flex()
1013 .flex_row()
1014 .items_center()
1015 .gap(Spacing::S2)
1016 .when_some(selected_option.as_ref().and_then(|o| o.icon), |this, ic| {
1017 this.child(
1018 div()
1019 .size(px(20.0))
1020 .flex_none()
1021 .flex()
1022 .items_center()
1023 .justify_center()
1024 .text_color(colors.text_secondary)
1025 .child(Icon::new(ic).text_size(px(16.0))),
1026 )
1027 })
1028 .child(
1029 div()
1030 .flex_1()
1031 .min_w_0()
1032 .text_size(Typography::TEXT_SM)
1033 .when(selected_option.is_some(), |this| this.font_medium())
1034 .text_color(value_fg)
1035 .truncate()
1036 .child(display_label),
1037 ),
1038 );
1039
1040 if exit_op > 0.01
1041 && let Some(prev_lbl) = snap.previous_label.clone()
1042 {
1043 lid_slot = lid_slot.child(
1044 div()
1045 .absolute()
1046 .inset_0()
1047 .mt(px(-(snap.fly_dir as f32) * 5.0 * (1.0 - exit_op)))
1048 .opacity(exit_op)
1049 .flex()
1050 .items_center()
1051 .text_size(Typography::TEXT_SM)
1052 .font_medium()
1053 .text_color(colors.text_secondary)
1054 .truncate()
1055 .child(prev_lbl),
1056 );
1057 }
1058
1059 let trigger_id = ElementId::NamedChild(self.id.clone().into(), "trigger".into());
1060 let int_hover = internal.clone();
1061 let int_click = internal.clone();
1062 let focus_for_open = snap.focus_handle.clone();
1063 let selected_for_open = selected_val.clone();
1064 let disabled = self.disabled;
1065
1066 let chevron_color = colors.text_muted;
1067 let lid_trigger = div()
1068 .id(trigger_id)
1069 .test_support()
1070 .role(Role::Button)
1071 .aria_label(self.label.clone())
1072 .on_click(move |_, window, cx| {
1073 if disabled {
1074 return;
1075 }
1076 let t_now = motion_now(cx);
1077 let mut became_open = false;
1078 let q_in = int_click.read(cx).query_input.clone();
1079 int_click.update(cx, |s, _| {
1080 s.open = !s.open;
1081 s.toggled_at_secs = t_now;
1082 became_open = s.open;
1083 if s.open {
1084 s.active_value = selected_for_open.clone();
1085 s.highlight_seeded = false;
1086 s.last_query = "".into();
1087 } else {
1088 s.highlight_seeded = false;
1089 }
1090 });
1091 if became_open {
1092 q_in.update(cx, |s, cx| {
1093 s.set_value("", window, cx);
1094 if can_search {
1095 s.focus(window, cx);
1096 }
1097 });
1098 if !can_search {
1099 window.focus(&focus_for_open, cx);
1100 }
1101 }
1102 window.refresh();
1103 })
1104 .absolute()
1105 .inset_0()
1106 .w_full()
1107 .h(ControlHeights::MD)
1108 .pl(px(14.0))
1109 .pr(px(36.0))
1110 .flex()
1111 .flex_row()
1112 .items_center()
1113 .gap(Spacing::S2)
1114 .when(!disabled, |this| this.cursor_pointer())
1115 .on_hover(move |hovered, window, cx| {
1116 int_hover.update(cx, |s, _| {
1117 s.trigger_hovered = *hovered;
1118 });
1119 window.refresh();
1120 })
1121 .child(lid_slot)
1122 .child(
1123 div()
1124 .absolute()
1125 .top(px(14.0))
1126 .right(px(12.0))
1127 .size(px(16.0))
1128 .child(
1129 canvas(
1130 |_, _, _| {},
1131 move |rect, _, window, _| {
1132 let cx_pt = f32::from(rect.origin.x + rect.size.width * 0.5);
1133 let cy_pt = f32::from(rect.origin.y + rect.size.height * 0.5);
1134 paint_rotated_chevron(
1135 cx_pt,
1136 cy_pt,
1137 chevron_deg,
1138 chevron_color,
1139 window,
1140 );
1141 },
1142 )
1143 .size_full(),
1144 ),
1145 );
1146
1147 let search_row_el = if show_search {
1149 let has_query = !needle.is_empty();
1150 let int_clear_q = internal.clone();
1151 let int_close_hit = internal.clone();
1152 let int_close_icon = internal.clone();
1153 let hover_tint = oklab_mix(colors.foreground, colors.surface_raised, 0.08);
1154 Some(
1155 div()
1156 .absolute()
1157 .inset_0()
1158 .pl(px(10.0))
1159 .pr(px(4.0))
1160 .flex()
1161 .flex_row()
1162 .items_center()
1163 .gap(Spacing::S2)
1164 .child(
1165 div()
1166 .id(ElementId::NamedChild(
1167 self.id.clone().into(),
1168 "search-icon-close".into(),
1169 ))
1170 .test_support()
1171 .role(Role::Button)
1172 .aria_label("Close")
1173 .on_click(move |_, window, cx| {
1174 let t_now = motion_now(cx);
1175 let q_in = int_close_icon.read(cx).query_input.clone();
1176 q_in.update(cx, |s, cx| s.set_value("", window, cx));
1177 int_close_icon.update(cx, |s, _| {
1178 s.open = false;
1179 s.toggled_at_secs = t_now;
1180 s.highlight_seeded = false;
1181 s.last_query = "".into();
1182 });
1183 window.refresh();
1184 })
1185 .size(px(24.0))
1186 .flex_none()
1187 .flex()
1188 .items_center()
1189 .justify_center()
1190 .rounded(Radii::PILL)
1191 .cursor_pointer()
1192 .hover(move |s| s.bg(hover_tint))
1193 .child(
1194 Icon::new(IconName::Search)
1195 .text_size(px(16.0))
1196 .text_color(colors.text_muted),
1197 ),
1198 )
1199 .child(
1200 div()
1201 .flex_1()
1202 .min_w_0()
1203 .text_size(Typography::TEXT_SM)
1204 .text_color(colors.foreground)
1205 .child(KitInput::new(&snap.query_input).appearance(false).w_full()),
1206 )
1207 .when(has_query, |this| {
1208 this.child(
1209 div()
1210 .id(ElementId::NamedChild(
1211 self.id.clone().into(),
1212 "clear-search".into(),
1213 ))
1214 .test_support()
1215 .role(Role::Button)
1216 .aria_label("Clear search")
1217 .on_click(move |_, window, cx| {
1218 let q_in = int_clear_q.read(cx).query_input.clone();
1219 q_in.update(cx, |s, cx| {
1220 s.set_value("", window, cx);
1221 s.focus(window, cx);
1222 });
1223 int_clear_q.update(cx, |s, _| {
1224 s.last_query = "".into();
1225 s.active_value = None;
1226 });
1227 window.refresh();
1228 })
1229 .size(px(24.0))
1230 .flex_none()
1231 .flex()
1232 .items_center()
1233 .justify_center()
1234 .rounded(Radii::PILL)
1235 .bg(hover_tint)
1236 .text_color(colors.text_secondary)
1237 .cursor_pointer()
1238 .child(Icon::new(IconName::X).text_size(px(13.0))),
1239 )
1240 })
1241 .child(
1242 div()
1243 .id(ElementId::NamedChild(
1244 self.id.clone().into(),
1245 "close-hit".into(),
1246 ))
1247 .test_support()
1248 .role(Role::Button)
1249 .aria_label("Close")
1250 .on_click(move |_, window, cx| {
1251 let t_now = motion_now(cx);
1252 let q_in = int_close_hit.read(cx).query_input.clone();
1253 q_in.update(cx, |s, cx| s.set_value("", window, cx));
1254 int_close_hit.update(cx, |s, _| {
1255 s.open = false;
1256 s.toggled_at_secs = t_now;
1257 s.highlight_seeded = false;
1258 s.last_query = "".into();
1259 });
1260 window.refresh();
1261 })
1262 .size(px(36.0))
1263 .flex_none()
1264 .flex()
1265 .items_center()
1266 .justify_center()
1267 .rounded(Radii::PILL)
1268 .cursor_pointer()
1269 .hover(move |s| s.bg(hover_tint))
1270 .child(
1271 div().size(px(16.0)).child(
1272 canvas(
1273 |_, _, _| {},
1274 move |rect, _, window, _| {
1275 let cx_pt =
1276 f32::from(rect.origin.x + rect.size.width * 0.5);
1277 let cy_pt =
1278 f32::from(rect.origin.y + rect.size.height * 0.5);
1279 paint_rotated_chevron(
1280 cx_pt,
1281 cy_pt,
1282 chevron_deg,
1283 chevron_color,
1284 window,
1285 );
1286 },
1287 )
1288 .size_full(),
1289 ),
1290 ),
1291 ),
1292 )
1293 } else {
1294 None
1295 };
1296
1297 let lid_el = div()
1298 .relative()
1299 .w_full()
1300 .h(ControlHeights::MD)
1301 .flex_none()
1302 .when(!show_search, |this| this.child(lid_trigger))
1303 .when_some(search_row_el, |this, sr| this.child(sr));
1304
1305 let list_face_el = if render_list_face {
1307 let hi_bg = oklab_mix(colors.foreground, colors.surface_raised, 0.065);
1308 let mut section_els = Vec::with_capacity(visible_sections.len());
1309
1310 for (sec_idx, sec) in visible_sections.iter().enumerate() {
1311 let mut group_div = div()
1312 .w_full()
1313 .flex_none()
1314 .flex()
1315 .flex_col()
1316 .gap(px(2.0))
1317 .when(sec_idx > 0, |this| this.mt(px(4.0)));
1318
1319 if let Some(sec_label) = &sec.label {
1320 group_div = group_div.child(
1321 div()
1322 .flex_none()
1323 .h(px(MORPH_SELECT_GROUP_HEADER_H))
1324 .px(px(10.0))
1325 .pt(px(8.0))
1326 .pb(px(4.0))
1327 .flex()
1328 .items_center()
1329 .text_size(Typography::TEXT_XS)
1330 .text_color(colors.text_muted)
1331 .child(sec_label.clone()),
1332 );
1333 }
1334
1335 for opt in &sec.options {
1336 let is_selected = selected_val.as_ref() == Some(&opt.value);
1337 let is_active = current_active.as_ref() == Some(&opt.value) && !opt.disabled;
1338 let check_op = arc_transition(
1339 (self.id.clone(), format!("check-op-{}", opt.value)),
1340 if is_selected { 1.0 } else { 0.0 },
1341 if reduced {
1342 Duration::ZERO
1343 } else {
1344 motion.duration.fast
1345 },
1346 motion.ease.standard,
1347 window,
1348 cx,
1349 );
1350 let check_scale = if reduced {
1351 if is_selected { 1.0 } else { 0.6 }
1352 } else {
1353 arc_spring(
1354 (self.id.clone(), format!("check-sc-{}", opt.value)),
1355 if is_selected { 1.0 } else { 0.6 },
1356 glide_spec,
1357 window,
1358 cx,
1359 )
1360 };
1361
1362 let row_fg = if opt.disabled {
1363 colors.text_muted
1364 } else if is_active || is_selected {
1365 colors.foreground
1366 } else {
1367 colors.text_secondary
1368 };
1369 let check_color = colors.foreground;
1370 let int_hi = internal.clone();
1371 let int_commit = internal.clone();
1372 let on_change = self.on_value_change.clone();
1373 let opt_val = opt.value.clone();
1374 let opt_val_for_hi = opt.value.clone();
1375 let opt_label = opt.label.clone();
1376 let opt_icon = opt.icon;
1377 let opt_meta = opt.meta.clone();
1378 let opt_disabled = opt.disabled;
1379 let row_y = computed_offsets
1380 .get(&opt.value)
1381 .map(|(y, _)| *y)
1382 .unwrap_or(0.0);
1383
1384 group_div = group_div.child(
1385 div()
1386 .id(ElementId::NamedChild(
1387 self.id.clone().into(),
1388 SharedString::from(format!("option-{}", opt.value)),
1389 ))
1390 .test_support()
1391 .role(Role::ListBoxOption)
1392 .aria_label(opt_label.clone())
1393 .relative()
1394 .flex_none()
1395 .w_full()
1396 .h(px(MORPH_SELECT_OPTION_H))
1397 .min_h(px(MORPH_SELECT_OPTION_H))
1398 .pl(px(8.0))
1399 .pr(px(10.0))
1400 .flex()
1401 .flex_row()
1402 .items_center()
1403 .gap(Spacing::S2)
1404 .rounded(px(6.0))
1405 .text_size(Typography::TEXT_SM)
1406 .text_color(row_fg)
1407 .opacity(if opt_disabled { 0.6 } else { 1.0 })
1408 .when(!opt_disabled, |this| this.cursor_pointer())
1409 .on_hover(move |hovered, window, cx| {
1410 if opt_disabled || !*hovered {
1411 return;
1412 }
1413 int_hi.update(cx, |s, _| {
1414 s.active_value = Some(opt_val_for_hi.clone());
1415 });
1416 window.refresh();
1417 })
1418 .on_click(move |_, window, cx| {
1419 if opt_disabled {
1420 return;
1421 }
1422 let t_now = motion_now(cx);
1423 let lift_y = MORPH_SELECT_LID_H + 6.0 + row_y;
1426 let q_in = int_commit.read(cx).query_input.clone();
1427 q_in.update(cx, |s, cx| s.set_value("", window, cx));
1428 int_commit.update(cx, |s, _| {
1429 let changed = s.last_selected.as_ref() != Some(&opt_val);
1430 s.uncontrolled_value = Some(opt_val.clone());
1431 s.last_selected = Some(opt_val.clone());
1432 s.open = false;
1433 s.toggled_at_secs = t_now;
1434 s.highlight_seeded = false;
1435 s.last_query = "".into();
1436 if changed {
1437 s.fly_used_lift = true;
1438 s.fly_from_x = 0.0;
1439 s.fly_from_y = lift_y;
1440 s.fly_epoch = s.fly_epoch.wrapping_add(1);
1441 s.fly_started_at_secs = t_now;
1442 }
1443 });
1444 if let Some(cb) = &on_change {
1445 cb(&opt_val, window, cx);
1446 }
1447 window.refresh();
1448 })
1449 .child(
1450 div()
1451 .flex_1()
1452 .min_w_0()
1453 .flex()
1454 .flex_row()
1455 .items_center()
1456 .gap(Spacing::S2)
1457 .font_medium()
1458 .when_some(opt_icon, |this, ic| {
1459 this.child(
1460 div()
1461 .size(px(20.0))
1462 .flex_none()
1463 .flex()
1464 .items_center()
1465 .justify_center()
1466 .text_color(colors.text_secondary)
1467 .child(Icon::new(ic).text_size(px(16.0))),
1468 )
1469 })
1470 .child(div().flex_1().min_w_0().truncate().child(opt_label)),
1471 )
1472 .when_some(opt_meta, |this, m| {
1473 this.child(
1474 div()
1475 .flex_none()
1476 .text_size(Typography::TEXT_XS)
1477 .text_color(colors.text_muted)
1478 .child(m),
1479 )
1480 })
1481 .child(
1482 div().size(px(16.0)).flex_none().child(
1483 canvas(
1484 |_, _, _| {},
1485 move |rect, _, window, _| {
1486 let cx_pt =
1487 f32::from(rect.origin.x + rect.size.width * 0.5);
1488 let cy_pt =
1489 f32::from(rect.origin.y + rect.size.height * 0.5);
1490 paint_scaled_check(
1491 cx_pt,
1492 cy_pt,
1493 check_scale,
1494 check_op,
1495 check_color,
1496 window,
1497 );
1498 },
1499 )
1500 .size_full(),
1501 ),
1502 ),
1503 );
1504 }
1505
1506 section_els.push(group_div.into_any_element());
1507 }
1508
1509 let options_box = if visible_sections.is_empty() {
1510 div()
1511 .w_full()
1512 .px(px(10.0))
1513 .pt(px(12.0))
1514 .pb(px(14.0))
1515 .text_size(Typography::TEXT_SM)
1516 .text_color(colors.text_muted)
1517 .child(SharedString::from(format!("No matches for “{needle}”")))
1518 .into_any_element()
1519 } else {
1520 div()
1521 .id(ElementId::NamedChild(
1522 self.id.clone().into(),
1523 "listbox".into(),
1524 ))
1525 .role(Role::ListBox)
1526 .relative()
1527 .w_full()
1528 .flex()
1529 .flex_col()
1530 .when(hi_op > 0.01, |this| {
1531 this.child(
1532 div()
1533 .absolute()
1534 .left_0()
1535 .right_0()
1536 .top(px(pill_y))
1537 .h(px(pill_h))
1538 .rounded(px(6.0))
1539 .bg(hi_bg)
1540 .opacity(hi_op),
1541 )
1542 })
1543 .children(section_els)
1544 .into_any_element()
1545 };
1546
1547 Some(
1548 div()
1549 .w(px(open_w))
1550 .px(px(6.0))
1551 .pb(px(6.0))
1552 .mt(px(list_face_y))
1553 .opacity(list_face_op)
1554 .flex()
1555 .flex_col()
1556 .child(
1557 div()
1559 .flex_none()
1560 .mx(px(8.0))
1561 .h(px(1.0))
1562 .bg(colors.border_subtle),
1563 )
1564 .child(
1565 div()
1566 .id(ElementId::NamedChild(
1567 self.id.clone().into(),
1568 "scroll".into(),
1569 ))
1570 .w_full()
1571 .h(px(list_scroll_h))
1572 .max_h(px(self.max_list_height))
1573 .pt(px(6.0))
1574 .overflow_y_scroll()
1575 .on_scroll(|_, _, cx| cx.stop_propagation())
1576 .child(options_box),
1577 ),
1578 )
1579 } else {
1580 None
1581 };
1582
1583 let int_key = internal.clone();
1584 let enabled_for_key = enabled_options.clone();
1585 let current_for_key = current_active.clone();
1586 let offsets_for_key = computed_offsets;
1587 let on_change_key = self.on_value_change.clone();
1588 let focus_handle = snap.focus_handle.clone();
1589 let align_end = self.align == MorphSelectAlign::End;
1590
1591 let shape_el = div()
1592 .id(ElementId::NamedChild(
1593 self.id.clone().into(),
1594 "shape".into(),
1595 ))
1596 .test_support()
1597 .track_focus(&focus_handle)
1598 .on_key_down(move |event: &KeyDownEvent, window, cx| {
1599 let currently_open = int_key.read(cx).open;
1600 if !currently_open {
1601 return;
1602 }
1603 let cur_pos = current_for_key
1604 .as_ref()
1605 .and_then(|c| enabled_for_key.iter().position(|o| &o.value == c));
1606 match event.keystroke.key.as_str() {
1607 "escape" => {
1608 let t_now = motion_now(cx);
1609 let q_in = int_key.read(cx).query_input.clone();
1610 q_in.update(cx, |s, cx| s.set_value("", window, cx));
1611 int_key.update(cx, |s, _| {
1612 s.open = false;
1613 s.toggled_at_secs = t_now;
1614 s.highlight_seeded = false;
1615 s.last_query = "".into();
1616 });
1617 window.refresh();
1618 }
1619 "down" | "arrowdown" => {
1620 if !enabled_for_key.is_empty() {
1621 let next_idx = match cur_pos {
1622 Some(i) => (i + 1).min(enabled_for_key.len() - 1),
1623 None => 0,
1624 };
1625 let next_val = enabled_for_key[next_idx].value.clone();
1626 int_key.update(cx, |s, _| s.active_value = Some(next_val));
1627 window.refresh();
1628 }
1629 }
1630 "up" | "arrowup" => {
1631 if !enabled_for_key.is_empty() {
1632 let prev_idx = match cur_pos {
1633 Some(i) => i.saturating_sub(1),
1634 None => 0,
1635 };
1636 let prev_val = enabled_for_key[prev_idx].value.clone();
1637 int_key.update(cx, |s, _| s.active_value = Some(prev_val));
1638 window.refresh();
1639 }
1640 }
1641 "home" => {
1642 if let Some(first) = enabled_for_key.first() {
1643 let v = first.value.clone();
1644 int_key.update(cx, |s, _| s.active_value = Some(v));
1645 window.refresh();
1646 }
1647 }
1648 "end" => {
1649 if let Some(last) = enabled_for_key.last() {
1650 let v = last.value.clone();
1651 int_key.update(cx, |s, _| s.active_value = Some(v));
1652 window.refresh();
1653 }
1654 }
1655 "enter" => {
1656 if let Some(idx) = cur_pos
1657 && let Some(opt) = enabled_for_key.get(idx)
1658 {
1659 let chosen = opt.value.clone();
1660 let row_y =
1661 offsets_for_key.get(&chosen).map(|(y, _)| *y).unwrap_or(0.0);
1662 let lift_y = MORPH_SELECT_LID_H + 6.0 + row_y;
1663 let t_now = motion_now(cx);
1664 let q_in = int_key.read(cx).query_input.clone();
1665 q_in.update(cx, |s, cx| s.set_value("", window, cx));
1666 int_key.update(cx, |s, _| {
1667 let changed = s.last_selected.as_ref() != Some(&chosen);
1668 s.uncontrolled_value = Some(chosen.clone());
1669 s.last_selected = Some(chosen.clone());
1670 s.open = false;
1671 s.toggled_at_secs = t_now;
1672 s.highlight_seeded = false;
1673 s.last_query = "".into();
1674 if changed {
1675 s.fly_used_lift = true;
1676 s.fly_from_x = 0.0;
1677 s.fly_from_y = lift_y;
1678 s.fly_epoch = s.fly_epoch.wrapping_add(1);
1679 s.fly_started_at_secs = t_now;
1680 }
1681 });
1682 if let Some(cb) = &on_change_key {
1683 cb(&chosen, window, cx);
1684 }
1685 window.refresh();
1686 }
1687 }
1688 _ => {}
1689 }
1690 })
1691 .absolute()
1692 .top_0()
1693 .when(!align_end, |this| this.left_0())
1694 .when(align_end, |this| this.right_0())
1695 .w(px(shape_w))
1696 .h(px(shape_h))
1697 .rounded(Radii::PANEL)
1698 .border_1()
1699 .border_color(shape_border)
1700 .bg(shape_bg)
1701 .shadow(shape_shadow)
1702 .opacity(if disabled { 0.55 } else { 1.0 })
1703 .overflow_hidden()
1704 .flex()
1705 .flex_col()
1706 .child(shape_probe)
1707 .child(lid_el)
1708 .when_some(list_face_el, |this, lf| this.child(lf));
1709
1710 let elevated = is_open || shape_h > MORPH_SELECT_LID_H + 0.5;
1711 let anchor = div()
1712 .relative()
1713 .w(px(anchor_w))
1714 .h(ControlHeights::MD)
1715 .child(measure_el)
1716 .child(if elevated {
1717 deferred(shape_el).with_priority(25).into_any_element()
1718 } else {
1719 shape_el.into_any_element()
1720 });
1721
1722 div()
1723 .id(self.id)
1724 .test_support()
1725 .flex()
1726 .flex_col()
1727 .when(!align_end, |this| this.items_start())
1728 .when(align_end, |this| this.items_end())
1729 .gap(Spacing::S2)
1730 .when(!self.hide_label, |this| {
1731 this.child(
1732 div()
1733 .text_size(Typography::TEXT_SM)
1734 .font_medium()
1735 .text_color(colors.text_secondary)
1736 .child(self.label),
1737 )
1738 })
1739 .child(anchor)
1740 }
1741}
1742
1743#[cfg(test)]
1744mod tests {
1745 use super::*;
1746
1747 #[test]
1748 fn normalize_morph_select_items_gathers_consecutive_loose_options() {
1749 let items = vec![
1750 MorphSelectItem::Option(MorphSelectOption::new("a", "Alpha")),
1751 MorphSelectItem::Option(MorphSelectOption::new("b", "Beta")),
1752 MorphSelectItem::Group(MorphSelectGroup::new(
1753 "Group 1",
1754 [MorphSelectOption::new("c", "Charlie")],
1755 )),
1756 MorphSelectItem::Option(MorphSelectOption::new("d", "Delta")),
1757 ];
1758 let sections = normalize_morph_select_items(&items);
1759 assert_eq!(sections.len(), 3);
1760 assert!(sections[0].label.is_none());
1761 assert_eq!(sections[0].options.len(), 2);
1762 assert_eq!(sections[1].label, Some("Group 1".into()));
1763 assert_eq!(sections[2].options.len(), 1);
1764 }
1765
1766 #[test]
1767 fn morph_select_option_matches_label_meta_and_keywords() {
1768 let opt = MorphSelectOption::new("tokyo", "Tokyo")
1769 .meta("UTC+9")
1770 .keywords("japan asia");
1771 assert!(opt.matches_query("tokyo"));
1772 assert!(opt.matches_query("utc+9"));
1773 assert!(opt.matches_query("japan"));
1774 assert!(!opt.matches_query("zurich"));
1775 }
1776
1777 #[test]
1778 fn morph_select_list_face_sample_respects_40ms_open_delay() {
1779 let (op_early, y_early) = morph_select_list_face_sample(0.02, true, false);
1780 assert!(op_early < 1e-4);
1781 assert!((y_early - (-6.0)).abs() < 1e-4);
1782
1783 let (op_settled, y_settled) = morph_select_list_face_sample(0.28, true, false);
1784 assert!((op_settled - 1.0).abs() < 1e-4);
1785 assert!(y_settled.abs() < 1e-4);
1786 }
1787}