1use std::{rc::Rc, time::Duration};
2
3use gpui::{
4 AnyElement, App, ElementId, Entity, EntityInputHandler, InteractiveElement, IntoElement,
5 ParentElement, Pixels, RenderOnce, SharedString, Styled, Window, div, prelude::FluentBuilder,
6 px,
7};
8use gpui_base::TestSupportExt;
9use gpui_material_components::{Icon, IconButton, IconName, ListItem, TextField, TextFieldState};
10use gpui_material_foundation::{Surface, current_material_strings, current_material_theme};
11use gpui_material_theme::{ColorRole, CornerShape, Direction, Elevation};
12
13use super::{
14 SearchMotion, SearchPopupOptions, SearchStyle, SearchViewVariant, SearchWindowOptions, length,
15 valid_dimension,
16};
17use crate::search::{SearchResult, SearchState, SearchValue};
18
19mod results;
20
21use results::{ResultBuilder, RowBuilder};
22
23type InputBuilder = Box<dyn FnOnce(TextField) -> AnyElement>;
24
25#[derive(IntoElement)]
27pub struct SearchView {
28 id: ElementId,
29 pub(super) label: SharedString,
30 pub(super) state: Entity<SearchState>,
31 pub(super) variant: SearchViewVariant,
32 pub(super) close_label: Option<SharedString>,
33 loading_label: Option<SharedString>,
34 empty_label: Option<SharedString>,
35 prompt: Option<SharedString>,
36 input: Option<InputBuilder>,
37 filters: Option<AnyElement>,
38 row: Option<RowBuilder>,
39 result_content: Option<ResultBuilder>,
40 pub(super) focused_width: Option<Pixels>,
41 docked_dimensions: (Pixels, Pixels),
42 gap: Pixels,
43 pub(super) style: SearchStyle,
44 pub(super) motion: SearchMotion,
45 pub(super) popup: SearchPopupOptions,
46 pub(super) window: SearchWindowOptions,
47 pub(super) sampled_in_bar: bool,
48}
49
50impl SearchView {
51 pub fn new(
54 id: impl Into<ElementId>,
55 label: impl Into<SharedString>,
56 state: &Entity<SearchState>,
57 ) -> Self {
58 Self {
59 id: id.into(),
60 label: label.into(),
61 state: state.clone(),
62 variant: SearchViewVariant::default(),
63 close_label: None,
64 loading_label: None,
65 empty_label: None,
66 prompt: None,
67 input: None,
68 filters: None,
69 row: None,
70 result_content: None,
71 focused_width: None,
72 docked_dimensions: (px(440.), px(424.)),
73 gap: px(0.),
74 style: SearchStyle::default(),
75 motion: SearchMotion::default(),
76 popup: SearchPopupOptions::default(),
77 window: SearchWindowOptions::default(),
78 sampled_in_bar: false,
79 }
80 }
81
82 pub(super) fn resolved_close_label(&self, window: &Window, cx: &App) -> SharedString {
83 self.close_label.clone().unwrap_or_else(|| {
84 SharedString::from(current_material_strings(window, cx).close_search.clone())
85 })
86 }
87
88 pub fn variant(mut self, variant: SearchViewVariant) -> Self {
90 self.variant = variant;
91 self
92 }
93
94 pub fn labels(
96 mut self,
97 close: SharedString,
98 loading: SharedString,
99 empty: SharedString,
100 prompt: SharedString,
101 ) -> Self {
102 self.close_label = Some(close);
103 self.loading_label = Some(loading);
104 self.empty_label = Some(empty);
105 self.prompt = Some(prompt);
106 self
107 }
108
109 pub fn input<E: IntoElement + 'static>(
111 mut self,
112 build: impl FnOnce(TextField) -> E + 'static,
113 ) -> Self {
114 self.input = Some(Box::new(move |field| build(field).into_any_element()));
115 self
116 }
117
118 pub fn filters(mut self, content: impl IntoElement) -> Self {
120 self.filters = Some(content.into_any_element());
121 self
122 }
123
124 pub fn result_row(
126 mut self,
127 build: impl Fn(ListItem, &SearchResult, &mut Window, &mut App) -> ListItem + 'static,
128 ) -> Self {
129 self.row = Some(Rc::new(build));
130 self
131 }
132
133 pub fn result_content<E: IntoElement + 'static>(
135 mut self,
136 build: impl FnOnce(&Entity<SearchState>, &mut Window, &mut App) -> E + 'static,
137 ) -> Self {
138 self.result_content = Some(Box::new(move |state, window, cx| {
139 build(state, window, cx).into_any_element()
140 }));
141 self
142 }
143
144 pub fn focused_width(mut self, width: Pixels) -> Self {
146 self.focused_width = valid_dimension(width);
147 self
148 }
149
150 pub fn docked_size(mut self, width: Pixels, height: Pixels) -> Self {
152 self.docked_dimensions = (
153 valid_dimension(width).unwrap_or(px(440.)),
154 valid_dimension(height).unwrap_or(px(424.)),
155 );
156 self
157 }
158
159 pub fn result_gap(mut self, gap: Pixels) -> Self {
161 self.gap = length(gap);
162 self
163 }
164
165 pub fn style(mut self, style: SearchStyle) -> Self {
167 self.style = style;
168 self
169 }
170
171 pub fn motion(mut self, motion: SearchMotion) -> Self {
173 self.motion = motion;
174 self
175 }
176
177 pub fn popup_options(mut self, options: SearchPopupOptions) -> Self {
179 self.popup = options;
180 self
181 }
182
183 pub fn window_options(mut self, options: SearchWindowOptions) -> Self {
185 self.window = options;
186 self
187 }
188
189 fn render_input_region(
190 &mut self,
191 editor: &Entity<TextFieldState>,
192 editor_width: Option<Pixels>,
193 direction: Direction,
194 duration: Duration,
195 window: &Window,
196 cx: &App,
197 ) -> impl IntoElement + use<> {
198 let close = self.state.clone();
199 let down_state = self.state.clone();
200 let down_editor = editor.clone();
201 let field = TextField::new((self.id.clone(), "editor"), self.label.clone(), editor)
202 .when_some(self.style.input_colors, TextField::colors);
203 let field = match self.input.take() {
204 Some(builder) => builder(field),
205 None => field.into_any_element(),
206 };
207 div()
208 .id((self.id.clone(), "input-region"))
209 .test_support()
210 .flex()
211 .flex_none()
212 .items_center()
213 .p_2()
214 .gap_2()
215 .when(direction == Direction::Rtl, Styled::flex_row_reverse)
216 .child(
217 IconButton::new(
218 (self.id.clone(), "close-search"),
219 self.resolved_close_label(window, cx),
220 Icon::new(IconName::Close),
221 )
222 .on_activate(move |window, cx| {
223 dismiss_search(&close, duration, window, cx);
224 }),
225 )
226 .child(
227 div()
228 .flex_1()
229 .min_w_0()
230 .when_some(editor_width, |editor, width| editor.max_w(width))
231 .capture_key_down(move |event, window, cx| {
232 if event.keystroke.key != "down" || event.keystroke.modifiers.modified() {
233 return;
234 }
235 if down_editor.update(cx, |input, cx| {
236 input.marked_text_range(window, cx).is_some()
237 }) {
238 return;
239 }
240 let target = {
241 let model = down_state.read(cx);
242 model.rows().first().and_then(|row| {
243 model
244 .result_focus
245 .get(&row.id)
246 .cloned()
247 .map(|focus| (row.id.clone(), focus, model.scroll.clone()))
248 })
249 };
250 if let Some((first_id, focus, scroll)) = target {
251 if scroll.bounds_for_item(0).is_some() {
252 scroll.scroll_to_reveal_item(0);
253 } else {
254 scroll.scroll_to(gpui::ListOffset {
255 item_ix: 0,
256 offset_in_item: px(0.),
257 });
258 }
259 down_state.update(cx, |state, _| {
260 state.active_result = Some(first_id);
261 });
262 focus.focus(window, cx);
263 window.refresh();
264 cx.stop_propagation();
265 }
266 })
267 .child(field),
268 )
269 }
270}
271
272impl RenderOnce for SearchView {
273 fn render(mut self, window: &mut Window, cx: &mut App) -> impl IntoElement {
274 let theme = current_material_theme(window, cx);
275 let rem_size = window.rem_size();
276 let font_revision = gpui_material_foundation::font_cache_revision(cx);
277 let (needs_animation, needs_layout) = {
278 let state = self.state.read(cx);
279 let needs_layout = match &state.result_layout {
280 Some((typography, cached_rem, cached_rev)) => {
281 *cached_rem != rem_size
282 || *cached_rev != font_revision
283 || *typography != theme.typography
284 }
285 None => true,
286 };
287 (!self.sampled_in_bar && state.is_animating(), needs_layout)
288 };
289 let animate = if needs_animation || needs_layout {
290 let measurement =
291 needs_layout.then(|| (theme.typography.clone(), rem_size, font_revision));
292 self.state.update(cx, |state, cx| {
293 let animate = if needs_animation {
294 state.sample_animation(window, cx)
295 } else {
296 false
297 };
298 if let Some(measurement) = measurement {
299 state.result_layout = Some(measurement);
300 state.invalidate_result_measurements();
301 }
302 animate
303 })
304 } else {
305 false
306 };
307 if animate && window.is_visible() {
308 window.request_animation_frame();
309 }
310 let model = self.state.read(cx);
311 let progress = if model.presented() {
312 model.progress()
313 } else {
314 1.
315 };
316 let editor = model.input.clone();
317 let layout = theme.layout;
318 let direction = layout.direction;
319 let size = window.viewport_size();
320 let docked = self.variant == SearchViewVariant::Docked;
321 let contained = self.variant == SearchViewVariant::FullScreenContained;
322 let split = docked && (self.gap > px(0.) || self.style.results_shape.is_some());
323 let geometry = self.window.insets;
324 let (left, right) = layout.horizontal(length(geometry.left), length(geometry.right));
325 let width = if docked {
326 self.docked_dimensions
327 .0
328 .min((size.width - px(16.)).max(px(0.)))
329 } else {
330 (size.width - left - right).max(px(0.))
331 };
332 let height = if docked {
333 self.docked_dimensions.1.min(size.height * 0.65)
334 } else {
335 (size.height - length(geometry.top) - length(geometry.bottom)).max(px(0.))
336 };
337 let editor_limit = if contained {
338 (width - px(24.)).max(px(0.))
339 } else {
340 width
341 };
342 let editor_width = self
343 .focused_width
344 .or(contained.then_some(px(720.)))
345 .map(|width| width.min(editor_limit));
346 let dismiss = self.state.clone();
347 let duration = self.motion.collapse;
348 let close_on_escape = if docked {
349 self.popup.dismiss_on_escape
350 } else {
351 self.window.dismiss_on_escape
352 };
353
354 let input =
355 self.render_input_region(&editor, editor_width, direction, duration, window, cx);
356 let results = self.render_results_region(duration, window, cx);
357
358 let panel = panel_surface(self.style, docked, false).w(width).h(height);
359 let panel = if split {
360 div()
361 .flex()
362 .flex_col()
363 .w(width)
364 .h(height)
365 .child(panel_surface(self.style, true, false).child(input))
366 .child(div().flex_none().h(self.gap.min(height * 0.35)))
367 .child(
368 panel_surface(self.style, true, true)
369 .flex_1()
370 .min_h_0()
371 .child(results),
372 )
373 .into_any_element()
374 } else {
375 panel
376 .child(if contained {
377 div()
378 .flex()
379 .justify_center()
380 .p_3()
381 .child(
382 panel_surface(self.style, false, false)
383 .shape(self.style.shape.unwrap_or(CornerShape::Full))
384 .w(editor_width.unwrap_or(width))
385 .child(input),
386 )
387 .into_any_element()
388 } else {
389 input.into_any_element()
390 })
391 .child(results)
392 .into_any_element()
393 };
394 div()
395 .id(self.id)
396 .test_support()
397 .when(!docked, |view| {
398 view.pl(left)
399 .pr(right)
400 .pt(length(geometry.top))
401 .pb(length(geometry.bottom))
402 })
403 .opacity(progress)
404 .capture_key_down(move |event, window, cx| {
405 if event.keystroke.key == "escape"
406 && close_on_escape
407 && dismiss_search(&dismiss, duration, window, cx)
408 {
409 cx.stop_propagation();
410 }
411 })
412 .child(panel)
413 }
414}
415
416fn panel_surface(style: SearchStyle, docked: bool, results: bool) -> Surface {
417 Surface::new(ColorRole::SurfaceContainerHigh)
418 .flex()
419 .flex_col()
420 .when_some(style.container, Surface::container_color)
421 .when_some(style.content, Surface::content_color)
422 .when_some(
423 if results {
424 style.results_shape.or(style.shape)
425 } else {
426 style.shape
427 }
428 .or(docked.then_some(CornerShape::Radii([28.; 4]))),
429 Surface::shape,
430 )
431 .when_some(style.tonal_elevation, Surface::tonal_elevation)
432 .when_some(
433 style
434 .shadow_elevation
435 .or(docked.then_some(Elevation::Level3)),
436 Surface::shadow_elevation,
437 )
438}
439
440pub(super) fn dismiss_search(
441 state: &Entity<SearchState>,
442 duration: Duration,
443 window: &mut Window,
444 cx: &mut App,
445) -> bool {
446 state.update(cx, |state, cx| {
447 let composing = state.input.update(cx, |input, cx| {
448 input.marked_text_range(window, cx).is_some()
449 });
450 if !composing {
451 state.animate_to(SearchValue::Collapsed, duration, window, cx);
452 }
453 !composing
454 })
455}