1use std::{cell::Cell, rc::Rc};
2
3use gpui::{
4 AccessibleAction, AnyElement, App, BorderStyle, Bounds, ContentMask, Corners, Edges, ElementId,
5 Entity, Hsla, InteractiveElement, IntoElement, MouseButton, ParentElement, Pixels, RenderOnce,
6 Role, SharedString, StatefulInteractiveElement, Styled, TextAlign, Window, canvas, div, point,
7 prelude::FluentBuilder, px, quad,
8};
9use gpui_base::{
10 TestSupportExt,
11 input::{InputAccessibility, InputBaseState, InputEditorStyle, InputModeKind},
12};
13use gpui_material_foundation::{
14 InteractionSource, InteractionState, animate, color, font_for_style, window_material_theme,
15};
16use gpui_material_theme::{
17 ColorRole, CornerRole, CornerShape, Direction, LayoutPolicy, MotionKind, MotionSpeed, TypeRole,
18 TypeStyle, TypographyEmphasis,
19};
20
21use super::{TextAreaState, TextFieldState};
22
23#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
25pub enum TextFieldVariant {
26 #[default]
27 Filled,
28 Outlined,
29}
30
31#[derive(Clone, Copy, Debug, Eq, PartialEq)]
33pub enum TextFieldLabelPosition {
34 Inside,
36 Cutout,
38 Above,
40}
41
42#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
44pub enum TextFieldLabelAlignment {
45 #[default]
46 Start,
47 Center,
48 End,
49}
50
51#[derive(Clone, Copy, Debug, Default)]
53pub struct TextFieldColorOverrides {
54 pub container: Option<Hsla>,
55 pub text: Option<Hsla>,
56 pub label: Option<Hsla>,
57 pub placeholder: Option<Hsla>,
58 pub leading: Option<Hsla>,
59 pub trailing: Option<Hsla>,
60 pub prefix: Option<Hsla>,
61 pub suffix: Option<Hsla>,
62 pub supporting: Option<Hsla>,
63 pub indicator: Option<Hsla>,
64 pub caret: Option<Hsla>,
65 pub selection: Option<Hsla>,
66}
67
68#[derive(Clone, Copy, Debug, Default)]
70pub struct TextFieldColors {
71 pub unfocused: TextFieldColorOverrides,
72 pub focused: TextFieldColorOverrides,
73 pub disabled: TextFieldColorOverrides,
74 pub invalid: TextFieldColorOverrides,
75 pub hovered_indicator: Option<Hsla>,
76}
77
78#[derive(Clone, Copy, Debug, PartialEq)]
80pub struct TextFieldLayout {
81 pub editor_bounds: Bounds<Pixels>,
83 pub text_bounds: Option<Bounds<Pixels>>,
85 pub line_count: usize,
87}
88
89type OnTextLayout = Box<dyn FnOnce(TextFieldLayout, &mut Window, &mut App)>;
90type DropdownRequest = Rc<dyn Fn(bool, &mut Window, &mut App)>;
91
92struct FieldDescription {
93 text: SharedString,
94 content: Option<AnyElement>,
95}
96
97#[derive(IntoElement)]
103pub struct TextField {
104 id: ElementId,
105 label: SharedString,
106 editor: Editor,
107 variant: TextFieldVariant,
108 label_content: Option<AnyElement>,
109 label_position: Option<TextFieldLabelPosition>,
110 label_minimized: bool,
111 expanded_alignment: TextFieldLabelAlignment,
112 minimized_alignment: TextFieldLabelAlignment,
113 placeholder: Option<(SharedString, AnyElement)>,
114 supporting: Option<FieldDescription>,
115 error: Option<SharedString>,
116 invalid: bool,
117 required: bool,
118 character_count: Option<usize>,
119 leading: Option<AnyElement>,
120 trailing: Option<AnyElement>,
121 prefix: Option<AnyElement>,
122 suffix: Option<AnyElement>,
123 dropdown_editor: bool,
124 expanded: Option<bool>,
125 dropdown_request: Option<DropdownRequest>,
126 font_scale: f32,
127 text_style: Option<TypeStyle>,
128 shape: Option<CornerShape>,
129 content_padding: Option<Edges<Pixels>>,
130 colors: TextFieldColors,
131 on_text_layout: Option<OnTextLayout>,
132 interaction_source: Option<Entity<InteractionSource>>,
133}
134
135#[derive(Clone)]
136enum Editor {
137 Single(Entity<TextFieldState>),
138 Multiple(Entity<TextAreaState>),
139 Secure(Entity<TextFieldState>),
140}
141
142impl Editor {
143 fn layout(&self, cx: &App) -> TextFieldLayout {
144 fn snapshot(state: &InputBaseState<impl InputModeKind>) -> TextFieldLayout {
145 TextFieldLayout {
146 editor_bounds: state.input_bounds(),
147 text_bounds: state.text_bounds(),
148 line_count: state.display_map().wrap_row_count(),
149 }
150 }
151 match self {
152 Self::Single(state) | Self::Secure(state) => snapshot(state.read(cx)),
153 Self::Multiple(state) => snapshot(state.read(cx)),
154 }
155 }
156}
157
158impl TextField {
159 pub fn new(
161 id: impl Into<ElementId>,
162 label: impl Into<SharedString>,
163 state: &Entity<TextFieldState>,
164 ) -> Self {
165 Self::with_editor(id, label, Editor::Single(state.clone()))
166 }
167
168 pub fn multiline(
170 id: impl Into<ElementId>,
171 label: impl Into<SharedString>,
172 state: &Entity<TextAreaState>,
173 ) -> Self {
174 Self::with_editor(id, label, Editor::Multiple(state.clone()))
175 }
176
177 pub fn secure(
181 id: impl Into<ElementId>,
182 label: impl Into<SharedString>,
183 state: &Entity<TextFieldState>,
184 ) -> Self {
185 Self::with_editor(id, label, Editor::Secure(state.clone()))
186 }
187
188 fn with_editor(
189 id: impl Into<ElementId>,
190 label: impl Into<SharedString>,
191 editor: Editor,
192 ) -> Self {
193 Self {
194 id: id.into(),
195 label: label.into(),
196 editor,
197 variant: TextFieldVariant::Filled,
198 label_content: None,
199 label_position: None,
200 label_minimized: false,
201 expanded_alignment: TextFieldLabelAlignment::Start,
202 minimized_alignment: TextFieldLabelAlignment::Start,
203 placeholder: None,
204 supporting: None,
205 error: None,
206 invalid: false,
207 required: false,
208 character_count: None,
209 leading: None,
210 trailing: None,
211 prefix: None,
212 suffix: None,
213 dropdown_editor: false,
214 expanded: None,
215 dropdown_request: None,
216 font_scale: 1.,
217 text_style: None,
218 shape: None,
219 content_padding: None,
220 colors: TextFieldColors::default(),
221 on_text_layout: None,
222 interaction_source: None,
223 }
224 }
225
226 pub fn variant(mut self, variant: TextFieldVariant) -> Self {
227 self.variant = variant;
228 self
229 }
230
231 pub fn font_scale(mut self, scale: f32) -> Self {
233 self.font_scale = scale;
234 self
235 }
236
237 pub fn text_style(mut self, style: TypeStyle) -> Self {
239 self.text_style = Some(style);
240 self
241 }
242
243 pub fn shape(mut self, shape: CornerShape) -> Self {
245 self.shape = Some(shape);
246 self
247 }
248
249 pub fn content_padding(mut self, padding: Edges<Pixels>) -> Self {
251 self.content_padding = Some(padding);
252 self
253 }
254
255 pub fn colors(mut self, colors: TextFieldColors) -> Self {
257 self.colors = colors;
258 self
259 }
260
261 pub fn on_text_layout(
264 mut self,
265 listener: impl FnOnce(TextFieldLayout, &mut Window, &mut App) + 'static,
266 ) -> Self {
267 self.on_text_layout = Some(Box::new(listener));
268 self
269 }
270
271 pub fn interaction_source(mut self, source: &Entity<InteractionSource>) -> Self {
274 self.interaction_source = Some(source.clone());
275 self
276 }
277
278 pub fn supporting_text(mut self, text: impl Into<SharedString>) -> Self {
279 self.supporting = Some(FieldDescription {
280 text: text.into(),
281 content: None,
282 });
283 self
284 }
285
286 pub fn label_content(mut self, element: impl IntoElement) -> Self {
288 self.label_content = Some(element.into_any_element());
289 self
290 }
291
292 pub fn label_position(mut self, position: TextFieldLabelPosition) -> Self {
293 self.label_position = Some(position);
294 self
295 }
296
297 pub fn label_always_minimized(mut self, minimized: bool) -> Self {
299 self.label_minimized = minimized;
300 self
301 }
302
303 pub fn label_alignment(
305 mut self,
306 expanded: TextFieldLabelAlignment,
307 minimized: TextFieldLabelAlignment,
308 ) -> Self {
309 self.expanded_alignment = expanded;
310 self.minimized_alignment = minimized;
311 self
312 }
313
314 pub fn placeholder_content(
316 mut self,
317 hint: impl Into<SharedString>,
318 element: impl IntoElement,
319 ) -> Self {
320 self.placeholder = Some((hint.into(), element.into_any_element()));
321 self
322 }
323
324 pub fn supporting_content(
326 mut self,
327 description: impl Into<SharedString>,
328 element: impl IntoElement,
329 ) -> Self {
330 self.supporting = Some(FieldDescription {
331 text: description.into(),
332 content: Some(element.into_any_element()),
333 });
334 self
335 }
336
337 pub fn error(mut self, message: impl Into<SharedString>) -> Self {
339 self.error = Some(message.into());
340 self.invalid = true;
341 self
342 }
343
344 pub fn invalid(mut self, invalid: bool) -> Self {
346 self.invalid = invalid;
347 self
348 }
349
350 pub fn required(mut self, required: bool) -> Self {
352 self.required = required;
353 self
354 }
355
356 pub fn character_count(mut self, limit: usize) -> Self {
359 self.character_count = Some(limit);
360 self
361 }
362
363 pub fn leading(mut self, element: impl IntoElement) -> Self {
365 self.leading = Some(element.into_any_element());
366 self
367 }
368
369 pub fn trailing(mut self, element: impl IntoElement) -> Self {
371 self.trailing = Some(element.into_any_element());
372 self
373 }
374
375 pub fn prefix(mut self, element: impl IntoElement) -> Self {
377 self.prefix = Some(element.into_any_element());
378 self
379 }
380
381 pub fn suffix(mut self, element: impl IntoElement) -> Self {
383 self.suffix = Some(element.into_any_element());
384 self
385 }
386
387 pub(super) fn dropdown(mut self, open: bool, request: Option<DropdownRequest>) -> Self {
388 self.dropdown_editor = true;
389 self.expanded = request.is_some().then_some(open);
390 self.dropdown_request = request;
391 self
392 }
393}
394
395fn configure_editor<M: InputModeKind>(state: &mut InputBaseState<M>, style: InputEditorStyle) {
396 state.set_accessibility(InputAccessibility::new(None).with_value_exposed(false));
399 state.set_editor_style(style);
400}
401
402fn editor_ink(mut color: Hsla) -> Hsla {
403 if color.a == 0. {
405 color.a = f32::EPSILON;
406 }
407 color
408}
409
410fn interaction_state(disabled: bool, hovered: bool, focus_visible: bool) -> InteractionState {
411 let mut state = InteractionState::default();
412 state.disabled = disabled;
413 state.hovered = hovered && !disabled;
414 state.focus_visible = focus_visible && !disabled;
415 state
416}
417
418type SetValue = Box<dyn Fn(SharedString, &mut Window, &mut App)>;
419
420fn edit_handler<M: InputModeKind>(state: Entity<InputBaseState<M>>) -> SetValue {
421 Box::new(move |value, window, cx| {
422 state.update(cx, |state, cx| {
423 if state.is_editable() {
424 state.replace_all(value, window, cx);
425 }
426 });
427 })
428}
429
430impl RenderOnce for TextField {
431 fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
432 use ColorRole::*;
433
434 let theme = window_material_theme(window, cx).clone();
435 let tone = |role| color(theme.colors.color(role));
436 let direction = theme.layout.direction;
437 let presentation = match &self.editor {
438 Editor::Single(state) | Editor::Secure(state) => state.read(cx).presentation(),
439 Editor::Multiple(state) => state.read(cx).presentation(),
440 };
441 let disabled = presentation.is_disabled();
442 let readonly = presentation.is_readonly();
443 let focus = presentation.focus_handle().clone();
444 let focused = !disabled && focus.is_focused(window);
445 let filled = self.variant == TextFieldVariant::Filled;
446 let label_position = self.label_position.unwrap_or(if filled {
447 TextFieldLabelPosition::Inside
448 } else {
449 TextFieldLabelPosition::Cutout
450 });
451 let label_inside = label_position == TextFieldLabelPosition::Inside;
452 let label_above = label_position == TextFieldLabelPosition::Above;
453 let has_cutout = label_position == TextFieldLabelPosition::Cutout && !filled;
454 let error = self.invalid;
455 let colors = self.colors;
456 let state_colors = match (disabled, error, focused) {
457 (true, _, _) => colors.disabled,
458 (_, true, _) => colors.invalid,
459 (_, _, true) => colors.focused,
460 _ => colors.unfocused,
461 };
462 let secondary = if disabled {
463 tone(OnSurface).opacity(0.38)
464 } else {
465 tone(OnSurfaceVariant)
466 };
467 let foreground =
468 state_colors
469 .text
470 .unwrap_or(if disabled { secondary } else { tone(OnSurface) });
471 let placeholder_color = state_colors.placeholder.unwrap_or(secondary);
472 let background = state_colors
473 .container
474 .unwrap_or_else(|| match (filled, disabled) {
475 (false, _) => gpui::transparent_black(),
476 (true, true) => tone(OnSurface).opacity(0.04),
477 (true, false) => tone(SurfaceContainerHighest),
478 });
479 let shape = self.shape.unwrap_or(
480 if filled {
481 CornerRole::ExtraSmallTop
482 } else {
483 CornerRole::ExtraSmall
484 }
485 .shape(),
486 );
487 let type_style = LayoutPolicy::scale_text(
488 self.text_style
489 .unwrap_or(TypeRole::BodyLarge.style(TypographyEmphasis::Baseline)),
490 self.font_scale,
491 );
492 let caption_style = LayoutPolicy::scale_text(
493 TypeRole::BodySmall.style(TypographyEmphasis::Baseline),
494 self.font_scale,
495 );
496 let font = font_for_style(&theme.typography, type_style, cx);
497 let has_text = match &self.editor {
498 Editor::Single(state) | Editor::Secure(state) => !state.read(cx).value().is_empty(),
499 Editor::Multiple(state) => !state.read(cx).value().is_empty(),
500 };
501 let effects = theme
502 .motion
503 .spec(MotionKind::Effects, MotionSpeed::Fast, cx.reduce_motion());
504 let floating = animate(
505 (self.id.clone(), "floating-label"),
506 f32::from(focused || has_text || self.label_minimized || label_above),
507 theme
508 .motion
509 .spec(MotionKind::Spatial, MotionSpeed::Fast, cx.reduce_motion()),
510 window,
511 cx,
512 )
513 .clamp(0., 1.);
514 let focus_amount = animate(
515 (self.id.clone(), "focus-indicator"),
516 f32::from(focused),
517 effects,
518 window,
519 cx,
520 )
521 .clamp(0., 1.);
522 let error_amount = animate(
523 (self.id.clone(), "error-indicator"),
524 f32::from(error && !disabled),
525 effects,
526 window,
527 cx,
528 )
529 .clamp(0., 1.);
530 let animated_color = |idle, active, invalid| {
531 let focused_tint = crate::motion::mix(idle, active, focus_amount);
532 crate::motion::mix(focused_tint, invalid, error_amount)
533 };
534 let indicator = if disabled {
535 colors
536 .disabled
537 .indicator
538 .unwrap_or(tone(OnSurface).opacity(0.12))
539 } else {
540 animated_color(
541 colors.unfocused.indicator.unwrap_or(tone(if filled {
542 OnSurfaceVariant
543 } else {
544 Outline
545 })),
546 colors.focused.indicator.unwrap_or(tone(Primary)),
547 colors.invalid.indicator.unwrap_or(tone(Error)),
548 )
549 };
550 let label_color = if disabled {
551 colors.disabled.label.unwrap_or(secondary)
552 } else {
553 animated_color(
554 colors.unfocused.label.unwrap_or(secondary),
555 colors.focused.label.unwrap_or(tone(Primary)),
556 colors.invalid.label.unwrap_or(tone(Error)),
557 )
558 };
559 let style = InputEditorStyle {
560 foreground: editor_ink(foreground),
561 background: tone(SurfaceContainer),
565 border: tone(OutlineVariant),
566 muted_foreground: match (has_text, self.placeholder.is_some()) {
567 (true, _) => editor_ink(placeholder_color),
568 (false, true) => editor_ink(gpui::transparent_black()),
569 (false, false) => editor_ink(placeholder_color.opacity(floating)),
570 },
571 caret: if self.dropdown_editor && readonly {
572 editor_ink(gpui::transparent_black())
575 } else {
576 editor_ink(
577 state_colors
578 .caret
579 .unwrap_or(tone(if error { Error } else { Primary })),
580 )
581 },
582 selection: editor_ink(state_colors.selection.unwrap_or(tone(Primary).opacity(0.3))),
583 ..Default::default()
584 };
585 let label = self.label;
586 let accessible_id = self.id.to_string();
587 let align = if direction == Direction::Rtl {
588 TextAlign::Right
589 } else {
590 TextAlign::Left
591 };
592 let layout_probe = self.on_text_layout.map(|listener| {
593 let editor = self.editor.clone();
594 let previous = window
595 .use_keyed_state((self.id.clone(), "field-layout"), cx, |_, _| {
596 Rc::new(Cell::new(None::<TextFieldLayout>))
597 })
598 .read(cx)
599 .clone();
600 canvas(
601 |_, _, _| (),
602 move |_, _, window, cx| {
603 let layout = editor.layout(cx);
604 if previous.replace(Some(layout)) != Some(layout) {
605 window.defer(cx, move |window, cx| listener(layout, window, cx));
606 }
607 },
608 )
609 .absolute()
610 .inset_0()
611 });
612 let (editor, role, value, set_value): (_, _, _, Option<SetValue>) = match self.editor {
613 Editor::Single(state) => {
614 let role = if presentation.is_masked() {
615 Role::PasswordInput
616 } else {
617 Role::TextInput
618 };
619 state.update(cx, |state, cx| {
620 state.set_text_align(align, cx);
621 configure_editor(state, style);
622 });
623 let value = (role != Role::PasswordInput).then(|| state.read(cx).value());
624 let set_value = (!readonly && !disabled && role != Role::PasswordInput)
625 .then(|| edit_handler(state.clone()));
626 (state.into_any_element(), role, value, set_value)
627 }
628 Editor::Multiple(state) => {
629 state.update(cx, |state, cx| {
630 state.set_text_align(align, cx);
631 configure_editor(state, style);
632 });
633 let value = state.read(cx).value();
634 let set_value = (!readonly && !disabled).then(|| edit_handler(state.clone()));
635 (
636 state.into_any_element(),
637 Role::MultilineTextInput,
638 Some(value),
639 set_value,
640 )
641 }
642 Editor::Secure(state) => {
643 state.update(cx, |state, cx| {
644 if !presentation.is_masked() {
645 state.set_masked(true, window, cx);
646 }
647 state.set_text_align(align, cx);
648 configure_editor(state, style);
649 });
650 (state.into_any_element(), Role::PasswordInput, None, None)
651 }
652 };
653 let support = self.error.map_or(self.supporting, |text| {
654 Some(FieldDescription {
655 text,
656 content: None,
657 })
658 });
659 let count: Option<SharedString> = self
660 .character_count
661 .zip(value.as_ref())
662 .map(|(limit, text)| format!("{} / {limit}", text.chars().count()).into());
663 let description = match (support.as_ref(), count.as_ref()) {
664 (Some(support), Some(count)) => Some(format!("{}. {count}", support.text).into()),
665 (Some(support), None) => Some(support.text.clone()),
666 (None, count) => count.cloned(),
667 };
668 let placeholder_hint = self.placeholder.as_ref().map_or_else(
669 || presentation.placeholder().clone(),
670 |(hint, _)| hint.clone(),
671 );
672 let label_size = type_style.size + (caption_style.size - type_style.size) * floating;
673 let label_height = type_style.line_height
674 + (caption_style.line_height - type_style.line_height) * floating;
675 let outline_width = px(1. + focus_amount);
676 let padding = self.content_padding.unwrap_or(Edges {
677 left: px(16.),
678 right: px(16.),
679 top: px(if label_inside { 8. } else { 4. }),
680 bottom: if label_inside && filled {
681 px(8.) - outline_width
682 } else {
683 px(4.)
684 },
685 });
686 let label_reserve = if label_inside {
687 px(caption_style.line_height)
688 } else {
689 px(0.)
690 };
691 let editor_top_padding = padding.top + label_reserve;
692 let editor_bottom_padding = padding.bottom + if filled { outline_width } else { px(0.) };
694 let minimum_height = px(56.)
695 .max(px(type_style.line_height + 16.) + label_reserve)
696 .max(px(type_style.line_height) + editor_top_padding + editor_bottom_padding);
697 let resting_top = f32::from(minimum_height - px(type_style.line_height)) * 0.5;
698 let floating_top = if label_inside {
699 f32::from(padding.top)
700 } else {
701 -caption_style.line_height * 0.5
702 };
703 let cutout = Rc::new(Cell::new(None::<Bounds<gpui::Pixels>>));
704 let measure_cutout = cutout.clone();
705 let label_top = resting_top + (floating_top - resting_top) * floating;
706 let hover = window
707 .use_keyed_state((self.id.clone(), "field-hover"), cx, |_, _| {
708 Rc::new(Cell::new(false))
709 })
710 .read(cx)
711 .clone();
712 let tracker = self.interaction_source.map(|source| {
713 let tracker = InteractionSource::track(&source, &self.id, window, cx);
714 tracker.record(
715 interaction_state(
716 disabled,
717 hover.get(),
718 focused && window.last_input_was_keyboard(),
719 ),
720 cx,
721 );
722 tracker
723 });
724 let outline_tint = if hover.get() && !disabled && !error {
725 crate::motion::mix(
726 colors.hovered_indicator.unwrap_or(foreground),
727 colors.focused.indicator.unwrap_or(tone(Primary)),
728 focus_amount,
729 )
730 } else {
731 indicator
732 };
733 let outline_canvas = canvas(
734 |_, _, _| (),
735 move |bounds, _, window, _| {
736 let [top_left, top_right, bottom_right, bottom_left] = shape
737 .radii(
738 bounds.size.width.into(),
739 bounds.size.height.into(),
740 direction,
741 )
742 .map(px);
743 let corners = Corners {
744 top_left,
745 top_right,
746 bottom_right,
747 bottom_left,
748 };
749 if background.a > 0. {
750 window.paint_quad(quad(
751 bounds,
752 corners,
753 background,
754 px(0.),
755 gpui::transparent_black(),
756 BorderStyle::Solid,
757 ));
758 }
759 let border = quad(
760 bounds,
761 corners,
762 gpui::transparent_black(),
763 if filled {
764 Edges {
765 bottom: outline_width,
766 ..Default::default()
767 }
768 } else {
769 Edges::all(outline_width)
770 },
771 outline_tint,
772 BorderStyle::Solid,
773 );
774 let device_pixel = px(1. / window.scale_factor());
777 let Some(label_bounds) = cutout.get().filter(|label| {
778 label.top() < bounds.top() + outline_width + device_pixel
779 && label.bottom() > bounds.top() - device_pixel
780 }) else {
781 window.paint_quad(border);
782 return;
783 };
784 let left = label_bounds.left().max(bounds.left());
787 let right = label_bounds.right().min(bounds.right());
788 for (min, max) in [
789 (bounds.origin, point(left, bounds.bottom())),
790 (point(right, bounds.top()), bounds.bottom_right()),
791 (
795 point(left, bounds.center().y),
796 point(right, bounds.bottom()),
797 ),
798 ] {
799 window.with_content_mask(
800 Some(ContentMask {
801 bounds: Bounds::from_corners(min, max),
802 }),
803 |window| window.paint_quad(border.clone()),
804 );
805 }
806 },
807 )
808 .absolute()
809 .inset_0();
810 let rtl = direction == Direction::Rtl;
811 let label_alignment = if floating >= 0.5 {
812 self.minimized_alignment
813 } else {
814 self.expanded_alignment
815 };
816 let label_padding = if has_cutout { px(4.) } else { px(0.) };
817 let label_left = (padding.left - label_padding).max(px(0.));
818 let label_right = (padding.right - label_padding).max(px(0.));
819 let leading_inset = if self.leading.is_some() {
820 56. * (1. - floating)
821 } else {
822 0.
823 };
824 let label_content = self
825 .label_content
826 .unwrap_or_else(|| label.clone().into_any_element());
827 let label_container = div()
828 .id("label")
829 .test_support()
830 .when_else(
831 label_above,
832 |label| label.pl(label_left).pr(label_right),
833 |label| {
834 label
835 .absolute()
836 .top(px(label_top))
837 .left(label_left + px(if rtl { 0. } else { leading_inset }))
838 .right(label_right + px(if rtl { leading_inset } else { 0. }))
839 },
840 )
841 .text_size(px(label_size))
842 .line_height(px(label_height))
843 .text_color(label_color)
844 .flex()
845 .map(|label| match label_alignment {
846 TextFieldLabelAlignment::Center => label.justify_center(),
847 TextFieldLabelAlignment::Start if rtl => label.justify_end(),
848 TextFieldLabelAlignment::End if !rtl => label.justify_end(),
849 _ => label,
850 })
851 .child(
852 div()
853 .id("label-text")
854 .test_support()
855 .min_w_0()
856 .max_w_full()
857 .relative()
858 .truncate()
859 .when(has_cutout, |label| label.px(px(4.)))
860 .role(Role::Label)
861 .a11y_synthetic_children(|tree| tree.parent_node().set_hidden())
862 .when(self.required, |label| {
863 label
864 .flex()
865 .items_baseline()
866 .gap(px(4.))
867 .when(rtl, Styled::flex_row_reverse)
868 })
869 .child(label_content)
870 .children(self.required.then_some("*"))
871 .when(has_cutout, |label| {
872 label.child(
873 canvas(
874 move |bounds, _, _| measure_cutout.set(Some(bounds)),
875 |_, _, _, _| {},
876 )
877 .absolute()
878 .inset_0(),
879 )
880 }),
881 )
882 .when(!disabled, |label| {
883 let focus = focus.clone();
884 label.on_mouse_down(MouseButton::Left, move |_, window, cx| {
885 focus.focus(window, cx);
886 })
887 });
888 let (above_label, attached_label) = if label_above {
889 (Some(label_container), None)
890 } else {
891 (None, Some(label_container))
892 };
893 let show_affixes = floating >= 0.5;
894 div()
895 .id(self.id)
896 .test_support()
897 .w_full()
898 .min_w_0()
899 .flex()
900 .flex_col()
901 .gap(px(4.))
902 .font_family(font.family.clone())
903 .role(match (self.expanded, readonly) {
904 (Some(_), true) => Role::ComboBox,
905 (Some(_), false) => Role::EditableComboBox,
906 _ => role,
907 })
908 .aria_label(label)
909 .accessibility_id(accessible_id)
910 .aria_placeholder(placeholder_hint)
911 .when_some(self.expanded, |field, expanded| {
912 field.aria_expanded(expanded)
913 })
914 .when_some(
915 self.dropdown_request.filter(|_| !disabled),
916 |field, request| {
917 let open = self.expanded.unwrap_or_default();
918 let click = request.clone();
919 field
920 .on_a11y_action(AccessibleAction::Click, move |_, window, cx| {
921 click(!open, window, cx);
922 })
923 .on_a11y_action(
924 if open {
925 AccessibleAction::Collapse
926 } else {
927 AccessibleAction::Expand
928 },
929 move |_, window, cx| request(!open, window, cx),
930 )
931 },
932 )
933 .when(!disabled, |field| field.track_focus(&focus).tab_stop(false))
934 .when_some(value, |field, value| field.aria_value(value))
935 .when_some(set_value, |field, set_value| {
936 field.on_a11y_action(AccessibleAction::SetValue, move |data, window, cx| {
937 if let Some(gpui::accesskit::ActionData::Value(value)) = data {
938 set_value(value.to_string().into(), window, cx);
939 }
940 })
941 })
942 .when_some(description, |field, text| field.aria_description(text))
943 .a11y_synthetic_children(move |tree| {
944 let node = tree.parent_node();
945 if error {
946 node.set_invalid(gpui::accesskit::Invalid::True);
947 }
948 if disabled {
949 node.set_disabled();
950 }
951 if readonly || disabled {
952 node.set_read_only();
953 }
954 if self.required {
955 node.set_required();
956 }
957 })
958 .children(above_label)
959 .child(
960 div()
961 .id("container")
962 .test_support()
963 .relative()
964 .flex()
965 .flex_col()
966 .when_else(
967 label_inside || presentation.is_multi_line(),
968 Styled::justify_end,
969 Styled::justify_center,
970 )
971 .min_h(minimum_height)
972 .pt(editor_top_padding)
973 .pr(padding.right)
974 .pb(editor_bottom_padding)
975 .pl(padding.left)
976 .when(!disabled, |field| {
977 field.on_hover(move |hovering, window, cx| {
978 if hover.replace(*hovering) != *hovering {
979 if let Some(tracker) = &tracker {
980 tracker.record(
981 interaction_state(
982 false,
983 *hovering,
984 focus.is_focused(window)
985 && window.last_input_was_keyboard(),
986 ),
987 cx,
988 );
989 }
990 window.refresh();
991 }
992 })
993 })
994 .child(outline_canvas)
995 .when(direction == Direction::Rtl, |field| {
996 field.text_align(TextAlign::Right)
997 })
998 .child(
999 div()
1000 .flex()
1001 .items_center()
1002 .gap(px(8.))
1003 .min_w_0()
1004 .font(font)
1005 .text_size(px(type_style.size))
1006 .line_height(px(type_style.line_height))
1007 .when(rtl, Styled::flex_row_reverse)
1008 .children(self.leading.map(|leading| {
1009 div()
1010 .w(px(48.))
1011 .flex_none()
1012 .flex()
1013 .items_center()
1014 .justify_center()
1015 .when_some(state_colors.leading, Styled::text_color)
1016 .child(leading)
1017 }))
1018 .children(self.prefix.filter(|_| show_affixes).map(|prefix| {
1019 div()
1020 .when_some(state_colors.prefix, Styled::text_color)
1021 .child(prefix)
1022 }))
1023 .child(
1024 div()
1025 .flex_1()
1026 .min_w_0()
1027 .relative()
1028 .child(editor)
1029 .children(
1030 self.placeholder.filter(|_| show_affixes && !has_text).map(
1031 |(_, content)| {
1032 div()
1033 .id("placeholder")
1034 .test_support()
1035 .absolute()
1036 .top_0()
1037 .left_0()
1038 .right_0()
1039 .text_color(placeholder_color)
1040 .role(Role::Label)
1041 .a11y_synthetic_children(|tree| {
1042 tree.parent_node().set_hidden()
1043 })
1044 .child(content)
1045 },
1046 ),
1047 )
1048 .children(layout_probe),
1049 )
1050 .children(self.suffix.filter(|_| show_affixes).map(|suffix| {
1051 div()
1052 .when_some(state_colors.suffix, Styled::text_color)
1053 .child(suffix)
1054 }))
1055 .children(self.trailing.map(|trailing| {
1056 div()
1057 .when_some(state_colors.trailing, Styled::text_color)
1058 .child(trailing)
1059 })),
1060 )
1061 .children(attached_label),
1062 )
1063 .when(support.is_some() || count.is_some(), |field| {
1064 field.child(
1065 div()
1066 .pl(padding.left)
1067 .pr(padding.right)
1068 .text_size(px(caption_style.size))
1069 .line_height(px(caption_style.line_height))
1070 .text_color(state_colors.supporting.unwrap_or(if error && !disabled {
1071 indicator
1072 } else {
1073 secondary
1074 }))
1075 .flex()
1076 .gap(px(8.))
1077 .justify_between()
1078 .when(rtl, Styled::flex_row_reverse)
1079 .child(div().flex_1().min_w_0().children(support.map(|support| {
1080 support
1081 .content
1082 .unwrap_or_else(|| support.text.into_any_element())
1083 })))
1084 .children(count.map(|count| div().flex_none().child(count))),
1085 )
1086 })
1087 }
1088}