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(crate::Icon::new(crate::IconName::Close).size(px(20.)));
843 items.push(clear_btn.into_any_element());
844 }
845
846 if is_secure && let Some(toggle) = visibility_toggle {
847 let toggle_focus = window
848 .use_keyed_state((id.clone(), "visibility-toggle-focus"), cx, |_, cx| {
849 cx.focus_handle()
850 })
851 .read(cx)
852 .clone();
853 let (show_label, hide_label) =
854 visibility_labels.unwrap_or_else(|| ("Show password".into(), "Hide password".into()));
855 let label = if toggle.visible {
856 hide_label
857 } else {
858 show_label
859 };
860 let icon = if toggle.visible {
861 crate::IconName::VisibilityOff
862 } else {
863 crate::IconName::Visibility
864 };
865 let next_visible = !toggle.visible;
866 let mut button = gpui_base::Button::new((id.clone(), "visibility-toggle"))
867 .track_focus(&toggle_focus)
868 .disabled(disabled)
869 .accessibility_label(label)
870 .size(px(36.))
871 .flex_none()
872 .flex()
873 .items_center()
874 .justify_center()
875 .rounded_full()
876 .text_color(tint)
877 .border_2()
878 .border_color(gpui::transparent_black())
879 .focus_visible(move |style| style.border_color(focus_ring))
880 .child(crate::Icon::new(icon).size(px(20.)));
881 if !disabled {
882 let on_toggle = toggle.on_toggle;
883 let bound = Rc::new(ThemeScope::bind_action(
884 move |window, cx| on_toggle(next_visible, window, cx),
885 window,
886 cx,
887 ));
888 let invoke_click = bound.clone();
889 let focus_click = editor_focus.clone();
890 button = button
891 .hover(move |style| style.bg(tint.opacity(0.08)))
892 .active(move |style| style.bg(tint.opacity(0.12)))
893 .on_click(move |event, window, cx| {
894 cx.stop_propagation();
895 invoke_click(window, cx);
896 if matches!(event, ClickEvent::Mouse(_)) {
897 focus_click.focus(window, cx);
898 }
899 })
900 .on_a11y_action(AccessibleAction::Click, move |_, window, cx| {
901 bound(window, cx);
902 });
903 }
904 items.push(button.into_any_element());
905 }
906
907 if let Some(custom) = custom_trailing {
908 items.push(custom);
909 }
910
911 match items.len() {
912 0 => None,
913 1 => items.into_iter().next(),
914 _ => Some(
915 div()
916 .flex()
917 .items_center()
918 .gap(px(4.))
919 .when(rtl, Styled::flex_row_reverse)
920 .children(items)
921 .into_any_element(),
922 ),
923 }
924}
925
926#[allow(clippy::too_many_arguments)]
927fn build_supporting_row(
928 support: Option<FieldDescription>,
929 count: Option<SharedString>,
930 padding: Edges<Pixels>,
931 caption_style: TypeStyle,
932 palette: &FieldPalette,
933 error: bool,
934 disabled: bool,
935 rtl: bool,
936) -> gpui::Div {
937 div()
938 .pl(padding.left)
939 .pr(padding.right)
940 .text_size(px(caption_style.size))
941 .line_height(px(caption_style.line_height))
942 .text_color(
943 palette
944 .state_colors
945 .supporting
946 .unwrap_or(if error && !disabled {
947 palette.indicator
948 } else {
949 palette.secondary
950 }),
951 )
952 .flex()
953 .gap(px(8.))
954 .justify_between()
955 .when(rtl, Styled::flex_row_reverse)
956 .child(div().flex_1().min_w_0().children(support.map(|support| {
957 support
958 .content
959 .unwrap_or_else(|| support.text.into_any_element())
960 })))
961 .children(count.map(|count| div().flex_none().child(count)))
962}
963
964impl RenderOnce for TextField {
965 fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
966 let theme = current_material_theme(window, cx).clone();
967 let direction = theme.layout.direction;
968 let rtl = direction == Direction::Rtl;
969 let presentation = match &self.editor {
970 Editor::Single(state) | Editor::Secure(state) => state.read(cx).presentation(),
971 Editor::Multiple(state) => state.read(cx).presentation(),
972 };
973 let disabled = presentation.is_disabled();
974 let readonly = presentation.is_readonly();
975 let focus = presentation.focus_handle().clone();
976 let focused = !disabled && focus.is_focused(window);
977 let filled = self.variant == TextFieldVariant::Filled;
978 let label_position = self.label_position.unwrap_or(if filled {
979 TextFieldLabelPosition::Inside
980 } else {
981 TextFieldLabelPosition::Cutout
982 });
983 let label_inside = self.show_label && label_position == TextFieldLabelPosition::Inside;
984 let label_above = self.show_label && label_position == TextFieldLabelPosition::Above;
985 let has_cutout =
986 self.show_label && label_position == TextFieldLabelPosition::Cutout && !filled;
987 let error = self.invalid;
988
989 let shape = self.shape.unwrap_or(
990 if filled {
991 CornerRole::ExtraSmallTop
992 } else {
993 CornerRole::ExtraSmall
994 }
995 .shape(),
996 );
997 let type_style = LayoutPolicy::scale_text(
998 theme.typography.scale_style(
999 self.text_style
1000 .unwrap_or(TypeRole::BodyLarge.style(TypographyEmphasis::Baseline)),
1001 ),
1002 self.font_scale,
1003 );
1004 let caption_style = LayoutPolicy::scale_text(
1005 theme
1006 .typography
1007 .style(TypeRole::BodySmall, TypographyEmphasis::Baseline),
1008 self.font_scale,
1009 );
1010 let font = font_for_style(&theme.typography, type_style, cx);
1011 let has_text = match &self.editor {
1012 Editor::Single(state) | Editor::Secure(state) => !state.read(cx).value().is_empty(),
1013 Editor::Multiple(state) => !state.read(cx).value().is_empty(),
1014 };
1015 let animation = sample_animation(
1016 &self.id,
1017 &theme,
1018 focused || has_text || self.label_minimized || label_above || !self.show_label,
1019 focused,
1020 error && !disabled,
1021 window,
1022 cx,
1023 );
1024 let effective_floating = if self.show_label {
1025 animation.floating
1026 } else {
1027 1.
1028 };
1029 let hover = window
1030 .use_keyed_state((self.id.clone(), "field-hover"), cx, |_, _| {
1031 Rc::new(Cell::new(false))
1032 })
1033 .read(cx)
1034 .clone();
1035 let tracker = self.interaction_source.map(|source| {
1036 let tracker = InteractionSource::track(&source, &self.id, window, cx);
1037 tracker.record(
1038 interaction_state(
1039 disabled,
1040 hover.get(),
1041 focused && window.last_input_was_keyboard(),
1042 ),
1043 cx,
1044 );
1045 tracker
1046 });
1047 let palette = resolve_palette(
1048 &theme,
1049 self.colors,
1050 filled,
1051 disabled,
1052 error,
1053 focused,
1054 hover.get(),
1055 &animation,
1056 );
1057 let style = build_editor_style(
1058 &theme,
1059 &palette,
1060 has_text,
1061 self.placeholder.is_some(),
1062 effective_floating,
1063 self.dropdown_editor && readonly,
1064 error,
1065 );
1066 let label = self.label;
1067 let accessible_id = self.id.to_string();
1068 let align = if rtl {
1069 TextAlign::Right
1070 } else {
1071 TextAlign::Left
1072 };
1073 let layout_probe =
1074 build_layout_probe(&self.id, &self.editor, self.on_text_layout, window, cx);
1075 let editor_for_clear = self.editor.clone();
1076 let is_secure = matches!(self.editor, Editor::Secure(_));
1077 let configured = configure_and_build_editor(
1078 &self.id,
1079 self.editor,
1080 self.obfuscation_mode,
1081 &presentation,
1082 align,
1083 style,
1084 &theme,
1085 readonly,
1086 disabled,
1087 window,
1088 cx,
1089 );
1090 let support = self.error.map_or(self.supporting, |text| {
1091 Some(FieldDescription {
1092 text,
1093 content: None,
1094 })
1095 });
1096 let support_text = support.as_ref().map(|support| &support.text);
1097 let (count, description) =
1098 if let Some((limit, text)) = self.character_count.zip(configured.value.as_ref()) {
1099 let cache = window.use_keyed_state((self.id.clone(), "char-count"), cx, |_, _| {
1100 CharacterCountCache::default()
1101 });
1102 cache.update(cx, |cache, _| {
1103 let text_or_limit_changed = cache.limit != Some(limit) || &cache.text != text;
1104 if text_or_limit_changed {
1105 cache.text = text.clone();
1106 cache.limit = Some(limit);
1107 cache.count_label = format!("{} / {limit}", text.chars().count()).into();
1108 }
1109 if text_or_limit_changed || cache.support_text.as_ref() != support_text {
1110 cache.support_text = support_text.cloned();
1111 cache.combined_support = Some(match support_text {
1112 Some(support) => format!("{support}. {}", cache.count_label).into(),
1113 None => cache.count_label.clone(),
1114 });
1115 }
1116 (
1117 Some(cache.count_label.clone()),
1118 cache.combined_support.clone(),
1119 )
1120 })
1121 } else {
1122 (None, support_text.cloned())
1123 };
1124 let placeholder_hint = self.placeholder.as_ref().map_or_else(
1125 || presentation.placeholder().clone(),
1126 |(hint, _)| hint.clone(),
1127 );
1128 let metrics = resolve_metrics(
1129 type_style,
1130 caption_style,
1131 &animation,
1132 theme.layout.density,
1133 self.min_height,
1134 self.indicator_width,
1135 self.content_padding,
1136 label_inside,
1137 filled,
1138 );
1139 let cutout = has_cutout.then(|| Rc::new(Cell::new(None::<Bounds<Pixels>>)));
1140 let outline_canvas = build_outline_canvas(
1141 shape,
1142 direction,
1143 palette.background,
1144 filled,
1145 metrics.outline_width,
1146 palette.outline_tint,
1147 cutout.clone(),
1148 );
1149 let trailing_tint = palette.state_colors.trailing.unwrap_or(palette.secondary);
1150 let focus_ring = color(theme.colors.color(ColorRole::Secondary));
1151 let trailing = build_trailing_controls(
1152 &self.id,
1153 &editor_for_clear,
1154 &focus,
1155 self.clearable,
1156 self.clear_label,
1157 self.visibility_toggle,
1158 self.visibility_labels,
1159 self.trailing,
1160 is_secure,
1161 has_text,
1162 disabled,
1163 readonly,
1164 rtl,
1165 trailing_tint,
1166 focus_ring,
1167 window,
1168 cx,
1169 );
1170 let (above_label, attached_label) = if self.show_label {
1171 build_label(
1172 LabelConfig {
1173 label: label.clone(),
1174 label_content: self.label_content,
1175 label_above,
1176 has_cutout,
1177 required: self.required,
1178 disabled,
1179 rtl,
1180 has_leading: self.leading.is_some(),
1181 has_trailing: trailing.is_some(),
1182 floating: animation.floating,
1183 expanded_alignment: self.expanded_alignment,
1184 minimized_alignment: self.minimized_alignment,
1185 label_color: palette.label_color,
1186 },
1187 &metrics,
1188 &focus,
1189 cutout,
1190 )
1191 } else {
1192 (None, None)
1193 };
1194 let show_affixes = effective_floating >= 0.5;
1195 let editor_row = build_editor_row(
1196 EditorSlots {
1197 leading: self.leading,
1198 prefix: self.prefix,
1199 editor: configured.element,
1200 placeholder: self.placeholder,
1201 layout_probe,
1202 suffix: self.suffix,
1203 trailing,
1204 },
1205 font.clone(),
1206 type_style,
1207 rtl,
1208 show_affixes,
1209 has_text,
1210 &palette,
1211 );
1212
1213 div()
1214 .id(self.id)
1215 .test_support()
1216 .w_full()
1217 .min_w_0()
1218 .flex()
1219 .flex_col()
1220 .gap(px(4.))
1221 .font_family(font.family)
1222 .role(match (self.expanded, readonly) {
1223 (Some(_), true) => Role::ComboBox,
1224 (Some(_), false) => Role::EditableComboBox,
1225 _ => configured.role,
1226 })
1227 .aria_label(label)
1228 .accessibility_id(accessible_id)
1229 .aria_placeholder(placeholder_hint)
1230 .when_some(self.expanded, |field, expanded| {
1231 field.aria_expanded(expanded)
1232 })
1233 .when_some(
1234 self.dropdown_request.filter(|_| !disabled),
1235 |field, request| {
1236 let open = self.expanded.unwrap_or_default();
1237 let click = request.clone();
1238 field
1239 .on_a11y_action(AccessibleAction::Click, move |_, window, cx| {
1240 click(!open, window, cx);
1241 })
1242 .on_a11y_action(
1243 if open {
1244 AccessibleAction::Collapse
1245 } else {
1246 AccessibleAction::Expand
1247 },
1248 move |_, window, cx| request(!open, window, cx),
1249 )
1250 },
1251 )
1252 .when(!disabled, |field| field.track_focus(&focus).tab_stop(false))
1253 .when_some(configured.value, |field, value| field.aria_value(value))
1254 .when_some(configured.set_value, |field, editor| {
1255 field.on_a11y_action(AccessibleAction::SetValue, move |data, window, cx| {
1256 if let Some(gpui::accesskit::ActionData::Value(value)) = data {
1257 editor.replace_all(value.to_string().into(), window, cx);
1258 }
1259 })
1260 })
1261 .when_some(description, |field, text| field.aria_description(text))
1262 .a11y_synthetic_children(move |tree| {
1263 let node = tree.parent_node();
1264 if error {
1265 node.set_invalid(gpui::accesskit::Invalid::True);
1266 }
1267 if disabled {
1268 node.set_disabled();
1269 }
1270 if readonly || disabled {
1271 node.set_read_only();
1272 }
1273 if self.required {
1274 node.set_required();
1275 }
1276 })
1277 .children(above_label)
1278 .child(
1279 div()
1280 .id("container")
1281 .test_support()
1282 .relative()
1283 .flex()
1284 .flex_col()
1285 .when_else(
1286 label_inside || presentation.is_multi_line(),
1287 Styled::justify_end,
1288 Styled::justify_center,
1289 )
1290 .min_h(metrics.minimum_height)
1291 .pt(metrics.editor_top_padding)
1292 .pr(metrics.padding.right)
1293 .pb(metrics.editor_bottom_padding)
1294 .pl(metrics.padding.left)
1295 .when(!disabled, |field| {
1296 field.on_hover(move |hovering, window, cx| {
1297 if hover.replace(*hovering) != *hovering {
1298 if let Some(tracker) = &tracker {
1299 tracker.record(
1300 interaction_state(
1301 false,
1302 *hovering,
1303 focus.is_focused(window)
1304 && window.last_input_was_keyboard(),
1305 ),
1306 cx,
1307 );
1308 }
1309 window.refresh();
1310 }
1311 })
1312 })
1313 .child(outline_canvas)
1314 .when(rtl, |field| field.text_align(TextAlign::Right))
1315 .child(editor_row)
1316 .children(attached_label),
1317 )
1318 .when(support.is_some() || count.is_some(), |field| {
1319 field.child(build_supporting_row(
1320 support,
1321 count,
1322 metrics.padding,
1323 caption_style,
1324 &palette,
1325 error,
1326 disabled,
1327 rtl,
1328 ))
1329 })
1330 }
1331}