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