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, Direction, LayoutPolicy, MaterialTheme, MotionKind,
22 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
423fn resolve_metrics(
424 type_style: TypeStyle,
425 caption_style: TypeStyle,
426 animation: &FieldAnimation,
427 content_padding: Option<Edges<Pixels>>,
428 label_inside: bool,
429 filled: bool,
430) -> FieldMetrics {
431 let label_size = type_style.size + (caption_style.size - type_style.size) * animation.floating;
432 let label_height = type_style.line_height
433 + (caption_style.line_height - type_style.line_height) * animation.floating;
434 let outline_width = px(1. + animation.focus_amount);
435 let padding = content_padding.unwrap_or(Edges {
436 left: px(16.),
437 right: px(16.),
438 top: px(if label_inside { 8. } else { 4. }),
439 bottom: if label_inside && filled {
440 px(8.) - outline_width
441 } else {
442 px(4.)
443 },
444 });
445 let label_reserve = if label_inside {
446 px(caption_style.line_height)
447 } else {
448 px(0.)
449 };
450 let editor_top_padding = padding.top + label_reserve;
451 let editor_bottom_padding = padding.bottom + if filled { outline_width } else { px(0.) };
453 let minimum_height = px(56.)
454 .max(px(type_style.line_height + 16.) + label_reserve)
455 .max(px(type_style.line_height) + editor_top_padding + editor_bottom_padding);
456 let resting_top = f32::from(minimum_height - px(type_style.line_height)) * 0.5;
457 let floating_top = if label_inside {
458 f32::from(padding.top)
459 } else {
460 -caption_style.line_height * 0.5
461 };
462 let label_top = resting_top + (floating_top - resting_top) * animation.floating;
463 FieldMetrics {
464 label_size,
465 label_height,
466 outline_width,
467 padding,
468 editor_top_padding,
469 editor_bottom_padding,
470 minimum_height,
471 label_top,
472 }
473}
474
475#[allow(clippy::too_many_arguments)]
476fn build_outline_canvas(
477 shape: CornerShape,
478 direction: Direction,
479 background: Hsla,
480 filled: bool,
481 outline_width: Pixels,
482 outline_tint: Hsla,
483 cutout: Option<Rc<Cell<Option<Bounds<Pixels>>>>>,
484) -> gpui::Canvas<()> {
485 canvas(
486 |_, _, _| (),
487 move |bounds, _, window, _| {
488 let [top_left, top_right, bottom_right, bottom_left] = shape
489 .radii(
490 bounds.size.width.into(),
491 bounds.size.height.into(),
492 direction,
493 )
494 .map(px);
495 let corners = Corners {
496 top_left,
497 top_right,
498 bottom_right,
499 bottom_left,
500 };
501 if background.a > 0. {
502 window.paint_quad(quad(
503 bounds,
504 corners,
505 background,
506 px(0.),
507 gpui::transparent_black(),
508 BorderStyle::Solid,
509 ));
510 }
511 let border = quad(
512 bounds,
513 corners,
514 gpui::transparent_black(),
515 if filled {
516 Edges {
517 bottom: outline_width,
518 ..Default::default()
519 }
520 } else {
521 Edges::all(outline_width)
522 },
523 outline_tint,
524 BorderStyle::Solid,
525 );
526 let Some(label_bounds) =
529 cutout
530 .as_ref()
531 .and_then(|cutout| cutout.get())
532 .filter(|label| {
533 let device_pixel = px(1. / window.scale_factor());
534 label.top() < bounds.top() + outline_width + device_pixel
535 && label.bottom() > bounds.top() - device_pixel
536 })
537 else {
538 window.paint_quad(border);
539 return;
540 };
541 let left = label_bounds.left().max(bounds.left());
544 let right = label_bounds.right().min(bounds.right());
545 for (min, max) in [
546 (bounds.origin, point(left, bounds.bottom())),
547 (point(right, bounds.top()), bounds.bottom_right()),
548 (
552 point(left, bounds.center().y),
553 point(right, bounds.bottom()),
554 ),
555 ] {
556 window.with_content_mask(
557 Some(ContentMask {
558 bounds: Bounds::from_corners(min, max),
559 }),
560 |window| window.paint_quad(border.clone()),
561 );
562 }
563 },
564 )
565 .absolute()
566 .inset_0()
567}
568
569struct LabelConfig {
570 label: SharedString,
571 label_content: Option<AnyElement>,
572 label_above: bool,
573 has_cutout: bool,
574 required: bool,
575 disabled: bool,
576 rtl: bool,
577 has_leading: bool,
578 has_trailing: bool,
579 floating: f32,
580 expanded_alignment: TextFieldLabelAlignment,
581 minimized_alignment: TextFieldLabelAlignment,
582 label_color: Hsla,
583}
584
585fn build_label(
586 config: LabelConfig,
587 metrics: &FieldMetrics,
588 focus: &FocusHandle,
589 measure_cutout: Option<Rc<Cell<Option<Bounds<Pixels>>>>>,
590) -> (Option<AnyElement>, Option<AnyElement>) {
591 let label_alignment = if config.floating >= 0.5 {
592 config.minimized_alignment
593 } else {
594 config.expanded_alignment
595 };
596 let label_padding = if config.has_cutout { px(4.) } else { px(0.) };
597 let label_left = (metrics.padding.left - label_padding).max(px(0.));
598 let label_right = (metrics.padding.right - label_padding).max(px(0.));
599 let leading_inset = if config.has_leading {
600 56. * (1. - config.floating)
601 } else {
602 0.
603 };
604 let trailing_inset = if config.has_trailing {
605 48. * (1. - config.floating)
606 } else {
607 0.
608 };
609 let (left_inset, right_inset) = if config.rtl {
610 (trailing_inset, leading_inset)
611 } else {
612 (leading_inset, trailing_inset)
613 };
614 let label_content = config
615 .label_content
616 .unwrap_or_else(|| config.label.into_any_element());
617 let label_container = div()
618 .id("label")
619 .test_support()
620 .when_else(
621 config.label_above,
622 |label| label.pl(label_left).pr(label_right),
623 |label| {
624 label
625 .absolute()
626 .top(px(metrics.label_top))
627 .left(label_left + px(left_inset))
628 .right(label_right + px(right_inset))
629 },
630 )
631 .text_size(px(metrics.label_size))
632 .line_height(px(metrics.label_height))
633 .text_color(config.label_color)
634 .flex()
635 .map(|label| match label_alignment {
636 TextFieldLabelAlignment::Center => label.justify_center(),
637 TextFieldLabelAlignment::Start if config.rtl => label.justify_end(),
638 TextFieldLabelAlignment::End if !config.rtl => label.justify_end(),
639 _ => label,
640 })
641 .child(
642 div()
643 .id("label-text")
644 .test_support()
645 .min_w_0()
646 .max_w_full()
647 .relative()
648 .truncate()
649 .when(config.has_cutout, |label| label.px(px(4.)))
650 .role(Role::Label)
651 .a11y_synthetic_children(|tree| tree.parent_node().set_hidden())
652 .when(config.required, |label| {
653 label
654 .flex()
655 .items_baseline()
656 .gap(px(4.))
657 .when(config.rtl, Styled::flex_row_reverse)
658 })
659 .child(label_content)
660 .children(config.required.then_some("*"))
661 .when_some(measure_cutout, |label, measure_cutout| {
662 label.child(
663 canvas(
664 move |bounds, _, _| measure_cutout.set(Some(bounds)),
665 |_, _, _, _| {},
666 )
667 .absolute()
668 .inset_0(),
669 )
670 }),
671 )
672 .when(!config.disabled, |label| {
673 let focus = focus.clone();
674 label.on_mouse_down(MouseButton::Left, move |_, window, cx| {
675 focus.focus(window, cx);
676 })
677 });
678 if config.label_above {
679 (Some(label_container.into_any_element()), None)
680 } else {
681 (None, Some(label_container.into_any_element()))
682 }
683}
684
685struct EditorSlots {
686 leading: Option<AnyElement>,
687 prefix: Option<AnyElement>,
688 editor: AnyElement,
689 placeholder: Option<(SharedString, AnyElement)>,
690 layout_probe: Option<gpui::Canvas<()>>,
691 suffix: Option<AnyElement>,
692 trailing: Option<AnyElement>,
693}
694
695#[allow(clippy::too_many_arguments)]
696fn build_editor_row(
697 slots: EditorSlots,
698 font: Font,
699 type_style: TypeStyle,
700 rtl: bool,
701 show_affixes: bool,
702 has_text: bool,
703 palette: &FieldPalette,
704) -> gpui::Div {
705 div()
706 .flex()
707 .items_center()
708 .gap(px(8.))
709 .min_w_0()
710 .font(font)
711 .text_size(px(type_style.size))
712 .line_height(px(type_style.line_height))
713 .when(rtl, Styled::flex_row_reverse)
714 .children(slots.leading.map(|leading| {
715 div()
716 .w(px(48.))
717 .flex_none()
718 .flex()
719 .items_center()
720 .justify_center()
721 .when_some(palette.state_colors.leading, Styled::text_color)
722 .child(leading)
723 }))
724 .children(slots.prefix.filter(|_| show_affixes).map(|prefix| {
725 div()
726 .when_some(palette.state_colors.prefix, Styled::text_color)
727 .child(prefix)
728 }))
729 .child(
730 div()
731 .flex_1()
732 .min_w_0()
733 .relative()
734 .child(slots.editor)
735 .children(slots.placeholder.filter(|_| show_affixes && !has_text).map(
736 |(_, content)| {
737 div()
738 .id("placeholder")
739 .test_support()
740 .absolute()
741 .top_0()
742 .left_0()
743 .right_0()
744 .text_color(palette.placeholder_color)
745 .role(Role::Label)
746 .a11y_synthetic_children(|tree| tree.parent_node().set_hidden())
747 .child(content)
748 },
749 ))
750 .children(slots.layout_probe),
751 )
752 .children(slots.suffix.filter(|_| show_affixes).map(|suffix| {
753 div()
754 .when_some(palette.state_colors.suffix, Styled::text_color)
755 .child(suffix)
756 }))
757 .children(slots.trailing.map(|trailing| {
758 div()
759 .when_some(palette.state_colors.trailing, Styled::text_color)
760 .child(trailing)
761 }))
762}
763
764#[allow(clippy::too_many_arguments)]
765fn build_trailing_controls(
766 id: &ElementId,
767 editor: &Editor,
768 editor_focus: &FocusHandle,
769 clearable: bool,
770 clear_label: Option<SharedString>,
771 visibility_toggle: Option<VisibilityToggle>,
772 visibility_labels: Option<(SharedString, SharedString)>,
773 custom_trailing: Option<AnyElement>,
774 is_secure: bool,
775 has_text: bool,
776 disabled: bool,
777 readonly: bool,
778 rtl: bool,
779 tint: Hsla,
780 focus_ring: Hsla,
781 window: &mut Window,
782 cx: &mut App,
783) -> Option<AnyElement> {
784 let mut items: Vec<AnyElement> = Vec::new();
785
786 if clearable && !disabled && !readonly && has_text {
787 let clear_focus = window
788 .use_keyed_state((id.clone(), "clear-button-focus"), cx, |_, cx| {
789 cx.focus_handle()
790 })
791 .read(cx)
792 .clone();
793 let label = clear_label.unwrap_or_else(|| "Clear".into());
794 let editor_click = editor.clone();
795 let editor_a11y = editor.clone();
796 let focus_click = editor_focus.clone();
797 let focus_a11y = editor_focus.clone();
798 let clear_btn = gpui_base::Button::new((id.clone(), "clear-button"))
799 .track_focus(&clear_focus)
800 .accessibility_label(label)
801 .size(px(36.))
802 .flex_none()
803 .flex()
804 .items_center()
805 .justify_center()
806 .rounded_full()
807 .text_color(tint)
808 .border_2()
809 .border_color(gpui::transparent_black())
810 .hover(move |style| style.bg(tint.opacity(0.08)))
811 .active(move |style| style.bg(tint.opacity(0.12)))
812 .focus_visible(move |style| style.border_color(focus_ring))
813 .on_click(move |_, window, cx| {
814 cx.stop_propagation();
815 editor_click.replace_all(SharedString::default(), window, cx);
816 focus_click.focus(window, cx);
817 })
818 .on_a11y_action(AccessibleAction::Click, move |_, window, cx| {
819 editor_a11y.replace_all(SharedString::default(), window, cx);
820 focus_a11y.focus(window, cx);
821 })
822 .child(crate::Icon::new(crate::IconName::Close).size(px(20.)));
823 items.push(clear_btn.into_any_element());
824 }
825
826 if is_secure && let Some(toggle) = visibility_toggle {
827 let toggle_focus = window
828 .use_keyed_state((id.clone(), "visibility-toggle-focus"), cx, |_, cx| {
829 cx.focus_handle()
830 })
831 .read(cx)
832 .clone();
833 let (show_label, hide_label) =
834 visibility_labels.unwrap_or_else(|| ("Show password".into(), "Hide password".into()));
835 let label = if toggle.visible {
836 hide_label
837 } else {
838 show_label
839 };
840 let icon = if toggle.visible {
841 crate::IconName::VisibilityOff
842 } else {
843 crate::IconName::Visibility
844 };
845 let next_visible = !toggle.visible;
846 let mut button = gpui_base::Button::new((id.clone(), "visibility-toggle"))
847 .track_focus(&toggle_focus)
848 .disabled(disabled)
849 .accessibility_label(label)
850 .size(px(36.))
851 .flex_none()
852 .flex()
853 .items_center()
854 .justify_center()
855 .rounded_full()
856 .text_color(tint)
857 .border_2()
858 .border_color(gpui::transparent_black())
859 .focus_visible(move |style| style.border_color(focus_ring))
860 .child(crate::Icon::new(icon).size(px(20.)));
861 if !disabled {
862 let on_toggle = toggle.on_toggle;
863 let bound = Rc::new(ThemeScope::bind_action(
864 move |window, cx| on_toggle(next_visible, window, cx),
865 window,
866 cx,
867 ));
868 let invoke_click = bound.clone();
869 let focus_click = editor_focus.clone();
870 button = button
871 .hover(move |style| style.bg(tint.opacity(0.08)))
872 .active(move |style| style.bg(tint.opacity(0.12)))
873 .on_click(move |event, window, cx| {
874 cx.stop_propagation();
875 invoke_click(window, cx);
876 if matches!(event, ClickEvent::Mouse(_)) {
877 focus_click.focus(window, cx);
878 }
879 })
880 .on_a11y_action(AccessibleAction::Click, move |_, window, cx| {
881 bound(window, cx);
882 });
883 }
884 items.push(button.into_any_element());
885 }
886
887 if let Some(custom) = custom_trailing {
888 items.push(custom);
889 }
890
891 match items.len() {
892 0 => None,
893 1 => items.into_iter().next(),
894 _ => Some(
895 div()
896 .flex()
897 .items_center()
898 .gap(px(4.))
899 .when(rtl, Styled::flex_row_reverse)
900 .children(items)
901 .into_any_element(),
902 ),
903 }
904}
905
906#[allow(clippy::too_many_arguments)]
907fn build_supporting_row(
908 support: Option<FieldDescription>,
909 count: Option<SharedString>,
910 padding: Edges<Pixels>,
911 caption_style: TypeStyle,
912 palette: &FieldPalette,
913 error: bool,
914 disabled: bool,
915 rtl: bool,
916) -> gpui::Div {
917 div()
918 .pl(padding.left)
919 .pr(padding.right)
920 .text_size(px(caption_style.size))
921 .line_height(px(caption_style.line_height))
922 .text_color(
923 palette
924 .state_colors
925 .supporting
926 .unwrap_or(if error && !disabled {
927 palette.indicator
928 } else {
929 palette.secondary
930 }),
931 )
932 .flex()
933 .gap(px(8.))
934 .justify_between()
935 .when(rtl, Styled::flex_row_reverse)
936 .child(div().flex_1().min_w_0().children(support.map(|support| {
937 support
938 .content
939 .unwrap_or_else(|| support.text.into_any_element())
940 })))
941 .children(count.map(|count| div().flex_none().child(count)))
942}
943
944impl RenderOnce for TextField {
945 fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
946 let theme = current_material_theme(window, cx).clone();
947 let direction = theme.layout.direction;
948 let rtl = direction == Direction::Rtl;
949 let presentation = match &self.editor {
950 Editor::Single(state) | Editor::Secure(state) => state.read(cx).presentation(),
951 Editor::Multiple(state) => state.read(cx).presentation(),
952 };
953 let disabled = presentation.is_disabled();
954 let readonly = presentation.is_readonly();
955 let focus = presentation.focus_handle().clone();
956 let focused = !disabled && focus.is_focused(window);
957 let filled = self.variant == TextFieldVariant::Filled;
958 let label_position = self.label_position.unwrap_or(if filled {
959 TextFieldLabelPosition::Inside
960 } else {
961 TextFieldLabelPosition::Cutout
962 });
963 let label_inside = label_position == TextFieldLabelPosition::Inside;
964 let label_above = label_position == TextFieldLabelPosition::Above;
965 let has_cutout = label_position == TextFieldLabelPosition::Cutout && !filled;
966 let error = self.invalid;
967
968 let shape = self.shape.unwrap_or(
969 if filled {
970 CornerRole::ExtraSmallTop
971 } else {
972 CornerRole::ExtraSmall
973 }
974 .shape(),
975 );
976 let type_style = LayoutPolicy::scale_text(
977 theme.typography.scale_style(
978 self.text_style
979 .unwrap_or(TypeRole::BodyLarge.style(TypographyEmphasis::Baseline)),
980 ),
981 self.font_scale,
982 );
983 let caption_style = LayoutPolicy::scale_text(
984 theme
985 .typography
986 .style(TypeRole::BodySmall, TypographyEmphasis::Baseline),
987 self.font_scale,
988 );
989 let font = font_for_style(&theme.typography, type_style, cx);
990 let has_text = match &self.editor {
991 Editor::Single(state) | Editor::Secure(state) => !state.read(cx).value().is_empty(),
992 Editor::Multiple(state) => !state.read(cx).value().is_empty(),
993 };
994 let animation = sample_animation(
995 &self.id,
996 &theme,
997 focused || has_text || self.label_minimized || label_above,
998 focused,
999 error && !disabled,
1000 window,
1001 cx,
1002 );
1003 let hover = window
1004 .use_keyed_state((self.id.clone(), "field-hover"), cx, |_, _| {
1005 Rc::new(Cell::new(false))
1006 })
1007 .read(cx)
1008 .clone();
1009 let tracker = self.interaction_source.map(|source| {
1010 let tracker = InteractionSource::track(&source, &self.id, window, cx);
1011 tracker.record(
1012 interaction_state(
1013 disabled,
1014 hover.get(),
1015 focused && window.last_input_was_keyboard(),
1016 ),
1017 cx,
1018 );
1019 tracker
1020 });
1021 let palette = resolve_palette(
1022 &theme,
1023 self.colors,
1024 filled,
1025 disabled,
1026 error,
1027 focused,
1028 hover.get(),
1029 &animation,
1030 );
1031 let style = build_editor_style(
1032 &theme,
1033 &palette,
1034 has_text,
1035 self.placeholder.is_some(),
1036 animation.floating,
1037 self.dropdown_editor && readonly,
1038 error,
1039 );
1040 let label = self.label;
1041 let accessible_id = self.id.to_string();
1042 let align = if rtl {
1043 TextAlign::Right
1044 } else {
1045 TextAlign::Left
1046 };
1047 let layout_probe =
1048 build_layout_probe(&self.id, &self.editor, self.on_text_layout, window, cx);
1049 let editor_for_clear = self.editor.clone();
1050 let is_secure = matches!(self.editor, Editor::Secure(_));
1051 let configured = configure_and_build_editor(
1052 &self.id,
1053 self.editor,
1054 self.obfuscation_mode,
1055 &presentation,
1056 align,
1057 style,
1058 &theme,
1059 readonly,
1060 disabled,
1061 window,
1062 cx,
1063 );
1064 let support = self.error.map_or(self.supporting, |text| {
1065 Some(FieldDescription {
1066 text,
1067 content: None,
1068 })
1069 });
1070 let support_text = support.as_ref().map(|support| &support.text);
1071 let (count, description) =
1072 if let Some((limit, text)) = self.character_count.zip(configured.value.as_ref()) {
1073 let cache = window.use_keyed_state((self.id.clone(), "char-count"), cx, |_, _| {
1074 CharacterCountCache::default()
1075 });
1076 cache.update(cx, |cache, _| {
1077 let text_or_limit_changed = cache.limit != Some(limit) || &cache.text != text;
1078 if text_or_limit_changed {
1079 cache.text = text.clone();
1080 cache.limit = Some(limit);
1081 cache.count_label = format!("{} / {limit}", text.chars().count()).into();
1082 }
1083 if text_or_limit_changed || cache.support_text.as_ref() != support_text {
1084 cache.support_text = support_text.cloned();
1085 cache.combined_support = Some(match support_text {
1086 Some(support) => format!("{support}. {}", cache.count_label).into(),
1087 None => cache.count_label.clone(),
1088 });
1089 }
1090 (
1091 Some(cache.count_label.clone()),
1092 cache.combined_support.clone(),
1093 )
1094 })
1095 } else {
1096 (None, support_text.cloned())
1097 };
1098 let placeholder_hint = self.placeholder.as_ref().map_or_else(
1099 || presentation.placeholder().clone(),
1100 |(hint, _)| hint.clone(),
1101 );
1102 let metrics = resolve_metrics(
1103 type_style,
1104 caption_style,
1105 &animation,
1106 self.content_padding,
1107 label_inside,
1108 filled,
1109 );
1110 let cutout = has_cutout.then(|| Rc::new(Cell::new(None::<Bounds<Pixels>>)));
1111 let outline_canvas = build_outline_canvas(
1112 shape,
1113 direction,
1114 palette.background,
1115 filled,
1116 metrics.outline_width,
1117 palette.outline_tint,
1118 cutout.clone(),
1119 );
1120 let trailing_tint = palette.state_colors.trailing.unwrap_or(palette.secondary);
1121 let focus_ring = color(theme.colors.color(ColorRole::Secondary));
1122 let trailing = build_trailing_controls(
1123 &self.id,
1124 &editor_for_clear,
1125 &focus,
1126 self.clearable,
1127 self.clear_label,
1128 self.visibility_toggle,
1129 self.visibility_labels,
1130 self.trailing,
1131 is_secure,
1132 has_text,
1133 disabled,
1134 readonly,
1135 rtl,
1136 trailing_tint,
1137 focus_ring,
1138 window,
1139 cx,
1140 );
1141 let (above_label, attached_label) = build_label(
1142 LabelConfig {
1143 label: label.clone(),
1144 label_content: self.label_content,
1145 label_above,
1146 has_cutout,
1147 required: self.required,
1148 disabled,
1149 rtl,
1150 has_leading: self.leading.is_some(),
1151 has_trailing: trailing.is_some(),
1152 floating: animation.floating,
1153 expanded_alignment: self.expanded_alignment,
1154 minimized_alignment: self.minimized_alignment,
1155 label_color: palette.label_color,
1156 },
1157 &metrics,
1158 &focus,
1159 cutout,
1160 );
1161 let show_affixes = animation.floating >= 0.5;
1162 let editor_row = build_editor_row(
1163 EditorSlots {
1164 leading: self.leading,
1165 prefix: self.prefix,
1166 editor: configured.element,
1167 placeholder: self.placeholder,
1168 layout_probe,
1169 suffix: self.suffix,
1170 trailing,
1171 },
1172 font.clone(),
1173 type_style,
1174 rtl,
1175 show_affixes,
1176 has_text,
1177 &palette,
1178 );
1179
1180 div()
1181 .id(self.id)
1182 .test_support()
1183 .w_full()
1184 .min_w_0()
1185 .flex()
1186 .flex_col()
1187 .gap(px(4.))
1188 .font_family(font.family)
1189 .role(match (self.expanded, readonly) {
1190 (Some(_), true) => Role::ComboBox,
1191 (Some(_), false) => Role::EditableComboBox,
1192 _ => configured.role,
1193 })
1194 .aria_label(label)
1195 .accessibility_id(accessible_id)
1196 .aria_placeholder(placeholder_hint)
1197 .when_some(self.expanded, |field, expanded| {
1198 field.aria_expanded(expanded)
1199 })
1200 .when_some(
1201 self.dropdown_request.filter(|_| !disabled),
1202 |field, request| {
1203 let open = self.expanded.unwrap_or_default();
1204 let click = request.clone();
1205 field
1206 .on_a11y_action(AccessibleAction::Click, move |_, window, cx| {
1207 click(!open, window, cx);
1208 })
1209 .on_a11y_action(
1210 if open {
1211 AccessibleAction::Collapse
1212 } else {
1213 AccessibleAction::Expand
1214 },
1215 move |_, window, cx| request(!open, window, cx),
1216 )
1217 },
1218 )
1219 .when(!disabled, |field| field.track_focus(&focus).tab_stop(false))
1220 .when_some(configured.value, |field, value| field.aria_value(value))
1221 .when_some(configured.set_value, |field, editor| {
1222 field.on_a11y_action(AccessibleAction::SetValue, move |data, window, cx| {
1223 if let Some(gpui::accesskit::ActionData::Value(value)) = data {
1224 editor.replace_all(value.to_string().into(), window, cx);
1225 }
1226 })
1227 })
1228 .when_some(description, |field, text| field.aria_description(text))
1229 .a11y_synthetic_children(move |tree| {
1230 let node = tree.parent_node();
1231 if error {
1232 node.set_invalid(gpui::accesskit::Invalid::True);
1233 }
1234 if disabled {
1235 node.set_disabled();
1236 }
1237 if readonly || disabled {
1238 node.set_read_only();
1239 }
1240 if self.required {
1241 node.set_required();
1242 }
1243 })
1244 .children(above_label)
1245 .child(
1246 div()
1247 .id("container")
1248 .test_support()
1249 .relative()
1250 .flex()
1251 .flex_col()
1252 .when_else(
1253 label_inside || presentation.is_multi_line(),
1254 Styled::justify_end,
1255 Styled::justify_center,
1256 )
1257 .min_h(metrics.minimum_height)
1258 .pt(metrics.editor_top_padding)
1259 .pr(metrics.padding.right)
1260 .pb(metrics.editor_bottom_padding)
1261 .pl(metrics.padding.left)
1262 .when(!disabled, |field| {
1263 field.on_hover(move |hovering, window, cx| {
1264 if hover.replace(*hovering) != *hovering {
1265 if let Some(tracker) = &tracker {
1266 tracker.record(
1267 interaction_state(
1268 false,
1269 *hovering,
1270 focus.is_focused(window)
1271 && window.last_input_was_keyboard(),
1272 ),
1273 cx,
1274 );
1275 }
1276 window.refresh();
1277 }
1278 })
1279 })
1280 .child(outline_canvas)
1281 .when(rtl, |field| field.text_align(TextAlign::Right))
1282 .child(editor_row)
1283 .children(attached_label),
1284 )
1285 .when(support.is_some() || count.is_some(), |field| {
1286 field.child(build_supporting_row(
1287 support,
1288 count,
1289 metrics.padding,
1290 caption_style,
1291 &palette,
1292 error,
1293 disabled,
1294 rtl,
1295 ))
1296 })
1297 }
1298}