1use std::{cell::Cell, rc::Rc};
2
3use gpui::{
4 AccessibleAction, AnyElement, App, BorderStyle, Bounds, ClickEvent, ContentMask, Corners,
5 Edges, ElementId, FocusHandle, Font, Hsla, InteractiveElement, IntoElement, MouseButton,
6 ParentElement, Pixels, RenderOnce, Role, SharedString, StatefulInteractiveElement, Styled,
7 TextAlign, Window, canvas, div, point, prelude::FluentBuilder, px, quad,
8};
9use gpui_base::{
10 ScrollbarAxis, TestSupportExt,
11 input::{
12 DiagnosticColors, InputAccessibility, InputBaseState, InputEditorStyle, InputModeKind,
13 InputPresentation,
14 },
15};
16use gpui_material_foundation::{
17 InteractionSource, InteractionState, ThemeScope, animate, color, current_material_theme,
18 font_for_style,
19};
20use gpui_material_theme::{
21 ColorRole, CornerRole, CornerShape, Density, Direction, LayoutPolicy, MaterialTheme,
22 MotionKind, MotionSpeed, TypeRole, TypeStyle, TypographyEmphasis,
23};
24
25use super::{
26 Editor, FieldDescription, OnTextLayout, TextField, TextFieldColorOverrides, TextFieldColors,
27 TextFieldLabelAlignment, TextFieldLabelPosition, TextFieldLayout, TextFieldObfuscationMode,
28 TextFieldVariant, VisibilityToggle,
29};
30
31struct FieldAnimation {
32 floating: f32,
33 focus_amount: f32,
34 error_amount: f32,
35}
36
37#[derive(Default)]
38struct CharacterCountCache {
39 text: SharedString,
40 limit: Option<usize>,
41 support_text: Option<SharedString>,
42 count_label: SharedString,
43 combined_support: Option<SharedString>,
44}
45
46struct FieldPalette {
47 state_colors: TextFieldColorOverrides,
48 secondary: Hsla,
49 foreground: Hsla,
50 placeholder_color: Hsla,
51 background: Hsla,
52 indicator: Hsla,
53 label_color: Hsla,
54 outline_tint: Hsla,
55}
56
57struct FieldMetrics {
58 label_size: f32,
59 label_height: f32,
60 outline_width: Pixels,
61 padding: Edges<Pixels>,
62 editor_top_padding: Pixels,
63 editor_bottom_padding: Pixels,
64 minimum_height: Pixels,
65 label_top: f32,
66}
67
68struct ConfiguredEditor {
69 element: AnyElement,
70 role: Role,
71 value: Option<SharedString>,
72 set_value: Option<Editor>,
73}
74
75fn configure_editor<M: InputModeKind>(state: &mut InputBaseState<M>, style: InputEditorStyle) {
76 state.set_accessibility(InputAccessibility::new(None).with_value_exposed(false));
79 state.set_editor_style(style);
80}
81
82fn editor_ink(mut color: Hsla) -> Hsla {
83 if color.a == 0. {
85 color.a = f32::EPSILON;
86 }
87 color
88}
89
90fn interaction_state(disabled: bool, hovered: bool, focus_visible: bool) -> InteractionState {
91 let mut state = InteractionState::default();
92 state.disabled = disabled;
93 state.hovered = hovered && !disabled;
94 state.focus_visible = focus_visible && !disabled;
95 state
96}
97
98fn sample_animation(
99 id: &ElementId,
100 theme: &MaterialTheme,
101 should_float: bool,
102 focused: bool,
103 invalid_active: bool,
104 window: &mut Window,
105 cx: &mut App,
106) -> FieldAnimation {
107 let effects = theme
108 .motion
109 .spec(MotionKind::Effects, MotionSpeed::Fast, cx.reduce_motion());
110 let floating = animate(
111 (id.clone(), "floating-label"),
112 f32::from(should_float),
113 theme
114 .motion
115 .spec(MotionKind::Spatial, MotionSpeed::Fast, cx.reduce_motion()),
116 window,
117 cx,
118 )
119 .clamp(0., 1.);
120 let focus_amount = animate(
121 (id.clone(), "focus-indicator"),
122 f32::from(focused),
123 effects,
124 window,
125 cx,
126 )
127 .clamp(0., 1.);
128 let error_amount = animate(
129 (id.clone(), "error-indicator"),
130 f32::from(invalid_active),
131 effects,
132 window,
133 cx,
134 )
135 .clamp(0., 1.);
136 FieldAnimation {
137 floating,
138 focus_amount,
139 error_amount,
140 }
141}
142
143#[allow(clippy::too_many_arguments)]
144fn resolve_palette(
145 theme: &MaterialTheme,
146 colors: TextFieldColors,
147 filled: bool,
148 disabled: bool,
149 error: bool,
150 focused: bool,
151 hovered: bool,
152 animation: &FieldAnimation,
153) -> FieldPalette {
154 use ColorRole::*;
155
156 let tone = |role| color(theme.colors.color(role));
157 let state_colors = match (disabled, error, focused) {
158 (true, _, _) => colors.disabled,
159 (_, true, _) => colors.invalid,
160 (_, _, true) => colors.focused,
161 _ => colors.unfocused,
162 };
163 let secondary = if disabled {
164 tone(OnSurface).opacity(0.38)
165 } else {
166 tone(OnSurfaceVariant)
167 };
168 let foreground =
169 state_colors
170 .text
171 .unwrap_or(if disabled { secondary } else { tone(OnSurface) });
172 let placeholder_color = state_colors.placeholder.unwrap_or(secondary);
173 let background = state_colors
174 .container
175 .unwrap_or_else(|| match (filled, disabled) {
176 (false, _) => gpui::transparent_black(),
177 (true, true) => tone(OnSurface).opacity(0.04),
178 (true, false) => tone(SurfaceContainerHighest),
179 });
180 let animated_color = |idle, active, invalid| {
181 let focused_tint = crate::motion::mix(idle, active, animation.focus_amount);
182 crate::motion::mix(focused_tint, invalid, animation.error_amount)
183 };
184 let indicator = if disabled {
185 colors
186 .disabled
187 .indicator
188 .unwrap_or(tone(OnSurface).opacity(0.12))
189 } else {
190 animated_color(
191 colors.unfocused.indicator.unwrap_or(tone(if filled {
192 OnSurfaceVariant
193 } else {
194 Outline
195 })),
196 colors.focused.indicator.unwrap_or(tone(Primary)),
197 colors.invalid.indicator.unwrap_or(tone(Error)),
198 )
199 };
200 let label_color = if disabled {
201 colors.disabled.label.unwrap_or(secondary)
202 } else {
203 animated_color(
204 colors.unfocused.label.unwrap_or(secondary),
205 colors.focused.label.unwrap_or(tone(Primary)),
206 colors.invalid.label.unwrap_or(tone(Error)),
207 )
208 };
209 let outline_tint = if hovered && !disabled && !error {
210 crate::motion::mix(
211 colors.hovered_indicator.unwrap_or(foreground),
212 colors.focused.indicator.unwrap_or(tone(Primary)),
213 animation.focus_amount,
214 )
215 } else {
216 indicator
217 };
218 FieldPalette {
219 state_colors,
220 secondary,
221 foreground,
222 placeholder_color,
223 background,
224 indicator,
225 label_color,
226 outline_tint,
227 }
228}
229
230#[allow(clippy::too_many_arguments)]
231fn build_editor_style(
232 theme: &MaterialTheme,
233 palette: &FieldPalette,
234 has_text: bool,
235 has_custom_placeholder: bool,
236 floating: f32,
237 hide_caret: bool,
238 error: bool,
239) -> InputEditorStyle {
240 use ColorRole::*;
241
242 let tone = |role| color(theme.colors.color(role));
243 InputEditorStyle {
244 foreground: editor_ink(palette.foreground),
245 background: editor_ink(tone(SurfaceContainer)),
250 border: editor_ink(tone(OutlineVariant)),
251 muted_foreground: match (has_text, has_custom_placeholder) {
252 (true, _) => editor_ink(palette.placeholder_color),
253 (false, true) => editor_ink(gpui::transparent_black()),
254 (false, false) => editor_ink(palette.placeholder_color.opacity(floating)),
255 },
256 caret: if hide_caret {
257 editor_ink(gpui::transparent_black())
260 } else {
261 editor_ink(palette.state_colors.caret.unwrap_or(tone(if error {
262 Error
263 } else {
264 Primary
265 })))
266 },
267 selection: editor_ink(
268 palette
269 .state_colors
270 .selection
271 .unwrap_or(tone(Primary).opacity(0.3)),
272 ),
273 diagnostics: DiagnosticColors {
274 error: editor_ink(tone(Error)),
275 warning: editor_ink(tone(Warning)),
276 info: editor_ink(tone(Info)),
277 hint: editor_ink(tone(OnSurfaceVariant)),
278 },
279 ..Default::default()
280 }
281}
282
283fn build_layout_probe(
284 id: &ElementId,
285 editor: &Editor,
286 on_text_layout: Option<OnTextLayout>,
287 window: &mut Window,
288 cx: &mut App,
289) -> Option<gpui::Canvas<()>> {
290 on_text_layout.map(|listener| {
291 let editor = editor.clone();
292 let previous = window
293 .use_keyed_state((id.clone(), "field-layout"), cx, |_, _| {
294 Rc::new(Cell::new(None::<TextFieldLayout>))
295 })
296 .read(cx)
297 .clone();
298 canvas(
299 |_, _, _| (),
300 move |_, _, window, cx| {
301 let layout = editor.layout(cx);
302 if previous.replace(Some(layout)) != Some(layout) {
303 window.defer(cx, move |window, cx| listener(layout, window, cx));
304 }
305 },
306 )
307 .absolute()
308 .inset_0()
309 })
310}
311
312#[allow(clippy::too_many_arguments)]
313fn configure_and_build_editor(
314 id: &ElementId,
315 editor: Editor,
316 obfuscation_mode: TextFieldObfuscationMode,
317 presentation: &InputPresentation,
318 align: TextAlign,
319 style: InputEditorStyle,
320 theme: &MaterialTheme,
321 readonly: bool,
322 disabled: bool,
323 window: &mut Window,
324 cx: &mut App,
325) -> ConfiguredEditor {
326 match editor {
327 Editor::Single(state) => {
328 let role = if presentation.is_masked() {
329 Role::PasswordInput
330 } else {
331 Role::TextInput
332 };
333 state.update(cx, |state, cx| {
334 state.set_text_align(align, cx);
335 configure_editor(state, style);
336 });
337 let value = (role != Role::PasswordInput).then(|| state.read(cx).value());
338 let set_value = (!readonly && !disabled && role != Role::PasswordInput)
339 .then(|| Editor::Single(state.clone()));
340 ConfiguredEditor {
341 element: state.into_any_element(),
342 role,
343 value,
344 set_value,
345 }
346 }
347 Editor::Multiple(state) => {
348 let scrollbar_id = (id.clone(), "editor-scrollbar");
349 let scrollbar_theme = theme.clone();
350 state.update(cx, |state, cx| {
351 state.set_text_align(align, cx);
352 configure_editor(state, style);
353 state.set_scrollbar_renderer(Some(Rc::new(move |scroll, _, _| {
354 let content = match scroll.axis() {
355 ScrollbarAxis::Vertical => crate::DisplayScrollbar::new(
356 scrollbar_id.clone(),
357 gpui::Axis::Vertical,
358 &scroll,
359 )
360 .into_any_element(),
361 ScrollbarAxis::Horizontal => crate::DisplayScrollbar::new(
362 scrollbar_id.clone(),
363 gpui::Axis::Horizontal,
364 &scroll,
365 )
366 .into_any_element(),
367 ScrollbarAxis::Both => div()
368 .absolute()
369 .inset_0()
370 .child(crate::DisplayScrollbar::new(
371 scrollbar_id.clone(),
372 gpui::Axis::Vertical,
373 &scroll,
374 ))
375 .child(crate::DisplayScrollbar::new(
376 scrollbar_id.clone(),
377 gpui::Axis::Horizontal,
378 &scroll,
379 ))
380 .into_any_element(),
381 };
382 ThemeScope::new(content)
383 .theme(scrollbar_theme.clone())
384 .into_any_element()
385 })));
386 });
387 let value = state.read(cx).value();
388 let set_value = (!readonly && !disabled).then(|| Editor::Multiple(state.clone()));
389 ConfiguredEditor {
390 element: state.into_any_element(),
391 role: Role::MultilineTextInput,
392 value: Some(value),
393 set_value,
394 }
395 }
396 Editor::Secure(state) => {
397 let masked = obfuscation_mode == TextFieldObfuscationMode::Hidden;
398 state.update(cx, |state, cx| {
399 if presentation.is_masked() != masked {
400 state.set_masked(masked, window, cx);
401 }
402 state.set_text_align(align, cx);
403 configure_editor(state, style);
404 });
405 let role = if masked {
406 Role::PasswordInput
407 } else {
408 Role::TextInput
409 };
410 let value = (!masked).then(|| state.read(cx).value());
411 let set_value =
412 (!readonly && !disabled && !masked).then(|| Editor::Secure(state.clone()));
413 ConfiguredEditor {
414 element: state.into_any_element(),
415 role,
416 value,
417 set_value,
418 }
419 }
420 }
421}
422
423#[allow(clippy::too_many_arguments)]
424fn resolve_metrics(
425 type_style: TypeStyle,
426 caption_style: TypeStyle,
427 animation: &FieldAnimation,
428 density: Density,
429 min_height: Option<Pixels>,
430 indicator_width: (Pixels, Pixels),
431 content_padding: Option<Edges<Pixels>>,
432 label_inside: bool,
433 filled: bool,
434) -> FieldMetrics {
435 let label_size = type_style.size + (caption_style.size - type_style.size) * animation.floating;
436 let label_height = type_style.line_height
437 + (caption_style.line_height - type_style.line_height) * animation.floating;
438 let (unfocused_indicator, focused_indicator) = indicator_width;
439 let unfocused_w = f32::from(unfocused_indicator);
440 let focused_w = f32::from(focused_indicator);
441 let outline_width = px(unfocused_w + (focused_w - unfocused_w) * animation.focus_amount);
442 let inside_vertical_pad = if density == Density::Compact { 6. } else { 8. };
443 let padding = content_padding.unwrap_or(Edges {
444 left: px(16.),
445 right: px(16.),
446 top: px(if label_inside {
447 inside_vertical_pad
448 } else {
449 4.
450 }),
451 bottom: if label_inside && filled {
452 (px(inside_vertical_pad) - outline_width).max(px(0.))
453 } else {
454 px(4.)
455 },
456 });
457 let label_reserve = if label_inside {
458 px(caption_style.line_height)
459 } else {
460 px(0.)
461 };
462 let editor_top_padding = padding.top + label_reserve;
463 let editor_bottom_padding = padding.bottom + if filled { outline_width } else { px(0.) };
465 let content_min_height =
466 px(type_style.line_height) + editor_top_padding + editor_bottom_padding;
467 let minimum_height = match min_height {
468 Some(height) => height.max(content_min_height),
469 None => px(density.visual_size(56.))
470 .max(px(type_style.line_height + 2. * inside_vertical_pad) + label_reserve)
471 .max(content_min_height),
472 };
473 let resting_top = f32::from(minimum_height - px(type_style.line_height)) * 0.5;
474 let floating_top = if label_inside {
475 f32::from(padding.top)
476 } else {
477 -caption_style.line_height * 0.5
478 };
479 let label_top = resting_top + (floating_top - resting_top) * animation.floating;
480 FieldMetrics {
481 label_size,
482 label_height,
483 outline_width,
484 padding,
485 editor_top_padding,
486 editor_bottom_padding,
487 minimum_height,
488 label_top,
489 }
490}
491
492#[allow(clippy::too_many_arguments)]
493fn build_outline_canvas(
494 shape: CornerShape,
495 direction: Direction,
496 background: Hsla,
497 filled: bool,
498 outline_width: Pixels,
499 outline_tint: Hsla,
500 cutout: Option<Rc<Cell<Option<Bounds<Pixels>>>>>,
501) -> gpui::Canvas<()> {
502 canvas(
503 |_, _, _| (),
504 move |bounds, _, window, _| {
505 let [top_left, top_right, bottom_right, bottom_left] = shape
506 .radii(
507 bounds.size.width.into(),
508 bounds.size.height.into(),
509 direction,
510 )
511 .map(px);
512 let corners = Corners {
513 top_left,
514 top_right,
515 bottom_right,
516 bottom_left,
517 };
518 if background.a > 0. {
519 window.paint_quad(quad(
520 bounds,
521 corners,
522 background,
523 px(0.),
524 gpui::transparent_black(),
525 BorderStyle::Solid,
526 ));
527 }
528 if outline_width <= px(0.) {
529 return;
530 }
531 let border = quad(
532 bounds,
533 corners,
534 gpui::transparent_black(),
535 if filled {
536 Edges {
537 bottom: outline_width,
538 ..Default::default()
539 }
540 } else {
541 Edges::all(outline_width)
542 },
543 outline_tint,
544 BorderStyle::Solid,
545 );
546 let Some(label_bounds) =
549 cutout
550 .as_ref()
551 .and_then(|cutout| cutout.get())
552 .filter(|label| {
553 let device_pixel = px(1. / window.scale_factor());
554 label.top() < bounds.top() + outline_width + device_pixel
555 && label.bottom() > bounds.top() - device_pixel
556 })
557 else {
558 window.paint_quad(border);
559 return;
560 };
561 let left = label_bounds.left().max(bounds.left());
564 let right = label_bounds.right().min(bounds.right());
565 for (min, max) in [
566 (bounds.origin, point(left, bounds.bottom())),
567 (point(right, bounds.top()), bounds.bottom_right()),
568 (
572 point(left, bounds.center().y),
573 point(right, bounds.bottom()),
574 ),
575 ] {
576 window.with_content_mask(
577 Some(ContentMask {
578 bounds: Bounds::from_corners(min, max),
579 }),
580 |window| window.paint_quad(border.clone()),
581 );
582 }
583 },
584 )
585 .absolute()
586 .inset_0()
587}
588
589struct LabelConfig {
590 label: SharedString,
591 label_content: Option<AnyElement>,
592 label_above: bool,
593 has_cutout: bool,
594 required: bool,
595 disabled: bool,
596 rtl: bool,
597 has_leading: bool,
598 has_trailing: bool,
599 floating: f32,
600 expanded_alignment: TextFieldLabelAlignment,
601 minimized_alignment: TextFieldLabelAlignment,
602 label_color: Hsla,
603}
604
605fn build_label(
606 config: LabelConfig,
607 metrics: &FieldMetrics,
608 focus: &FocusHandle,
609 measure_cutout: Option<Rc<Cell<Option<Bounds<Pixels>>>>>,
610) -> (Option<AnyElement>, Option<AnyElement>) {
611 let label_alignment = if config.floating >= 0.5 {
612 config.minimized_alignment
613 } else {
614 config.expanded_alignment
615 };
616 let label_padding = if config.has_cutout { px(4.) } else { px(0.) };
617 let label_left = (metrics.padding.left - label_padding).max(px(0.));
618 let label_right = (metrics.padding.right - label_padding).max(px(0.));
619 let leading_inset = if config.has_leading {
620 56. * (1. - config.floating)
621 } else {
622 0.
623 };
624 let trailing_inset = if config.has_trailing {
625 48. * (1. - config.floating)
626 } else {
627 0.
628 };
629 let (left_inset, right_inset) = if config.rtl {
630 (trailing_inset, leading_inset)
631 } else {
632 (leading_inset, trailing_inset)
633 };
634 let label_content = config
635 .label_content
636 .unwrap_or_else(|| config.label.into_any_element());
637 let label_container = div()
638 .id("label")
639 .test_support()
640 .when_else(
641 config.label_above,
642 |label| label.pl(label_left).pr(label_right),
643 |label| {
644 label
645 .absolute()
646 .top(px(metrics.label_top))
647 .left(label_left + px(left_inset))
648 .right(label_right + px(right_inset))
649 },
650 )
651 .text_size(px(metrics.label_size))
652 .line_height(px(metrics.label_height))
653 .text_color(config.label_color)
654 .flex()
655 .map(|label| match label_alignment {
656 TextFieldLabelAlignment::Center => label.justify_center(),
657 TextFieldLabelAlignment::Start if config.rtl => label.justify_end(),
658 TextFieldLabelAlignment::End if !config.rtl => label.justify_end(),
659 _ => label,
660 })
661 .child(
662 div()
663 .id("label-text")
664 .test_support()
665 .min_w_0()
666 .max_w_full()
667 .relative()
668 .truncate()
669 .when(config.has_cutout, |label| label.px(px(4.)))
670 .role(Role::Label)
671 .a11y_synthetic_children(|tree| tree.parent_node().set_hidden())
672 .when(config.required, |label| {
673 label
674 .flex()
675 .items_baseline()
676 .gap(px(4.))
677 .when(config.rtl, Styled::flex_row_reverse)
678 })
679 .child(label_content)
680 .children(config.required.then_some("*"))
681 .when_some(measure_cutout, |label, measure_cutout| {
682 label.child(
683 canvas(
684 move |bounds, _, _| measure_cutout.set(Some(bounds)),
685 |_, _, _, _| {},
686 )
687 .absolute()
688 .inset_0(),
689 )
690 }),
691 )
692 .when(!config.disabled, |label| {
693 let focus = focus.clone();
694 label.on_mouse_down(MouseButton::Left, move |_, window, cx| {
695 focus.focus(window, cx);
696 })
697 });
698 if config.label_above {
699 (Some(label_container.into_any_element()), None)
700 } else {
701 (None, Some(label_container.into_any_element()))
702 }
703}
704
705struct EditorSlots {
706 leading: Option<AnyElement>,
707 prefix: Option<AnyElement>,
708 editor: AnyElement,
709 placeholder: Option<(SharedString, AnyElement)>,
710 layout_probe: Option<gpui::Canvas<()>>,
711 suffix: Option<AnyElement>,
712 trailing: Option<AnyElement>,
713}
714
715#[allow(clippy::too_many_arguments)]
716fn build_editor_row(
717 slots: EditorSlots,
718 font: Font,
719 type_style: TypeStyle,
720 rtl: bool,
721 show_affixes: bool,
722 has_text: bool,
723 palette: &FieldPalette,
724) -> gpui::Div {
725 div()
726 .flex()
727 .items_center()
728 .gap(px(8.))
729 .min_w_0()
730 .font(font)
731 .text_size(px(type_style.size))
732 .line_height(px(type_style.line_height))
733 .when(rtl, Styled::flex_row_reverse)
734 .children(slots.leading.map(|leading| {
735 div()
736 .w(px(48.))
737 .flex_none()
738 .flex()
739 .items_center()
740 .justify_center()
741 .when_some(palette.state_colors.leading, Styled::text_color)
742 .child(leading)
743 }))
744 .children(slots.prefix.filter(|_| show_affixes).map(|prefix| {
745 div()
746 .when_some(palette.state_colors.prefix, Styled::text_color)
747 .child(prefix)
748 }))
749 .child(
750 div()
751 .flex_1()
752 .min_w_0()
753 .relative()
754 .child(slots.editor)
755 .children(slots.placeholder.filter(|_| show_affixes && !has_text).map(
756 |(_, content)| {
757 div()
758 .id("placeholder")
759 .test_support()
760 .absolute()
761 .top_0()
762 .left_0()
763 .right_0()
764 .text_color(palette.placeholder_color)
765 .role(Role::Label)
766 .a11y_synthetic_children(|tree| tree.parent_node().set_hidden())
767 .child(content)
768 },
769 ))
770 .children(slots.layout_probe),
771 )
772 .children(slots.suffix.filter(|_| show_affixes).map(|suffix| {
773 div()
774 .when_some(palette.state_colors.suffix, Styled::text_color)
775 .child(suffix)
776 }))
777 .children(slots.trailing.map(|trailing| {
778 div()
779 .when_some(palette.state_colors.trailing, Styled::text_color)
780 .child(trailing)
781 }))
782}
783
784#[allow(clippy::too_many_arguments)]
785fn build_trailing_controls(
786 id: &ElementId,
787 editor: &Editor,
788 editor_focus: &FocusHandle,
789 clearable: bool,
790 clear_label: Option<SharedString>,
791 visibility_toggle: Option<VisibilityToggle>,
792 visibility_labels: Option<(SharedString, SharedString)>,
793 custom_trailing: Option<AnyElement>,
794 is_secure: bool,
795 has_text: bool,
796 disabled: bool,
797 readonly: bool,
798 rtl: bool,
799 tint: Hsla,
800 focus_ring: Hsla,
801 window: &mut Window,
802 cx: &mut App,
803) -> Option<AnyElement> {
804 let mut items: Vec<AnyElement> = Vec::new();
805
806 if clearable && !disabled && !readonly && has_text {
807 let clear_focus = window
808 .use_keyed_state((id.clone(), "clear-button-focus"), cx, |_, cx| {
809 cx.focus_handle()
810 })
811 .read(cx)
812 .clone();
813 let label = clear_label.unwrap_or_else(|| "Clear".into());
814 let editor_click = editor.clone();
815 let editor_a11y = editor.clone();
816 let focus_click = editor_focus.clone();
817 let focus_a11y = editor_focus.clone();
818 let clear_btn = gpui_base::Button::new((id.clone(), "clear-button"))
819 .track_focus(&clear_focus)
820 .accessibility_label(label)
821 .size(px(36.))
822 .flex_none()
823 .flex()
824 .items_center()
825 .justify_center()
826 .rounded_full()
827 .text_color(tint)
828 .border_2()
829 .border_color(gpui::transparent_black())
830 .hover(move |style| style.bg(tint.opacity(0.08)))
831 .active(move |style| style.bg(tint.opacity(0.12)))
832 .focus_visible(move |style| style.border_color(focus_ring))
833 .on_click(move |_, window, cx| {
834 cx.stop_propagation();
835 editor_click.replace_all(SharedString::default(), window, cx);
836 focus_click.focus(window, cx);
837 })
838 .on_a11y_action(AccessibleAction::Click, move |_, window, cx| {
839 editor_a11y.replace_all(SharedString::default(), window, cx);
840 focus_a11y.focus(window, cx);
841 })
842 .child(
843 div()
844 .size_full()
845 .flex()
846 .items_center()
847 .justify_center()
848 .on_mouse_down(MouseButton::Left, |_, window, _| {
849 window.prevent_default();
850 })
851 .child(crate::Icon::new(crate::IconName::Close).size(px(20.))),
852 );
853 items.push(clear_btn.into_any_element());
854 }
855
856 if is_secure && let Some(toggle) = visibility_toggle {
857 let toggle_focus = window
858 .use_keyed_state((id.clone(), "visibility-toggle-focus"), cx, |_, cx| {
859 cx.focus_handle()
860 })
861 .read(cx)
862 .clone();
863 let (show_label, hide_label) =
864 visibility_labels.unwrap_or_else(|| ("Show password".into(), "Hide password".into()));
865 let label = if toggle.visible {
866 hide_label
867 } else {
868 show_label
869 };
870 let icon = if toggle.visible {
871 crate::IconName::VisibilityOff
872 } else {
873 crate::IconName::Visibility
874 };
875 let next_visible = !toggle.visible;
876 let mut button = gpui_base::Button::new((id.clone(), "visibility-toggle"))
877 .track_focus(&toggle_focus)
878 .disabled(disabled)
879 .accessibility_label(label)
880 .size(px(36.))
881 .flex_none()
882 .flex()
883 .items_center()
884 .justify_center()
885 .rounded_full()
886 .text_color(tint)
887 .border_2()
888 .border_color(gpui::transparent_black())
889 .focus_visible(move |style| style.border_color(focus_ring))
890 .child(
891 div()
892 .size_full()
893 .flex()
894 .items_center()
895 .justify_center()
896 .when(!disabled, |icon_slot| {
897 icon_slot.on_mouse_down(MouseButton::Left, |_, window, _| {
898 window.prevent_default();
899 })
900 })
901 .child(crate::Icon::new(icon).size(px(20.))),
902 );
903 if !disabled {
904 let on_toggle = toggle.on_toggle;
905 let bound = Rc::new(ThemeScope::bind_action(
906 move |window, cx| on_toggle(next_visible, window, cx),
907 window,
908 cx,
909 ));
910 let invoke_click = bound.clone();
911 let focus_click = editor_focus.clone();
912 button = button
913 .hover(move |style| style.bg(tint.opacity(0.08)))
914 .active(move |style| style.bg(tint.opacity(0.12)))
915 .on_click(move |event, window, cx| {
916 cx.stop_propagation();
917 invoke_click(window, cx);
918 if matches!(event, ClickEvent::Mouse(_)) {
919 focus_click.focus(window, cx);
920 }
921 })
922 .on_a11y_action(AccessibleAction::Click, move |_, window, cx| {
923 bound(window, cx);
924 });
925 }
926 items.push(button.into_any_element());
927 }
928
929 if let Some(custom) = custom_trailing {
930 items.push(custom);
931 }
932
933 match items.len() {
934 0 => None,
935 1 => items.into_iter().next(),
936 _ => Some(
937 div()
938 .flex()
939 .items_center()
940 .gap(px(4.))
941 .when(rtl, Styled::flex_row_reverse)
942 .children(items)
943 .into_any_element(),
944 ),
945 }
946}
947
948#[allow(clippy::too_many_arguments)]
949fn build_supporting_row(
950 support: Option<FieldDescription>,
951 count: Option<SharedString>,
952 padding: Edges<Pixels>,
953 caption_style: TypeStyle,
954 palette: &FieldPalette,
955 error: bool,
956 disabled: bool,
957 rtl: bool,
958) -> impl IntoElement {
959 div()
960 .id("supporting")
961 .test_support()
962 .pl(padding.left)
963 .pr(padding.right)
964 .text_size(px(caption_style.size))
965 .line_height(px(caption_style.line_height))
966 .text_color(
967 palette
968 .state_colors
969 .supporting
970 .unwrap_or(if error && !disabled {
971 palette.indicator
972 } else {
973 palette.secondary
974 }),
975 )
976 .flex()
977 .gap(px(8.))
978 .justify_between()
979 .when(rtl, Styled::flex_row_reverse)
980 .on_mouse_down(MouseButton::Left, |_, window, _| {
981 window.prevent_default();
982 })
983 .on_mouse_down(MouseButton::Right, |_, window, _| {
984 window.prevent_default();
985 })
986 .on_mouse_down(MouseButton::Middle, |_, window, _| {
987 window.prevent_default();
988 })
989 .child(div().flex_1().min_w_0().children(support.map(|support| {
990 support
991 .content
992 .unwrap_or_else(|| support.text.into_any_element())
993 })))
994 .children(count.map(|count| div().flex_none().child(count)))
995}
996
997impl RenderOnce for TextField {
998 fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
999 let theme = current_material_theme(window, cx).clone();
1000 let direction = theme.layout.direction;
1001 let rtl = direction == Direction::Rtl;
1002 let presentation = match &self.editor {
1003 Editor::Single(state) | Editor::Secure(state) => state.read(cx).presentation(),
1004 Editor::Multiple(state) => state.read(cx).presentation(),
1005 };
1006 let disabled = presentation.is_disabled();
1007 let readonly = presentation.is_readonly();
1008 let focus = presentation.focus_handle().clone();
1009 if disabled && focus.is_focused(window) {
1010 let blur_focus = focus.clone();
1011 window.defer(cx, move |window, cx| {
1012 if blur_focus.is_focused(window) {
1013 window.blur(cx);
1014 }
1015 });
1016 }
1017 let focused = !disabled && focus.is_focused(window);
1018 let filled = self.variant == TextFieldVariant::Filled;
1019 let label_position = self.label_position.unwrap_or(if filled {
1020 TextFieldLabelPosition::Inside
1021 } else {
1022 TextFieldLabelPosition::Cutout
1023 });
1024 let label_inside = self.show_label && label_position == TextFieldLabelPosition::Inside;
1025 let label_above = self.show_label && label_position == TextFieldLabelPosition::Above;
1026 let has_cutout =
1027 self.show_label && label_position == TextFieldLabelPosition::Cutout && !filled;
1028 let error = self.invalid;
1029
1030 let shape = self.shape.unwrap_or(
1031 if filled {
1032 CornerRole::ExtraSmallTop
1033 } else {
1034 CornerRole::ExtraSmall
1035 }
1036 .shape(),
1037 );
1038 let type_style = LayoutPolicy::scale_text(
1039 theme.typography.scale_style(
1040 self.text_style
1041 .unwrap_or(TypeRole::BodyLarge.style(TypographyEmphasis::Baseline)),
1042 ),
1043 self.font_scale,
1044 );
1045 let caption_style = LayoutPolicy::scale_text(
1046 theme
1047 .typography
1048 .style(TypeRole::BodySmall, TypographyEmphasis::Baseline),
1049 self.font_scale,
1050 );
1051 let font = font_for_style(&theme.typography, type_style, cx);
1052 let has_text = match &self.editor {
1053 Editor::Single(state) | Editor::Secure(state) => !state.read(cx).value().is_empty(),
1054 Editor::Multiple(state) => !state.read(cx).value().is_empty(),
1055 };
1056 let animation = sample_animation(
1057 &self.id,
1058 &theme,
1059 focused || has_text || self.label_minimized || label_above || !self.show_label,
1060 focused,
1061 error && !disabled,
1062 window,
1063 cx,
1064 );
1065 let effective_floating = if self.show_label {
1066 animation.floating
1067 } else {
1068 1.
1069 };
1070 let hover = window
1071 .use_keyed_state((self.id.clone(), "field-hover"), cx, |_, _| {
1072 Rc::new(Cell::new(false))
1073 })
1074 .read(cx)
1075 .clone();
1076 let tracker = self.interaction_source.map(|source| {
1077 let tracker = InteractionSource::track(&source, &self.id, window, cx);
1078 tracker.record(
1079 interaction_state(
1080 disabled,
1081 hover.get(),
1082 focused && window.last_input_was_keyboard(),
1083 ),
1084 cx,
1085 );
1086 tracker
1087 });
1088 let palette = resolve_palette(
1089 &theme,
1090 self.colors,
1091 filled,
1092 disabled,
1093 error,
1094 focused,
1095 hover.get(),
1096 &animation,
1097 );
1098 let style = build_editor_style(
1099 &theme,
1100 &palette,
1101 has_text,
1102 self.placeholder.is_some(),
1103 effective_floating,
1104 self.dropdown_editor && readonly,
1105 error,
1106 );
1107 let label = self.label;
1108 let accessible_id = self.id.to_string();
1109 let align = if rtl {
1110 TextAlign::Right
1111 } else {
1112 TextAlign::Left
1113 };
1114 let layout_probe =
1115 build_layout_probe(&self.id, &self.editor, self.on_text_layout, window, cx);
1116 let editor_for_clear = self.editor.clone();
1117 let is_secure = matches!(self.editor, Editor::Secure(_));
1118 let configured = configure_and_build_editor(
1119 &self.id,
1120 self.editor,
1121 self.obfuscation_mode,
1122 &presentation,
1123 align,
1124 style,
1125 &theme,
1126 readonly,
1127 disabled,
1128 window,
1129 cx,
1130 );
1131 let support = self.error.map_or(self.supporting, |text| {
1132 Some(FieldDescription {
1133 text,
1134 content: None,
1135 })
1136 });
1137 let support_text = support.as_ref().map(|support| &support.text);
1138 let (count, description) =
1139 if let Some((limit, text)) = self.character_count.zip(configured.value.as_ref()) {
1140 let cache = window.use_keyed_state((self.id.clone(), "char-count"), cx, |_, _| {
1141 CharacterCountCache::default()
1142 });
1143 cache.update(cx, |cache, _| {
1144 let text_or_limit_changed = cache.limit != Some(limit) || &cache.text != text;
1145 if text_or_limit_changed {
1146 cache.text = text.clone();
1147 cache.limit = Some(limit);
1148 cache.count_label = format!("{} / {limit}", text.chars().count()).into();
1149 }
1150 if text_or_limit_changed || cache.support_text.as_ref() != support_text {
1151 cache.support_text = support_text.cloned();
1152 cache.combined_support = Some(match support_text {
1153 Some(support) => format!("{support}. {}", cache.count_label).into(),
1154 None => cache.count_label.clone(),
1155 });
1156 }
1157 (
1158 Some(cache.count_label.clone()),
1159 cache.combined_support.clone(),
1160 )
1161 })
1162 } else {
1163 (None, support_text.cloned())
1164 };
1165 let placeholder_hint = self.placeholder.as_ref().map_or_else(
1166 || presentation.placeholder().clone(),
1167 |(hint, _)| hint.clone(),
1168 );
1169 let metrics = resolve_metrics(
1170 type_style,
1171 caption_style,
1172 &animation,
1173 theme.layout.density,
1174 self.min_height,
1175 self.indicator_width,
1176 self.content_padding,
1177 label_inside,
1178 filled,
1179 );
1180 let cutout = has_cutout.then(|| Rc::new(Cell::new(None::<Bounds<Pixels>>)));
1181 let outline_canvas = build_outline_canvas(
1182 shape,
1183 direction,
1184 palette.background,
1185 filled,
1186 metrics.outline_width,
1187 palette.outline_tint,
1188 cutout.clone(),
1189 );
1190 let trailing_tint = palette.state_colors.trailing.unwrap_or(palette.secondary);
1191 let focus_ring = color(theme.colors.color(ColorRole::Secondary));
1192 let trailing = build_trailing_controls(
1193 &self.id,
1194 &editor_for_clear,
1195 &focus,
1196 self.clearable,
1197 self.clear_label,
1198 self.visibility_toggle,
1199 self.visibility_labels,
1200 self.trailing,
1201 is_secure,
1202 has_text,
1203 disabled,
1204 readonly,
1205 rtl,
1206 trailing_tint,
1207 focus_ring,
1208 window,
1209 cx,
1210 );
1211 let (above_label, attached_label) = if self.show_label {
1212 build_label(
1213 LabelConfig {
1214 label: label.clone(),
1215 label_content: self.label_content,
1216 label_above,
1217 has_cutout,
1218 required: self.required,
1219 disabled,
1220 rtl,
1221 has_leading: self.leading.is_some(),
1222 has_trailing: trailing.is_some(),
1223 floating: animation.floating,
1224 expanded_alignment: self.expanded_alignment,
1225 minimized_alignment: self.minimized_alignment,
1226 label_color: palette.label_color,
1227 },
1228 &metrics,
1229 &focus,
1230 cutout,
1231 )
1232 } else {
1233 (None, None)
1234 };
1235 let show_affixes = effective_floating >= 0.5;
1236 let editor_row = build_editor_row(
1237 EditorSlots {
1238 leading: self.leading,
1239 prefix: self.prefix,
1240 editor: configured.element,
1241 placeholder: self.placeholder,
1242 layout_probe,
1243 suffix: self.suffix,
1244 trailing,
1245 },
1246 font.clone(),
1247 type_style,
1248 rtl,
1249 show_affixes,
1250 has_text,
1251 &palette,
1252 );
1253
1254 div()
1255 .id(self.id)
1256 .test_support()
1257 .w_full()
1258 .min_w_0()
1259 .flex()
1260 .flex_col()
1261 .gap(px(4.))
1262 .font_family(font.family)
1263 .role(match (self.expanded, readonly) {
1264 (Some(_), true) => Role::ComboBox,
1265 (Some(_), false) => Role::EditableComboBox,
1266 _ => configured.role,
1267 })
1268 .aria_label(label)
1269 .accessibility_id(accessible_id)
1270 .aria_placeholder(placeholder_hint)
1271 .when_some(self.expanded, |field, expanded| {
1272 field.aria_expanded(expanded)
1273 })
1274 .when_some(
1275 self.dropdown_request.filter(|_| !disabled),
1276 |field, request| {
1277 let open = self.expanded.unwrap_or_default();
1278 let click = request.clone();
1279 field
1280 .on_a11y_action(AccessibleAction::Click, move |_, window, cx| {
1281 click(!open, window, cx);
1282 })
1283 .on_a11y_action(
1284 if open {
1285 AccessibleAction::Collapse
1286 } else {
1287 AccessibleAction::Expand
1288 },
1289 move |_, window, cx| request(!open, window, cx),
1290 )
1291 },
1292 )
1293 .when(!disabled, |field| field.track_focus(&focus).tab_stop(false))
1294 .when_some(configured.value, |field, value| field.aria_value(value))
1295 .when_some(configured.set_value, |field, editor| {
1296 field.on_a11y_action(AccessibleAction::SetValue, move |data, window, cx| {
1297 if let Some(gpui::accesskit::ActionData::Value(value)) = data {
1298 editor.replace_all(value.to_string().into(), window, cx);
1299 }
1300 })
1301 })
1302 .when_some(description, |field, text| field.aria_description(text))
1303 .a11y_synthetic_children(move |tree| {
1304 let node = tree.parent_node();
1305 if error {
1306 node.set_invalid(gpui::accesskit::Invalid::True);
1307 }
1308 if disabled {
1309 node.set_disabled();
1310 }
1311 if readonly || disabled {
1312 node.set_read_only();
1313 }
1314 if self.required {
1315 node.set_required();
1316 }
1317 })
1318 .child(
1319 div()
1320 .w_full()
1321 .min_w_0()
1322 .flex()
1323 .flex_col()
1324 .gap(px(4.))
1325 .when(!disabled && self.expanded != Some(true), |region| {
1326 let blur_focus = focus.clone();
1327 region.on_mouse_down_out(move |_, window, cx| {
1328 if blur_focus.is_focused(window) {
1329 window.blur(cx);
1330 }
1331 })
1332 })
1333 .children(above_label)
1334 .child(
1335 div()
1336 .id("container")
1337 .test_support()
1338 .relative()
1339 .flex()
1340 .flex_col()
1341 .when_else(
1342 label_inside || presentation.is_multi_line(),
1343 Styled::justify_end,
1344 Styled::justify_center,
1345 )
1346 .min_h(metrics.minimum_height)
1347 .pt(metrics.editor_top_padding)
1348 .pr(metrics.padding.right)
1349 .pb(metrics.editor_bottom_padding)
1350 .pl(metrics.padding.left)
1351 .when(!disabled, |field| {
1352 field.on_hover(move |hovering, window, cx| {
1353 if hover.replace(*hovering) != *hovering {
1354 if let Some(tracker) = &tracker {
1355 tracker.record(
1356 interaction_state(
1357 false,
1358 *hovering,
1359 focus.is_focused(window)
1360 && window.last_input_was_keyboard(),
1361 ),
1362 cx,
1363 );
1364 }
1365 window.refresh();
1366 }
1367 })
1368 })
1369 .child(outline_canvas)
1370 .when(rtl, |field| field.text_align(TextAlign::Right))
1371 .child(editor_row)
1372 .children(attached_label),
1373 ),
1374 )
1375 .when(support.is_some() || count.is_some(), |field| {
1376 field.child(build_supporting_row(
1377 support,
1378 count,
1379 metrics.padding,
1380 caption_style,
1381 &palette,
1382 error,
1383 disabled,
1384 rtl,
1385 ))
1386 })
1387 }
1388}