1use std::{cell::Cell, rc::Rc};
4
5use crate::layout::layout_ext::{apply_layout_size, finish_view_sized};
6use crate::transactional_layout::TransactionalLayoutPending;
7use ailloli_ui_core::event::pointer::{MouseButton, PointerEvent};
8use ailloli_ui_core::event::{Event, Key, KeyState, NamedKey, WheelDelta};
9use ailloli_ui_core::geometry::{Constraints, Rect, Size};
10use ailloli_ui_core::scroll::{ScrollAxes, ScrollBehavior, ScrollMetrics, ScrollState};
11use ailloli_ui_core::style::{
12 Border, BoxShadow, FlexItemStyle, LayoutSizeHint, LayoutStyle, Radius,
13};
14use ailloli_ui_core::{Color, FontId, IconId, Offset, TextStyle, Theme};
15use ailloli_ui_runtime::app::Invalidation;
16use ailloli_ui_runtime::component::reactive::with_untracked_reads;
17use ailloli_ui_runtime::component::{
18 Binding, ComponentNode, Context, IntoView, Signal, View, Widget,
19};
20use ailloli_ui_runtime::input::{ClickAction, EventCtx, FocusPolicy, InputRole, IntoClickAction};
21use ailloli_ui_runtime::layout::{
22 ChildLayout, LayoutArtifact, LayoutChild, LayoutCtx, LayoutPass, LayoutResult,
23};
24use ailloli_ui_runtime::scene::PaintCtx;
25use ailloli_ui_runtime::{
26 DrawBorder, DrawBoxShadow, DrawCmd, DrawImage, DrawRRect, DrawRect, DrawText,
27};
28use ailloli_ui_text::{TextBuffer, TextEditState};
29
30use super::popup::{
31 apply_opacity, measure_text, paint_overlay_text_in_rect, paint_popup_border, paint_popup_shell,
32};
33use super::select::{SelectSize, SelectStyle};
34use super::text_field_core::{
35 display_text_for_edit, handle_single_line_text_event, ime_cursor_rect, layout_single_line_text,
36 read_display_buffer, text_input_content_rect, TextFieldEventOptions,
37};
38use super::text_input::TextInputStyle;
39
40#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
41pub enum CommandPaletteSize {
50 Compact,
52 #[default]
54 Default,
55}
56
57#[derive(Clone, Debug)]
58pub struct CommandPaletteStyle {
75 pub input: TextInputStyle,
77 pub popup: SelectStyle,
79 pub backdrop: Color,
81 pub panel_background: Color,
83 pub border: Border,
85 pub shadows: Vec<BoxShadow>,
87 pub title_text: TextStyle,
89 pub subtitle_text: TextStyle,
91 pub shortcut_text: TextStyle,
93 pub no_results_text: TextStyle,
95 pub icon_tint: Color,
97 pub disabled_opacity: f32,
99 pub width: f32,
101 pub input_height: f32,
103 pub row_height: f32,
105 pub panel_max_height: f32,
107 pub panel_top: f32,
109 pub padding: f32,
111 pub gap: f32,
113 pub icon_size: f32,
115 pub radius: Radius,
117}
118
119impl Default for CommandPaletteStyle {
120 fn default() -> Self {
121 Self::from_theme(Theme::default(), CommandPaletteSize::Default)
122 }
123}
124
125impl CommandPaletteStyle {
126 pub fn from_theme(theme: Theme, size: CommandPaletteSize) -> Self {
141 let palette = theme.palette();
142 let popup = SelectStyle::from_theme(
143 theme,
144 match size {
145 CommandPaletteSize::Compact => SelectSize::Compact,
146 CommandPaletteSize::Default => SelectSize::Default,
147 },
148 );
149 let (width, input_height, row_height, panel_top, padding, text_size) = match size {
150 CommandPaletteSize::Compact => (430.0, 34.0, 38.0, 52.0, 10.0, 12),
151 CommandPaletteSize::Default => (520.0, 40.0, 44.0, 72.0, 12.0, 13),
152 };
153 let mut input = TextInputStyle::from_theme(theme);
154 input.bg = palette.surface;
155 input.border = palette.border;
156 input.border_focused = palette.focus;
157 input.placeholder = palette.text_muted;
158 input.text = TextStyle::new(FontId::Ui, text_size, palette.text);
159 input.pad_x = padding;
160 input.pad_y = ((input_height - input.text.px_size as f32 * 1.2) * 0.5).max(4.0);
161
162 Self {
163 input,
164 popup: SelectStyle {
165 width,
166 height: input_height,
167 option_height: row_height,
168 popup_max_height: 260.0,
169 radius: Radius::uniform(theme.radius().lg),
170 ..popup
171 },
172 backdrop: Color::BLACK.with_alpha(0.32),
173 panel_background: palette.surface_elevated,
174 border: Border::new(1.0, palette.border),
175 shadows: vec![theme.shadows().lg],
176 title_text: TextStyle::new(FontId::Ui, text_size, palette.text),
177 subtitle_text: TextStyle::new(FontId::Ui, 11, palette.text_muted),
178 shortcut_text: TextStyle::new(FontId::Mono, 11, palette.text_muted),
179 no_results_text: TextStyle::new(FontId::Ui, text_size, palette.text_muted),
180 icon_tint: palette.text_muted,
181 disabled_opacity: 0.45,
182 width,
183 input_height,
184 row_height,
185 panel_max_height: 360.0,
186 panel_top,
187 padding,
188 gap: 8.0,
189 icon_size: 16.0,
190 radius: Radius::uniform(theme.radius().lg),
191 }
192 }
193}
194
195pub struct CommandItem<A = ()> {
210 title: String,
212 subtitle: Option<String>,
214 shortcut: Option<String>,
216 keywords: Vec<String>,
218 icon: Option<IconId>,
220 disabled: Binding<bool>,
222 action: Option<Rc<ClickAction<A>>>,
224}
225
226impl<A> Clone for CommandItem<A> {
227 fn clone(&self) -> Self {
228 Self {
229 title: self.title.clone(),
230 subtitle: self.subtitle.clone(),
231 shortcut: self.shortcut.clone(),
232 keywords: self.keywords.clone(),
233 icon: self.icon.clone(),
234 disabled: self.disabled.clone(),
235 action: self.action.clone(),
236 }
237 }
238}
239
240impl<A: 'static> CommandItem<A> {
241 pub fn new(title: impl Into<String>) -> Self {
251 Self {
252 title: title.into(),
253 subtitle: None,
254 shortcut: None,
255 keywords: Vec::new(),
256 icon: None,
257 disabled: Binding::Static(false),
258 action: None,
259 }
260 }
261
262 pub fn subtitle(mut self, subtitle: impl Into<String>) -> Self {
274 self.subtitle = Some(subtitle.into());
275 self
276 }
277
278 pub fn shortcut(mut self, shortcut: impl Into<String>) -> Self {
288 self.shortcut = Some(shortcut.into());
289 self
290 }
291
292 pub fn keyword(mut self, keyword: impl Into<String>) -> Self {
302 self.keywords.push(keyword.into());
303 self
304 }
305
306 pub fn keywords(mut self, keywords: impl IntoIterator<Item = impl Into<String>>) -> Self {
319 self.keywords.extend(keywords.into_iter().map(Into::into));
320 self
321 }
322
323 pub fn leading_icon(mut self, icon: IconId) -> Self {
334 self.icon = Some(icon);
335 self
336 }
337
338 pub fn disabled(mut self, disabled: impl Into<Binding<bool>>) -> Self {
351 self.disabled = disabled.into();
352 self
353 }
354
355 pub fn on_select(mut self, action: impl IntoClickAction<A>) -> Self {
370 self.action = Some(Rc::new(action.into_click_action()));
371 self
372 }
373}
374
375pub struct CommandPalette<A = ()> {
394 pub(crate) layout: LayoutStyle,
396 pub(crate) flex_item: FlexItemStyle,
398 open: Option<Binding<bool>>,
400 bound_open: Option<Signal<bool>>,
402 default_open: bool,
404 query: Option<Signal<String>>,
406 default_query: String,
408 placeholder: Binding<String>,
410 disabled: Binding<bool>,
412 items: Vec<CommandItem<A>>,
414 style: CommandPaletteStyle,
416 child: Option<View<A>>,
418}
419
420crate::impl_layout_builders!(CommandPalette);
421
422impl<A: 'static> Default for CommandPalette<A> {
423 fn default() -> Self {
424 Self::new()
425 }
426}
427
428impl<A: 'static> CommandPalette<A> {
429 pub fn new() -> Self {
441 Self {
442 layout: LayoutStyle::default(),
443 flex_item: FlexItemStyle::default(),
444 open: None,
445 bound_open: None,
446 default_open: false,
447 query: None,
448 default_query: String::new(),
449 placeholder: Binding::Static("Type a command...".to_string()),
450 disabled: Binding::Static(false),
451 items: Vec::new(),
452 style: CommandPaletteStyle::default(),
453 child: None,
454 }
455 }
456
457 pub fn open(mut self, open: impl Into<Binding<bool>>) -> Self {
469 self.open = Some(open.into());
470 self.bound_open = None;
471 self
472 }
473
474 pub fn bind_open(mut self, open: impl Into<Signal<bool>>) -> Self {
487 let signal = open.into();
488 self.open = Some(Binding::Signal(signal.clone()));
489 self.bound_open = Some(signal);
490 self
491 }
492
493 pub fn default_open(mut self, open: bool) -> Self {
506 self.default_open = open;
507 self
508 }
509
510 pub fn bind_query(mut self, query: impl Into<Signal<String>>) -> Self {
526 self.query = Some(query.into());
527 self
528 }
529
530 pub fn default_query(mut self, query: impl Into<String>) -> Self {
540 self.default_query = query.into();
541 self
542 }
543
544 pub fn placeholder(mut self, placeholder: impl Into<Binding<String>>) -> Self {
556 self.placeholder = placeholder.into();
557 self
558 }
559
560 pub fn disabled(mut self, disabled: impl Into<Binding<bool>>) -> Self {
573 self.disabled = disabled.into();
574 self
575 }
576
577 pub fn item(mut self, item: CommandItem<A>) -> Self {
587 self.items.push(item);
588 self
589 }
590
591 pub fn command_style(mut self, style: CommandPaletteStyle) -> Self {
605 self.style = style;
606 self
607 }
608
609 pub fn command_size(mut self, size: CommandPaletteSize) -> Self {
620 self.style = CommandPaletteStyle::from_theme(Theme::default(), size);
621 self
622 }
623
624 pub fn child(mut self, child: impl IntoView<A>) -> Self {
635 self.child = Some(child.into_view());
636 self
637 }
638}
639
640struct CommandPaletteComponent<A> {
642 layout: LayoutStyle,
644 open: Option<Binding<bool>>,
646 bound_open: Option<Signal<bool>>,
648 default_open: bool,
650 query: Option<Signal<String>>,
652 default_query: String,
654 placeholder: Binding<String>,
656 disabled: Binding<bool>,
658 items: Vec<CommandItem<A>>,
660 style: CommandPaletteStyle,
662 child: Option<View<A>>,
664}
665
666impl<A: 'static> ComponentNode<A> for CommandPaletteComponent<A> {
667 fn build(&self, context: &mut Context<A>) -> View<A> {
668 let query = self
669 .query
670 .clone()
671 .unwrap_or_else(|| context.signal(self.default_query.clone()));
672 let current = query.read();
673 let mut children = Vec::new();
674 if let Some(child) = self.child.clone() {
675 children.push(child);
676 }
677 View::node(
678 CommandPaletteWidget {
679 layout: self.layout,
680 open: self.open.clone(),
681 bound_open: self.bound_open.clone(),
682 internal_open: context.signal(self.default_open),
683 query: query.clone(),
684 placeholder: self.placeholder.clone(),
685 disabled: self.disabled.clone(),
686 items: self.items.clone(),
687 style: self.style.clone(),
688 scroll: context.signal_with_invalidation(ScrollState::new(), Invalidation::Paint),
689 active_index: context.signal(None),
690 buffer: context.signal(TextBuffer::from_string(current.clone())),
691 edit: context.signal(edit_at_end(¤t)),
692 pending_scroll: Cell::new(None),
693 },
694 children,
695 )
696 }
697}
698
699impl<A: 'static> IntoView<A> for CommandPalette<A> {
700 fn into_view(self) -> View<A> {
701 finish_view_sized(
702 View::component(CommandPaletteComponent {
703 layout: self.layout,
704 open: self.open,
705 bound_open: self.bound_open,
706 default_open: self.default_open,
707 query: self.query,
708 default_query: self.default_query,
709 placeholder: self.placeholder,
710 disabled: self.disabled,
711 items: self.items,
712 style: self.style,
713 child: self.child,
714 }),
715 self.flex_item,
716 LayoutSizeHint::from_layout(self.layout),
717 )
718 }
719}
720
721struct CommandPaletteWidget<A> {
723 layout: LayoutStyle,
725 open: Option<Binding<bool>>,
727 bound_open: Option<Signal<bool>>,
729 internal_open: Signal<bool>,
731 query: Signal<String>,
733 placeholder: Binding<String>,
735 disabled: Binding<bool>,
737 items: Vec<CommandItem<A>>,
739 style: CommandPaletteStyle,
741 scroll: Signal<ScrollState>,
743 active_index: Signal<Option<usize>>,
745 buffer: Signal<TextBuffer>,
747 edit: Signal<TextEditState>,
749 pending_scroll: Cell<Option<TransactionalLayoutPending<Option<ScrollState>>>>,
751}
752
753impl<A: 'static> Widget<A> for CommandPaletteWidget<A> {
754 fn debug_name(&self) -> &'static str {
755 "CommandPalette"
756 }
757
758 fn layout(
759 &self,
760 engine: &mut ailloli_ui_runtime::layout::LayoutEngine<'_, A>,
761 ctx: &mut LayoutCtx<'_>,
762 children: &mut [LayoutChild],
763 constraints: Constraints,
764 ) -> LayoutResult {
765 let size = host_slot_size(engine, ctx, children, constraints, self.layout);
766 let mut child_layouts = Vec::new();
767 if let Some(child) = children.first_mut() {
768 let r = ctx.with_layout_pass(LayoutPass::Commit, |ctx| {
769 child.layout(engine, ctx, Constraints::tight(size.w, size.h))
770 });
771 child_layouts.push(ChildLayout {
772 offset: Offset::default(),
773 size: r.size,
774 paint_bounds: Rect::new(0.0, 0.0, r.size.w, r.size.h),
775 visual_bounds: r.visual_bounds,
776 });
777 }
778
779 let (_, text_layout) = layout_single_line_text(
780 ctx,
781 Constraints::loose(self.style.width, self.style.input_height),
782 LayoutStyle::default()
783 .width(self.style.width)
784 .height(self.style.input_height),
785 &self.query,
786 &self.buffer,
787 &self.edit,
788 Some(self.placeholder.read()),
789 self.text_style(),
790 );
791
792 let paint_bounds = Rect::new(0.0, 0.0, size.w, size.h);
793 let overlay_hit_bounds = if self.is_open() && !self.disabled.read() {
794 vec![paint_bounds]
795 } else {
796 Vec::new()
797 };
798 if ctx.layout_pass().is_committed() {
799 let state = (self.is_open() && !self.disabled.read())
800 .then(|| self.clamped_scroll(self.list_rect_for_size(size).size()))
801 .flatten();
802 self.pending_scroll
803 .set(TransactionalLayoutPending::new(ctx, state));
804 }
805
806 LayoutResult {
807 size,
808 children: child_layouts,
809 paint_bounds,
810 visual_bounds: paint_bounds,
811 overlay_hit_bounds,
812 clip: None,
813 is_window_root_clip: false,
814 artifact: text_layout.map(LayoutArtifact::Text),
815 }
816 }
817
818 fn paint(&self, _ctx: &mut PaintCtx<'_>, _bounds: Rect, _layout: &LayoutResult) {}
819
820 fn layout_committed(&self, ctx: &mut LayoutCtx<'_>, _bounds: Rect, _layout: &LayoutResult) {
822 if let Some(state) = self
823 .pending_scroll
824 .take()
825 .and_then(|pending| pending.into_committed(ctx))
826 .flatten()
827 {
828 self.scroll.set(state);
829 }
830 }
831
832 fn paint_overlay(&self, ctx: &mut PaintCtx<'_>, bounds: Rect, layout: &LayoutResult) {
833 if !self.is_open() || self.disabled.read() {
834 return;
835 }
836 self.paint_palette(ctx, bounds, layout);
837 }
838
839 fn event(&self, ctx: &mut EventCtx<A>, event: &Event, bounds: Rect, layout: &LayoutResult) {
840 if !self.is_open() || self.disabled.read() {
841 return;
842 }
843
844 match event {
845 Event::Focus(focus) if !focus.focused => {
846 self.close();
847 ctx.request_repaint();
848 }
849 Event::Pointer(PointerEvent::Button {
850 pos,
851 button: MouseButton::Left,
852 pressed,
853 ..
854 }) if self.input_rect(bounds).contains(pos.x, pos.y) => {
855 let _ = handle_single_line_text_event(
856 ctx,
857 event,
858 self.input_rect(bounds),
859 layout,
860 &self.query,
861 &self.buffer,
862 &self.edit,
863 self.text_style(),
864 TextFieldEventOptions {
865 consume_handled_events: true,
866 },
867 );
868 if *pressed {
869 self.active_index.set(self.first_enabled_index());
870 }
871 ctx.request_repaint();
872 ctx.stop_propagation();
873 }
874 Event::Pointer(PointerEvent::Moved { .. }) => {
875 let _ = handle_single_line_text_event(
876 ctx,
877 event,
878 self.input_rect(bounds),
879 layout,
880 &self.query,
881 &self.buffer,
882 &self.edit,
883 self.text_style(),
884 TextFieldEventOptions {
885 consume_handled_events: true,
886 },
887 );
888 }
889 Event::Pointer(PointerEvent::Button {
890 pos,
891 button: MouseButton::Left,
892 pressed: false,
893 ..
894 }) if self.list_rect(bounds).contains(pos.x, pos.y) => {
895 if let Some(index) = self.item_at(bounds, *pos) {
896 self.activate_item(ctx, index);
897 } else {
898 ctx.stop_propagation();
899 }
900 }
901 Event::Pointer(PointerEvent::Button {
902 pos,
903 button: MouseButton::Left,
904 pressed: false,
905 ..
906 }) if !self.panel_rect(bounds).contains(pos.x, pos.y) => {
907 self.close();
908 ctx.request_repaint();
909 ctx.stop_propagation();
910 }
911 Event::Pointer(PointerEvent::Wheel {
912 pos,
913 delta,
914 modifiers,
915 ..
916 }) if self.list_rect(bounds).contains(pos.x, pos.y) => {
917 self.scroll_list(ctx, bounds, *delta, *modifiers);
918 }
919 Event::Keyboard(key) if key.state == KeyState::Pressed => {
920 self.handle_keyboard(ctx, &key.key, event, bounds, layout);
921 }
922 Event::Ime(_) => {
923 let before = self.query.read();
924 let handled = handle_single_line_text_event(
925 ctx,
926 event,
927 self.input_rect(bounds),
928 layout,
929 &self.query,
930 &self.buffer,
931 &self.edit,
932 self.text_style(),
933 TextFieldEventOptions {
934 consume_handled_events: true,
935 },
936 );
937 self.after_text_event(ctx, before, handled);
938 }
939 _ => {}
940 }
941 }
942
943 fn focus_policy(&self) -> FocusPolicy {
944 if self.is_open() && !self.disabled.read() {
945 FocusPolicy::Focusable
946 } else {
947 FocusPolicy::NotFocusable
948 }
949 }
950
951 fn input_role(&self) -> InputRole {
952 if self.is_open() && !self.disabled.read() {
953 InputRole::TextSingleLine
954 } else {
955 InputRole::None
956 }
957 }
958
959 fn ime_cursor_rect(&self, bounds: Rect, layout: &LayoutResult) -> Option<Rect> {
960 if !self.is_open() || self.disabled.read() {
961 return None;
962 }
963 ime_cursor_rect(
964 self.input_rect(bounds),
965 layout,
966 &self.query,
967 &self.buffer,
968 &self.edit,
969 self.text_style(),
970 )
971 }
972}
973
974impl<A: 'static> CommandPaletteWidget<A> {
975 fn is_open(&self) -> bool {
977 self.open
978 .as_ref()
979 .map(Binding::read)
980 .unwrap_or_else(|| self.internal_open.read())
981 }
982
983 fn close(&self) {
985 if let Some(bound) = &self.bound_open {
986 bound.set(false);
987 } else if self.open.is_none() {
988 self.internal_open.set(false);
989 }
990 self.active_index.set(None);
991 }
992
993 fn text_style(&self) -> TextInputStyle {
995 if self.disabled.read() {
996 let opacity = self.style.disabled_opacity;
997 let mut input = self.style.input;
998 input.bg = apply_opacity(input.bg, opacity);
999 input.border = apply_opacity(input.border, opacity);
1000 input.border_focused = apply_opacity(input.border_focused, opacity);
1001 input.placeholder = apply_opacity(input.placeholder, opacity);
1002 input.text.color = apply_opacity(input.text.color, opacity);
1003 input
1004 } else {
1005 self.style.input
1006 }
1007 }
1008
1009 fn panel_rect(&self, bounds: Rect) -> Rect {
1011 let width = self.style.width.min((bounds.w - 32.0).max(240.0));
1012 let height = self.panel_height();
1013 Rect::new(
1014 bounds.x + (bounds.w - width) * 0.5,
1015 bounds.y + self.style.panel_top.min((bounds.h - height).max(12.0)),
1016 width,
1017 height.min((bounds.h - 24.0).max(self.style.input_height + 8.0)),
1018 )
1019 }
1020
1021 fn input_rect(&self, bounds: Rect) -> Rect {
1023 let panel = self.panel_rect(bounds);
1024 Rect::new(
1025 panel.x + self.style.padding,
1026 panel.y + self.style.padding,
1027 (panel.w - self.style.padding * 2.0).max(0.0),
1028 self.style.input_height,
1029 )
1030 }
1031
1032 fn list_rect(&self, bounds: Rect) -> Rect {
1034 let panel = self.panel_rect(bounds);
1035 let input = self.input_rect(bounds);
1036 Rect::new(
1037 panel.x,
1038 input.bottom() + self.style.padding,
1039 panel.w,
1040 (panel.bottom() - input.bottom() - self.style.padding).max(0.0),
1041 )
1042 }
1043
1044 fn list_rect_for_size(&self, size: Size) -> Rect {
1046 self.list_rect(Rect::new(0.0, 0.0, size.w, size.h))
1047 }
1048
1049 fn panel_height(&self) -> f32 {
1051 let rows = self.filtered_indices().len().max(1) as f32;
1052 let list_h = (rows * self.style.row_height).min(self.style.popup.popup_max_height);
1053 (self.style.padding * 3.0 + self.style.input_height + list_h)
1054 .min(self.style.panel_max_height)
1055 }
1056
1057 fn filtered_indices(&self) -> Vec<usize> {
1059 filtered_indices(&self.query.read(), &self.items)
1060 }
1061
1062 fn first_enabled_index(&self) -> Option<usize> {
1064 self.filtered_indices()
1065 .into_iter()
1066 .find(|idx| !self.items[*idx].disabled.read())
1067 }
1068
1069 fn last_enabled_index(&self) -> Option<usize> {
1071 self.filtered_indices()
1072 .into_iter()
1073 .rev()
1074 .find(|idx| !self.items[*idx].disabled.read())
1075 }
1076
1077 fn next_enabled_index(&self, current: Option<usize>) -> Option<usize> {
1079 let filtered = self.filtered_indices();
1080 next_enabled(&filtered, current, |idx| !self.items[idx].disabled.read())
1081 }
1082
1083 fn previous_enabled_index(&self, current: Option<usize>) -> Option<usize> {
1085 let filtered = self.filtered_indices();
1086 previous_enabled(&filtered, current, |idx| !self.items[idx].disabled.read())
1087 }
1088
1089 fn clamped_scroll(&self, viewport: Size) -> Option<ScrollState> {
1091 let rows = self.filtered_indices().len().max(1);
1092 let content = Size::new(viewport.w, rows as f32 * self.style.row_height);
1093 let retained = with_untracked_reads(|| self.scroll.read());
1094 let out = retained.clamp_to(ScrollMetrics::new(viewport, content), ScrollAxes::VERTICAL);
1095 out.changed.then_some(out.state())
1096 }
1097
1098 fn item_at(&self, bounds: Rect, pos: ailloli_ui_core::Point) -> Option<usize> {
1100 let list = self.list_rect(bounds);
1101 let filtered = self.filtered_indices();
1102 if filtered.is_empty() {
1103 return None;
1104 }
1105 let y = pos.y - list.y + self.scroll.read().offset.y;
1106 let row = (y / self.style.row_height).floor() as usize;
1107 filtered.get(row).copied()
1108 }
1109
1110 fn activate_item(&self, ctx: &mut EventCtx<A>, index: usize) {
1112 let Some(item) = self.items.get(index) else {
1113 return;
1114 };
1115 if item.disabled.read() {
1116 ctx.stop_propagation();
1117 return;
1118 }
1119 if let Some(action) = &item.action {
1120 action.run(ctx);
1121 }
1122 self.close();
1123 ctx.request_repaint();
1124 ctx.stop_propagation();
1125 }
1126
1127 fn scroll_list(
1129 &self,
1130 ctx: &mut EventCtx<A>,
1131 bounds: Rect,
1132 delta: WheelDelta,
1133 modifiers: ailloli_ui_core::event::Modifiers,
1134 ) {
1135 let list = self.list_rect(bounds);
1136 let rows = self.filtered_indices().len().max(1);
1137 let metrics = ScrollMetrics::new(
1138 Size::new(list.w, list.h),
1139 Size::new(list.w, rows as f32 * self.style.row_height),
1140 );
1141 let behavior =
1142 ScrollBehavior::new(ScrollAxes::VERTICAL).with_line_px(self.style.row_height);
1143 let out = self.scroll.read().scroll_by(
1144 behavior.wheel_delta_with_modifiers(delta, modifiers),
1145 metrics,
1146 ScrollAxes::VERTICAL,
1147 );
1148 if out.changed {
1149 self.scroll.set(out.state());
1150 ctx.request_repaint();
1151 ctx.stop_propagation();
1152 }
1153 }
1154
1155 fn handle_keyboard(
1157 &self,
1158 ctx: &mut EventCtx<A>,
1159 key: &Key,
1160 event: &Event,
1161 bounds: Rect,
1162 layout: &LayoutResult,
1163 ) {
1164 match key {
1165 Key::Named(NamedKey::Escape) => {
1166 self.close();
1167 ctx.request_repaint();
1168 ctx.stop_propagation();
1169 return;
1170 }
1171 Key::Named(NamedKey::ArrowDown) => {
1172 self.move_active(ctx, Direction::Next);
1173 return;
1174 }
1175 Key::Named(NamedKey::ArrowUp) => {
1176 self.move_active(ctx, Direction::Previous);
1177 return;
1178 }
1179 Key::Named(NamedKey::Home) => {
1180 self.set_active(ctx, self.first_enabled_index());
1181 return;
1182 }
1183 Key::Named(NamedKey::End) => {
1184 self.set_active(ctx, self.last_enabled_index());
1185 return;
1186 }
1187 Key::Named(NamedKey::Enter) | Key::Named(NamedKey::Space) => {
1188 if let Some(index) = self
1189 .active_index
1190 .read()
1191 .or_else(|| self.first_enabled_index())
1192 {
1193 self.activate_item(ctx, index);
1194 }
1195 return;
1196 }
1197 _ => {}
1198 }
1199
1200 let before = self.query.read();
1201 let handled = handle_single_line_text_event(
1202 ctx,
1203 event,
1204 self.input_rect(bounds),
1205 layout,
1206 &self.query,
1207 &self.buffer,
1208 &self.edit,
1209 self.text_style(),
1210 TextFieldEventOptions {
1211 consume_handled_events: true,
1212 },
1213 );
1214 self.after_text_event(ctx, before, handled);
1215 }
1216
1217 fn after_text_event(&self, ctx: &mut EventCtx<A>, before: String, handled: bool) {
1219 if handled && self.query.read() != before {
1220 self.scroll.set(ScrollState::new());
1221 self.active_index.set(self.first_enabled_index());
1222 ctx.request_repaint();
1223 }
1224 }
1225
1226 fn move_active(&self, ctx: &mut EventCtx<A>, direction: Direction) {
1228 let next = match direction {
1229 Direction::Next => self.next_enabled_index(self.active_index.read()),
1230 Direction::Previous => self.previous_enabled_index(self.active_index.read()),
1231 };
1232 self.set_active(ctx, next);
1233 }
1234
1235 fn set_active(&self, ctx: &mut EventCtx<A>, next: Option<usize>) {
1237 if self.active_index.read() != next {
1238 self.active_index.set(next);
1239 ctx.request_repaint();
1240 }
1241 ctx.stop_propagation();
1242 }
1243
1244 fn paint_palette(&self, ctx: &mut PaintCtx<'_>, bounds: Rect, layout: &LayoutResult) {
1246 ctx.push_overlay(DrawCmd::Rect(DrawRect {
1247 rect: bounds,
1248 color: self.style.backdrop,
1249 }));
1250 let panel = self.panel_rect(bounds);
1251 for shadow in self.style.shadows.iter().copied().filter(|s| !s.inset) {
1252 ctx.push_overlay(DrawCmd::BoxShadow(DrawBoxShadow {
1253 rect: panel,
1254 radius: self.style.radius,
1255 shadow,
1256 }));
1257 }
1258 paint_popup_shell(ctx, panel, &self.style.popup);
1259 self.paint_input(ctx, self.input_rect(bounds), layout);
1260 self.paint_rows(ctx, self.list_rect(bounds));
1261 paint_popup_border(ctx, panel, &self.style.popup);
1262 }
1263
1264 fn paint_input(&self, ctx: &mut PaintCtx<'_>, input: Rect, layout: &LayoutResult) {
1266 let style = self.text_style();
1267 ctx.push_overlay(DrawCmd::RRect(DrawRRect {
1268 rect: input,
1269 radius: style.radius,
1270 color: style.bg,
1271 }));
1272 ctx.push_overlay(DrawCmd::Border(DrawBorder {
1273 rect: input,
1274 radius: Radius::uniform(style.radius),
1275 border: Border::new(1.0, style.border_focused),
1276 }));
1277 paint_overlay_single_line_text(
1278 ctx,
1279 input,
1280 layout,
1281 &self.query,
1282 &self.buffer,
1283 &self.edit,
1284 Some(self.placeholder.read()),
1285 style,
1286 true,
1287 );
1288 }
1289
1290 fn paint_rows(&self, ctx: &mut PaintCtx<'_>, list: Rect) {
1292 let filtered = self.filtered_indices();
1293 ctx.with_overlay_clip(list, |ctx| {
1294 if filtered.is_empty() {
1295 let row = Rect::new(list.x, list.y, list.w, self.style.row_height);
1296 paint_overlay_text_in_rect(
1297 ctx,
1298 "No results",
1299 self.style.no_results_text,
1300 row.inflate(-self.style.padding, 0.0),
1301 self.style.disabled_opacity,
1302 );
1303 return;
1304 }
1305
1306 for (row_idx, item_idx) in filtered.iter().copied().enumerate() {
1307 let item = &self.items[item_idx];
1308 let row = Rect::new(
1309 list.x,
1310 list.y - self.scroll.read().offset.y + row_idx as f32 * self.style.row_height,
1311 list.w,
1312 self.style.row_height,
1313 );
1314 if row.bottom() < list.y || row.y > list.bottom() {
1315 continue;
1316 }
1317 self.paint_row(ctx, row, item, self.active_index.read() == Some(item_idx));
1318 }
1319 });
1320 }
1321
1322 fn paint_row(&self, ctx: &mut PaintCtx<'_>, row: Rect, item: &CommandItem<A>, active: bool) {
1324 let disabled = item.disabled.read();
1325 let opacity = if disabled {
1326 self.style.disabled_opacity
1327 } else {
1328 1.0
1329 };
1330 if active {
1331 ctx.push_overlay(DrawCmd::Rect(DrawRect {
1332 rect: row,
1333 color: apply_opacity(self.style.popup.option_active, opacity),
1334 }));
1335 }
1336
1337 let mut x = row.x + self.style.padding;
1338 if let Some(icon) = &item.icon {
1339 ctx.push_overlay(DrawCmd::Image(DrawImage {
1340 rect: Rect::new(
1341 x,
1342 row.y + (row.h - self.style.icon_size) * 0.5,
1343 self.style.icon_size,
1344 self.style.icon_size,
1345 ),
1346 icon: icon.clone(),
1347 tint: apply_opacity(self.style.icon_tint, opacity),
1348 rotation_rad: 0.0,
1349 }));
1350 x += self.style.icon_size + self.style.gap;
1351 }
1352
1353 let shortcut_w = item
1354 .shortcut
1355 .as_ref()
1356 .map(|s| measure_text(ctx.text_system.as_deref_mut(), s, self.style.shortcut_text).w)
1357 .unwrap_or(0.0);
1358 let text_right = row.right() - self.style.padding - shortcut_w - self.style.gap;
1359 let title_h = if item.subtitle.is_some() { 20.0 } else { row.h };
1360 paint_overlay_text_in_rect(
1361 ctx,
1362 &item.title,
1363 if disabled {
1364 TextStyle {
1365 color: apply_opacity(self.style.title_text.color, opacity),
1366 ..self.style.title_text
1367 }
1368 } else {
1369 self.style.title_text
1370 },
1371 Rect::new(x, row.y + 1.0, (text_right - x).max(0.0), title_h),
1372 opacity,
1373 );
1374 if let Some(subtitle) = &item.subtitle {
1375 paint_overlay_text_in_rect(
1376 ctx,
1377 subtitle,
1378 self.style.subtitle_text,
1379 Rect::new(x, row.y + 21.0, (text_right - x).max(0.0), 18.0),
1380 opacity,
1381 );
1382 }
1383 if let Some(shortcut) = &item.shortcut {
1384 paint_overlay_text_in_rect(
1385 ctx,
1386 shortcut,
1387 self.style.shortcut_text,
1388 Rect::new(
1389 row.right() - self.style.padding - shortcut_w,
1390 row.y,
1391 shortcut_w,
1392 row.h,
1393 ),
1394 opacity,
1395 );
1396 }
1397 }
1398}
1399
1400#[derive(Debug, Clone, Copy)]
1401enum Direction {
1403 Next,
1405 Previous,
1407}
1408
1409fn edit_at_end(text: &str) -> TextEditState {
1411 let mut edit = TextEditState::new();
1412 let buffer = TextBuffer::from_string(text.to_string());
1413 edit.set_caret(&buffer, text.len(), false);
1414 edit
1415}
1416
1417fn filtered_indices<A>(query: &str, items: &[CommandItem<A>]) -> Vec<usize> {
1419 let q = query.trim().to_ascii_lowercase();
1420 items
1421 .iter()
1422 .enumerate()
1423 .filter_map(|(idx, item)| {
1424 (q.is_empty()
1425 || item.title.to_ascii_lowercase().contains(&q)
1426 || item
1427 .subtitle
1428 .as_ref()
1429 .is_some_and(|s| s.to_ascii_lowercase().contains(&q))
1430 || item
1431 .keywords
1432 .iter()
1433 .any(|s| s.to_ascii_lowercase().contains(&q)))
1434 .then_some(idx)
1435 })
1436 .collect()
1437}
1438
1439fn next_enabled(
1441 filtered: &[usize],
1442 current: Option<usize>,
1443 enabled: impl Fn(usize) -> bool,
1444) -> Option<usize> {
1445 if filtered.is_empty() {
1446 return None;
1447 }
1448 let start = current
1449 .and_then(|current| filtered.iter().position(|idx| *idx == current))
1450 .unwrap_or(filtered.len().saturating_sub(1));
1451 (1..=filtered.len())
1452 .map(|offset| filtered[(start + offset) % filtered.len()])
1453 .find(|idx| enabled(*idx))
1454}
1455
1456fn previous_enabled(
1458 filtered: &[usize],
1459 current: Option<usize>,
1460 enabled: impl Fn(usize) -> bool,
1461) -> Option<usize> {
1462 if filtered.is_empty() {
1463 return None;
1464 }
1465 let start = current
1466 .and_then(|current| filtered.iter().position(|idx| *idx == current))
1467 .unwrap_or(0);
1468 (1..=filtered.len())
1469 .map(|offset| filtered[(start + filtered.len() - offset) % filtered.len()])
1470 .find(|idx| enabled(*idx))
1471}
1472
1473fn host_slot_size<A: 'static>(
1475 engine: &mut ailloli_ui_runtime::layout::LayoutEngine<'_, A>,
1476 ctx: &mut LayoutCtx<'_>,
1477 children: &mut [LayoutChild],
1478 constraints: Constraints,
1479 layout: LayoutStyle,
1480) -> Size {
1481 let intrinsic = if let Some(child) = children.first_mut() {
1482 ctx.with_layout_pass(LayoutPass::Measure, |ctx| {
1483 child.layout(engine, ctx, constraints.loosen()).size
1484 })
1485 } else {
1486 Size::new(
1487 finite_or(constraints.max_w, 0.0),
1488 finite_or(constraints.max_h, 0.0),
1489 )
1490 };
1491 apply_layout_size(intrinsic, layout, constraints)
1492}
1493
1494fn finite_or(value: f32, fallback: f32) -> f32 {
1496 if value.is_finite() {
1497 value
1498 } else {
1499 fallback
1500 }
1501}
1502
1503#[allow(clippy::too_many_arguments)]
1504fn paint_overlay_single_line_text(
1510 ctx: &mut PaintCtx<'_>,
1511 bounds: Rect,
1512 layout: &LayoutResult,
1513 value: &Signal<String>,
1514 buffer: &Signal<TextBuffer>,
1515 edit: &Signal<TextEditState>,
1516 placeholder: Option<String>,
1517 style: TextInputStyle,
1518 focused: bool,
1519) {
1520 let buffer = read_display_buffer(value, buffer);
1521 let value = buffer.as_str();
1522 let is_empty = value.is_empty();
1523 let edit_state = edit.read();
1524 let (display, caret_in_display) = display_text_for_edit(
1525 &value,
1526 edit_state.caret_byte.min(value.len()),
1527 edit_state.preedit.as_ref(),
1528 );
1529 let text = if is_empty && display.is_empty() {
1530 placeholder.unwrap_or_default()
1531 } else {
1532 display
1533 };
1534 let text_color = if is_empty && edit_state.preedit.is_none() {
1535 style.placeholder
1536 } else {
1537 style.text.color
1538 };
1539 let style = TextInputStyle {
1540 text: TextStyle {
1541 color: text_color,
1542 ..style.text
1543 },
1544 ..style
1545 };
1546
1547 let Some(layout_handle) = layout
1548 .artifact
1549 .as_ref()
1550 .and_then(|artifact| match artifact {
1551 LayoutArtifact::Text(layout) if layout.text() == text => Some(layout.clone()),
1552 _ => None,
1553 })
1554 else {
1555 return;
1556 };
1557
1558 let content_rect = text_input_content_rect(bounds, style);
1559 let baseline_x = content_rect.x - edit_state.scroll_x;
1560 let baseline_y = bounds.y + style.pad_y + style.text.px_size as f32;
1561 let px = style.text.px_size as f32;
1562 let y_top = (baseline_y - px).round();
1563 let frame_time_ms = ctx.frame_time_ms() as i64;
1564
1565 ctx.with_overlay_clip(content_rect, |ctx| {
1566 if edit_state.preedit.is_none() {
1567 if let Some(sel) = edit_state.selection {
1568 if !sel.is_collapsed() {
1569 let (lo, hi) = sel.normalized();
1570 let lo = lo.min(text.len());
1571 let hi = hi.min(text.len());
1572 if hi > lo {
1573 let x0 = (baseline_x + layout_handle.caret_x_at(lo)).round();
1574 let x1 = (baseline_x + layout_handle.caret_x_at(hi)).round();
1575 ctx.push_overlay(DrawCmd::Rect(DrawRect {
1576 rect: Rect::new(x0, y_top, (x1 - x0).max(1.0), px + 2.0),
1577 color: style.selection_bg,
1578 }));
1579 }
1580 }
1581 }
1582 }
1583
1584 ctx.push_overlay(DrawCmd::Text(DrawText {
1585 pos: [baseline_x, baseline_y],
1586 color: style.text.color,
1587 decoration: ailloli_ui_core::TextDecoration::None,
1588 layout: layout_handle.clone(),
1589 }));
1590
1591 if focused && style.caret_blink_ms > 0 {
1592 let on = ((frame_time_ms / style.caret_blink_ms) % 2) == 0;
1593 if on {
1594 let caret_x = (baseline_x + layout_handle.caret_x_at(caret_in_display)).round();
1595 ctx.push_overlay(DrawCmd::Rect(DrawRect {
1596 rect: Rect::new(caret_x, y_top, style.caret_w, px + 2.0),
1597 color: style.caret,
1598 }));
1599 }
1600 }
1601 });
1602}
1603
1604trait RectExt {
1606 fn size(self) -> Size;
1608}
1609
1610impl RectExt for Rect {
1611 fn size(self) -> Size {
1612 Size::new(self.w, self.h)
1613 }
1614}
1615
1616#[cfg(test)]
1617mod tests {
1618 use std::cell::RefCell;
1621
1622 use super::*;
1623 use ailloli_ui_core::Size;
1624 use ailloli_ui_text::{TextLayoutParams, TextSystem, WrapMode};
1625
1626 fn signal<T: 'static>(value: T) -> Signal<T> {
1628 Signal::new(Rc::new(RefCell::new(value)), Rc::new(|| {}))
1629 }
1630
1631 #[test]
1632 fn command_palette_query_paint_skips_a_mismatched_committed_artifact() {
1633 let value = signal("fresh".to_string());
1634 let buffer = signal(TextBuffer::from_string("fresh".to_string()));
1635 let edit = signal(edit_at_end("fresh"));
1636 let style = TextInputStyle::default();
1637 let mut text_system = TextSystem::new();
1638 let stale = text_system.layout_cached(TextLayoutParams {
1639 text: "stale",
1640 style: style.text,
1641 max_width: Some(200.0),
1642 wrap_mode: WrapMode::NoWrap,
1643 });
1644 let layout = LayoutResult {
1645 size: Size::new(200.0, 40.0),
1646 children: Vec::new(),
1647 paint_bounds: Rect::new(0.0, 0.0, 200.0, 40.0),
1648 visual_bounds: Rect::new(0.0, 0.0, 200.0, 40.0),
1649 overlay_hit_bounds: Vec::new(),
1650 clip: None,
1651 is_window_root_clip: false,
1652 artifact: Some(LayoutArtifact::Text(stale)),
1653 };
1654 let mut paint = PaintCtx::with_text_system(&mut text_system);
1655
1656 paint_overlay_single_line_text(
1657 &mut paint,
1658 Rect::new(0.0, 0.0, 200.0, 40.0),
1659 &layout,
1660 &value,
1661 &buffer,
1662 &edit,
1663 None,
1664 style,
1665 true,
1666 );
1667
1668 assert!(paint.overlay_layers.iter().all(|layer| {
1669 layer
1670 .cmds
1671 .iter()
1672 .all(|cmd| !matches!(cmd, DrawCmd::Text(_)))
1673 }));
1674 }
1675}