Skip to content

An open source design system that's fully customizable and agent ready

TypeScript

fix(Field): consume FormLayoutContext for horizontal-labels grid layout (#2059)

Kenton Quatmana026372203a7
diff --git a/packages/cli/templates/blocks/components/FormLayout/FormLayoutHorizontalLabels.tsx b/packages/cli/templates/blocks/components/FormLayout/FormLayoutHorizontalLabels.tsx
index 206602cad6..4a20253ea1 100644
--- a/packages/cli/templates/blocks/components/FormLayout/FormLayoutHorizontalLabels.tsx
+++ b/packages/cli/templates/blocks/components/FormLayout/FormLayoutHorizontalLabels.tsx
@@ -4,11 +4,13 @@ import {useState} from 'react';
import {XDSFormLayout} from '@xds/core/FormLayout';
import {XDSTextInput} from '@xds/core/TextInput';
import {XDSSelector} from '@xds/core/Selector';
+import {XDSTextArea} from '@xds/core/TextArea';
export default function FormLayoutHorizontalLabels() {
const [displayName, setDisplayName] = useState('Jane Doe');
const [email, setEmail] = useState('[email protected]');
const [timezone, setTimezone] = useState('America/Los_Angeles');
+ const [bio, setBio] = useState('');
return (
<XDSFormLayout direction="horizontal-labels">
@@ -28,6 +30,7 @@ export default function FormLayoutHorizontalLabels() {
{label: 'UTC', value: 'UTC'},
]}
/>
+ <XDSTextArea label="Bio" value={bio} onChange={setBio} rows={3} />
</XDSFormLayout>
);
}
diff --git a/packages/core/src/Field/XDSField.test.tsx b/packages/core/src/Field/XDSField.test.tsx
index 52b169bd0c..92f3d7c405 100644
--- a/packages/core/src/Field/XDSField.test.tsx
+++ b/packages/core/src/Field/XDSField.test.tsx
@@ -10,6 +10,7 @@
import {describe, it, expect, vi} from 'vitest';
import {render, screen} from '@testing-library/react';
import {XDSField} from './XDSField';
+import {XDSFormLayoutContext} from '../FormLayout/XDSFormLayoutContext';
describe('XDSField', () => {
it('renders with label', () => {
@@ -260,4 +261,107 @@ describe('XDSField', () => {
);
warnSpy.mockRestore();
});
+
+ // ─── Horizontal-labels context ────────────────────────────────────────
+
+ describe('horizontal-labels layout', () => {
+ const horizontalLabelsWrapper = ({
+ children,
+ }: {
+ children: React.ReactNode;
+ }) => (
+ <XDSFormLayoutContext.Provider value={{direction: 'horizontal-labels'}}>
+ {children}
+ </XDSFormLayoutContext.Provider>
+ );
+
+ it('applies display:contents when in horizontal-labels context', () => {
+ const {container} = render(
+ <XDSField label="Name" inputID="name-input">
+ <input id="name-input" />
+ </XDSField>,
+ {wrapper: horizontalLabelsWrapper},
+ );
+ const field = container.firstChild as HTMLElement;
+ expect(field.className).toContain('horizontalLabels');
+ });
+
+ it('renders label and input as direct grid children via display:contents', () => {
+ render(
+ <XDSField label="Name" inputID="name-input" data-testid="field">
+ <input id="name-input" data-testid="name" />
+ </XDSField>,
+ {wrapper: horizontalLabelsWrapper},
+ );
+ const field = screen.getByTestId('field');
+ // With display:contents, the field's children participate in the parent grid.
+ // The field should contain: label alignment wrapper + input wrapper div
+ const label = screen.getByText('Name');
+ expect(label.tagName).toBe('LABEL');
+ expect(field.contains(label)).toBe(true);
+ expect(field.contains(screen.getByTestId('name'))).toBe(true);
+ });
+
+ it('groups description with input in column 2', () => {
+ render(
+ <XDSField
+ label="Email"
+ inputID="email-input"
+ description="We won't share it"
+ descriptionID="email-desc"
+ data-testid="field">
+ <input id="email-input" data-testid="email" />
+ </XDSField>,
+ {wrapper: horizontalLabelsWrapper},
+ );
+ const descEl = screen.getByText("We won't share it");
+ const inputEl = screen.getByTestId('email');
+ // Both description and input should be inside the same wrapper div (column 2)
+ expect(descEl.parentElement).toBe(inputEl.parentElement);
+ });
+
+ it('groups status message with input in column 2', () => {
+ render(
+ <XDSField
+ label="Email"
+ inputID="email-input"
+ status={{type: 'error', message: 'Required'}}
+ data-testid="field">
+ <input id="email-input" data-testid="email" />
+ </XDSField>,
+ {wrapper: horizontalLabelsWrapper},
+ );
+ const statusEl = screen.getByRole('alert');
+ const inputEl = screen.getByTestId('email');
+ // Both status and input should be inside the same wrapper div (column 2)
+ expect(statusEl.parentElement).toBe(inputEl.parentElement);
+ });
+
+ it('does not apply display:contents in vertical context', () => {
+ const {container} = render(
+ <XDSField label="Name" inputID="name-input">
+ <input id="name-input" />
+ </XDSField>,
+ );
+ const field = container.firstChild as HTMLElement;
+ expect(field.className).not.toContain('horizontalLabels');
+ expect(field.className).toContain('container');
+ });
+
+ it('wraps label in alignment div with top padding', () => {
+ render(
+ <XDSField label="Name" inputID="name-input" data-testid="field">
+ <input id="name-input" />
+ </XDSField>,
+ {wrapper: horizontalLabelsWrapper},
+ );
+ const field = screen.getByTestId('field');
+ // First child should be the label alignment wrapper
+ const labelWrapper = field.children[0] as HTMLElement;
+ expect(labelWrapper.tagName).toBe('DIV');
+ expect(labelWrapper.className).toContain('horizontalLabelAlign');
+ // Label should be inside
+ expect(labelWrapper.querySelector('label')).not.toBeNull();
+ });
+ });
});
diff --git a/packages/core/src/Field/XDSField.tsx b/packages/core/src/Field/XDSField.tsx
index ef18deffca..c004f1df6f 100644
--- a/packages/core/src/Field/XDSField.tsx
+++ b/packages/core/src/Field/XDSField.tsx
@@ -14,14 +14,16 @@
* - /packages/cli/templates/blocks/components/Field/ (showcase blocks)
*/
-import {type HTMLAttributes, type ReactNode} from 'react';
+import {type HTMLAttributes, type ReactNode, useContext} from 'react';
import * as stylex from '@stylexjs/stylex';
import type {StyleXStyles} from '@stylexjs/stylex';
import {XDSFieldLabel} from './XDSFieldLabel';
import {XDSFieldStatus} from './XDSFieldStatus';
-import {spacingVars} from '../theme/tokens.stylex';
+import {spacingVars, borderVars} from '../theme/tokens.stylex';
import type {XDSIconType} from '../Icon';
import {xdsClassName, mergeProps} from '../utils';
+import {XDSFormLayoutContext} from '../FormLayout/XDSFormLayoutContext';
+import {XDSText} from '../Text';
const styles = stylex.create({
container: {
@@ -31,6 +33,15 @@ const styles = stylex.create({
containerGap: {
gap: spacingVars['--spacing-1'],
},
+ horizontalLabels: {
+ display: 'contents',
+ },
+ horizontalLabelAlign: {
+ // Align label text with input text by matching the input wrapper's
+ // top border + top padding. Works for both single-line inputs and
+ // textareas (labels stay top-aligned, not vertically centered).
+ paddingTop: `calc(${borderVars['--border-width']} + ${spacingVars['--spacing-1']})`,
+ },
inputStatusWrapper: {
display: 'flex',
flexDirection: 'column',
@@ -177,6 +188,9 @@ export function XDSField({
ref,
...props
}: XDSFieldProps) {
+ const {direction} = useContext(XDSFormLayoutContext);
+ const isHorizontalLabels = direction === 'horizontal-labels';
+
const resolvedDescriptionID =
descriptionID ?? (description ? `${inputID}-desc` : undefined);
const resolvedMessageID =
@@ -188,6 +202,64 @@ export function XDSField({
);
}
+ const labelNode = (
+ <XDSFieldLabel
+ label={label}
+ inputID={inputID}
+ isLabelHidden={isLabelHidden}
+ isDisabled={isDisabled}
+ isOptional={isOptional}
+ isRequired={isRequired}
+ labelIcon={labelIcon}
+ labelTooltip={labelTooltip}
+ description={isHorizontalLabels ? undefined : description}
+ descriptionID={isHorizontalLabels ? undefined : resolvedDescriptionID}
+ />
+ );
+
+ const statusNode = status?.message ? (
+ <XDSFieldStatus
+ type={status.type}
+ message={status.message}
+ id={resolvedMessageID}
+ variant={statusVariant}
+ />
+ ) : null;
+
+ // ─── Horizontal-labels mode ───────────────────────────────────────────
+ // Use display:contents so the parent grid's `auto 1fr` columns place
+ // the label in column 1 and the input group in column 2. Description
+ // and status are grouped with the input in column 2.
+ // The label wrapper gets top padding to align label text with input text.
+ if (isHorizontalLabels) {
+ return (
+ <div
+ ref={ref}
+ {...mergeProps(
+ xdsClassName('field', {layout: 'horizontal-labels'}),
+ stylex.props(styles.horizontalLabels, xstyle),
+ className,
+ style,
+ )}
+ {...props}>
+ <div {...stylex.props(styles.horizontalLabelAlign)}>{labelNode}</div>
+ <div {...stylex.props(styles.inputStatusWrapper)}>
+ {description && (
+ <XDSText
+ type="supporting"
+ display="block"
+ id={resolvedDescriptionID}>
+ {description}
+ </XDSText>
+ )}
+ {children}
+ {statusNode}
+ </div>
+ </div>
+ );
+ }
+
+ // ─── Default mode (vertical / horizontal) ─────────────────────────────
return (
<div
ref={ref}
@@ -202,41 +274,16 @@ export function XDSField({
style,
)}
{...props}>
- <XDSFieldLabel
- label={label}
- inputID={inputID}
- isLabelHidden={isLabelHidden}
- isDisabled={isDisabled}
- isOptional={isOptional}
- isRequired={isRequired}
- labelIcon={labelIcon}
- labelTooltip={labelTooltip}
- description={description}
- descriptionID={resolvedDescriptionID}
- />
+ {labelNode}
{statusVariant === 'attached' ? (
<div {...stylex.props(styles.inputStatusWrapper)}>
{children}
- {status?.message && (
- <XDSFieldStatus
- type={status.type}
- message={status.message}
- id={resolvedMessageID}
- variant="attached"
- />
- )}
+ {statusNode}
</div>
) : (
<>
{children}
- {status?.message && (
- <XDSFieldStatus
- type={status.type}
- message={status.message}
- id={resolvedMessageID}
- variant="detached"
- />
- )}
+ {statusNode}
</>
)}
</div>
diff --git a/packages/core/src/FormLayout/XDSFormLayout.test.tsx b/packages/core/src/FormLayout/XDSFormLayout.test.tsx
index 39799da0f8..5424d75587 100644
--- a/packages/core/src/FormLayout/XDSFormLayout.test.tsx
+++ b/packages/core/src/FormLayout/XDSFormLayout.test.tsx
@@ -13,6 +13,7 @@ import {useContext} from 'react';
import {XDSFormLayout} from './XDSFormLayout';
import {XDSFormLayoutContext} from './XDSFormLayoutContext';
import type {XDSFormLayoutDirection} from './XDSFormLayoutContext';
+import {XDSField} from '../Field';
// Helper component to read context
function DirectionReader() {
@@ -182,4 +183,68 @@ describe('XDSFormLayout', () => {
);
expect(container.firstChild).toMatchSnapshot();
});
+
+ // ─── Horizontal-labels with real Field children ─────────────────────────
+
+ it('horizontal-labels renders XDSField children with display:contents', () => {
+ render(
+ <XDSFormLayout direction="horizontal-labels" data-testid="layout">
+ <XDSField label="Name" inputID="name">
+ <input id="name" data-testid="name-input" />
+ </XDSField>
+ <XDSField label="Email" inputID="email">
+ <input id="email" data-testid="email-input" />
+ </XDSField>
+ </XDSFormLayout>,
+ );
+
+ const layout = screen.getByTestId('layout');
+
+ // Labels should be accessible
+ expect(screen.getByLabelText('Name')).toBeInTheDocument();
+ expect(screen.getByLabelText('Email')).toBeInTheDocument();
+
+ // The label and input wrapper should be direct grid-participating children
+ // (via display:contents on the Field wrapper)
+ const nameLabel = screen.getByText('Name');
+ const emailLabel = screen.getByText('Email');
+ expect(nameLabel.tagName).toBe('LABEL');
+ expect(emailLabel.tagName).toBe('LABEL');
+
+ // Both fields should be inside the layout
+ expect(layout.contains(nameLabel)).toBe(true);
+ expect(layout.contains(screen.getByTestId('name-input'))).toBe(true);
+ expect(layout.contains(emailLabel)).toBe(true);
+ expect(layout.contains(screen.getByTestId('email-input'))).toBe(true);
+ });
+
+ it('horizontal-labels with XDSField: label and input wrapper are siblings under display:contents', () => {
+ render(
+ <XDSFormLayout direction="horizontal-labels" data-testid="layout">
+ <XDSField
+ label="Username"
+ inputID="username"
+ data-testid="username-field">
+ <input id="username" data-testid="username-input" />
+ </XDSField>
+ </XDSFormLayout>,
+ );
+
+ const field = screen.getByTestId('username-field');
+ // Field should have display:contents class
+ expect(field.className).toContain('horizontalLabels');
+
+ // Field's direct children should be: label alignment div + input wrapper div
+ const fieldChildren = Array.from(field.children);
+ expect(fieldChildren.length).toBe(2);
+ // First child is the label alignment wrapper containing the <label>
+ expect(fieldChildren[0].tagName).toBe('DIV');
+ expect(fieldChildren[0].querySelector('label')).not.toBeNull();
+ // Second child is the input wrapper div
+ expect(fieldChildren[1].tagName).toBe('DIV');
+ // The input should be inside the wrapper div (column 2)
+ expect(
+ fieldChildren[1].contains(screen.getByTestId('username-input')),
+ ).toBe(true);
+ });
});