An open source design system that's fully customizable and agent ready
TypeScript
feat(TimeInput): add native picker option (#5811)
Xinzi Zhou03eb63196eeb
diff --git a/.changeset/time-input-native-picker-option.md b/.changeset/time-input-native-picker-option.mdnew file mode 100644index 0000000000..54c9663aae--- /dev/null+++ b/.changeset/time-input-native-picker-option.md@@ -0,0 +1,6 @@+---+'@astryxdesign/core': patch+---++[feat] Add `nativePicker` to TimeInput so coarse pointers use the browser/OS time picker by default, with `always` and `never` overrides. Seconds and custom increments retain Astryx's typed field.+@imdreamrunnerdiff --git a/apps/storybook/stories/TimeInput.stories.tsx b/apps/storybook/stories/TimeInput.stories.tsxindex dda1f7bbd5..93a8278e6f 100644--- a/apps/storybook/stories/TimeInput.stories.tsx+++ b/apps/storybook/stories/TimeInput.stories.tsx@@ -64,6 +64,12 @@ const meta: Meta<typeof TimeInput> = {control: 'boolean',description: 'Whether to show a clear button',},+ nativePicker: {+ control: 'radio',+ options: ['touch', 'always', 'never'],+ description:+ 'Native browser/OS time picker on touch by default, native wherever compatible, or Astryx typed field everywhere',+ },increment: {control: 'number',description: 'Minutes to increment/decrement with arrow keys',@@ -97,6 +103,39 @@ export const WithValue: Story = {},};+export const NativePickerModes: Story = {+ render: () => {+ const [value, setValue] = useState<ISOTimeString | undefined>(+ '14:30' as ISOTimeString,+ );+ return (+ <div style={{display: 'flex', flexDirection: 'column', gap: 16}}>+ <TimeInput+ label="nativePicker='touch' (default)"+ description="Native picker on a coarse primary pointer; Astryx typed field on a fine pointer"+ value={value}+ onChange={setValue}+ nativePicker="touch"+ />+ <TimeInput+ label="nativePicker='always'"+ description="Native picker wherever input type=time is compatible"+ value={value}+ onChange={setValue}+ nativePicker="always"+ />+ <TimeInput+ label="nativePicker='never'"+ description="Astryx typed field on every pointer type"+ value={value}+ onChange={setValue}+ nativePicker="never"+ />+ </div>+ );+ },+};+export const TwentyFourHourFormat: Story = {render: args => {const [value, setValue] = useState<ISOTimeString | undefined>(@@ -377,7 +416,8 @@ export const StatusVariantComparison: Story = {'22:00' as ISOTimeString,);return (- <div style={{display: 'flex', flexDirection: 'column', gap: 24, width: 280}}>+ <div+ style={{display: 'flex', flexDirection: 'column', gap: 24, width: 280}}><TimeInputlabel="Attached (default)"value={a}diff --git a/packages/cli/assets/templates/blocks/components/TimeInput/TimeInputShowcase.doc.mjs b/packages/cli/assets/templates/blocks/components/TimeInput/TimeInputShowcase.doc.mjsindex 33f28a9383..ef62f8bfa7 100644--- a/packages/cli/assets/templates/blocks/components/TimeInput/TimeInputShowcase.doc.mjs+++ b/packages/cli/assets/templates/blocks/components/TimeInput/TimeInputShowcase.doc.mjs@@ -10,6 +10,6 @@ export const doc = {aspectRatio: 16 / 9,isShowcase: true,description:- 'A time input field.',+ 'A time input that uses the browser/OS picker on touch by default and Astryx typed entry on fine pointers.',componentsUsed: ['TimeInput'],};diff --git a/packages/cli/assets/templates/blocks/components/TimeInput/TimeInputShowcase.tsx b/packages/cli/assets/templates/blocks/components/TimeInput/TimeInputShowcase.tsxindex 909bc55408..8334d58b3b 100644--- a/packages/cli/assets/templates/blocks/components/TimeInput/TimeInputShowcase.tsx+++ b/packages/cli/assets/templates/blocks/components/TimeInput/TimeInputShowcase.tsx@@ -4,15 +4,21 @@import {useState} from 'react';import {TimeInput, type ISOTimeString} from '@astryxdesign/core/TimeInput';+import {Stack} from '@astryxdesign/core/Layout';export default function TimeInputShowcase() {const [time, setTime] = useState<ISOTimeString | undefined>(undefined);return (- <TimeInput- label="Time"- placeholder="Select a time"- value={time}- onChange={setTime}- />+ <Stack+ direction="vertical"+ width="100%"+ style={{minWidth: 240, maxWidth: 400}}>+ <TimeInput+ label="Time"+ placeholder="Select a time"+ value={time}+ onChange={setTime}+ />+ </Stack>);}diff --git a/packages/core/locales/en.json b/packages/core/locales/en.jsonindex 7fe56b23a7..8dcd5b541f 100644--- a/packages/core/locales/en.json+++ b/packages/core/locales/en.json@@ -895,6 +895,10 @@"defaultMessage": "Invalid time","description": "Screen-reader-only live-region alert in TimeInput / DateTimeInput when the typed time cannot be parsed. \"Time\" = clock time (HH:MM). The field silently reverts on blur, so this is the only rejection feedback a screen-reader user gets."},+ "@astryx.timeInput.openPicker": {+ "defaultMessage": "Open {label}",+ "description": "Aria label for the clock button that opens TimeInput's browser/OS time picker. `{label}` is the field label, for example `Start time`."+ },"@astryx.topNav.heading.dialogLabel": {"defaultMessage": "Navigation menu","description": "Screen-reader-only accessible name for the dropdown dialog opened from a TopNavHeading's overflow menu. Kept separate from the SideNav sibling."diff --git a/packages/core/src/DateTimeInput/DateTimeInput.tsx b/packages/core/src/DateTimeInput/DateTimeInput.tsxindex a9a6a30c50..71669b3139 100644--- a/packages/core/src/DateTimeInput/DateTimeInput.tsx+++ b/packages/core/src/DateTimeInput/DateTimeInput.tsx@@ -1742,7 +1742,11 @@ function PointerDateTimeField({value={nativeTimeValue}onChange={handleNativeTimeChange}placeholder={timePlaceholder}- label={resolvedTimeLabel}+ inputLabel={resolvedTimeLabel}+ openPickerLabel={t('@astryx.dateTimeInput.openTimePicker', {+ label: resolvedTimeLabel,+ })}+ iconThemeProps={themeProps('date-time-input-clock-icon')}min={timeMin}max={timeMax}hourFormat={hourFormat}diff --git a/packages/core/src/DateTimeInput/NativeTimeSegment.tsx b/packages/core/src/DateTimeInput/NativeTimeSegment.tsxindex 59431fa762..c88be2ccb3 100644--- a/packages/core/src/DateTimeInput/NativeTimeSegment.tsx+++ b/packages/core/src/DateTimeInput/NativeTimeSegment.tsx@@ -5,8 +5,8 @@/*** @file NativeTimeSegment.tsx* @input Uses React, native picker segment styles, and shared time utilities- * @output Exports NativeTimeSegment — the OS-picker time half of DateTimeInput- * @position Internal DateTimeInput surface selected by `nativePicker`+ * @output Exports NativeTimeSegment — the shared OS-picker time control+ * @position Internal native control used by DateTimeInput and TimeInput** Hands time picking to the platform through `<input type="time">`. The input* is deliberately uncontrolled and observed through native event listeners,@@ -15,9 +15,12 @@* React's synthetic change event.** SYNC: When modified, update these files to stay in sync:- * - /packages/core/src/DateTimeInput/DateTimeInput.tsx (surface selection)- * - /packages/core/src/DateTimeInput/NativePickerSegments.test.tsx (native surface tests)- * - /packages/core/src/DateTimeInput/DateTimeInput.doc.mjs (prop docs)+ * - /packages/core/src/DateTimeInput/DateTimeInput.tsx (DateTimeInput integration)+ * - /packages/core/src/TimeInput/TimeInput.tsx (TimeInput integration)+ * - /packages/core/src/DateTimeInput/NativePickerSegments.test.tsx (DateTimeInput tests)+ * - /packages/core/src/TimeInput/NativeTimeInput.test.tsx (TimeInput tests)+ * - /packages/core/src/DateTimeInput/DateTimeInput.doc.mjs (DateTimeInput prop docs)+ * - /packages/core/src/TimeInput/TimeInput.doc.mjs (TimeInput prop docs)*/import {useCallback, useEffect, useRef, useState} from 'react';@@ -28,6 +31,7 @@ import {useMediaQuery} from '../hooks/useMediaQuery';import {useMergedRefs} from '../hooks/useMergedRefs';import {Icon} from '../Icon';import {useTranslator} from '../i18n';+import type {ThemeProps} from '../utils/themeProps';import {VisuallyHidden} from '../VisuallyHidden';import {focusOutlineStyles,@@ -36,10 +40,8 @@ import {formatISOTime,isTimeInRange,parseISOTime,- themeProps,type ISOTimeString,} from '../utils';-import type {DateTimeInputHourFormat} from './DateTimeInput';import {nativePickerSegmentStyles as styles} from './nativePickerSegmentStyles';const FRACTIONAL_SECONDS = /\.\d+$/;@@ -64,10 +66,14 @@ export type NativeTimeSegmentProps = {value?: ISOTimeString;onChange: (value: ISOTimeString | undefined) => void;placeholder: string;- label: string;+ inputLabel?: string;+ openPickerLabel: string;+ ariaLabelledBy?: string;+ iconThemeProps?: ThemeProps;+ hasAutoFocus?: boolean;min?: ISOTimeString;max?: ISOTimeString;- hourFormat: DateTimeInputHourFormat;+ hourFormat: '12h' | '24h';isEffectivelyDisabled: boolean;hasDisabledMessage: boolean;isEffectivelyRequired: boolean;@@ -76,14 +82,18 @@ export type NativeTimeSegmentProps = {ariaDescribedBy?: string;};-/** The native time half rendered inside DateTimeInput's time wrapper. */+/** The shared native time control rendered inside Astryx field chrome. */export function NativeTimeSegment({id,inputRef,value,onChange,placeholder,- label,+ inputLabel,+ openPickerLabel,+ ariaLabelledBy,+ iconThemeProps,+ hasAutoFocus = false,min,max,hourFormat,@@ -256,19 +266,14 @@ export function NativeTimeSegment({type="button"onClick={openPicker}disabled={isEffectivelyDisabled}- aria-label={t('@astryx.dateTimeInput.openTimePicker', {label})}+ aria-label={openPickerLabel}tabIndex={-1}{...stylex.props(focusOutlineStyles.focusVisible,styles.iconButton,isEffectivelyDisabled && styles.iconButtonDisabled,)}>- <Icon- icon="clock"- size="sm"- color="secondary"- {...themeProps('date-time-input-clock-icon')}- />+ <Icon icon="clock" size="sm" color="secondary" {...iconThemeProps} /></button><span {...stylex.props(styles.slot)}><input@@ -286,8 +291,11 @@ export function NativeTimeSegment({disabled={isEffectivelyDisabled && !hasDisabledMessage}aria-disabled={hasDisabledMessage ? 'true' : undefined}readOnly={hasDisabledMessage || undefined}- aria-label={label}+ aria-label={ariaLabelledBy ? undefined : inputLabel}+ aria-labelledby={ariaLabelledBy}aria-describedby={ariaDescribedBy}+ autoFocus={hasAutoFocus}+ data-autofocus={hasAutoFocus || undefined}aria-required={isEffectivelyRequired ? 'true' : undefined}aria-invalid={statusType === 'error' || !isInputValid ? 'true' : undefineddiff --git a/packages/core/src/TimeInput/NativeTimeInput.test.tsx b/packages/core/src/TimeInput/NativeTimeInput.test.tsxnew file mode 100644index 0000000000..b1168d3715--- /dev/null+++ b/packages/core/src/TimeInput/NativeTimeInput.test.tsx@@ -0,0 +1,269 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file NativeTimeInput.test.tsx+ * @input Uses vitest, Testing Library, TimeInput, and InputGroup+ * @output Regression tests for TimeInput's browser/OS picker surface+ * @position Testing; covers nativePicker selection and standalone integration+ */++import {afterEach, describe, expect, it, vi} from 'vitest';+import {act, fireEvent, render, screen} from '@testing-library/react';+import {TimeInput} from './TimeInput';+import {InputGroup, InputGroupText} from '../InputGroup';+import {resetDateSegmentProbe} from '../DateInput/nativeDateSegments';+import type {ISOTimeString} from '../utils';++const HOVER_CAPABLE = /\(\s*hover\s*:\s*hover\s*\)/;++function stubPointer(isCoarse: boolean): void {+ vi.stubGlobal('matchMedia', (query: string) => ({+ matches: /pointer:\s*coarse/.test(query)+ ? isCoarse+ : /pointer:\s*fine/.test(query)+ ? !isCoarse+ : HOVER_CAPABLE.test(query),+ media: query,+ onchange: null,+ addListener: () => {},+ removeListener: () => {},+ addEventListener: () => {},+ removeEventListener: () => {},+ dispatchEvent: () => false,+ }));+}++function getNativeTimeInput(): HTMLInputElement {+ const input = document.querySelector<HTMLInputElement>('input[type="time"]');+ if (!input) {+ throw new Error('TimeInput rendered no native time control');+ }+ return input;+}++afterEach(() => {+ vi.unstubAllGlobals();+ vi.restoreAllMocks();+ resetDateSegmentProbe();+});++describe('TimeInput nativePicker', () => {+ it('uses the browser/OS picker on a coarse pointer by default', () => {+ stubPointer(true);+ render(+ <TimeInput+ label="Start time"+ value={'14:30' as ISOTimeString}+ onChange={() => {}}+ />,+ );++ expect(getNativeTimeInput()).toHaveValue('14:30');+ expect(screen.getByLabelText('Start time')).toBe(getNativeTimeInput());+ expect(screen.getByRole('button', {name: 'Open Start time'})).toBeVisible();+ expect(document.querySelector('input[type="text"]')).toBeNull();+ });++ it('keeps the Astryx typed field on a fine pointer by default', () => {+ stubPointer(false);+ render(<TimeInput label="Start time" onChange={() => {}} />);++ expect(screen.getByRole('textbox', {name: 'Start time'})).toHaveAttribute(+ 'type',+ 'text',+ );+ expect(document.querySelector('input[type="time"]')).toBeNull();+ });++ it('supports explicit always and never modes', () => {+ stubPointer(false);+ const {rerender} = render(+ <TimeInput+ label="Start time"+ nativePicker="always"+ onChange={() => {}}+ />,+ );+ expect(getNativeTimeInput()).toBeInTheDocument();++ stubPointer(true);+ rerender(+ <TimeInput label="Start time" nativePicker="never" onChange={() => {}} />,+ );+ expect(+ screen.getByRole('textbox', {name: 'Start time'}),+ ).toBeInTheDocument();+ expect(document.querySelector('input[type="time"]')).toBeNull();+ });++ it.each([+ ['seconds', {hasSeconds: true}],+ ['custom increment', {increment: 15}],+ ] as const)('retains the typed field for %s', (_name, props) => {+ stubPointer(true);+ render(+ <TimeInput+ label="Start time"+ nativePicker="always"+ onChange={() => {}}+ {...props}+ />,+ );++ expect(+ screen.getByRole('textbox', {name: 'Start time'}),+ ).toBeInTheDocument();+ expect(document.querySelector('input[type="time"]')).toBeNull();+ });++ it('commits native edits and rejects values outside min/max', () => {+ stubPointer(true);+ const onChange = vi.fn();+ render(+ <TimeInput+ label="Start time"+ value={'09:00' as ISOTimeString}+ onChange={onChange}+ min={'08:00' as ISOTimeString}+ max={'17:00' as ISOTimeString}+ />,+ );+ const input = getNativeTimeInput();++ fireEvent.change(input, {target: {value: '10:15'}});+ expect(onChange).toHaveBeenCalledExactlyOnceWith('10:15');++ fireEvent.change(input, {target: {value: '18:00'}});+ expect(onChange).toHaveBeenCalledTimes(1);+ expect(input).toHaveAttribute('aria-invalid', 'true');+ });++ it('keeps the native picker enabled while changeAction is pending', () => {+ stubPointer(true);+ const changeAction = vi.fn(async () => new Promise<void>(() => {}));+ render(+ <TimeInput+ label="Start time"+ value={'09:00' as ISOTimeString}+ onChange={() => {}}+ changeAction={changeAction}+ />,+ );+ const input = getNativeTimeInput();++ fireEvent.change(input, {target: {value: '10:00'}});++ expect(changeAction).toHaveBeenCalledExactlyOnceWith('10:00');+ expect(input).not.toBeDisabled();+ expect(input).toHaveAttribute('aria-busy', 'true');+ });++ it('preserves grouped accessible names and descriptions', () => {+ stubPointer(true);+ render(+ <InputGroup label="Schedule" description="Use local time">+ <InputGroupText>Starts</InputGroupText>+ <TimeInput+ label="Start time"+ description="Business hours only"+ nativePicker="always"+ onChange={() => {}}+ />+ </InputGroup>,+ );++ const input = screen.getByLabelText('Schedule Start time');+ const describedBy =+ input.getAttribute('aria-describedby')?.split(' ') ?? [];+ const describedText = describedBy+ .map(id => document.getElementById(id)?.textContent)+ .join(' ');+ expect(describedText).toContain('Use local time');+ expect(describedText).toContain('Business hours only');+ });++ it('keeps a disabled reason discoverable without enabling the picker', () => {+ stubPointer(true);+ render(+ <TimeInput+ label="Start time"+ nativePicker="always"+ isDisabled+ disabledMessage="Time edits are locked"+ onChange={() => {}}+ />,+ );++ const input = getNativeTimeInput();+ expect(input).not.toBeDisabled();+ expect(input).toHaveAttribute('aria-disabled', 'true');+ expect(input).toHaveAttribute('readonly');+ expect(+ screen.getByRole('button', {name: 'Open Start time'}),+ ).toBeDisabled();+ const tooltip = document.querySelector<HTMLElement>('[role="tooltip"]');+ expect(tooltip).not.toBeNull();+ expect(input.getAttribute('aria-describedby')).toContain(tooltip?.id);+ });++ it('forwards refs and autofocus to the native input', () => {+ stubPointer(true);+ const ref = vi.fn();+ render(+ <TimeInput+ ref={ref}+ label="Start time"+ nativePicker="always"+ hasAutoFocus+ onChange={() => {}}+ />,+ );++ expect(ref).toHaveBeenCalledWith(getNativeTimeInput());+ expect(getNativeTimeInput()).toHaveAttribute('data-autofocus', 'true');+ });++ it('clears without refocusing and reopening the native picker', () => {+ stubPointer(true);+ const onChange = vi.fn();+ render(+ <TimeInput+ label="Start time"+ value={'09:00' as ISOTimeString}+ nativePicker="always"+ hasClear+ onChange={onChange}+ />,+ );+ const input = getNativeTimeInput();+ const showPicker = vi.fn();+ input.showPicker = showPicker;++ fireEvent.click(screen.getByRole('button', {name: 'Clear Start time'}));++ expect(onChange).toHaveBeenCalledExactlyOnceWith(undefined);+ expect(input).not.toHaveFocus();+ expect(showPicker).not.toHaveBeenCalled();+ });++ it('opens the native picker from the clock button', () => {+ stubPointer(true);+ render(+ <TimeInput+ label="Start time"+ nativePicker="always"+ onChange={() => {}}+ />,+ );+ const input = getNativeTimeInput();+ const showPicker = vi.fn();+ input.showPicker = showPicker;++ act(() => {+ screen.getByRole('button', {name: 'Open Start time'}).click();+ });++ expect(input).toHaveFocus();+ expect(showPicker).toHaveBeenCalledTimes(1);+ });+});diff --git a/packages/core/src/TimeInput/TimeInput.doc.mjs b/packages/core/src/TimeInput/TimeInput.doc.mjsindex e235261e2a..95bf35aa09 100644--- a/packages/core/src/TimeInput/TimeInput.doc.mjs+++ b/packages/core/src/TimeInput/TimeInput.doc.mjs@@ -21,12 +21,12 @@ export const docs = {usage: {description:- 'TimeInput lets users enter a time of day and converts it to a standard format. It also allows users to adjust times using the arrow keys. Use it in forms, scheduling flows, or any interface where users need to select a specific time.',+ "TimeInput uses a browser/OS time picker on coarse pointers by default and Astryx's typed field on fine pointers. It converts values to a standard format and supports arrow-key adjustment on the typed surface. Use it in forms, scheduling flows, or any interface where users need to select a specific time.",bestPractices: [{guidance: true,description:- 'Choose the hour format (12h or 24h) that matches your audience\'s locale: 12-hour with AM/PM for US-centric UIs, 24-hour for international or technical contexts.',+ "Choose the hour format (12h or 24h) that matches your audience's locale: 12-hour with AM/PM for US-centric UIs, 24-hour for international or technical contexts.",},{guidance: true,@@ -56,12 +56,12 @@ export const docs = {{guidance: false,description:- 'Don\'t use TimeInput for combined date-and-time selection; pair it with a separate DateInput instead.',+ "Don't use TimeInput for combined date-and-time selection; pair it with a separate DateInput instead.",},{guidance: false,description:- 'Don\'t hide the label; even when space is tight, keep the label visible or provide a description so the purpose is clear.',+ "Don't hide the label; even when space is tight, keep the label visible or provide a description so the purpose is clear.",},{guidance: false,@@ -74,13 +74,13 @@ export const docs = {name: 'Clock icon',required: false,description:- 'A leading clock icon that identifies the field as a time input.',+ 'A leading clock icon that identifies the field and opens the browser/OS picker in native mode.',},{- name: 'Text input',+ name: 'Time control',required: true,description:- 'The editable text field where users type or see the formatted time.',+ 'A real input type=time in native modes, or Astryx\'s editable text field for fine pointers, nativePicker="never", seconds, and custom increments.',},{name: 'Clear button',@@ -210,6 +210,13 @@ export const docs = {'Number of minutes to add or subtract when the user presses the up or down arrow key.',default: '1',},+ {+ name: 'nativePicker',+ type: "'touch' | 'always' | 'never'",+ description:+ "Which surface selects the time. 'touch' (the default) uses the browser/OS input type=time on a coarse pointer and Astryx's typed field on a fine pointer; 'always' requests the native control on every pointer; 'never' keeps Astryx's typed field everywhere. Native mode forwards min/max and enforces them on commit. hasSeconds or increment other than 1 automatically retains the typed field because iOS has no seconds wheel and treats step as validation rather than picker cadence. hourFormat formats the closed value; the open OS picker follows the device locale.",+ default: "'touch'",+ },{name: 'placeholder',type: 'string',@@ -257,7 +264,11 @@ export const docs = {],theming: {targets: [- {className: 'astryx-time-input', visualProps: ['size', 'status'], states: ['disabled']},+ {+ className: 'astryx-time-input',+ visualProps: ['size', 'status'],+ states: ['disabled'],+ },],},};@@ -366,6 +377,13 @@ export const docsZh = {description: '用户按上或下方向键时增加或减少的分钟数。',default: '1',},+ {+ name: 'nativePicker',+ type: "'touch' | 'always' | 'never'",+ description:+ "选择时间所用的界面。'touch'(默认)在粗指针设备上使用浏览器/操作系统的 input type=time,在精细指针设备上使用 Astryx 文本字段;'always' 在所有指针类型上请求原生控件;'never' 始终使用 Astryx 文本字段。原生模式会传递 min/max 并在提交时强制校验。hasSeconds 或 increment 不为 1 时会自动保留文本字段,因为 iOS 没有秒滚轮,并且只把 step 当作校验规则而非选择器步进。hourFormat 控制关闭状态的显示;打开的系统选择器遵循设备区域设置。",+ default: "'touch'",+ },{name: 'placeholder',type: 'string',@@ -406,17 +424,21 @@ export const docsZh = {],theming: {targets: [- {className: 'astryx-time-input', visualProps: ['size', 'status'], states: ['disabled']},+ {+ className: 'astryx-time-input',+ visualProps: ['size', 'status'],+ states: ['disabled'],+ },],},usage: {description:- 'TimeInput lets users enter a time of day and converts it to a standard format. It also allows users to adjust times using the arrow keys. Use it in forms, scheduling flows, or any interface where users need to select a specific time.',+ 'TimeInput 默认在粗指针设备上使用浏览器/操作系统的时间选择器,在精细指针设备上使用 Astryx 文本字段。它将时间转换为标准格式,并在文本字段界面支持方向键调整。适用于表单、排期流程和其他时间选择场景。',bestPractices: [{guidance: true,description:- 'Choose the hour format (12h or 24h) that matches your audience\'s locale: 12-hour with AM/PM for US-centric UIs, 24-hour for international or technical contexts.',+ "Choose the hour format (12h or 24h) that matches your audience's locale: 12-hour with AM/PM for US-centric UIs, 24-hour for international or technical contexts.",},{guidance: true,@@ -441,12 +463,12 @@ export const docsZh = {{guidance: false,description:- 'Don\'t use TimeInput for combined date-and-time selection; pair it with a separate DateInput instead.',+ "Don't use TimeInput for combined date-and-time selection; pair it with a separate DateInput instead.",},{guidance: false,description:- 'Don\'t hide the label; even when space is tight, keep the label visible or provide a description so the purpose is clear.',+ "Don't hide the label; even when space is tight, keep the label visible or provide a description so the purpose is clear.",},{guidance: false,@@ -459,13 +481,13 @@ export const docsZh = {name: 'Clock icon',required: false,description:- 'A leading clock icon that identifies the field as a time input.',+ '用于识别时间字段的前置时钟图标;在原生模式下也可打开浏览器/操作系统选择器。',},{- name: 'Text input',+ name: 'Time control',required: true,description:- 'The editable text field where users type or see the formatted time.',+ '原生模式下使用真正的 input type=time;精细指针、nativePicker="never"、秒或自定义步进场景使用 Astryx 可编辑文本字段。',},{name: 'Clear button',@@ -492,10 +514,10 @@ export const docsZh = {/** @type {import('@astryxdesign/cli/authoring').ComponentTranslationDoc} */export const docsDense = {description:- 'Time input that converts free-text entry to standard format with arrow-key adjustment.',+ 'Time input with browser/OS picker on touch by default and Astryx typed-field fallbacks for seconds or custom increments.',usage: {description:- 'TimeInput lets users enter a time of day and converts it to a standard format. It also allows users to adjust times using the arrow keys. Use it in forms, scheduling flows, or any interface where users need to select a specific time.',+ 'TimeInput uses a browser/OS picker on coarse pointers by default and Astryx typed entry on fine pointers. It standardizes values and supports arrow-key adjustment on the typed surface.',bestPractices: [{guidance: true,@@ -525,17 +547,16 @@ export const docsDense = {{guidance: false,description:- 'Don\'t use for date-and-time; pair with DateInput instead.',+ "Don't use for date-and-time; pair with DateInput instead.",},{guidance: false,- description:- 'Don\'t hide the label; keep it visible for clarity.',+ description: "Don't hide the label; keep it visible for clarity.",},{guidance: false,description:- 'Don\'t wrap a disabled TimeInput in Tooltip; use the disabledMessage prop instead.',+ "Don't wrap a disabled TimeInput in Tooltip; use the disabledMessage prop instead.",},],},@@ -562,10 +583,13 @@ export const docsDense = {hourFormat:"Display format. '12h' shows AM/PM; '24h' uses 24-hour notation.",increment: 'Minutes to add/subtract on arrow up/down.',+ nativePicker:+ "picker surface: 'touch' (default) = browser/OS on coarse pointer, 'always' = native wherever compatible, 'never' = Astryx typed field. hasSeconds or increment!=1 retains typed field; min/max enforced on commit.",placeholder: 'Placeholder when empty. Focused+empty shows format hint.',size: 'Input element height.',status: 'Colored border+icon. Message rendered below input.',- statusVariant: 'How status message is placed: attached overlaps below input; detached floats below w/ spacing; tooltip hides the box and shows it on the status icon.',+ statusVariant:+ 'How status message is placed: attached overlaps below input; detached floats below w/ spacing; tooltip hides the box and shows it on the status icon.',labelTooltip: 'Tooltip as info icon at label row end.',xstyle:'StyleX styles for layout customization. Must be stylex.create() value, not inline style.',diff --git a/packages/core/src/TimeInput/TimeInput.tsx b/packages/core/src/TimeInput/TimeInput.tsxindex b8ed5ad50f..dc41adf599 100644--- a/packages/core/src/TimeInput/TimeInput.tsx+++ b/packages/core/src/TimeInput/TimeInput.tsx@@ -4,13 +4,14 @@/*** @file TimeInput.tsx- * @input Uses React, useId, useState, useCallback, useRef, Field, Icon, InputGroupContext, useAnnounce- * @output Exports TimeInput component, TimeInputProps+ * @input Uses React, Field, NativeTimeSegment, InputGroupContext, pointer media queries, and shared time utilities+ * @output Exports TimeInput, TimeInputProps, and TimeInputNativePicker* @position Core implementation; consumed by index.ts, tested by TimeInput.test.tsx** SYNC: When modified, update these files to stay in sync:* - /packages/core/src/TimeInput/TimeInput.doc.mjs (props table, features, implementation notes)- * - /packages/core/src/TimeInput/TimeInput.test.tsx (tests for new/changed behavior)+ * - /packages/core/src/TimeInput/TimeInput.test.tsx (typed-field tests)+ * - /packages/core/src/TimeInput/NativeTimeInput.test.tsx (native-picker tests)* - /packages/core/src/TimeInput/index.ts (exports if types change)* - /apps/storybook/stories/TimeInput.stories.tsx (storybook stories)* - /packages/cli/assets/templates/blocks/components/TimeInput/ (showcase blocks)@@ -65,6 +66,7 @@ import type {SizeValue} from '../utils/types';import {useSize} from '../SizeContext/SizeContext';import {useAnnounce} from '../hooks/useAnnounce';import {useInputContainer} from '../hooks/useInputContainer';+import {useMediaQuery} from '../hooks/useMediaQuery';import {useInputStatusIcon} from '../hooks/useInputStatusIcon';import {useResolvedRequired} from '../hooks/useResolvedRequired';import {useInputGroup} from '../InputGroup/InputGroupContext';@@ -74,6 +76,10 @@ import {themeProps} from '../utils/themeProps';import {useTranslator} from '../i18n';import {useMergedRefs} from '../hooks/useMergedRefs';+import {NativeTimeSegment} from '../DateTimeInput/NativeTimeSegment';++const TOUCH_POINTER_QUERY = '(pointer: coarse)';+const styles = stylex.create({icon: {display: 'flex',@@ -128,6 +134,9 @@ export type TimeInputSize = keyof typeof sizeStyles;export type TimeInputHourFormat = '12h' | '24h';+/** Which surface TimeInput uses for time selection. */+export type TimeInputNativePicker = 'touch' | 'always' | 'never';+// Re-export shared types for convenienceexport type {@@ -262,6 +271,20 @@ export interface TimeInputProps extends Omit<*/increment?: number;+ /**+ * Which time-selection surface to use.+ *+ * - `'touch'`: browser/OS picker on coarse pointers, Astryx's typed field on+ * fine pointers+ * - `'always'`: browser/OS picker wherever `<input type="time">` is supported+ * - `'never'`: Astryx's typed field everywhere+ *+ * Native time pickers cannot preserve seconds or Astryx's arrow-key cadence,+ * so `hasSeconds` or `increment !== 1` keeps the typed field.+ * @default 'touch'+ */+ nativePicker?: TimeInputNativePicker;+/*** Placeholder text shown when no time is selected.* @default "Select a time"@@ -336,6 +359,7 @@ export function TimeInput({hasAutoFocus = false,hourFormat = '12h',increment = 1,+ nativePicker = 'touch',placeholder: placeholderFromProps,size: sizeProp,status,@@ -352,12 +376,20 @@ export function TimeInput({const placeholder =placeholderFromProps ?? t('@astryx.timeInput.placeholder');const size = useSize(sizeProp, 'md');+ const isTouch = useMediaQuery(TOUCH_POINTER_QUERY);+ const requestsNativePicker =+ nativePicker === 'always' || (nativePicker === 'touch' && isTouch);+ // iOS has no seconds wheel and treats step as validation rather than wheel+ // cadence. Preserve those explicit Astryx contracts instead of degrading them.+ const usesNativeTimePicker =+ requestsNativePicker && !hasSeconds && increment === 1;const id = useId();const inputLabelID = useId();const descriptionID = useId();const statusMessageID = useId();const inputRef = useRef<HTMLInputElement | null>(null);+ const mergedInputRef = useMergedRefs(ref, inputRef);const containerRef = useRef<HTMLDivElement | null>(null);const inputGroup = useInputGroup();@@ -592,8 +624,11 @@ export function TimeInput({// Handle clear button clickconst handleClear = useCallback(() => {fireChange(undefined);- inputRef.current?.focus();- }, [fireChange]);+ // Focusing a native time control reopens the OS picker on iOS.+ if (!usesNativeTimePicker) {+ inputRef.current?.focus();+ }+ }, [fireChange, usesNativeTimePicker]);// Focus input when clicking anywhere on the wrapper (icons, padding, etc.)const {onClick: handleWrapperClick, onMouseUp: handleWrapperMouseUp} =@@ -612,8 +647,8 @@ export function TimeInput({// unconditionally is safe.disabledMessageTooltip.ref(el);}}- onClick={handleWrapperClick}- onMouseUp={handleWrapperMouseUp}+ onClick={usesNativeTimePicker ? undefined : handleWrapperClick}+ onMouseUp={usesNativeTimePicker ? undefined : handleWrapperMouseUp}{...mergeProps(themeProps('time-input', {size,@@ -633,9 +668,6 @@ export function TimeInput({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}>@@ -647,47 +679,74 @@ export function TimeInput({{status.message}</VisuallyHidden>)}- <input- ref={useMergedRefs(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={isEffectivelyRequired ? 'true' : undefined}- aria-invalid={- status?.type === 'error' || !isInputValid ? 'true' : undefined- }- aria-busy={isBusy || undefined}- aria-labelledby={ariaLabelledBy}- {...stylex.props(- styles.input,- isDisabled && styles.inputDisabled,- !isInputValid && styles.inputInvalid,- )}- />- {/*- Live region announcing invalid typed input to assistive technology.- The value silently reverts on blur, so without this a screen-reader- user would get no feedback that their entry was rejected (WCAG 3.3.1).- */}- <VisuallyHidden as="div" role="alert" aria-live="assertive">- {!isInputValid ? t('@astryx.timeInput.invalidTime') : ''}- </VisuallyHidden>+ {usesNativeTimePicker ? (+ <NativeTimeSegment+ id={id}+ inputRef={mergedInputRef}+ value={optimisticValue}+ onChange={fireChange}+ placeholder={placeholder}+ openPickerLabel={t('@astryx.timeInput.openPicker', {label})}+ ariaLabelledBy={ariaLabelledBy}+ hasAutoFocus={hasAutoFocus}+ min={min}+ max={max}+ hourFormat={hourFormat}+ isEffectivelyDisabled={isDisabled}+ hasDisabledMessage={showsDisabledMessage}+ isEffectivelyRequired={isEffectivelyRequired}+ isBusy={isBusy}+ statusType={status?.type}+ ariaDescribedBy={ariaDescribedBy}+ />+ ) : (+ <>+ <div {...stylex.props(styles.icon)}>+ <Icon icon="clock" size="sm" color="secondary" />+ </div>+ <input+ ref={mergedInputRef}+ 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={isEffectivelyRequired ? 'true' : undefined}+ aria-invalid={+ status?.type === 'error' || !isInputValid ? 'true' : undefined+ }+ aria-busy={isBusy || undefined}+ aria-labelledby={ariaLabelledBy}+ {...stylex.props(+ styles.input,+ isDisabled && styles.inputDisabled,+ !isInputValid && styles.inputInvalid,+ )}+ />+ {/*+ Live region announcing invalid typed input to assistive technology.+ The value silently reverts on blur, so without this a screen-reader+ user would get no feedback that their entry was rejected (WCAG 3.3.1).+ */}+ <VisuallyHidden as="div" role="alert" aria-live="assertive">+ {!isInputValid ? t('@astryx.timeInput.invalidTime') : ''}+ </VisuallyHidden>+ </>+ )}{isBusy && <Spinner size="sm" />}- {hasClear && value && !isDisabled && (+ {hasClear && optimisticValue && !isDisabled && (<InputClearButtonlabel={t('@astryx.timeInput.clearLabel', {label})}onClick={handleClear}diff --git a/packages/core/src/TimeInput/index.ts b/packages/core/src/TimeInput/index.tsindex b57ed78797..e4a1da8bc7 100644--- a/packages/core/src/TimeInput/index.ts+++ b/packages/core/src/TimeInput/index.ts@@ -16,6 +16,7 @@ export type {TimeInputProps,TimeInputSize,TimeInputHourFormat,+ TimeInputNativePicker,TimeInputStatus,TimeInputStatusType,} from './TimeInput';