1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
//! Field component for wrapping form inputs with labels, descriptions, and error states.
//!
//! A `Field` does two things a control beside it cannot do for itself: it
//! *names* it, and it opens an ambient [`FormContext`] carrying that name, the
//! field's `disabled`, and the focus handle its label click lands on. See
//! [`crate::elements::form`] for why that is ambient rather than a prop.
use crate::a11y::{A11y, Announce};
use crate::element_id;
use crate::elements::form::{self, FormContext, WithFormContext};
use crate::theme::{ActiveTheme, ControlSize, Themeable};
use crate::traits::accessible::Accessible;
use crate::traits::control_sized::ControlSized;
use crate::traits::disableable::Disableable;
use crate::traits::labelable::Labelable;
use gpui::{
div, prelude::FluentBuilder, rems, AnyElement, App, ElementId, InteractiveElement, IntoElement,
ParentElement, Rems, RenderOnce, Role, SharedString, StatefulInteractiveElement, Styled,
Window,
};
/// Width of the label column in the beside layout.
const LABEL_COLUMN_WIDTH: Rems = Rems(8.0);
/// Gap between the label column and the input beside it.
const LABEL_COLUMN_GAP: Rems = Rems(0.75);
/// Creates a new Field builder with the given id.
pub fn field(id: impl Into<ElementId>) -> Field {
Field::new(id)
}
/// Label position relative to the input.
#[derive(Default, Clone, Copy, PartialEq, Eq)]
pub enum LabelPosition {
/// Label is displayed above the input (default).
#[default]
Above,
/// Label is displayed beside the input (horizontal layout).
Beside,
}
/// A field component for wrapping form inputs with labels, descriptions, and error states.
///
/// # Example
///
/// ```ignore
/// field("username")
/// .label("Username")
/// .description("Enter your username")
/// .required(true)
/// .child(input("username"))
/// ```
#[derive(IntoElement)]
pub struct Field {
id: ElementId,
label: Option<SharedString>,
description: Option<SharedString>,
error: Option<SharedString>,
required: bool,
label_position: LabelPosition,
child: Option<AnyElement>,
disabled: bool,
size: ControlSize,
}
impl Field {
/// Create a new Field with the given id.
///
/// The id is required — it carries the field's accessibility node, scopes
/// the label's own id, and keys the focus handle the label publishes. See
/// [`crate::element_id`] for the rule it has to satisfy.
pub fn new(id: impl Into<ElementId>) -> Self {
Field {
id: id.into(),
label: None,
description: None,
error: None,
required: false,
label_position: LabelPosition::default(),
child: None,
disabled: false,
size: ControlSize::default(),
}
}
/// Set the description/help text for this field.
pub fn description(mut self, description: impl Into<SharedString>) -> Self {
self.description = Some(description.into());
self
}
/// Set an error message for this field.
/// When set, the field will display in an error state.
pub fn error(mut self, error: impl Into<SharedString>) -> Self {
self.error = Some(error.into());
self
}
/// Mark this field as required.
/// Displays a required indicator next to the label.
pub fn required(mut self, required: bool) -> Self {
self.required = required;
self
}
/// Set the label position (above or beside the input).
pub fn label_position(mut self, position: LabelPosition) -> Self {
self.label_position = position;
self
}
/// Set the child element (typically a form input).
pub fn child(mut self, child: impl IntoElement) -> Self {
self.child = Some(child.into_any_element());
self
}
}
impl Labelable for Field {
fn label(mut self, label: impl Into<SharedString>) -> Self {
self.label = Some(label.into());
self
}
}
impl Disableable for Field {
fn is_disabled(&self) -> bool {
self.disabled
}
/// Dims this field's own label, description and error, **and** publishes
/// `disabled` to the control inside it through the ambient
/// [`FormContext`].
///
/// A control that reads [`form::disabled_here`] therefore needs nothing
/// said about it twice. A control that has not adopted the context still
/// needs its own `disabled(true)` — a field's child is an opaque
/// `AnyElement`, so this element cannot reach into it.
fn disabled(mut self, disabled: bool) -> Self {
self.disabled = disabled;
self
}
}
impl ControlSized for Field {
fn control_size(mut self, size: ControlSize) -> Self {
self.size = size;
self
}
}
impl Accessible for Field {
/// A `Role::Group` named by the label.
///
/// This is label association expressed as its *result* rather than as the
/// relation: gpui has no `labelled_by` builder — accesskit has the
/// relation, gpui's `AriaProperties` has no field for it — so the field
/// announces the name over the label and the control, and republishes it
/// through [`FormContext::name`] for the control to announce as its own.
fn a11y(&self) -> A11y {
let a11y = A11y::new(Role::Group);
match &self.label {
Some(label) => a11y.name(label.clone()),
None => a11y,
}
}
}
impl RenderOnce for Field {
fn render(self, _window: &mut Window, cx: &mut App) -> impl IntoElement {
let a11y = self.a11y();
// Before the theme, which borrows `cx` immutably for the rest of the
// function.
let focus_handle = form::field_focus_handle(&self.id, cx);
let theme = cx.theme();
let metrics = theme.control(self.size);
let has_error = self.error.is_some();
// Its own `disabled`, over any group around it. One line, and it is
// the whole of what adopting the cascade costs.
let disabled = form::disabled_here(self.disabled);
let label_color = if disabled {
theme.fg_disabled()
} else if has_error {
theme.danger()
} else {
theme.fg()
};
let label_element = self.label.clone().map(|label_text| {
let handle = focus_handle.clone();
div()
.id(element_id::scoped(&self.id, "label"))
// `debug_selector` compiles to a no-op that never calls its
// closure unless gpui's `test-support` is on, so a consumer
// pays nothing for it — the same trade `src/elements/table.rs`
// makes. It is what makes "a click on the label lands focus on
// the control" assertable at all.
.debug_selector(|| "gpuikit-field-label".into())
.flex()
.gap(rems(0.25))
// Clicking a label focuses the control it names. A control
// that has not adopted `form::focus_handle_here` tracks no
// such handle, and the click is inert rather than wrong.
.cursor_pointer()
.on_click(move |_, window, cx| window.focus(&handle, cx))
.child(
div()
.text_sm()
.font_weight(gpui::FontWeight::MEDIUM)
.text_color(label_color)
.child(label_text),
)
.when(self.required && !disabled, |this| {
this.child(div().text_sm().text_color(theme.danger()).child("*"))
})
});
let description_element = self.description.map(|desc| {
div()
.text_xs()
.text_color(if disabled {
theme.fg_disabled()
} else {
theme.fg_muted()
})
.child(desc)
});
let error_element = self
.error
.map(|err| div().text_xs().text_color(theme.danger()).child(err));
// What the field tells the control beside it: what it is called, that
// it is disabled, and which handle its label clicks.
let context = {
let context = FormContext::new()
.disabled(disabled)
.focus_handle(focus_handle);
match self.label {
Some(label) => context.name(label),
None => context,
}
};
let child = self.child.map(|child| WithFormContext::new(context, child));
match self.label_position {
LabelPosition::Above => {
// Vertical layout: label above input
div()
.id(self.id)
.announce(a11y)
.flex()
.flex_col()
.gap(rems(0.375))
.when(disabled, |el| el.cursor_not_allowed())
.when_some(label_element, |container, label| container.child(label))
.when_some(description_element, |container, desc| container.child(desc))
.when_some(child, |container, child| container.child(child))
.when_some(error_element, |container, err| container.child(err))
}
LabelPosition::Beside => {
// Horizontal layout: label beside input
div()
.id(self.id)
.announce(a11y)
.flex()
.flex_col()
.gap(rems(0.375))
.when(disabled, |el| el.cursor_not_allowed())
.child(
div()
.flex()
.items_start()
.gap(LABEL_COLUMN_GAP)
.when_some(label_element, |container, label| {
container.child(
div()
.flex()
.flex_col()
.justify_center()
.gap(rems(0.25))
// The label's box is exactly the
// input's box, so the two lines of
// text centre against each other —
// rather than the old
// `pt(rems(0.5)) // Align with input`,
// which was a guess at a height the
// input did not declare.
.min_h(metrics.height)
.min_w(LABEL_COLUMN_WIDTH)
.child(label)
.when_some(description_element, |this, desc| {
this.child(desc)
}),
)
})
.when_some(child, |container, child| {
container.child(div().flex_1().child(child))
}),
)
.when_some(error_element, |container, err| {
container.child(div().pl(LABEL_COLUMN_WIDTH + LABEL_COLUMN_GAP).child(err))
})
}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::a11y::test_support::announced;
use gpui::TestAppContext;
#[gpui::test]
fn a_field_announces_its_label_as_a_group(cx: &mut TestAppContext) {
cx.update(crate::theme::init);
let cx = cx.add_empty_window();
let announced =
cx.update(|window, cx| announced(field("street").label("Street"), window, cx));
assert_eq!(announced.role, Some(Role::Group));
assert_eq!(announced.name(), Some("Street"));
assert_eq!(announced.id, Some(ElementId::Name("street".into())));
}
/// The name the field publishes to the control beside it is the same
/// string it announces itself — there is no second place for the two to
/// disagree.
#[test]
fn a_field_publishes_its_label_as_the_ambient_name() {
let field = field("street").label("Street");
assert_eq!(
field.a11y().accessible_name().map(|name| name.to_string()),
Some("Street".to_string())
);
}
/// A field inside a disabled group is disabled, without being told.
#[test]
fn a_field_inherits_an_enclosing_groups_disabled() {
form::scope(FormContext::new().disabled(true), || {
assert!(form::disabled_here(field("street").is_disabled()));
});
assert!(!form::disabled_here(field("street").is_disabled()));
}
}