BlueGit

ict rusty-teams

Files

rusty-teams / vendor / gpui-component / src / input / search.rs

search.rs

search.rs 19.8 KiB Download Raw
1use ropey::Rope;
2use rust_i18n::t;
3use std::ops::Range;
4
5use gpui::{
6 App, AppContext as _, Context, Empty, Entity, FocusHandle, Focusable, Half,
7 InteractiveElement as _, IntoElement, ParentElement as _, Pixels, Render, Styled, Subscription,
8 WeakEntity, Window, actions, div, prelude::FluentBuilder as _,
9};
10
11use crate::{
12 ActiveTheme, Disableable, ElementExt, IconName, Selectable, Sizable,
13 button::{Button, ButtonVariants},
14 h_flex,
15 input::{
16 Enter, Escape, IndentInline, Input, InputBaseState, InputEvent, InputState, OutdentInline,
17 Replace,
18 },
19 label::Label,
20 v_flex,
21};
22
23const CONTEXT: &'static str = "SearchPanel";
24
25actions!(input, [Tab]);
26
27#[cfg(test)]
28use gpui_base::input::SearchMatcher;
29
30#[derive(Clone, Copy)]
31#[cfg(test)]
32enum MoveDirection {
33 Up,
34 Down,
35}
36
37#[cfg(test)]
38fn next_scroll_direction(
39 previous_match_ix: usize,
40 current_match_ix: usize,
41) -> Option<MoveDirection> {
42 if current_match_ix <= previous_match_ix {
43 None
44 } else {
45 Some(MoveDirection::Down)
46 }
47}
48
49#[cfg(test)]
50fn prev_scroll_direction(
51 previous_match_ix: usize,
52 current_match_ix: usize,
53) -> Option<MoveDirection> {
54 if current_match_ix >= previous_match_ix {
55 None
56 } else {
57 Some(MoveDirection::Up)
58 }
59}
60
61pub(super) struct SearchPanel<M: crate::input::overlay::OverlayMode> {
62 editor: WeakEntity<InputBaseState<M>>,
63 search_input: Entity<InputState>,
64 replace_input: Entity<InputState>,
65 session: gpui_base::input::SearchSession,
66 input_width: Pixels,
67
68 _subscriptions: Vec<Subscription>,
69}
70
71impl<M: crate::input::overlay::OverlayMode> SearchPanel<M> {
72 pub(super) fn replace_mode(&self) -> bool {
73 self.session.replace_mode
74 }
75
76 pub(super) fn sync_session(&mut self, session: &gpui_base::input::SearchSession) {
77 self.session = session.clone();
78 }
79
80 /// The query the panel's search input currently holds.
81 pub(super) fn query(&self, cx: &App) -> gpui::SharedString {
82 self.search_input.read(cx).value()
83 }
84
85 /// The panel's search input, so a test can assert what re-invoking search
86 /// does to its value and selection.
87 #[cfg(test)]
88 pub(super) fn search_input(&self) -> &Entity<InputState> {
89 &self.search_input
90 }
91
92 pub(crate) fn new(
93 editor: Entity<InputBaseState<M>>,
94 window: &mut Window,
95 cx: &mut App,
96 ) -> Entity<Self> {
97 let search_input = cx.new(|cx| InputState::new(window, cx));
98 let replace_input = cx.new(|cx| InputState::new(window, cx));
99
100 cx.new(|cx| {
101 let _subscriptions =
102 vec![
103 cx.subscribe(&search_input, |this: &mut Self, _, ev: &InputEvent, cx| {
104 // Handle search input changes
105 match ev {
106 InputEvent::Change => {
107 this.update_search_query(None, cx);
108 }
109 _ => {}
110 }
111 }),
112 ];
113
114 Self {
115 editor: editor.downgrade(),
116 search_input,
117 replace_input,
118 session: gpui_base::input::SearchSession::default(),
119 input_width: Pixels::ZERO,
120 _subscriptions,
121 }
122 })
123 }
124
125 pub(super) fn show_with_focus(
126 &mut self,
127 selected_text: &Rope,
128 replace_mode: bool,
129 visible_range_offset: Option<Range<usize>>,
130 focus: bool,
131 window: &mut Window,
132 cx: &mut Context<Self>,
133 ) {
134 self.session.open = true;
135 self.session.replace_mode = replace_mode;
136 if focus {
137 self.search_input
138 .update(cx, |input, cx| input.focus(window, cx));
139 }
140
141 self.search_input.update(cx, |this, cx| {
142 if selected_text.len() > 0 {
143 this.set_value(selected_text.to_string(), window, cx);
144 }
145 this.select_all(window, cx);
146 });
147
148 // The `set_value` does not emit `InputEvent::Change`, so update the query
149 // here to match the value of the search input.
150 self.update_search_query(visible_range_offset, cx);
151 }
152
153 /// Update the matcher by the value of the search input.
154 ///
155 /// The `visible_range_offset` is to select the nearest match of the visible range,
156 /// it is passed in, because the editor may be borrowed by the caller.
157 fn update_search_query(
158 &mut self,
159 visible_range_offset: Option<Range<usize>>,
160 cx: &mut Context<Self>,
161 ) {
162 let query = self.search_input.read(cx).value();
163 let editor = self.editor.clone();
164 let _ = editor.update(cx, |state, cx| {
165 state.set_search_query(query.clone(), self.session.case_insensitive, cx);
166 });
167 if let Ok(session) = editor.read_with(cx, |state, _| state.search_session().clone()) {
168 self.session = session;
169 }
170 if let Some(visible_range_offset) = visible_range_offset {
171 self.session
172 .matcher
173 .update_cursor_by_offset(visible_range_offset.start);
174 }
175 cx.notify();
176 }
177
178 fn replaceable(&self, cx: &App) -> bool {
179 self.editor
180 .read_with(cx, |editor, _| editor.is_replaceable())
181 .unwrap_or(false)
182 }
183
184 pub(super) fn hide(&mut self, window: &mut Window, cx: &mut Context<Self>) {
185 self.hide_with_focus(true, window, cx);
186 }
187
188 pub(super) fn hide_with_focus(
189 &mut self,
190 focus_editor: bool,
191 window: &mut Window,
192 cx: &mut Context<Self>,
193 ) {
194 self.session.open = false;
195 let _ = self.editor.update(cx, |state, cx| {
196 state.close_search(cx);
197 if focus_editor {
198 state.focus(window, cx);
199 }
200 });
201 cx.notify();
202 }
203
204 fn on_action_enter(&mut self, action: &Enter, window: &mut Window, cx: &mut Context<Self>) {
205 if action.shift {
206 self.prev(window, cx);
207 } else {
208 self.next(window, cx);
209 }
210 }
211
212 fn on_action_escape(&mut self, _: &Escape, window: &mut Window, cx: &mut Context<Self>) {
213 self.hide(window, cx);
214 }
215
216 fn on_action_tab(&mut self, _: &IndentInline, window: &mut Window, cx: &mut Context<Self>) {
217 self.cycle_focus(window, cx);
218 }
219
220 fn on_action_tab_prev(
221 &mut self,
222 _: &OutdentInline,
223 window: &mut Window,
224 cx: &mut Context<Self>,
225 ) {
226 self.cycle_focus(window, cx);
227 }
228
229 /// Cycle focus between the search and the replace input, to keep the Tab key
230 /// staying in the panel.
231 ///
232 /// There are only 2 inputs, so the forward and the backward are the same.
233 fn cycle_focus(&mut self, window: &mut Window, cx: &mut Context<Self>) {
234 if !self.session.replace_mode || !self.replaceable(cx) {
235 return;
236 }
237
238 let search_focus_handle = self.search_input.read(cx).focus_handle(cx);
239 let focus_handle = if search_focus_handle.is_focused(window) {
240 self.replace_input.read(cx).focus_handle(cx)
241 } else {
242 search_focus_handle
243 };
244 focus_handle.focus(window, cx);
245 }
246
247 fn on_action_replace(&mut self, _: &Replace, window: &mut Window, cx: &mut Context<Self>) {
248 self.toggle_replace_mode(window, cx);
249 }
250
251 /// Toggle the replace field, and move focus to the field that is going to be used.
252 fn toggle_replace_mode(&mut self, window: &mut Window, cx: &mut Context<Self>) {
253 if !self.replaceable(cx) {
254 return;
255 }
256
257 self.session.replace_mode = !self.session.replace_mode;
258 let replace_mode = self.session.replace_mode;
259 let _ = self.editor.update(cx, |state, cx| {
260 state.set_search_replace_mode(replace_mode, cx);
261 });
262 let focus_handle = if self.session.replace_mode {
263 self.replace_input.read(cx).focus_handle(cx)
264 } else {
265 self.search_input.read(cx).focus_handle(cx)
266 };
267 focus_handle.focus(window, cx);
268 cx.notify();
269 }
270
271 fn prev(&mut self, _: &mut Window, cx: &mut Context<Self>) {
272 let _ = self.editor.update(cx, |state, cx| {
273 _ = state.previous_search_match(cx);
274 });
275 }
276
277 fn next(&mut self, _: &mut Window, cx: &mut Context<Self>) {
278 let _ = self.editor.update(cx, |state, cx| {
279 _ = state.next_search_match(cx);
280 });
281 }
282
283 fn replace_next(&mut self, window: &mut Window, cx: &mut Context<Self>) {
284 if !self.replaceable(cx) {
285 self.session.replace_mode = false;
286 cx.notify();
287 return;
288 }
289
290 let replacement = self.replace_input.read(cx).value();
291 let _ = self.editor.update(cx, |state, cx| {
292 _ = state.replace_current_search_match(&replacement, window, cx);
293 });
294 }
295
296 fn replace_all(&mut self, window: &mut Window, cx: &mut Context<Self>) {
297 if !self.replaceable(cx) {
298 self.session.replace_mode = false;
299 cx.notify();
300 return;
301 }
302
303 let replacement = self.replace_input.read(cx).value();
304 let _ = self.editor.update(cx, |state, cx| {
305 _ = state.replace_all_search_matches(&replacement, window, cx);
306 });
307 }
308}
309
310impl<M: crate::input::overlay::OverlayMode> Focusable for SearchPanel<M> {
311 fn focus_handle(&self, cx: &App) -> FocusHandle {
312 self.search_input.read(cx).focus_handle(cx)
313 }
314}
315
316impl<M: crate::input::overlay::OverlayMode> Render for SearchPanel<M> {
317 fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
318 if !self.session.open {
319 return Empty.into_any_element();
320 }
321
322 let has_matches = !self.session.matcher.is_empty();
323 let allow_replace = self.replaceable(cx);
324 if !allow_replace {
325 self.session.replace_mode = false;
326 }
327
328 v_flex()
329 .id("search-panel")
330 .occlude()
331 .track_focus(&self.focus_handle(cx))
332 .key_context(CONTEXT)
333 .on_action(cx.listener(Self::on_action_enter))
334 .on_action(cx.listener(Self::on_action_escape))
335 .on_action(cx.listener(Self::on_action_tab))
336 .on_action(cx.listener(Self::on_action_tab_prev))
337 .on_action(cx.listener(Self::on_action_replace))
338 .font_family(cx.theme().font_family.clone())
339 .items_center()
340 .py_2()
341 .px_3()
342 .w_full()
343 .gap_1()
344 .bg(cx.theme().tokens.popover)
345 .border_b_1()
346 .rounded(cx.theme().radius.half())
347 .border_color(cx.theme().border)
348 .child(
349 h_flex()
350 .w_full()
351 .gap_2()
352 .child(
353 div()
354 .flex()
355 .flex_1()
356 .gap_1()
357 .child(
358 Input::new(&self.search_input)
359 .focus_bordered(false)
360 .suffix(
361 Button::new("case-insensitive")
362 .selected(!self.session.case_insensitive)
363 .toggled(!self.session.case_insensitive)
364 .xsmall()
365 .compact()
366 .text()
367 .icon(IconName::CaseSensitive)
368 .on_click(cx.listener(|this, _, _, cx| {
369 this.session.case_insensitive =
370 !this.session.case_insensitive;
371 this.update_search_query(None, cx);
372 cx.notify();
373 })),
374 )
375 .small()
376 .w_full()
377 .shadow_none(),
378 )
379 .on_prepaint({
380 let view = cx.entity();
381 move |bounds, _, cx| {
382 view.update(cx, |r, _| r.input_width = bounds.size.width)
383 }
384 }),
385 )
386 .when(allow_replace, |this| {
387 this.child(
388 Button::new("replace-mode")
389 .xsmall()
390 .ghost()
391 .icon(IconName::Replace)
392 .selected(self.session.replace_mode)
393 .toggled(self.session.replace_mode)
394 .on_click(cx.listener(|this, _, window, cx| {
395 this.toggle_replace_mode(window, cx);
396 })),
397 )
398 })
399 .child(
400 Button::new("prev")
401 .xsmall()
402 .ghost()
403 .icon(IconName::ChevronLeft)
404 .disabled(!has_matches)
405 .on_click(cx.listener(|this, _, window, cx| {
406 this.prev(window, cx);
407 })),
408 )
409 .child(
410 Button::new("next")
411 .xsmall()
412 .ghost()
413 .icon(IconName::ChevronRight)
414 .disabled(!has_matches)
415 .on_click(cx.listener(|this, _, window, cx| {
416 this.next(window, cx);
417 })),
418 )
419 .child(
420 Label::new(self.session.matcher.label())
421 .when(!has_matches, |this| {
422 this.text_color(cx.theme().muted_foreground)
423 })
424 .text_left()
425 .min_w_16(),
426 )
427 .child(div().w_7())
428 .child(
429 Button::new("close")
430 .xsmall()
431 .ghost()
432 .icon(IconName::Close)
433 .on_click(cx.listener(|this, _, window, cx| {
434 this.on_action_escape(&Escape, window, cx);
435 })),
436 ),
437 )
438 .when(self.session.replace_mode && allow_replace, |this| {
439 this.child(
440 h_flex()
441 .w_full()
442 .gap_2()
443 .child(
444 Input::new(&self.replace_input)
445 .focus_bordered(false)
446 .small()
447 .w(self.input_width)
448 .shadow_none(),
449 )
450 .child(
451 Button::new("replace-one")
452 .small()
453 .label(t!("Input.Replace"))
454 .disabled(!has_matches)
455 .on_click(cx.listener(|this, _, window, cx| {
456 this.replace_next(window, cx);
457 })),
458 )
459 .child(
460 Button::new("replace-all")
461 .small()
462 .label(t!("Input.Replace All"))
463 .disabled(!has_matches)
464 .on_click(cx.listener(|this, _, window, cx| {
465 this.replace_all(window, cx);
466 })),
467 ),
468 )
469 })
470 .into_any_element()
471 }
472}
473
474#[cfg(test)]
475mod tests {
476 use super::*;
477 use ropey::Rope;
478
479 #[test]
480 fn test_search() {
481 let mut matcher = SearchMatcher::new();
482 matcher.update(&Rope::from("Hello 世界 this is a Is test string."));
483 matcher.update_query("Is", true);
484
485 assert_eq!(matcher.len(), 3);
486 let mut matches = matcher.clone();
487 assert_eq!(matches.current_match_index(), 0);
488 assert_eq!(matches.next(), Some(18..20));
489 assert_eq!(matches.next(), Some(23..25));
490 assert_eq!(matches.current_match_index(), 2);
491 assert_eq!(matches.next(), Some(15..17));
492 assert_eq!(matches.current_match_index(), 0);
493 assert_eq!(matches.next_back(), Some(23..25));
494 assert_eq!(matches.current_match_index(), 2);
495 assert_eq!(matches.next_back(), Some(18..20));
496 assert_eq!(matches.current_match_index(), 1);
497 assert_eq!(matches.next_back(), Some(15..17));
498 assert_eq!(matches.current_match_index(), 0);
499 assert_eq!(matches.next_back(), Some(23..25));
500
501 matcher.update_query("IS", false);
502 assert_eq!(matcher.len(), 0);
503 assert_eq!(matcher.next(), None);
504 assert_eq!(matcher.next_back(), None);
505 }
506
507 #[test]
508 fn test_search_label() {
509 let mut matcher = SearchMatcher::new();
510 matcher.update(&Rope::from("Hello 世界 this is a Is test string."));
511 matcher.update_query("Is", true);
512 assert_eq!(matcher.label(), "1/3");
513 matcher.next();
514 assert_eq!(matcher.label(), "2/3");
515 matcher.next();
516 assert_eq!(matcher.label(), "3/3");
517 matcher.next();
518 assert_eq!(matcher.label(), "1/3");
519
520 matcher.update_query("IS", false);
521 assert_eq!(matcher.label(), "0/0");
522 }
523
524 #[test]
525 fn test_select_range_start() {
526 let mut matcher = SearchMatcher::new();
527 matcher.update(&Rope::from(".....aaaaa.....aaaaa.....aaaaa"));
528 matcher.update_query("aaaaa", false);
529 matcher.update_cursor_by_offset(0);
530 assert_eq!(matcher.current_match_index(), 0);
531
532 matcher.update_cursor_by_offset(5);
533 assert_eq!(matcher.current_match_index(), 0);
534
535 matcher.update_cursor_by_offset(12);
536 assert_eq!(matcher.current_match_index(), 1);
537
538 matcher.update_cursor_by_offset(16);
539 assert_eq!(matcher.current_match_index(), 1);
540
541 matcher.update_cursor_by_offset(30);
542 assert_eq!(matcher.current_match_index(), 2);
543
544 matcher.update_cursor_by_offset(31);
545 assert_eq!(matcher.current_match_index(), 2);
546 }
547
548 #[test]
549 fn test_next_scroll_direction_returns_down_without_wrap() {
550 assert!(matches!(
551 next_scroll_direction(0, 1),
552 Some(MoveDirection::Down)
553 ));
554 }
555
556 #[test]
557 fn test_next_scroll_direction_returns_none_on_wrap() {
558 assert!(next_scroll_direction(2, 0).is_none());
559 }
560
561 #[test]
562 fn test_next_scroll_direction_returns_none_for_single_match() {
563 assert!(next_scroll_direction(0, 0).is_none());
564 }
565
566 #[test]
567 fn test_prev_scroll_direction_returns_up_without_wrap() {
568 assert!(matches!(
569 prev_scroll_direction(2, 1),
570 Some(MoveDirection::Up)
571 ));
572 }
573
574 #[test]
575 fn test_prev_scroll_direction_returns_none_on_wrap() {
576 assert!(prev_scroll_direction(0, 2).is_none());
577 }
578
579 #[test]
580 fn test_prev_scroll_direction_returns_none_for_single_match() {
581 assert!(prev_scroll_direction(0, 0).is_none());
582 }
583}