An open source design system that's fully customizable and agent ready
TypeScript
feat(timeinput): support InputGroup composition (#3522)
Cindy Zhang05be2c64459b
diff --git a/.changeset/timeinput-inputgroup.md b/.changeset/timeinput-inputgroup.mdnew file mode 100644index 0000000000..72088f1b4e--- /dev/null+++ b/.changeset/timeinput-inputgroup.md@@ -0,0 +1,6 @@+---+'@astryxdesign/core': patch+---++[feat] Add InputGroup compatibility for TimeInput (#3520)+@cixzhangdiff --git a/apps/storybook/stories/InputGroup.stories.tsx b/apps/storybook/stories/InputGroup.stories.tsxindex 5593ba4c3c..90c22205ed 100644--- a/apps/storybook/stories/InputGroup.stories.tsx+++ b/apps/storybook/stories/InputGroup.stories.tsx@@ -6,7 +6,9 @@ import {InputGroup} from '@astryxdesign/core/InputGroup';import {InputGroupText} from '@astryxdesign/core/InputGroup';import {TextInput} from '@astryxdesign/core/TextInput';import {NumberInput} from '@astryxdesign/core/NumberInput';+import {TimeInput} from '@astryxdesign/core/TimeInput';import {Icon} from '@astryxdesign/core/Icon';+import type {ISOTimeString} from '@astryxdesign/core';const meta: Meta<typeof InputGroup> = {title: 'Core/InputGroup',@@ -137,6 +139,31 @@ export const WithNumberInput: Story = {},};+export const WithTimeInput: Story = {+ render: args => {+ const [value, setValue] = useState<ISOTimeString | undefined>(+ '09:00' as ISOTimeString,+ );+ return (+ <InputGroup {...args}>+ <InputGroupText>Starts</InputGroupText>+ <TimeInput+ label="Start time"+ isLabelHidden+ value={value}+ onChange={setValue}+ hourFormat="24h"+ placeholder="09:00"+ />+ </InputGroup>+ );+ },+ args: {+ label: 'Schedule',+ description: 'Use local time',+ },+};+export const WithDescription: Story = {render: args => {const [value, setValue] = useState('');diff --git a/packages/core/src/InputGroup/InputGroup.doc.mjs b/packages/core/src/InputGroup/InputGroup.doc.mjsindex 20c0c85941..7168635df7 100644--- a/packages/core/src/InputGroup/InputGroup.doc.mjs+++ b/packages/core/src/InputGroup/InputGroup.doc.mjs@@ -8,18 +8,28 @@ export const docs = {group: 'Field',category: 'Data Input',isHiddenFromOverview: true,- keywords: ["inputgroup","addon","prefix","suffix","connected","grouped","input"],+ keywords: [+ 'inputgroup',+ 'addon',+ 'prefix',+ 'suffix',+ 'connected',+ 'grouped',+ 'input',+ ],theming: {targets: [{className: 'astryx-input-group', visualProps: ['size', 'status']},],},- description: 'Groups an input with prefix/suffix addons in a visually connected container with shared border and focus ring.',+ description:+ 'Groups an input with prefix/suffix addons in a visually connected container with shared border and focus ring.',props: [{name: 'children',type: 'ReactNode',- description: 'Input and InputGroupText children.',+ description:+ 'InputGroupText and compatible input children: TextInput, NumberInput, or TimeInput.',required: true,},{@@ -84,39 +94,117 @@ export const docs = {description: 'Test selector.',},],- components: [- {name: 'InputGroupText'},- ],+ components: [{name: 'InputGroupText'}],usage: {- description: 'InputGroup connects an input with prefix/suffix addons in a single visual unit. Use it for URL fields, currency inputs, search fields with action buttons, or any input that needs contextual decorations.',+ description:+ 'InputGroup connects an input with prefix/suffix addons in a single visual unit. Use it for URL fields, currency inputs, search fields with action buttons, or any input that needs contextual decorations.',bestPractices: [- {guidance: true, description: 'Use text addons to show units, prefixes, or suffixes that clarify the input format (e.g., "$", "kg", "https://").'},- {guidance: true, description: 'Use InputGroupText for static prefixes/suffixes like "$", "kg", or "https://".'},- {guidance: true, description: "Keep each inner input's label specific; grouped inputs automatically combine the group label with their own label and inherit the group description/status context."},- {guidance: false, description: 'Don\'t put multiple text inputs in one group; use separate fields instead.'},- {guidance: false, description: 'Don\'t use InputGroup for unrelated inputs; it\'s for a single input with decorations.'},+ {+ guidance: true,+ description:+ 'Use text addons to show units, prefixes, or suffixes that clarify the input format (e.g., "$", "kg", "https://").',+ },+ {+ guidance: true,+ description:+ 'Use InputGroupText for static prefixes/suffixes like "$", "kg", or "https://".',+ },+ {+ guidance: true,+ description:+ 'Use InputGroup with compatible single-line inputs: TextInput, NumberInput, and TimeInput.',+ },+ {+ guidance: true,+ description:+ "Keep each inner input's label specific; grouped inputs automatically combine the group label with their own label and inherit the group description/status context.",+ },+ {+ guidance: false,+ description:+ "Don't put multiple text inputs in one group; use separate fields instead.",+ },+ {+ guidance: false,+ description:+ "Don't use InputGroup for unrelated inputs; it's for a single input with decorations.",+ },+ {+ guidance: false,+ description:+ "Don't use InputGroup with TextArea, Slider, Switch, CheckboxInput, or RadioList.",+ },],anatomy: [{name: 'Label', required: true, description: 'Text above the group.'},- {name: 'Prefix addon', required: false, description: 'Content before the input (text, icon, or button).'},- {name: 'Input', required: true, description: 'The main input element (TextInput, NumberInput, etc.).'},- {name: 'Suffix addon', required: false, description: 'Content after the input (text, icon, or button).'},- {name: 'Status message', required: false, description: 'An error, warning, or success message below the group.'},+ {+ name: 'Prefix addon',+ required: false,+ description: 'Content before the input (text, icon, or button).',+ },+ {+ name: 'Input',+ required: true,+ description:+ 'The main input element (TextInput, NumberInput, or TimeInput).',+ },+ {+ name: 'Suffix addon',+ required: false,+ description: 'Content after the input (text, icon, or button).',+ },+ {+ name: 'Status message',+ required: false,+ description: 'An error, warning, or success message below the group.',+ },],},};/** @type {import('../docs-types').TranslationDoc} */export const docsDense = {- description: 'groups input with prefix/suffix addons in a connected container',+ description:+ 'groups input with prefix/suffix addons in a connected container',usage: {- description: 'InputGroup connects an input with addons. Use for URL fields, currency inputs, search with actions.',+ description:+ 'InputGroup connects an input with addons. Use for URL fields, currency inputs, search with actions.',bestPractices: [- {guidance: true, description: 'Use text addons to show units, prefixes, or suffixes that clarify input format (e.g. "$", "kg", "https://").'},- {guidance: true, description: 'Use InputGroupText for static prefixes/suffixes like "$", "kg", or "https://".'},- {guidance: true, description: "Keep each inner input's label specific; grouped inputs combine the group label with their own label and inherit group description/status."},- {guidance: false, description: 'Don\'t put multiple text inputs in one group; use separate fields instead.'},- {guidance: false, description: 'Don\'t use InputGroup for unrelated inputs; it\'s for a single input with decorations.'},+ {+ guidance: true,+ description:+ 'Use text addons to show units, prefixes, or suffixes that clarify input format (e.g. "$", "kg", "https://").',+ },+ {+ guidance: true,+ description:+ 'Use InputGroupText for static prefixes/suffixes like "$", "kg", or "https://".',+ },+ {+ guidance: true,+ description:+ 'Use InputGroup with compatible single-line inputs: TextInput, NumberInput, and TimeInput.',+ },+ {+ guidance: true,+ description:+ "Keep each inner input's label specific; grouped inputs combine the group label with their own label and inherit group description/status.",+ },+ {+ guidance: false,+ description:+ "Don't put multiple text inputs in one group; use separate fields instead.",+ },+ {+ guidance: false,+ description:+ "Don't use InputGroup for unrelated inputs; it's for a single input with decorations.",+ },+ {+ guidance: false,+ description:+ "Don't use InputGroup with TextArea, Slider, Switch, CheckboxInput, or RadioList.",+ },],},};diff --git a/packages/core/src/TimeInput/TimeInput.doc.mjs b/packages/core/src/TimeInput/TimeInput.doc.mjsindex 1a5ec33b92..b5532de5a0 100644--- a/packages/core/src/TimeInput/TimeInput.doc.mjs+++ b/packages/core/src/TimeInput/TimeInput.doc.mjs@@ -48,6 +48,11 @@ export const docs = {description:'Enable hasClear when the field is optional, so users can remove a previously selected time.',},+ {+ guidance: true,+ description:+ 'Place TimeInput inside InputGroup when the time needs a single-line prefix or suffix addon, like a start/end label or timezone marker.',+ },{guidance: false,description:diff --git a/packages/core/src/TimeInput/TimeInput.test.tsx b/packages/core/src/TimeInput/TimeInput.test.tsxindex 69ee78ad86..61f1b8baed 100644--- a/packages/core/src/TimeInput/TimeInput.test.tsx+++ b/packages/core/src/TimeInput/TimeInput.test.tsx@@ -13,6 +13,7 @@ import {describe, it, expect, vi, beforeEach} from 'vitest';import {render, screen, fireEvent, waitFor} from '@testing-library/react';import userEvent from '@testing-library/user-event';import {TimeInput} from './TimeInput';+import {InputGroup, InputGroupText} from '../InputGroup';import type {ISOTimeString} from '../utils';describe('TimeInput', () => {@@ -206,6 +207,116 @@ describe('TimeInput', () => {fireEvent.click(wrapper);expect(input).toHaveFocus();});+ describe('InputGroup integration', () => {+ it('labels grouped TimeInput from the group and inner input labels', () => {+ render(+ <InputGroup label="Schedule" description="Use local time">+ <InputGroupText>Starts</InputGroupText>+ <TimeInput+ label="Start time"+ isLabelHidden+ value={'09:00' as ISOTimeString}+ onChange={() => {}}+ />+ </InputGroup>,+ );++ const group = screen.getByRole('group', {name: 'Schedule'});+ const groupLabelID = group.getAttribute('aria-labelledby');+ const input = screen.getByRole('textbox', {+ name: 'Schedule Start time',+ });+ const labelledByIDs =+ input.getAttribute('aria-labelledby')?.split(' ') ?? [];++ expect(labelledByIDs).toHaveLength(2);+ expect(labelledByIDs[0]).toBe(groupLabelID);+ expect(document.getElementById(labelledByIDs[1])).toHaveTextContent(+ 'Start time',+ );+ expect(input).not.toHaveAttribute('aria-label');+ expect(input).toHaveAttribute(+ 'aria-describedby',+ group.getAttribute('aria-describedby'),+ );+ });++ it('includes group and local described-by content when grouped', () => {+ render(+ <InputGroup+ label="Schedule"+ description="Use local time"+ status={{type: 'warning', message: 'Schedule is unusual'}}>+ <InputGroupText>Starts</InputGroupText>+ <TimeInput+ label="Start time"+ isLabelHidden+ value={'09:00' as ISOTimeString}+ onChange={() => {}}+ description="Business hours only"+ status={{type: 'error', message: 'Start time is required'}}+ isDisabled+ disabledMessage="Time edits are locked"+ />+ </InputGroup>,+ );++ const input = screen.getByRole('textbox', {+ name: 'Schedule Start time',+ });+ const describedByIDs =+ input.getAttribute('aria-describedby')?.split(' ') ?? [];+ const describedText = describedByIDs+ .map(id => document.getElementById(id)?.textContent)+ .join(' ');++ expect(describedText).toContain('Use local time');+ expect(describedText).toContain('Schedule is unusual');+ expect(describedText).toContain('Business hours only');+ expect(describedText).toContain('Start time is required');+ expect(describedText).toContain('Time edits are locked');+ });++ it('does not render duplicate Field label chrome when grouped', () => {+ render(+ <InputGroup label="Schedule">+ <InputGroupText>Starts</InputGroupText>+ <TimeInput+ label="Start time"+ isLabelHidden+ value={'09:00' as ISOTimeString}+ onChange={() => {}}+ />+ </InputGroup>,+ );++ expect(screen.getByText('Schedule')).toBeInTheDocument();+ expect(screen.getByText('Start time')).toBeInTheDocument();+ expect(screen.getByText('Start time').tagName).toBe('SPAN');+ expect(document.querySelector('label')).toBeNull();+ });++ it('suppresses the local status icon when grouped', () => {+ const {container} = render(+ <InputGroup label="Schedule">+ <InputGroupText>Starts</InputGroupText>+ <TimeInput+ label="Start time"+ isLabelHidden+ value={'09:00' as ISOTimeString}+ onChange={() => {}}+ status={{type: 'error'}}+ />+ </InputGroup>,+ );++ // The clock icon remains, but the trailing status icon is suppressed in+ // grouped mode so the shared InputGroup border/status treatment is not+ // duplicated.+ expect(container.querySelectorAll('svg')).toHaveLength(1);+ });+ });+describe('disabledMessage', () => {// jsdom does not implement the Popover API used by the tooltip, so mock// showPopover/hidePopover to toggle a `popover-open` attribute the testsdiff --git a/packages/core/src/TimeInput/TimeInput.tsx b/packages/core/src/TimeInput/TimeInput.tsxindex 9c363b656a..1939ede585 100644--- a/packages/core/src/TimeInput/TimeInput.tsx+++ b/packages/core/src/TimeInput/TimeInput.tsx@@ -4,7 +4,7 @@/*** @file TimeInput.tsx- * @input Uses React, useId, useState, useEffect, useCallback, useRef, Field, Icon+ * @input Uses React, useId, useState, useCallback, useRef, Field, Icon, InputGroupContext* @output Exports TimeInput component, TimeInputProps* @position Core implementation; consumed by index.ts, tested by TimeInput.test.tsx*@@ -48,6 +48,7 @@ import {} from '../Field';import {Icon} from '../Icon';import {Spinner} from '../Spinner';+import {VisuallyHidden} from '../VisuallyHidden';import {type ISOTimeString,parseTimeInput,@@ -58,11 +59,14 @@ import {isTimeInRange,mergeProps,mergeRefs,+ getInputARIA,} from '../utils';import type {BaseProps} from '../BaseProps';import type {SizeValue} from '../utils/types';import {useSize} from '../SizeContext/SizeContext';import {useInputContainer} from '../hooks/useInputContainer';+import {useInputGroup} from '../InputGroup/InputGroupContext';+import {groupStyles} from '../InputGroup/groupStyles';import {useTooltip} from '../Tooltip';import {themeProps} from '../utils/themeProps';@@ -350,10 +354,12 @@ export function TimeInput({const size = useSize(sizeProp, 'md');const id = useId();+ const inputLabelID = useId();const descriptionID = useId();const statusMessageID = useId();const inputRef = useRef<HTMLInputElement | null>(null);const containerRef = useRef<HTMLDivElement | null>(null);+ const inputGroup = useInputGroup();const [, startTransition] = useTransition();const [optimisticValue, setOptimisticValue] = useOptimistic(value);@@ -388,14 +394,15 @@ export function TimeInput({success: 'success',};- const ariaDescribedBy =+ const {ariaLabelledBy, ariaDescribedBy} = getInputARIA(+ inputLabelID,[description ? descriptionID : null,status?.message ? statusMessageID : null,showsDisabledMessage ? disabledMessageTooltip.describedBy : null,- ]- .filter(Boolean)- .join(' ') || undefined;+ ],+ inputGroup,+ );// Pending input while user is typing (null = show formatted value)const [pendingInput, setPendingInput] = useState<string | null>(null);@@ -564,6 +571,109 @@ export function TimeInput({disabled: isDisabled,});+ const inputWrapper = (+ <div+ ref={el => {+ containerRef.current = el;+ // Anchor + hover/focus listeners for the disabled-message tooltip.+ // Handlers are gated internally by isEnabled, so attaching+ // unconditionally is safe.+ disabledMessageTooltip.ref(el);+ }}+ onClick={handleWrapperClick}+ onMouseUp={handleWrapperMouseUp}+ {...mergeProps(+ themeProps('time-input', {size, status: status?.type ?? null}),+ stylex.props(+ inputWrapperStyles.base,+ sizeStyles[size],+ isDisabled && inputWrapperStyles.disabled,+ status && inputStatusBorderStyles[status.type],+ status && inputStatusHoverShadowStyles[status.type],+ status && inputStatusFocusWithinStyles[status.type],+ inputGroup && groupStyles.inGroup,+ xstyle,+ ),+ className,+ style,+ )}>+ <div {...stylex.props(styles.icon)}>+ <Icon icon="clock" size="sm" color="secondary" />+ </div>+ {inputGroup && <VisuallyHidden id={inputLabelID}>{label}</VisuallyHidden>}+ {inputGroup && description && (+ <VisuallyHidden as="div" id={descriptionID}>+ {description}+ </VisuallyHidden>+ )}+ {inputGroup && status?.message && (+ <VisuallyHidden+ as="div"+ id={statusMessageID}+ role={status.type === 'error' ? 'alert' : 'status'}+ aria-live={status.type === 'error' ? 'assertive' : 'polite'}>+ {status.message}+ </VisuallyHidden>+ )}+ <input+ ref={mergeRefs(ref, inputRef)}+ id={id}+ type="text"+ value={displayValue}+ onChange={handleInputChange}+ onFocus={handleFocus}+ onBlur={handleBlur}+ onKeyDown={handleInputKeyDown}+ placeholder={displayPlaceholder}+ // With a disabledMessage the input keeps focusability via+ // aria-disabled so the reason is focus-discoverable; typing and+ // arrow-key adjustment are blocked with readOnly and the guards.+ disabled={isDisabled && !showsDisabledMessage}+ aria-disabled={showsDisabledMessage ? 'true' : undefined}+ readOnly={showsDisabledMessage || undefined}+ autoFocus={hasAutoFocus}+ data-autofocus={hasAutoFocus || undefined}+ aria-describedby={ariaDescribedBy}+ aria-required={isRequired === true ? 'true' : undefined}+ aria-invalid={status?.type === 'error' ? 'true' : undefined}+ aria-busy={isBusy || undefined}+ aria-labelledby={ariaLabelledBy}+ {...stylex.props(+ styles.input,+ isDisabled && styles.inputDisabled,+ !isInputValid && styles.inputInvalid,+ )}+ />+ {isBusy && <Spinner size="sm" />}+ {hasClear && value && !isDisabled && (+ <button+ type="button"+ onClick={handleClear}+ aria-label={`Clear ${label}`}+ {...stylex.props(styles.clearButton)}>+ <Icon icon="close" size="sm" color="secondary" />+ </button>+ )}+ {status && !inputGroup && (+ <Icon+ icon={statusIconMap[status.type]}+ size="md"+ color={statusIconColorMap[status.type]}+ />+ )}+ </div>+ );++ if (inputGroup) {+ return (+ <>+ {inputWrapper}+ {showsDisabledMessage &&+ disabledMessageTooltip.renderTooltip(disabledMessage)}+ </>+ );+ }+return (<Fieldlabel={label}@@ -585,80 +695,7 @@ export function TimeInput({}labelTooltip={labelTooltip}width={width}>- <div- ref={el => {- containerRef.current = el;- // Anchor + hover/focus listeners for the disabled-message tooltip.- // Handlers are gated internally by isEnabled, so attaching- // unconditionally is safe.- disabledMessageTooltip.ref(el);- }}- onClick={handleWrapperClick}- onMouseUp={handleWrapperMouseUp}- {...mergeProps(- themeProps('time-input', {size, status: status?.type ?? null}),- stylex.props(- inputWrapperStyles.base,- sizeStyles[size],- isDisabled && inputWrapperStyles.disabled,- status && inputStatusBorderStyles[status.type],- status && inputStatusHoverShadowStyles[status.type],- status && inputStatusFocusWithinStyles[status.type],- xstyle,- ),- className,- style,- )}>- <div {...stylex.props(styles.icon)}>- <Icon icon="clock" size="sm" color="secondary" />- </div>- <input- ref={mergeRefs(ref, inputRef)}- id={id}- type="text"- value={displayValue}- onChange={handleInputChange}- onFocus={handleFocus}- onBlur={handleBlur}- onKeyDown={handleInputKeyDown}- placeholder={displayPlaceholder}- // With a disabledMessage the input keeps focusability via- // aria-disabled so the reason is focus-discoverable; typing and- // arrow-key adjustment are blocked with readOnly and the guards.- disabled={isDisabled && !showsDisabledMessage}- aria-disabled={showsDisabledMessage ? 'true' : undefined}- readOnly={showsDisabledMessage || undefined}- autoFocus={hasAutoFocus}- data-autofocus={hasAutoFocus || undefined}- aria-describedby={ariaDescribedBy}- aria-required={isRequired === true ? 'true' : undefined}- aria-invalid={status?.type === 'error' ? 'true' : undefined}- aria-busy={isBusy || undefined}- {...stylex.props(- styles.input,- isDisabled && styles.inputDisabled,- !isInputValid && styles.inputInvalid,- )}- />- {isBusy && <Spinner size="sm" />}- {hasClear && value && !isDisabled && (- <button- type="button"- onClick={handleClear}- aria-label={`Clear ${label}`}- {...stylex.props(styles.clearButton)}>- <Icon icon="close" size="sm" color="secondary" />- </button>- )}- {status && (- <Icon- icon={statusIconMap[status.type]}- size="md"- color={statusIconColorMap[status.type]}- />- )}- </div>-+ {inputWrapper}{showsDisabledMessage &&disabledMessageTooltip.renderTooltip(disabledMessage)}</Field>