gpui-deck 0.0.1

Headless GPUI primitives with application-owned presentation.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
//! Searchable actions composed from the existing text input and GPUI scrolling.
//! GPUI Deck owns matching and the highlighted action; applications own the
//! surrounding surface, item presentation, and the action's effects.

use gpui::{
    AnyElement, App, AppContext as _, Bounds, Context, ElementId, Entity, EntityId,
    EntityInputHandler as _, EventEmitter, FocusHandle, Focusable as _, InteractiveElement,
    Interactivity, IntoElement, MouseButton, ParentElement, Pixels, RenderOnce, Role, ScrollHandle,
    SharedString, StatefulInteractiveElement, StyleRefinement, Styled, Subscription, Window, div,
    prelude::FluentBuilder as _, px,
};

use crate::{
    ElementExt as _, Input, InputAccessibility, InputBase, InputState, InputStyles,
    TestSupportExt as _,
    a11y_disabled::A11yDisabledExt as _,
    input::{InputEvent, MoveDown, MoveUp},
};

/// One value, label, and searchable aliases in a fixed collection. Values must be unique.
#[derive(Clone, Debug)]
pub struct SearchItem {
    value: SharedString,
    label: SharedString,
    search_text: String,
    disabled: bool,
    group: Option<SharedString>,
}

impl SearchItem {
    pub fn new(value: impl Into<SharedString>, label: impl Into<SharedString>) -> Self {
        let value = value.into();
        let label = label.into();
        Self {
            search_text: format!("{value} {label}").to_lowercase(),
            value,
            label,
            disabled: false,
            group: None,
        }
    }

    /// Adds searchable aliases without changing the visible or accessible label.
    pub fn keywords<S: AsRef<str>>(mut self, keywords: impl IntoIterator<Item = S>) -> Self {
        for keyword in keywords {
            self.search_text.push(' ');
            self.search_text.push_str(&keyword.as_ref().to_lowercase());
        }
        self
    }

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

    /// Names the result group. Group labels do not change matching or item order.
    pub fn group(mut self, label: impl Into<SharedString>) -> Self {
        self.group = Some(label.into());
        self
    }

    pub fn group_label(&self) -> Option<&SharedString> {
        self.group.as_ref()
    }

    pub fn value(&self) -> &SharedString {
        &self.value
    }

    pub fn label(&self) -> &SharedString {
        &self.label
    }

    pub fn is_disabled(&self) -> bool {
        self.disabled
    }
}

fn collect_items(items: impl IntoIterator<Item = SearchItem>) -> Vec<SearchItem> {
    let items: Vec<_> = items.into_iter().collect();
    for (index, item) in items.iter().enumerate() {
        assert!(
            items[..index].iter().all(|other| other.value != item.value),
            "SearchItem values must be unique"
        );
        if index > 0 && items[index - 1].group != item.group {
            assert!(
                items[..index].iter().all(|other| other.group != item.group),
                "SearchItem groups must be contiguous"
            );
        }
    }
    items
}

/// Ranks one lowercase query term against an item's lowercase search text, or
/// `None` when the term's characters do not appear in order. A match at a word
/// start ranks above any other substring, which ranks above a subsequence; a
/// tighter subsequence ranks above a looser one.
fn term_score(text: &str, term: &str) -> Option<u32> {
    if term.is_empty() {
        return Some(0);
    }
    let mut substring = None;
    for (start, _) in text.match_indices(term) {
        let word_start = text[..start]
            .chars()
            .next_back()
            .is_none_or(|previous| !previous.is_alphanumeric());
        if word_start {
            return Some(300);
        }
        substring = Some(200);
    }
    if substring.is_some() {
        return substring;
    }
    let length = term.chars().count();
    // The shortest window containing the term's characters in order.
    let chars: Vec<char> = text.chars().collect();
    let pattern: Vec<char> = term.chars().collect();
    let mut shortest: Option<usize> = None;
    for start in 0..chars.len() {
        if chars[start] != pattern[0] {
            continue;
        }
        let mut matched = 1;
        let mut end = start;
        while matched < pattern.len() {
            end += 1;
            if end >= chars.len() {
                break;
            }
            if chars[end] == pattern[matched] {
                matched += 1;
            }
        }
        if matched == pattern.len() {
            let span = end - start + 1;
            shortest = Some(shortest.map_or(span, |current| current.min(span)));
        }
    }
    shortest.map(|span| 1 + (99 * length / span) as u32)
}

/// An explicit command activation. The application decides what it does.
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum CommandEvent {
    Action(SharedString),
}

/// A query input and its fixed collection of searchable actions in one window.
///
/// InputState is the query's source of truth. The characters of each
/// whitespace-separated query term must appear in order, case-insensitively, in
/// the value, label, or keywords. Results rank word-start matches above other
/// substrings and those above looser in-order matches, summed over terms. Groups
/// stay contiguous, ordered by their best result; equal scores and an empty
/// query keep collection order.
/// Query changes highlight the first enabled result. Arrows move that highlight
/// without committing a value, and Enter or a pointer click emits an action.
///
/// Keep this entity in the application and observe it to render its results.
/// The command has no open/close lifecycle; compose it inside Dialog when needed.
pub struct CommandState {
    items: Vec<SearchItem>,
    input: Entity<InputState>,
    focus: FocusHandle,
    // Only the last text processed by the derived filter, never a second value.
    filtered_query: SharedString,
    visible: Vec<usize>,
    // Inverse of the ranked result order, indexed by the source item.
    visible_positions: Vec<Option<usize>>,
    highlighted: Option<usize>,
    scroll: ScrollHandle,
    option_bounds: Vec<Option<Bounds<Pixels>>>,
    _input_observation: Subscription,
    _input_events: Subscription,
}

impl CommandState {
    pub fn new(
        items: impl IntoIterator<Item = SearchItem>,
        window: &mut Window,
        cx: &mut Context<Self>,
    ) -> Self {
        let items = collect_items(items);
        let input = cx.new(|cx| InputState::new(window, cx).placeholder("Search commands..."));
        let focus = input.focus_handle(cx);
        let input_observation = cx.observe(&input, |state, _, cx| {
            state.sync_query(cx);
            // Focus and disabled changes also affect the application-owned frame.
            cx.notify();
        });
        let input_events = cx.subscribe_in(&input, window, |state, _, event, window, cx| {
            if matches!(
                event,
                InputEvent::PressEnter {
                    secondary: false,
                    shift: false
                }
            ) && state.focus.is_focused(window)
            {
                state.activate_highlighted(window, cx);
            }
        });
        Self {
            option_bounds: vec![None; items.len()],
            visible: (0..items.len()).collect(),
            visible_positions: (0..items.len()).map(Some).collect(),
            highlighted: items.iter().position(|item| !item.disabled),
            items,
            input,
            focus,
            filtered_query: SharedString::default(),
            scroll: ScrollHandle::new(),
            _input_observation: input_observation,
            _input_events: input_events,
        }
    }

    /// The native query input, also available for application text styling.
    pub fn input(&self) -> &Entity<InputState> {
        &self.input
    }

    /// The only ordinary Tab stop supplied by this component.
    pub fn focus_handle(&self) -> &FocusHandle {
        &self.focus
    }

    pub fn items(&self) -> &[SearchItem] {
        &self.items
    }

    /// Replaces available actions and refilters the existing native query without
    /// changing input focus, selection, composition, or editing history.
    /// Keeps the highlighted value when it remains enabled and visible.
    pub fn set_items(
        &mut self,
        items: impl IntoIterator<Item = SearchItem>,
        window: &mut Window,
        cx: &mut Context<Self>,
    ) {
        let highlighted = self
            .highlighted
            .map(|index| self.items[index].value.clone());
        let items = collect_items(items);
        self.option_bounds = vec![None; items.len()];
        self.items = items;
        self.filter_query(self.input.read(cx).value());
        if let Some(value) = highlighted {
            self.highlighted = self
                .visible
                .iter()
                .copied()
                .find(|&index| !self.items[index].disabled && self.items[index].value == value)
                .or(self.highlighted);
        }
        cx.notify();
        window.refresh();
    }

    /// Original item indices in display order, including matching disabled items.
    pub fn visible_indices(&self) -> &[usize] {
        &self.visible
    }

    /// Nonempty named groups in first-result order. Render each group's options
    /// in [`Self::visible_group_indices`] order; ungrouped options use None.
    pub fn visible_groups(&self) -> Vec<SharedString> {
        let mut groups = Vec::new();
        for &index in &self.visible {
            if let Some(group) = &self.items[index].group
                && !groups.contains(group)
            {
                groups.push(group.clone());
            }
        }
        groups
    }

    pub fn visible_group_indices(&self, group: Option<&str>) -> Vec<usize> {
        self.visible
            .iter()
            .copied()
            .filter(|&index| self.items[index].group.as_deref() == group)
            .collect()
    }

    pub fn highlighted_index(&self) -> Option<usize> {
        self.highlighted
    }

    /// Changes the native input and immediately refreshes its derived results.
    /// Like InputState::set_value, this resets the query's editing history.
    pub fn set_query(
        &mut self,
        query: impl Into<SharedString>,
        window: &mut Window,
        cx: &mut Context<Self>,
    ) {
        let query: SharedString = query.into();
        self.input.update(cx, |input, cx| {
            input.set_value(query.to_string(), window, cx)
        });
        self.sync_query(cx);
        cx.notify();
    }

    pub(crate) fn activate_highlighted(&mut self, window: &mut Window, cx: &mut Context<Self>) {
        self.sync_query(cx);
        if let Some(index) = self.highlighted {
            self.activate(index, window, cx);
        }
    }

    pub(crate) fn sync_query(&mut self, cx: &mut Context<Self>) {
        let query = self.input.read(cx).value();
        if query == self.filtered_query {
            return;
        }
        self.filter_query(query);
    }

    fn filter_query(&mut self, query: SharedString) {
        let terms: Vec<_> = query.split_whitespace().map(str::to_lowercase).collect();
        let scored: Vec<(usize, u32)> = self
            .items
            .iter()
            .enumerate()
            .filter_map(|(index, item)| {
                terms
                    .iter()
                    .map(|term| term_score(&item.search_text, term))
                    .sum::<Option<u32>>()
                    .map(|score| (index, score))
            })
            .collect();
        // Groups stay contiguous: they order by their best item, and items by
        // score within their group. Equal scores keep collection order.
        let best = |group: &Option<SharedString>| {
            scored
                .iter()
                .filter(|(index, _)| &self.items[*index].group == group)
                .map(|(_, score)| *score)
                .max()
                .unwrap_or(0)
        };
        let mut ranked: Vec<(u32, usize, u32, usize)> = scored
            .iter()
            .map(|&(index, score)| {
                let group = &self.items[index].group;
                let first = self
                    .items
                    .iter()
                    .position(|item| &item.group == group)
                    .unwrap_or(index);
                (best(group), first, score, index)
            })
            .collect();
        ranked.sort_by(|a, b| {
            b.0.cmp(&a.0)
                .then(a.1.cmp(&b.1))
                .then(b.2.cmp(&a.2))
                .then(a.3.cmp(&b.3))
        });
        self.visible = ranked.into_iter().map(|(_, _, _, index)| index).collect();
        self.visible_positions.clear();
        self.visible_positions.resize(self.items.len(), None);
        for (position, &index) in self.visible.iter().enumerate() {
            self.visible_positions[index] = Some(position);
        }
        self.highlighted = self
            .visible
            .iter()
            .copied()
            .find(|&index| !self.items[index].disabled);
        self.filtered_query = query;
        self.option_bounds.fill(None);
        self.scroll.set_offset(Default::default());
        self.scroll_to_highlight();
    }

    pub(crate) fn is_composing(&self, window: &mut Window, cx: &mut Context<Self>) -> bool {
        self.input.update(cx, |input, cx| {
            input.marked_text_range(window, cx).is_some()
        })
    }

    fn visible_position(&self, index: usize) -> Option<usize> {
        self.visible_positions.get(index).copied().flatten()
    }

    fn scroll_to_highlight(&self) {
        let Some(bounds) = self.highlighted.and_then(|index| self.option_bounds[index]) else {
            return;
        };
        let viewport = self.scroll.bounds();
        let mut offset = self.scroll.offset();
        // Bounds are stored without the viewport's scroll offset, so nested
        // group wrappers do not change which exact option must be revealed.
        let top = bounds.top() + offset.y;
        let bottom = bounds.bottom() + offset.y;
        if top < viewport.top() {
            offset.y += viewport.top() - top;
        } else if bottom > viewport.bottom() {
            offset.y -= bottom - viewport.bottom();
        }
        offset.y = offset.y.clamp(-self.scroll.max_offset().y, px(0.));
        self.scroll.set_offset(offset);
    }

    pub(crate) fn move_cursor(
        &mut self,
        forward: bool,
        window: &mut Window,
        cx: &mut Context<Self>,
    ) {
        if !self.focus.is_focused(window)
            || self.input.read(cx).presentation().is_disabled()
            || self.is_composing(window, cx)
        {
            cx.propagate();
            return;
        }
        self.sync_query(cx);
        let count = self.visible.len();
        if count == 0 {
            return;
        }
        let start = self
            .highlighted
            .and_then(|index| self.visible_position(index))
            .unwrap_or(if forward { count - 1 } else { 0 });
        for distance in 1..=count {
            let position = if forward {
                (start + distance) % count
            } else {
                (start + count - distance) % count
            };
            let index = self.visible[position];
            if !self.items[index].disabled {
                self.highlight(index, window, cx);
                break;
            }
        }
    }

    pub(crate) fn highlight(&mut self, index: usize, window: &mut Window, cx: &mut Context<Self>) {
        if self.highlighted == Some(index)
            || self.visible_position(index).is_none()
            || self.items[index].disabled
            || self.input.read(cx).presentation().is_disabled()
            || self.is_composing(window, cx)
        {
            return;
        }
        self.highlighted = Some(index);
        self.scroll_to_highlight();
        cx.notify();
        window.refresh();
    }

    fn activate(&mut self, index: usize, window: &mut Window, cx: &mut Context<Self>) {
        if self.visible_position(index).is_none()
            || self.items[index].disabled
            || self.input.read(cx).presentation().is_disabled()
            || self.is_composing(window, cx)
        {
            return;
        }
        self.highlight(index, window, cx);
        self.focus.focus(window, cx);
        cx.emit(CommandEvent::Action(self.items[index].value.clone()));
    }
}

impl EventEmitter<CommandEvent> for CommandState {}

/// An unstyled command root containing a query input and a result list.
///
/// Only Input's unmodified Up/Down actions move the command cursor. Home/End,
/// Space, selection, clipboard, and IME input remain owned by the text engine.
#[derive(IntoElement)]
pub struct Command {
    base: crate::ObservedElement<gpui::Stateful<gpui::Div>>,
    state: Entity<CommandState>,
    label: Option<SharedString>,
}

impl Command {
    pub fn new(id: impl Into<ElementId>, state: &Entity<CommandState>) -> Self {
        Self {
            base: div().id(id).test_support(),
            state: state.clone(),
            label: None,
        }
    }

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

impl Styled for Command {
    fn style(&mut self) -> &mut StyleRefinement {
        self.base.style()
    }
}

impl ParentElement for Command {
    fn extend(&mut self, elements: impl IntoIterator<Item = AnyElement>) {
        self.base.extend(elements);
    }
}

impl InteractiveElement for Command {
    fn interactivity(&mut self) -> &mut Interactivity {
        self.base.interactivity()
    }
}

impl StatefulInteractiveElement for Command {}

impl RenderOnce for Command {
    fn render(self, _: &mut Window, _: &mut App) -> impl IntoElement {
        let up = self.state.clone();
        let down = self.state;
        self.base
            .role(Role::Group)
            .when_some(self.label, |this, label| this.aria_label(label))
            .on_action(move |_: &MoveUp, window, cx| {
                up.update(cx, |state, cx| state.move_cursor(false, window, cx));
            })
            .on_action(move |_: &MoveDown, window, cx| {
                down.update(cx, |state, cx| state.move_cursor(true, window, cx));
            })
    }
}

/// The query's application-styled InputBase frame and existing native Input.
#[derive(IntoElement)]
pub struct CommandInput {
    base: InputBase,
    state: Entity<CommandState>,
    label: Option<SharedString>,
    placeholder: SharedString,
}

impl CommandInput {
    pub fn new(id: impl Into<ElementId>, state: &Entity<CommandState>) -> Self {
        Self {
            base: InputBase::new(id).role(None::<Role>),
            state: state.clone(),
            label: None,
            placeholder: "Search commands...".into(),
        }
    }

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

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

    pub fn styles(mut self, build: impl FnOnce(InputStyles) -> InputStyles) -> Self {
        self.base = self.base.styles(build);
        self
    }
}

impl Styled for CommandInput {
    fn style(&mut self) -> &mut StyleRefinement {
        self.base.style()
    }
}

impl InteractiveElement for CommandInput {
    fn interactivity(&mut self) -> &mut Interactivity {
        self.base.interactivity()
    }
}

impl StatefulInteractiveElement for CommandInput {}

impl RenderOnce for CommandInput {
    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
        let input = self.state.read(cx).input.clone();
        input.update(cx, |input, cx| {
            if input.presentation().placeholder() != &self.placeholder {
                input.set_placeholder(self.placeholder.clone(), window, cx);
            }
            let accessibility = input
                .accessibility()
                .cloned()
                .unwrap_or_else(|| InputAccessibility::new(Some(Role::TextInput)));
            let label = self
                .label
                .or_else(|| accessibility.label().cloned())
                .unwrap_or_else(|| "Search commands".into());
            input.set_accessibility(
                accessibility
                    .with_role(Some(Role::TextInput))
                    .with_label(Some(label))
                    .with_placeholder(Some(self.placeholder)),
            );
        });
        let presentation = input.read(cx).presentation();
        self.base
            .semantic_owner::<Input>(input.entity_id())
            .focused(presentation.focus_handle().is_focused(window))
            .disabled(presentation.is_disabled())
            .child(Input::new(&input))
    }
}

/// A named, vertically scrolling result list with no independent Tab stop.
///
/// Render CommandOption children for `visible_indices()` in that exact order,
/// optionally inside CommandGroup wrappers. Keep extra controls and empty-result
/// text outside this list; group headings never participate in navigation.
/// Applications supply its height limit, spacing, and item presentation.
#[derive(IntoElement)]
pub struct CommandList {
    base: crate::ObservedElement<gpui::Stateful<gpui::Div>>,
    state: Entity<CommandState>,
    label: Option<SharedString>,
    multiple: bool,
}

impl CommandList {
    pub fn new(id: impl Into<ElementId>, state: &Entity<CommandState>) -> Self {
        Self {
            base: div().id(id).test_support().flex().flex_col().min_h_0(),
            state: state.clone(),
            label: None,
            multiple: false,
        }
    }

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

    pub(crate) fn from_base(
        base: crate::ObservedElement<gpui::Stateful<gpui::Div>>,
        state: &Entity<CommandState>,
        label: Option<SharedString>,
        multiple: bool,
    ) -> Self {
        Self {
            base,
            state: state.clone(),
            label,
            multiple,
        }
    }
}

impl Styled for CommandList {
    fn style(&mut self) -> &mut StyleRefinement {
        self.base.style()
    }
}

impl ParentElement for CommandList {
    fn extend(&mut self, elements: impl IntoIterator<Item = AnyElement>) {
        self.base.extend(elements);
    }
}

impl InteractiveElement for CommandList {
    fn interactivity(&mut self) -> &mut Interactivity {
        self.base.interactivity()
    }
}

impl StatefulInteractiveElement for CommandList {}

impl RenderOnce for CommandList {
    fn render(self, _: &mut Window, cx: &mut App) -> impl IntoElement {
        self.base
            .role(Role::ListBox)
            .when_some(self.label, |this, label| this.aria_label(label))
            .overflow_y_scroll()
            .track_scroll(&self.state.read(cx).scroll)
            .a11y_selection(false, self.multiple)
    }
}

/// A named, non-focusable result group with an application-styled heading.
/// Render only the matching [`CommandState::visible_group_indices`] options.
/// A group without visible matching items contributes no layout or native nodes.
#[derive(IntoElement)]
pub struct CommandGroup {
    base: crate::ObservedElement<gpui::Stateful<gpui::Div>>,
    state: Entity<CommandState>,
    label: SharedString,
    heading: gpui::Div,
    children: Vec<AnyElement>,
}

impl CommandGroup {
    pub fn new(
        id: impl Into<ElementId>,
        state: &Entity<CommandState>,
        label: impl Into<SharedString>,
    ) -> Self {
        let id = id.into();
        let label = label.into();
        Self::from_base(
            div().id(id).test_support(),
            state,
            label.clone(),
            div().child(label),
        )
    }

    pub(crate) fn from_base(
        base: crate::ObservedElement<gpui::Stateful<gpui::Div>>,
        state: &Entity<CommandState>,
        label: SharedString,
        heading: gpui::Div,
    ) -> Self {
        Self {
            base,
            state: state.clone(),
            label,
            heading,
            children: Vec::new(),
        }
    }

    pub fn heading(mut self, build: impl FnOnce(gpui::Div) -> gpui::Div) -> Self {
        self.heading = build(self.heading);
        self
    }
}

impl Styled for CommandGroup {
    fn style(&mut self) -> &mut StyleRefinement {
        self.base.style()
    }
}

impl ParentElement for CommandGroup {
    fn extend(&mut self, elements: impl IntoIterator<Item = AnyElement>) {
        self.children.extend(elements);
    }
}

impl RenderOnce for CommandGroup {
    fn render(self, _: &mut Window, cx: &mut App) -> impl IntoElement {
        if self
            .state
            .read(cx)
            .visible_group_indices(Some(&self.label))
            .is_empty()
        {
            return gpui::Empty.into_any_element();
        }
        // The heading precedes options while the group's accessible name stays
        // independent of its decorative presentation.
        self.base
            .role(Role::Group)
            .aria_label(self.label.clone())
            .flex()
            .flex_col()
            .flex_shrink_0()
            .child(
                self.heading
                    .id("heading")
                    .test_support()
                    .role(Role::Heading)
                    .aria_level(3)
                    .aria_label(self.label),
            )
            .children(self.children)
            .into_any_element()
    }
}

fn option_id(state: EntityId, index: usize) -> ElementId {
    (
        ElementId::from(("command-option", state)),
        index.to_string(),
    )
        .into()
}

/// One action row. The native text input keeps keyboard focus during navigation.
///
/// The highlighted row exposes selected metadata but is not a committed value.
/// The pinned GPUI API cannot link an input to a sibling list's active descendant;
/// this component does not claim that unsupported relationship.
#[derive(IntoElement)]
pub struct CommandOption {
    base: crate::ObservedElement<gpui::Stateful<gpui::Div>>,
    state: Entity<CommandState>,
    index: usize,
    selected: Option<bool>,
}

impl CommandOption {
    pub fn new(state: &Entity<CommandState>, index: usize) -> Self {
        Self {
            base: div()
                .id(option_id(state.entity_id(), index))
                .test_support()
                .flex_shrink_0(),
            state: state.clone(),
            index,
            selected: None,
        }
    }

    pub(crate) fn from_base(
        base: crate::ObservedElement<gpui::Stateful<gpui::Div>>,
        state: &Entity<CommandState>,
        index: usize,
        selected: bool,
    ) -> Self {
        Self {
            base,
            state: state.clone(),
            index,
            selected: Some(selected),
        }
    }
}

impl Styled for CommandOption {
    fn style(&mut self) -> &mut StyleRefinement {
        self.base.style()
    }
}

impl ParentElement for CommandOption {
    fn extend(&mut self, elements: impl IntoIterator<Item = AnyElement>) {
        self.base.extend(elements);
    }
}

impl InteractiveElement for CommandOption {
    fn interactivity(&mut self) -> &mut Interactivity {
        self.base.interactivity()
    }
}

impl StatefulInteractiveElement for CommandOption {}

impl RenderOnce for CommandOption {
    fn render(self, _: &mut Window, cx: &mut App) -> impl IntoElement {
        let state = self.state.read(cx);
        let item = state
            .items
            .get(self.index)
            .expect("CommandOption index must identify an item");
        if state.visible_position(self.index).is_none() {
            return gpui::Empty.into_any_element();
        }
        let disabled = item.disabled || state.input.read(cx).presentation().is_disabled();
        let selected = self
            .selected
            .unwrap_or(state.highlighted == Some(self.index));
        let label = item.label.clone();
        let index = self.index;
        let focus = state.focus.clone();
        let hover = self.state.clone();
        let activate = self.state;
        let geometry = activate.clone();
        self.base
            .role(Role::ListBoxOption)
            .aria_label(label)
            .aria_selected(selected)
            .on_mouse_down(MouseButton::Left, move |_, window, cx| {
                cx.stop_propagation();
                if !disabled {
                    focus.focus(window, cx);
                }
            })
            .when(!disabled, |this| {
                this.on_hover(move |hovered, window, cx| {
                    if *hovered {
                        hover.update(cx, |state, cx| state.highlight(index, window, cx));
                    }
                })
                .on_click(move |_, window, cx| {
                    activate.update(cx, |state, cx| state.activate(index, window, cx));
                })
            })
            .on_prepaint(move |bounds, window, cx| {
                geometry.update(cx, |state, _| {
                    let first = state.option_bounds[index].is_none();
                    state.option_bounds[index] = Some(Bounds::new(
                        bounds.origin - state.scroll.offset(),
                        bounds.size,
                    ));
                    if first && state.highlighted == Some(index) {
                        let previous = state.scroll.offset();
                        state.scroll_to_highlight();
                        if state.scroll.offset() != previous {
                            window.request_animation_frame();
                        }
                    }
                });
            })
            .a11y_disabled(disabled)
            .into_any_element()
    }
}

#[cfg(test)]
mod tests {
    use std::{cell::RefCell, rc::Rc};

    use gpui::{
        KeyDownEvent, KeyUpEvent, Keystroke, Modifiers, Render, TestAppContext, VisualTestContext,
        px,
    };

    use super::*;
    use crate::{Button, Root};

    struct Harness {
        command: Entity<CommandState>,
        after: FocusHandle,
        _observation: Subscription,
    }

    impl Render for Harness {
        fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
            let state = self.command.read(cx);
            div()
                .w(px(320.))
                .flex()
                .flex_col()
                .child(
                    Command::new("commands", &self.command)
                        .accessibility_label("Session commands")
                        .flex()
                        .flex_col()
                        .child(CommandInput::new("query", &self.command).h(px(32.)))
                        .child(
                            CommandList::new("results", &self.command)
                                .accessibility_label("Results")
                                .h(px(64.))
                                .children(state.visible_indices().iter().map(|&index| {
                                    CommandOption::new(&self.command, index)
                                        .debug_selector(move || format!("option-{index}").into())
                                        .h(px(32.))
                                        .child(state.items()[index].label().clone())
                                })),
                        ),
                )
                .child(
                    Button::new("after")
                        .track_focus(&self.after)
                        .h(px(32.))
                        .child("After"),
                )
        }
    }

    type Actions = Rc<RefCell<Vec<SharedString>>>;

    fn items() -> Vec<SearchItem> {
        vec![
            SearchItem::new("edit", "Edit session").keywords(["preferences", "settings"]),
            SearchItem::new("share", "Share").disabled(true),
            SearchItem::new("cursor", "Toggle cursor").keywords(["pointer"]),
            SearchItem::new("toolbar", "Toggle toolbar pin"),
            SearchItem::new("notes", "메모").keywords(["memo"]),
        ]
    }

    fn harness(
        cx: &mut TestAppContext,
        items: Vec<SearchItem>,
    ) -> (&mut VisualTestContext, Entity<Harness>, Actions) {
        cx.update(crate::init);
        let (root, cx) = cx.add_window_view(move |window, cx| {
            let view = cx.new(|cx| {
                let command = cx.new(|cx| CommandState::new(items, window, cx));
                let observation = cx.observe(&command, |_, _, cx| cx.notify());
                Harness {
                    command,
                    after: cx.focus_handle(),
                    _observation: observation,
                }
            });
            Root::new(view, window, cx)
        });
        let view = root
            .read_with(cx, |root, _| root.view().clone())
            .downcast::<Harness>()
            .unwrap();
        let actions = Rc::new(RefCell::new(Vec::new()));
        cx.update(|window, cx| {
            let command = view.read(cx).command.clone();
            let actions = actions.clone();
            cx.subscribe(&command, move |_, event: &CommandEvent, _| {
                let CommandEvent::Action(value) = event;
                actions.borrow_mut().push(value.clone());
            })
            .detach();
            window.activate_window();
            let focus = command.read(cx).focus_handle().clone();
            focus.focus(window, cx);
            window.draw(cx).clear(cx);
        });
        cx.run_until_parked();
        (cx, view, actions)
    }

    fn draw(cx: &mut VisualTestContext) {
        cx.update(|window, cx| window.draw(cx).clear(cx));
    }

    fn press(cx: &mut VisualTestContext, key: &str) {
        let keystroke =
            cx.update(|_, cx| Keystroke::parse_with_os(key, cx.platform_info().os).unwrap());
        cx.simulate_event(KeyDownEvent {
            keystroke: keystroke.clone(),
            is_held: false,
            prefer_character_input: false,
        });
        cx.simulate_event(KeyUpEvent { keystroke });
        draw(cx);
    }

    fn set_query(cx: &mut VisualTestContext, view: &Entity<Harness>, query: &str) {
        cx.update(|window, cx| {
            let command = view.read(cx).command.clone();
            command.update(cx, |state, cx| {
                state.set_query(query.to_owned(), window, cx)
            });
        });
        draw(cx);
    }

    #[gpui::test]
    fn filtering_uses_native_query_and_keeps_plain_text_editing(cx: &mut TestAppContext) {
        let (cx, view, actions) = harness(cx, items());
        set_query(cx, &view, "  PREF session ");
        cx.update(|_, cx| {
            let state = view.read(cx).command.read(cx);
            assert_eq!(state.input().read(cx).value(), "  PREF session ");
            assert_eq!(state.visible_indices(), [0]);
            assert_eq!(state.highlighted_index(), Some(0));
        });
        // The filter also follows programmatic input changes, which emit no Change event.
        cx.update(|window, cx| {
            let input = view.read(cx).command.read(cx).input().clone();
            input.update(cx, |input, cx| input.set_value("pOIntER", window, cx));
        });
        draw(cx);
        cx.update(|_, cx| {
            assert_eq!(view.read(cx).command.read(cx).visible_indices(), [2]);
        });
        set_query(cx, &view, "");
        cx.simulate_input("Toggle");
        cx.simulate_input(" ");
        draw(cx);
        cx.update(|_, cx| {
            let state = view.read(cx).command.read(cx);
            assert_eq!(state.input().read(cx).value(), "Toggle ");
            assert_eq!(state.visible_indices(), [2, 3]);
            assert_eq!(state.highlighted_index(), Some(2));
        });
        cx.simulate_keystrokes("home");
        draw(cx);
        cx.update(|_, cx| {
            let state = view.read(cx).command.read(cx);
            assert_eq!(state.input().read(cx).selected_range(), 0..0);
            assert_eq!(state.highlighted_index(), Some(2));
        });
        cx.simulate_keystrokes("end");
        draw(cx);
        cx.update(|_, cx| {
            assert_eq!(
                view.read(cx)
                    .command
                    .read(cx)
                    .input()
                    .read(cx)
                    .selected_range(),
                7..7,
            );
        });
        set_query(cx, &view, "no results");
        press(cx, "enter");
        cx.update(|_, cx| {
            let state = view.read(cx).command.read(cx);
            assert!(state.visible_indices().is_empty());
            assert_eq!(state.highlighted_index(), None);
        });
        set_query(cx, &view, "Share");
        press(cx, "enter");
        let first_option = cx.debug_bounds("option-1").unwrap().center();
        cx.simulate_click(first_option, Modifiers::default());
        draw(cx);
        cx.update(|window, cx| {
            let state = view.read(cx).command.read(cx);
            assert_eq!(state.visible_indices(), [1]);
            assert_eq!(state.highlighted_index(), None);
            assert!(state.focus_handle().is_focused(window));
            #[cfg(feature = "test-support")]
            {
                let input = crate::test_support::find(window, &[], &"query".into()).unwrap();
                assert_eq!(input.role(), Some(Role::TextInput));
                assert_eq!(input.label(), Some("Search commands"));
                assert_eq!(input.value(), Some("Share"));
                let option = crate::test_support::snapshots(window)
                    .into_iter()
                    .find(|item| item.role() == Some(Role::ListBoxOption))
                    .unwrap();
                assert_eq!(option.label(), Some("Share"));
                assert_eq!(option.disabled(), Some(true));
                assert_eq!(option.selected(), Some(false));
            }
        });
        assert!(actions.borrow().is_empty());
    }

    #[gpui::test]
    fn arrows_and_pointer_share_one_cursor_and_leave_the_input_focused(cx: &mut TestAppContext) {
        let (cx, view, actions) = harness(cx, items());
        cx.simulate_keystrokes("down");
        draw(cx);
        cx.update(|window, cx| {
            let state = view.read(cx).command.read(cx);
            assert_eq!(state.highlighted_index(), Some(2), "skip the disabled row");
            assert!(state.focus_handle().is_focused(window));
            assert!(
                state.scroll.offset().y < px(0.),
                "reveal an offscreen result"
            );
        });
        assert!(actions.borrow().is_empty());
        cx.simulate_keystrokes("up up");
        draw(cx);
        cx.update(|_, cx| {
            assert_eq!(view.read(cx).command.read(cx).highlighted_index(), Some(4));
        });
        let last_option = cx.debug_bounds("option-4").unwrap().center();
        cx.simulate_click(last_option, Modifiers::default());
        draw(cx);
        assert_eq!(*actions.borrow(), [SharedString::from("notes")]);
        press(cx, "enter");
        assert_eq!(
            *actions.borrow(),
            ["notes", "notes"].map(SharedString::from)
        );
        set_query(cx, &view, "Toggle");
        cx.simulate_keystrokes("down");
        draw(cx);
        press(cx, "enter");
        assert_eq!(
            *actions.borrow(),
            ["notes", "notes", "toolbar"].map(SharedString::from),
        );
        cx.update(|window, cx| {
            let state = view.read(cx).command.read(cx);
            assert!(state.focus_handle().is_focused(window));
            assert_eq!(state.input().read(cx).value(), "Toggle");
        });
        cx.simulate_keystrokes("tab");
        draw(cx);
        cx.update(|window, cx| assert!(view.read(cx).after.is_focused(window)));
    }

    #[gpui::test]
    fn marked_text_never_navigates_or_executes_a_command(cx: &mut TestAppContext) {
        let mut items = items();
        items.push(SearchItem::new("note-settings", "메모 설정"));
        let (cx, view, actions) = harness(cx, items);
        cx.update(|window, cx| {
            let input = view.read(cx).command.read(cx).input().clone();
            input.update(cx, |input, cx| {
                input.replace_and_mark_text_in_range(None, "메", Some(1..1), window, cx);
            });
        });
        draw(cx);
        cx.simulate_keystrokes("down");
        press(cx, "enter");
        cx.update(|window, cx| {
            let command = view.read(cx).command.clone();
            assert_eq!(command.read(cx).visible_indices(), [4, 5]);
            assert_eq!(command.read(cx).highlighted_index(), Some(4));
            let input = command.read(cx).input().clone();
            input.update(cx, |input, cx| {
                assert!(input.marked_text_range(window, cx).is_some());
                input.replace_text_in_range(None, "메모", window, cx);
            });
        });
        assert!(actions.borrow().is_empty());
        draw(cx);
        cx.simulate_keystrokes("down");
        press(cx, "enter");
        assert_eq!(*actions.borrow(), [SharedString::from("note-settings")]);
        cx.update(|window, cx| {
            let input = view.read(cx).command.read(cx).input().clone();
            input.update(cx, |input, cx| {
                assert!(input.marked_text_range(window, cx).is_none());
                assert_eq!(input.value(), "메모");
            });
        });
    }

    #[gpui::test]
    fn fuzzy_terms_rank_word_starts_and_keep_groups_contiguous(cx: &mut TestAppContext) {
        let (cx, view, actions) = harness(
            cx,
            vec![
                SearchItem::new("export", "Export recording").group("File"),
                SearchItem::new("report", "Send report").group("File"),
                SearchItem::new("present", "Present slides").group("View"),
                SearchItem::new("pointer", "Show pointer").group("View"),
            ],
        );
        let visible = |query: &str, cx: &mut VisualTestContext| {
            cx.update(|window, cx| {
                let command = view.read(cx).command.clone();
                command.update(cx, |state, cx| {
                    state.set_query(query.to_owned(), window, cx);
                    state.visible_indices().to_vec()
                })
            })
        };
        assert_eq!(visible("", cx), [0, 1, 2, 3], "an empty query keeps order");
        assert_eq!(
            visible("rep", cx),
            [1, 0, 2],
            "a word start ranks above in-order letters"
        );
        assert_eq!(
            visible("pnt", cx),
            [3, 2, 1],
            "tighter in-order matches rank first"
        );
        assert_eq!(
            visible("po", cx),
            [3, 0, 1],
            "the best group leads, kept contiguous"
        );
        cx.update(|_, cx| {
            let groups = view.read(cx).command.read(cx).visible_groups();
            assert_eq!(groups, ["View", "File"]);
            assert_eq!(view.read(cx).command.read(cx).highlighted_index(), Some(3));
        });
        draw(cx);
        press(cx, "enter");
        assert_eq!(*actions.borrow(), ["pointer"].map(SharedString::from));
        press(cx, "down");
        press(cx, "enter");
        let first = cx.debug_bounds("option-3").unwrap().center();
        cx.simulate_click(first, Modifiers::default());
        draw(cx);
        assert_eq!(
            *actions.borrow(),
            ["pointer", "export", "pointer"].map(SharedString::from)
        );
        assert_eq!(visible("re sl", cx), [2], "every term must match");
        assert!(visible("xyz", cx).is_empty());
    }
}