1use std::{cell::Cell, rc::Rc};
2
3use gpui::{
4 AccessibleAction, App, Bounds, EntityInputHandler, InteractiveElement, IntoElement,
5 ParentElement, Pixels, RenderOnce, Role, StatefulInteractiveElement, Styled, TextAlign, Window,
6 div, prelude::FluentBuilder, px,
7};
8use gpui_base::TestSupportExt;
9use gpui_material_foundation::{
10 InteractionSource, InteractionState, current_material_theme, font_for_style,
11};
12use gpui_material_theme::{CornerRole, Direction, LayoutPolicy, TypeRole, TypographyEmphasis};
13
14use super::{
15 Editor, FieldDescription, TextField, TextFieldLabelPosition, TextFieldVariant,
16 controls::build_trailing_controls,
17 editor::{
18 CharacterCountCache, EditorSlots, build_editor_row, build_layout_probe,
19 build_supporting_row, configure_and_build_editor,
20 },
21 label::{LabelConfig, build_label},
22 metrics::resolve_metrics,
23 outline::build_outline_canvas,
24 palette::{build_editor_style, resolve_palette, sample_animation},
25};
26
27fn interaction_state(disabled: bool, hovered: bool, focus_visible: bool) -> InteractionState {
28 let mut state = InteractionState::default();
29 state.disabled = disabled;
30 state.hovered = hovered && !disabled;
31 state.focus_visible = focus_visible && !disabled;
32 state
33}
34
35impl RenderOnce for TextField {
36 fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
37 let theme = current_material_theme(window, cx).clone();
38 let direction = theme.layout.direction;
39 let rtl = direction == Direction::Rtl;
40 let component_disabled = window
41 .use_keyed_state((self.id.clone(), "component-disabled"), cx, |_, _| {
42 Rc::new(Cell::new(false))
43 })
44 .read(cx)
45 .clone();
46 let state_disabled = match &self.editor {
47 Editor::Single(state) | Editor::Secure(state) => {
48 state.read(cx).presentation().is_disabled()
49 }
50 Editor::Multiple(state) => state.read(cx).presentation().is_disabled(),
51 };
52 if self.disabled {
53 if !state_disabled {
54 component_disabled.set(true);
55 self.editor.set_disabled(true, cx);
56 }
57 } else if component_disabled.replace(false) {
58 self.editor.set_disabled(false, cx);
59 }
60 let presentation = match &self.editor {
61 Editor::Single(state) | Editor::Secure(state) => state.read(cx).presentation(),
62 Editor::Multiple(state) => state.read(cx).presentation(),
63 };
64 let disabled = self.disabled || presentation.is_disabled();
65 let readonly = presentation.is_readonly();
66 let focus = presentation.focus_handle().clone();
67 if disabled && focus.is_focused(window) {
68 let blur_focus = focus.clone();
69 window.defer(cx, move |window, cx| {
70 if blur_focus.is_focused(window) {
71 window.blur(cx);
72 }
73 });
74 }
75 let focused = !disabled && focus.is_focused(window);
76 let filled = self.variant == TextFieldVariant::Filled;
77 let label_position = self.label_position.unwrap_or(if filled {
78 TextFieldLabelPosition::Inside
79 } else {
80 TextFieldLabelPosition::Cutout
81 });
82 let label_inside = self.show_label && label_position == TextFieldLabelPosition::Inside;
83 let label_above = self.show_label && label_position == TextFieldLabelPosition::Above;
84 let has_cutout =
85 self.show_label && label_position == TextFieldLabelPosition::Cutout && !filled;
86 let error = self.invalid;
87
88 let shape = self.shape.unwrap_or(
89 if filled {
90 CornerRole::ExtraSmallTop
91 } else {
92 CornerRole::ExtraSmall
93 }
94 .shape(),
95 );
96 let type_style = LayoutPolicy::scale_text(
97 theme.typography.scale_style(
98 self.text_style
99 .unwrap_or(TypeRole::BodyLarge.style(TypographyEmphasis::Baseline)),
100 ),
101 self.font_scale,
102 );
103 let caption_style = LayoutPolicy::scale_text(
104 theme
105 .typography
106 .style(TypeRole::BodySmall, TypographyEmphasis::Baseline),
107 self.font_scale,
108 );
109 let font = font_for_style(&theme.typography, type_style, cx);
110 let has_text = match &self.editor {
111 Editor::Single(state) | Editor::Secure(state) => state.update(cx, |state, cx| {
112 !state.value().is_empty()
113 || state
114 .marked_text_range(window, cx)
115 .is_some_and(|range| !range.is_empty())
116 }),
117 Editor::Multiple(state) => state.update(cx, |state, cx| {
118 !state.value().is_empty()
119 || state
120 .marked_text_range(window, cx)
121 .is_some_and(|range| !range.is_empty())
122 }),
123 };
124 let animation = sample_animation(
125 &self.id,
126 &theme,
127 focused || has_text || self.label_minimized || label_above || !self.show_label,
128 focused,
129 error && !disabled,
130 window,
131 cx,
132 );
133 let effective_floating = if self.show_label {
134 animation.floating
135 } else {
136 1.
137 };
138 let hover = window
139 .use_keyed_state((self.id.clone(), "field-hover"), cx, |_, _| {
140 Rc::new(Cell::new(false))
141 })
142 .read(cx)
143 .clone();
144 let tracker = self.interaction_source.map(|source| {
145 let tracker = InteractionSource::track(&source, &self.id, window, cx);
146 tracker.record(
147 interaction_state(
148 disabled,
149 hover.get(),
150 focused && window.last_input_was_keyboard(),
151 ),
152 cx,
153 );
154 tracker
155 });
156 let palette = resolve_palette(
157 &theme,
158 self.colors,
159 filled,
160 disabled,
161 error,
162 focused,
163 hover.get(),
164 &animation,
165 );
166 let style = build_editor_style(
167 &theme,
168 &palette,
169 has_text,
170 self.placeholder.is_some(),
171 effective_floating,
172 self.dropdown_editor && readonly,
173 error,
174 );
175 let label = self.label;
176 let accessible_id = self.id.to_string();
177 let align = if rtl {
178 TextAlign::Right
179 } else {
180 TextAlign::Left
181 };
182 let layout_probe =
183 build_layout_probe(&self.id, &self.editor, self.on_text_layout, window, cx);
184 let editor_for_clear = self.editor.clone();
185 let is_secure = matches!(self.editor, Editor::Secure(_));
186 let configured = configure_and_build_editor(
187 &self.id,
188 self.editor,
189 self.obfuscation_mode,
190 &presentation,
191 align,
192 style,
193 &theme,
194 readonly,
195 disabled,
196 window,
197 cx,
198 );
199 let support = self.error.map_or(self.supporting, |text| {
200 Some(FieldDescription {
201 text,
202 content: None,
203 })
204 });
205 let support_text = support.as_ref().map(|support| &support.text);
206 let (count, description) =
207 if let Some((limit, text)) = self.character_count.zip(configured.value.as_ref()) {
208 let cache = window.use_keyed_state((self.id.clone(), "char-count"), cx, |_, _| {
209 CharacterCountCache::default()
210 });
211 cache.update(cx, |cache, _| {
212 let text_or_limit_changed = cache.limit != Some(limit) || &cache.text != text;
213 if text_or_limit_changed {
214 cache.text = text.clone();
215 cache.limit = Some(limit);
216 cache.count_label = format!("{} / {limit}", text.chars().count()).into();
217 }
218 if text_or_limit_changed || cache.support_text.as_ref() != support_text {
219 cache.support_text = support_text.cloned();
220 cache.combined_support = Some(match support_text {
221 Some(support) => format!("{support}. {}", cache.count_label).into(),
222 None => cache.count_label.clone(),
223 });
224 }
225 (
226 Some(cache.count_label.clone()),
227 cache.combined_support.clone(),
228 )
229 })
230 } else {
231 (None, support_text.cloned())
232 };
233 let placeholder_hint = self.placeholder.as_ref().map_or_else(
234 || presentation.placeholder().clone(),
235 |(hint, _)| hint.clone(),
236 );
237 let metrics = resolve_metrics(
238 type_style,
239 caption_style,
240 &animation,
241 theme.layout.density,
242 direction,
243 self.min_height,
244 self.indicator_width,
245 self.content_padding,
246 label_inside,
247 filled,
248 );
249 let cutout = has_cutout.then(|| Rc::new(Cell::new(None::<Bounds<Pixels>>)));
250 let outline_canvas = build_outline_canvas(
251 shape,
252 direction,
253 palette.background,
254 filled,
255 metrics.outline_width,
256 palette.outline_tint,
257 cutout.clone(),
258 );
259 let trailing_tint = palette.state_colors.trailing.unwrap_or(palette.secondary);
260 let trailing = build_trailing_controls(
261 &self.id,
262 &editor_for_clear,
263 &focus,
264 self.clearable,
265 self.clear_label,
266 self.visibility_toggle,
267 self.visibility_labels,
268 self.trailing,
269 is_secure,
270 has_text,
271 disabled,
272 readonly,
273 rtl,
274 theme.layout.density,
275 trailing_tint,
276 window,
277 cx,
278 );
279 let (above_label, attached_label) = if self.show_label {
280 build_label(
281 LabelConfig {
282 label: label.clone(),
283 label_content: self.label_content,
284 label_above,
285 has_cutout,
286 required: self.required,
287 disabled,
288 rtl,
289 has_leading: self.leading.is_some(),
290 trailing_clearance: trailing.clearance,
291 floating: animation.floating,
292 expanded_alignment: self.expanded_alignment,
293 minimized_alignment: self.minimized_alignment,
294 label_color: palette.label_color,
295 },
296 &metrics,
297 &focus,
298 cutout,
299 )
300 } else {
301 (None, None)
302 };
303 let show_affixes = effective_floating >= 0.5;
304 let editor_row = build_editor_row(
305 EditorSlots {
306 leading: self.leading,
307 prefix: self.prefix,
308 editor: configured.element,
309 placeholder: self.placeholder,
310 layout_probe,
311 suffix: self.suffix,
312 trailing: trailing.element,
313 readonly_dropdown: self.dropdown_editor && readonly,
314 },
315 font.clone(),
316 type_style,
317 rtl,
318 show_affixes,
319 has_text,
320 &palette,
321 );
322
323 div()
324 .id(self.id)
325 .test_support()
326 .w_full()
327 .min_w_0()
328 .flex()
329 .flex_col()
330 .gap(px(4.))
331 .font_family(font.family)
332 .role(match (self.expanded, readonly) {
333 (Some(_), true) => Role::ComboBox,
334 (Some(_), false) => Role::EditableComboBox,
335 _ => configured.role,
336 })
337 .aria_label(label)
338 .accessibility_id(accessible_id)
339 .aria_placeholder(placeholder_hint)
340 .when_some(self.expanded, |field, expanded| {
341 field.aria_expanded(expanded)
342 })
343 .when_some(
344 self.dropdown_request.filter(|_| !disabled),
345 |field, request| {
346 let open = self.expanded.unwrap_or_default();
347 let click = request.clone();
348 field
349 .on_a11y_action(AccessibleAction::Click, move |_, window, cx| {
350 click(!open, window, cx);
351 })
352 .on_a11y_action(
353 if open {
354 AccessibleAction::Collapse
355 } else {
356 AccessibleAction::Expand
357 },
358 move |_, window, cx| request(!open, window, cx),
359 )
360 },
361 )
362 .when(!disabled, |field| field.track_focus(&focus).tab_stop(false))
363 .when_some(configured.value, |field, value| field.aria_value(value))
364 .when_some(configured.set_value, |field, editor| {
365 field.on_a11y_action(AccessibleAction::SetValue, move |data, window, cx| {
366 if let Some(gpui::accesskit::ActionData::Value(value)) = data {
367 editor.replace_all(value.to_string().into(), window, cx);
368 }
369 })
370 })
371 .when_some(description, |field, text| field.aria_description(text))
372 .a11y_synthetic_children(move |tree| {
373 let node = tree.parent_node();
374 if error && !disabled {
375 node.set_invalid(gpui::accesskit::Invalid::True);
376 }
377 if disabled {
378 node.set_disabled();
379 }
380 if readonly || disabled {
381 node.set_read_only();
382 }
383 if self.required {
384 node.set_required();
385 }
386 })
387 .child(
388 div()
389 .w_full()
390 .min_w_0()
391 .flex()
392 .flex_col()
393 .gap(px(4.))
394 .when(!disabled && self.expanded != Some(true), |region| {
395 let blur_focus = focus.clone();
396 region.on_mouse_down_out(move |_, window, cx| {
397 if blur_focus.is_focused(window) {
398 window.blur(cx);
399 }
400 })
401 })
402 .children(above_label)
403 .child(
404 div()
405 .id("container")
406 .test_support()
407 .relative()
408 .flex()
409 .flex_col()
410 .when_else(
411 label_inside || presentation.is_multi_line(),
412 Styled::justify_end,
413 Styled::justify_center,
414 )
415 .min_h(metrics.minimum_height)
416 .pt(metrics.editor_top_padding)
417 .pr(metrics.padding.right)
418 .pb(metrics.editor_bottom_padding)
419 .pl(metrics.padding.left)
420 .when(!disabled, |field| {
421 field.on_hover(move |hovering, window, cx| {
422 if hover.replace(*hovering) != *hovering {
423 if let Some(tracker) = &tracker {
424 tracker.record(
425 interaction_state(
426 false,
427 *hovering,
428 focus.is_focused(window)
429 && window.last_input_was_keyboard(),
430 ),
431 cx,
432 );
433 }
434 window.refresh();
435 }
436 })
437 })
438 .child(outline_canvas)
439 .when(rtl, |field| field.text_align(TextAlign::Right))
440 .child(editor_row)
441 .children(attached_label),
442 ),
443 )
444 .when(support.is_some() || count.is_some(), |field| {
445 field.child(build_supporting_row(
446 support,
447 count,
448 metrics.padding,
449 caption_style,
450 &palette,
451 error,
452 disabled,
453 rtl,
454 ))
455 })
456 }
457}