An open source design system that's fully customizable and agent ready
TypeScript
fix(TimeInput, DateTimeInput): time text follows the locale's hour cycle and day periods (#9022)
nynexman4464faee47927679
diff --git a/.changeset/time-input-locale-hour-cycle.md b/.changeset/time-input-locale-hour-cycle.mdnew file mode 100644index 0000000000..3fa689257f--- /dev/null+++ b/.changeset/time-input-locale-hour-cycle.md@@ -0,0 +1,7 @@+---+'@astryxdesign/core': patch+---++[feat] TimeInput, DateTimeInput: the `hourFormat` default follows the locale. This is a default change. The old default was always `'12h'`; the new default, when `hourFormat` is unset, is the `InternationalizationProvider` locale's hour cycle, so a `de-DE`, `en-GB`, or `vi-VN` app shows "14:30" like `Timestamp` beside it, while `en-US` and an app with no provider keep "2:30 PM". To keep the old default, pass `hourFormat="12h"`. To honor a person's own 12/24-hour preference everywhere, put it on the provider locale (`en-US-u-hc-h23`). Twelve-hour text now uses the locale's own day period ("오후 2:30", "午後2:30", "2:30 p. m.") instead of a fixed English AM/PM, along with its digits and separator, and the typed field reads that text back. Fixes #8992.++@nynexman4464diff --git a/docs/architecture/internationalization.md b/docs/architecture/internationalization.mdindex 62f83ed883..d12bc1e85f 100644--- a/docs/architecture/internationalization.md+++ b/docs/architecture/internationalization.md@@ -317,6 +317,7 @@ inferred from an implementation pull request.`packages/core/src/Timestamp/formatRelativeTime.ts`,`packages/core/src/PowerSearch/formatFilterValue.ts`,`packages/core/src/NumberInput/numberParser.ts`,+ `packages/core/src/utils/timeFormat.ts`,`packages/core/src/i18n/useCollator.ts`, `packages/charts/src/formatters.ts` —shared locale-sensitive formatters, parsers, and collation. Component consumerspass the provider locale; naming a module here does not approve a duplicatediff --git a/internal/eslint-plugin-astryx/README.md b/internal/eslint-plugin-astryx/README.mdindex a36e2de3c6..7e089cae57 100644--- a/internal/eslint-plugin-astryx/README.md+++ b/internal/eslint-plugin-astryx/README.md@@ -76,6 +76,9 @@ Approved implementations:- `packages/core/src/PowerSearch/formatFilterValue.ts`- `packages/core/src/NumberInput/numberParser.ts` — reads typed and pastednumbers under the field's locale+- `packages/core/src/utils/timeFormat.ts` — time-of-day text for TimeInput and+ DateTimeInput: the locale's hour cycle, digits, separator, and day periods,+ formatted and parsed back- `packages/core/src/i18n/useCollator.ts`- `packages/charts/src/formatters.ts`diff --git a/internal/eslint-plugin-astryx/no-raw-intl-locale.js b/internal/eslint-plugin-astryx/no-raw-intl-locale.jsindex cb8f348205..52eeb7f172 100644--- a/internal/eslint-plugin-astryx/no-raw-intl-locale.js+++ b/internal/eslint-plugin-astryx/no-raw-intl-locale.js@@ -116,6 +116,9 @@ const APPROVED_IMPLEMENTATION_FILES = [// NumberInput's locale-aware read of typed and pasted text: it derives the// grouping/decimal separators and group sizes from Intl rather than a table.'packages/core/src/NumberInput/numberParser.ts',+ // TimeInput/DateTimeInput time text: the locale's hour cycle, digits,+ // separator and day-period words, read off Intl and parsed back.+ 'packages/core/src/utils/timeFormat.ts','packages/core/src/i18n/useCollator.ts','packages/charts/src/formatters.ts',];diff --git a/internal/eslint-plugin-astryx/no-raw-intl-locale.test.mjs b/internal/eslint-plugin-astryx/no-raw-intl-locale.test.mjsindex c66226a5e1..18fa0b4173 100644--- a/internal/eslint-plugin-astryx/no-raw-intl-locale.test.mjs+++ b/internal/eslint-plugin-astryx/no-raw-intl-locale.test.mjs@@ -38,6 +38,7 @@ const RELATIVE_TIME_INFRA_FILE ='packages/core/src/Timestamp/formatRelativeTime.ts';const NUMBER_PARSER_INFRA_FILE ='packages/core/src/NumberInput/numberParser.ts';+const TIME_FORMAT_INFRA_FILE = 'packages/core/src/utils/timeFormat.ts';const NUMBER_PARSER_TEST_ORACLE_FILE ='packages/core/src/NumberInput/numberParser.test.ts';const NUMBER_PARSER_DOCBLOCK_ORACLE_FILE =@@ -138,6 +139,10 @@ tester.run('no-raw-intl-locale', rule, {code: `new Intl.NumberFormat(locale).formatToParts(12345.6);`,filename: NUMBER_PARSER_INFRA_FILE,},+ {+ code: `new Intl.DateTimeFormat(locale, {hour: 'numeric'}).resolvedOptions();`,+ filename: TIME_FORMAT_INFRA_FILE,+ },// -- Named test-oracle files retain meaningful explicit-locale fixtures. --{code: `number.toLocaleString('en-US');`,@@ -270,6 +275,11 @@ tester.run('no-raw-intl-locale', rule, {filename: NUMBER_PARSER_INFRA_FILE,errors: [ambientIntlInImplementation],},+ {+ code: `new Intl.DateTimeFormat(undefined, {hour: 'numeric'});`,+ filename: TIME_FORMAT_INFRA_FILE,+ errors: [ambientIntlInImplementation],+ },{code: `new Intl.RelativeTimeFormat();`,filename: RELATIVE_TIME_INFRA_FILE,diff --git a/packages/core/locales/en.json b/packages/core/locales/en.jsonindex 3db897c2fc..efb2a761cb 100644--- a/packages/core/locales/en.json+++ b/packages/core/locales/en.json@@ -1013,11 +1013,11 @@},"@astryx.dateTimeInput.timeHint12h": {"defaultMessage": "e.g., 2:30 PM",- "description": "Placeholder hint shown in the DateTimeInput time field when focused and empty with 12-hour format. Gives an example of expected input format."+ "description": "Placeholder hint shown in the TimeInput and DateTimeInput time fields when focused and empty with 12-hour format. Gives an example of expected input format; write the example time as your locale writes 12-hour time."},"@astryx.dateTimeInput.timeHint24h": {"defaultMessage": "e.g., 14:30",- "description": "Placeholder hint shown in the DateTimeInput time field when focused and empty with 24-hour format. Gives an example of expected input format."+ "description": "Placeholder hint shown in the TimeInput and DateTimeInput time fields when focused and empty with 24-hour format. Gives an example of expected input format; write the example time as your locale writes 24-hour time."},"@astryx.dateTimeInput.timeSuffix": {"defaultMessage": "{label} time",diff --git a/packages/core/src/DateTimeInput/DateTimeInput.doc.mjs b/packages/core/src/DateTimeInput/DateTimeInput.doc.mjsindex cd69c44070..c3d0cd49f6 100644--- a/packages/core/src/DateTimeInput/DateTimeInput.doc.mjs+++ b/packages/core/src/DateTimeInput/DateTimeInput.doc.mjs@@ -115,8 +115,8 @@ export const docs = {name: 'hourFormat',type: "'12h' | '24h'",description:- "Hour display format. '12h' shows AM/PM; '24h' uses 24-hour notation.",- default: "'12h'",+ "Hour display format. '12h' shows the locale's day period; '24h' uses 24-hour notation. When unset, follows the InternationalizationProvider locale's hour cycle (en-US 12-hour, en-GB 24-hour); a person's own preference rides on the locale tag (e.g. 'en-US-u-hc-h23').",+ default: "the locale's hour cycle",},{name: 'timeIncrement',@@ -270,7 +270,7 @@ export const docs = {{guidance: true,description:- "Choose the hour format (12h or 24h) that matches your audience's locale.",+ "Leave hourFormat unset so the field follows the InternationalizationProvider locale's hour cycle (12-hour in en-US, 24-hour in en-GB or de-DE). Set it only when the field itself needs a fixed format, and carry a person's own 12/24-hour preference on the provider locale (e.g. 'en-US-u-hc-h23') rather than on each field.",},{guidance: false,@@ -393,7 +393,7 @@ export const docsZh = {{guidance: true,description:- "Choose the hour format (12h or 24h) that matches your audience's locale.",+ "Leave hourFormat unset so the field follows the InternationalizationProvider locale's hour cycle (12-hour in en-US, 24-hour in en-GB or de-DE). Set it only when the field itself needs a fixed format, and carry a person's own 12/24-hour preference on the provider locale (e.g. 'en-US-u-hc-h23') rather than on each field.",},{guidance: false,@@ -502,8 +502,9 @@ export const docsZh = {{name: 'hourFormat',type: "'12h' | '24h'",- description: "控制显示格式。'12h' 显示 AM/PM;'24h' 使用 24 小时制。",- default: "'12h'",+ description:+ "控制显示格式。'12h' 使用区域设置的上午/下午用语;'24h' 使用 24 小时制。未设置时遵循 InternationalizationProvider 区域设置的小时制(en-US 为 12 小时制,en-GB 为 24 小时制);用户自己的偏好可通过区域标签传入(例如 'en-US-u-hc-h23')。",+ default: '区域设置的小时制',},{name: 'timeIncrement',@@ -648,7 +649,7 @@ export const docsDense = {{guidance: true,description:- "Choose the hour format (12h or 24h) that matches your audience's locale.",+ "Leave hourFormat unset so the field follows the InternationalizationProvider locale's hour cycle (12-hour in en-US, 24-hour in en-GB or de-DE). Set it only when the field itself needs a fixed format, and carry a person's own 12/24-hour preference on the provider locale (e.g. 'en-US-u-hc-h23') rather than on each field.",},{guidance: false,@@ -690,7 +691,8 @@ export const docsDense = {dateConstraints: 'custom constraint fns to disable specific dates',hasSeconds:'include seconds; retains Astryx time field because iOS native picker has no seconds wheel',- hourFormat: "display format. '12h' shows AM/PM; '24h' uses 24-hour",+ hourFormat:+ "display format. '12h' shows the locale's day period; '24h' uses 24-hour. Unset follows the provider locale's hour cycle (a -u-hc- tag carries a user preference)",timeIncrement:'minute step for Astryx typed field; non-default retains Astryx time field in native modes because iOS native step is validation-only',timeOptionInterval:diff --git a/packages/core/src/DateTimeInput/DateTimeInput.spec.md b/packages/core/src/DateTimeInput/DateTimeInput.spec.mdindex 19501bb98f..2d050794f5 100644--- a/packages/core/src/DateTimeInput/DateTimeInput.spec.md+++ b/packages/core/src/DateTimeInput/DateTimeInput.spec.md@@ -38,15 +38,15 @@ system_specs: [spec:AST-043, spec:AST-085, spec:AST-086, spec:AST-102]## Contract at a glance-| Area | Contract |-| ----------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |-| Public contract | One controlled ISO date-time value presented through coordinated date and time segments; `presentation` selects Astryx, native, or adaptive picker surfaces. |-| Behavior | Date and time changes emit one combined value; clear emits `undefined`; controlled empty state remains empty in every rendered picker. |-| End-user impact | People selecting a date and time see one value reflected consistently in the closed field and the active picker, including after clearing. |-| Builder impact | None. |-| Compatibility/readiness | Records shipped behavior; no API, default, or DOM change. The presentation matrix and deprecated `nativePicker` mapping follow `spec:AST-043`. Fixed segment height, locale time text and parsing, busy paint, and caller handlers while disabled are listed under Current-state impact. |-| Review checks | Reject competing picker selection, date/time output that is not one valid combined value, presentation precedence drift, lost per-segment fallback, or broken segment accessibility. |-| Governing rules | `spec:AST-043`, `family:input-fields`, `family:overlay-dismissal`, `spec:AST-085`, `spec:AST-086` FR8, and objective platform accessibility standards. |+| Area | Contract |+| ----------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |+| Public contract | One controlled ISO date-time value presented through coordinated date and time segments; `presentation` selects Astryx, native, or adaptive picker surfaces. |+| Behavior | Date and time changes emit one combined value; clear emits `undefined`; controlled empty state remains empty in every rendered picker. |+| End-user impact | People selecting a date and time see one value reflected consistently in the closed field and the active picker, including after clearing. |+| Builder impact | A caller that relied on the `12h` hour-format default under a 24-hour locale passes `hourFormat="12h"` to keep twelve-hour time text. A per-user 12/24-hour preference goes on the provider locale as a `-u-hc-` extension (`en-US-u-hc-h23`). |+| Compatibility/readiness | The `hourFormat` default is the provider locale's hour cycle (`12h` for `en`/`en-US` and with no provider); every other released default, API, and DOM shape holds. The presentation matrix and deprecated `nativePicker` mapping follow `spec:AST-043`. Fixed segment height, typed-time prefix commits, busy paint, and caller handlers while disabled are listed under Current-state impact. |+| Review checks | Reject competing picker selection, date/time output that is not one valid combined value, presentation precedence drift, lost per-segment fallback, or broken segment accessibility. |+| Governing rules | `spec:AST-043`, `family:input-fields`, `family:overlay-dismissal`, `spec:AST-085`, `spec:AST-086` FR8, and objective platform accessibility standards. |This table is a review projection; the body below is authoritative.@@ -59,9 +59,11 @@ or pointer-adaptive combinations of those surfaces.## Compatibility and migration-- Released default preserved: `yes`-- Compatibility class: no public surface change; existing types, defaults,- callbacks, roles, and exports remain stable+- Released default preserved: `yes`, except `hourFormat`, which follows the+ provider locale's hour cycle (`12h` for `en` and `en-US`, the released+ default with no provider) and shares TimeInput's locale time text+- Compatibility class: default change for non-English-US locales; existing+ types, callbacks, roles, and exports remain stable- Controlled/uncontrolled behavior: DateTimeInput remains controlled; `undefined`represents no committed date-time value- Migration decision: none; picker presentation and deprecated `nativePicker`@@ -113,7 +115,7 @@ Consumer migration instructions belong in consumer docs and release notes.| FR4 | When `changeAction` is present, every value-change path MUST call `onChange` first, show the proposed controlled value optimistically, and contribute to one busy state until the controlled value accepts or replaces it. | `family:input-fields/FR6` || FR5 | The two pointer segments share one row while each retains its intrinsic basis; when the container is narrower, flex wrapping moves them into separate full-width rows. Each segment is the shared element height for its size, as a minimum that grows with a set text size under `spec:AST-102` FR4. Implementation gap: the height is fixed at that size. | Public docs, current source, focused layout tests; `spec:AST-102` FR4 || FR6 | Date-time bounds and date constraints MUST prevent invalid commits. Native controls MAY receive platform hints, but JavaScript validation remains the final commit boundary; calendar-only options MAY be unavailable on native surfaces. | Public docs, current source, focused presentation tests |-| FR7 | A preset-time listbox MUST remain optional, preserve typed entry, expose one selected option independently from keyboard highlight, and limit offered values to the selected date's effective minimum and maximum. Time text and typed times MUST follow the active locale's digits, separator, and day-period words (`architecture:internationalization` INV1a, INV8). Implementation gap: time text, preset options, and the stepped-time announcement use ASCII digits, a `:` separator, and a fixed English "AM"/"PM", and the typed time parser takes no locale. | Public docs, current source, focused interaction tests; `architecture:internationalization` INV1a, INV8 |+| FR7 | A preset-time listbox MUST remain optional, preserve typed entry, expose one selected option independently from keyboard highlight, and limit offered values to the selected date's effective minimum and maximum. Time text and typed times MUST follow the active locale's digits, separator, and day-period words (`architecture:internationalization` INV1a, INV8). The hour format is `hourFormat` when set, else the provider locale's hour cycle; time text, preset options, and the stepped-time announcement come from the shared time formatter, and typed times parse the locale's digits, separators, and day-period words as well as English. Implementation gap: the typed time field commits as soon as a prefix parses. | Public docs, current source, focused interaction tests; `architecture:internationalization` INV1a, INV8 || FR8 | Base props and `ref` MUST reach the date segment's input; a caller `aria-describedby` joins the component's own descriptions, and a caller DOM handler runs after the field's own handler. `container*` reaches the Field box and `control*` the segment row; root `xstyle`, `className`, and `style` are not accepted. | `family:input-fields` FR10; `DateTimeInput.fr10.test.tsx` || FR9 | A disabled field MUST keep both segments focusable with `aria-disabled` and no native `disabled`, block every value-changing path, keep the calendar button's tab stop, and paint the keyboard focus ring. Explicit `isLoading` makes every surface inert the same way; a pending `changeAction` does so only on the popover surface, and the bottom sheet and any field with a native date segment keep accepting edits. The busy start is announced once. Implementation gap: a caller `onKeyDown` and other DOM handlers on the date segment still run while disabled (`spec:AST-085` FR2). Implementation gap: a busy field that is not disabled takes the disabled paint (half opacity), on every surface while `isLoading` and on the popover while a `changeAction` is pending, against `spec:AST-085` FR6. | `spec:AST-085` FR1, FR2, FR6; `spec:AST-086` FR8; current source and tests |@@ -229,24 +231,23 @@ leading clock glyph uses `date-time-input-clock-icon`.## Verification map-| Contract | Verification | Representative states | Mutation or failure expectation | Audit section |-| ------------------- | ------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------- |-| FR1–FR2 | `DateTimeInput.test.tsx` | empty, calendar selection, typed date/time, clear | A stale Calendar selection, partial output, or invalid mutation makes a public-state test fail. | `audit:DateTimeInput/behavior` |-| FR3, FR6 | `Presentation.test.tsx`, `NativePickerSegments.test.tsx`, `DateTimeInputTouch.test.tsx` | forced, adaptive, legacy, native fallback, constrained commit | A substituted surface, precedence drift, or invalid commit makes a presentation test fail. | `audit:DateTimeInput/surfaces` |-| FR4, FR9, AR4 | `DateTimeInput.test.tsx`, `DateTimeInputTouch.test.tsx`; `BusyOwnerAnnouncement.test.tsx` DateTimeInput case | pending, loading, disabled reason | Mutation during busy/disabled state or stale optimistic output makes a state test fail. Evidence gap: no test asserts that caller handlers still run while disabled. | `audit:DateTimeInput/state` |-| FR5 | `DateTimeInput.test.tsx` | intrinsic row, narrow-container wrap classes | Removing the intrinsic basis or wrap styles makes the class-level layout assertions fail; rendered geometry remains review evidence. Evidence gap: no test asserts segment heights or text growth. | `audit:DateTimeInput/layout` |-| FR7, AR1–AR3 | `DateTimeInput.test.tsx`, `DateTimeInputTouch.test.tsx` | popovers, time options, keyboard/focus | Wrong role, name, state, keyboard behavior, or focus behavior makes a focused interaction test fail. Evidence gap: no test asserts locale-specific time text or parsing. | `audit:DateTimeInput/interaction` |-| FR8 | `DateTimeInput.fr10.test.tsx` | each surface; caller id, describedby, onClick, onKeyDown | A base prop off the date input, a dropped caller description, or styling on the wrong part fails. | `audit:DateTimeInput/api` |-| Theming anatomy map | `scripts/check-knowledge.mjs`, `themingTargets.test.ts` | root, segments, icons, listbox, options | Missing, undocumented, or wrongly placed targets fail knowledge or target checks. | `audit:DateTimeInput/theming` |+| Contract | Verification | Representative states | Mutation or failure expectation | Audit section |+| ------------------- | ------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------- |+| FR1–FR2 | `DateTimeInput.test.tsx` | empty, calendar selection, typed date/time, clear | A stale Calendar selection, partial output, or invalid mutation makes a public-state test fail. | `audit:DateTimeInput/behavior` |+| FR3, FR6 | `Presentation.test.tsx`, `NativePickerSegments.test.tsx`, `DateTimeInputTouch.test.tsx` | forced, adaptive, legacy, native fallback, constrained commit | A substituted surface, precedence drift, or invalid commit makes a presentation test fail. | `audit:DateTimeInput/surfaces` |+| FR4, FR9, AR4 | `DateTimeInput.test.tsx`, `DateTimeInputTouch.test.tsx`; `BusyOwnerAnnouncement.test.tsx` DateTimeInput case | pending, loading, disabled reason | Mutation during busy/disabled state or stale optimistic output makes a state test fail. Evidence gap: no test asserts that caller handlers still run while disabled. | `audit:DateTimeInput/state` |+| FR5 | `DateTimeInput.test.tsx` | intrinsic row, narrow-container wrap classes | Removing the intrinsic basis or wrap styles makes the class-level layout assertions fail; rendered geometry remains review evidence. Evidence gap: no test asserts segment heights or text growth. | `audit:DateTimeInput/layout` |+| FR7, AR1–AR3 | `DateTimeInput.test.tsx`, `DateTimeInputTouch.test.tsx` | popovers, time options, keyboard/focus | Wrong role, name, state, keyboard behavior, or focus behavior makes a focused interaction test fail. A provider-locale test asserts the closed time text follows the locale's hour cycle and day period; the shared formatter's tests cover parsing. | `audit:DateTimeInput/interaction` |+| FR8 | `DateTimeInput.fr10.test.tsx` | each surface; caller id, describedby, onClick, onKeyDown | A base prop off the date input, a dropped caller description, or styling on the wrong part fails. | `audit:DateTimeInput/api` |+| Theming anatomy map | `scripts/check-knowledge.mjs`, `themingTargets.test.ts` | root, segments, icons, listbox, options | Missing, undocumented, or wrongly placed targets fail knowledge or target checks. | `audit:DateTimeInput/theming` |## Current-state impact- **Fixed height (FR5).** Segments hold the fixed shared element height insteadof growing with a set text size, against `spec:AST-102` FR4.-- **Time text and parsing (FR7).** Time text, preset options, and the stepped- announcement use ASCII digits, a `:` separator, and English "AM"/"PM", and- typed times parse without the locale, against- `architecture:internationalization` INV1a and INV8.+- **Typed-time prefix commits (FR7).** The typed time field commits a parsed+ prefix, so a typed time can commit a different time, against+ `architecture:internationalization` INV8.- **Busy paint (FR9).** A busy field that is not disabled takes the disabledhalf-opacity paint, against `spec:AST-085` FR6.- **Caller handlers while disabled (FR9).** Caller DOM handlers on the datediff --git a/packages/core/src/DateTimeInput/DateTimeInput.test.tsx b/packages/core/src/DateTimeInput/DateTimeInput.test.tsxindex 497b452de3..c78347ca84 100644--- a/packages/core/src/DateTimeInput/DateTimeInput.test.tsx+++ b/packages/core/src/DateTimeInput/DateTimeInput.test.tsx@@ -239,6 +239,26 @@ describe('DateTimeInput', () => {expect(screen.getByDisplayValue('2:30 PM')).toBeInTheDocument();});+ it("follows the provider locale's hour cycle when hourFormat is unset", () => {+ const renderIn = (locale: string) => (+ <InternationalizationProvider locale={locale}>+ <DateTimeInput+ label="Meeting"+ value={'2026-03-15T14:30' as ISODateTimeString}+ onChange={() => {}}+ />+ </InternationalizationProvider>+ );+ const {rerender} = render(renderIn('en-US'));+ expect(screen.getByDisplayValue('2:30 PM')).toBeInTheDocument();++ rerender(renderIn('de-DE'));+ expect(screen.getByDisplayValue('14:30')).toBeInTheDocument();++ rerender(renderIn('ko-KR'));+ expect(screen.getByDisplayValue('오후 2:30')).toBeInTheDocument();+ });+it('displays formatted time in 24h format', () => {render(<DateTimeInputdiff --git a/packages/core/src/DateTimeInput/DateTimeInput.tsx b/packages/core/src/DateTimeInput/DateTimeInput.tsxindex 679073d714..39e13cd10c 100644--- a/packages/core/src/DateTimeInput/DateTimeInput.tsx+++ b/packages/core/src/DateTimeInput/DateTimeInput.tsx@@ -71,9 +71,6 @@ import {type ISOTimeString,parseDateInput,parseISOTime,- parseTimeInput,- formatDisplayTime12h,- formatDisplayTime24h,formatISOTime,isTimeInRange,adjustTime,@@ -102,6 +99,11 @@ import {useSize} from '../SizeContext/SizeContext';import {themeProps} from '../utils/themeProps';import {focusOutlineStyles} from '../utils/focusOutline.stylex';import {useLocale, useTranslator} from '../i18n';+import {+ formatLocaleTime,+ parseLocaleTime,+ resolveHourFormat,+} from '../utils/timeFormat';import {useMergedRefs} from '../hooks/useMergedRefs';import {useHighlightedOptionScroll} from '../hooks/useHighlightedOptionScroll';@@ -412,8 +414,11 @@ export interface DateTimeInputProps extends Omit<hasSeconds?: boolean;/**- * Hour display format.- * @default '12h'+ * Hour display format: '12h' with the locale's day period, or '24h'.+ * When unset, follows the `InternationalizationProvider` locale's hour+ * cycle (`en-US` 12-hour, `en-GB` 24-hour); a per-user preference rides on+ * the locale tag (`en-US-u-hc-h23`).+ * @default the locale's hour cycle*/hourFormat?: DateTimeInputHourFormat;@@ -836,8 +841,11 @@ function PointerDateTimeField({}const nativeTimeValue = nativeTimeDraft ?? valueParts.time;- const formatDisplayTime =- hourFormat === '12h' ? formatDisplayTime12h : formatDisplayTime24h;+ const formatDisplayTime = useCallback(+ (time: ISOTimeString, includeSeconds: boolean) =>+ formatLocaleTime(time, locale, hourFormat, includeSeconds),+ [locale, hourFormat],+ );const timeDisplayValue = useMemo(() => {if (timePendingInput !== null) {@@ -852,12 +860,12 @@ function PointerDateTimeField({if (timePendingInput === null || !timePendingInput.trim()) {return true;}- const parsed = parseTimeInput(timePendingInput, hasSeconds);+ const parsed = parseLocaleTime(timePendingInput, locale, hasSeconds);if (!parsed) {return false;}return isTimeInRange(parsed, timeMin, timeMax);- }, [timePendingInput, hasSeconds, timeMin, timeMax]);+ }, [timePendingInput, locale, hasSeconds, timeMin, timeMax]);const resolvedTimePlaceholder = useMemo(() => {if (isTimeFocused && !timeDisplayValue) {@@ -1362,7 +1370,7 @@ function PointerDateTimeField({const text = e.target.value;setTimePendingInput(text);- const parsed = parseTimeInput(text, hasSeconds);+ const parsed = parseLocaleTime(text, locale, hasSeconds);// Typing narrows nothing — free-form entry is the contract, and a time// between two options must stay reachable. The list instead follows the@@ -1386,6 +1394,7 @@ function PointerDateTimeField({}},[+ locale,hasSeconds,timeMin,timeMax,@@ -1440,7 +1449,7 @@ function PointerDateTimeField({return;}- const parsed = parseTimeInput(timePendingInput, hasSeconds);+ const parsed = parseLocaleTime(timePendingInput, locale, hasSeconds);if (parsed && isTimeInRange(parsed, timeMin, timeMax)) {if (parsed !== valueParts.time && valueParts.date) {const combined = combineDateTime(valueParts.date, parsed);@@ -1453,6 +1462,7 @@ function PointerDateTimeField({},[timePendingInput,+ locale,hasSeconds,timeMin,timeMax,@@ -1530,7 +1540,7 @@ function PointerDateTimeField({const typed =timeHighlightFollowsTypingRef.current &&timePendingInput !== null- ? parseTimeInput(timePendingInput, hasSeconds)+ ? parseLocaleTime(timePendingInput, locale, hasSeconds): null;const option = timeOptions[activeTimeIndex];if (typed) {@@ -1582,6 +1592,7 @@ function PointerDateTimeField({},[valueParts,+ locale,hasSeconds,timeIncrement,timeMin,@@ -2034,11 +2045,18 @@ export function DateTimeInput(props: DateTimeInputProps) {props.presentation,props.nativePicker,);+ const locale = useLocale();const {presentation: _presentation,nativePicker: _nativePicker,- ...rest+ ...surfaceProps} = props;+ // Every surface gets the resolved hour format, so typed text, the native+ // field's resting text, preset times, and the sheet wheels agree.+ const rest = {+ ...surfaceProps,+ hourFormat: resolveHourFormat(locale, props.hourFormat),+ };if (effective === 'native') {return (<PointerDateTimeFielddiff --git a/packages/core/src/DateTimeInput/NativeTimeSegment.tsx b/packages/core/src/DateTimeInput/NativeTimeSegment.tsxindex 303ca5ab51..4344e49628 100644--- a/packages/core/src/DateTimeInput/NativeTimeSegment.tsx+++ b/packages/core/src/DateTimeInput/NativeTimeSegment.tsx@@ -34,13 +34,12 @@ import type {InputStatusType} from '../Field';import {useMediaQuery} from '../hooks/useMediaQuery';import {useMergedRefs} from '../hooks/useMergedRefs';import {Icon} from '../Icon';-import {useTranslator} from '../i18n';+import {useLocale, useTranslator} from '../i18n';+import {formatLocaleTime} from '../utils/timeFormat';import type {ThemeProps} from '../utils/themeProps';import {VisuallyHidden} from '../VisuallyHidden';import {focusOutlineStyles,- formatDisplayTime12h,- formatDisplayTime24h,formatISOTime,isTimeInRange,parseISOTime,@@ -126,6 +125,7 @@ export function NativeTimeSegment({...inputProps} = controlProps ?? {};const t = useTranslator();+ const locale = useLocale();const isTouchPointer = useMediaQuery('(pointer: coarse)');const internalInputRef = useRef<HTMLInputElement | null>(null);const mergedInputRef = useMergedRefs(inputRef, internalInputRef);@@ -151,10 +151,8 @@ export function NativeTimeSegment({const nativeValue = normalizeNativeTime(value) ?? '';const isInputValid = rejectedValue === null;- const formatDisplayTime =- hourFormat === '12h' ? formatDisplayTime12h : formatDisplayTime24h;const overlayText = nativeValue- ? formatDisplayTime(nativeValue, false)+ ? formatLocaleTime(nativeValue, locale, hourFormat, false): placeholder;const showsOverlay = !!overlayText && !(isFocused && isSegmentEditable);diff --git a/packages/core/src/DateTimeInput/TouchDateTimeField.tsx b/packages/core/src/DateTimeInput/TouchDateTimeField.tsxindex 654dcecdd2..e4efec2eb7 100644--- a/packages/core/src/DateTimeInput/TouchDateTimeField.tsx+++ b/packages/core/src/DateTimeInput/TouchDateTimeField.tsx@@ -69,9 +69,8 @@ import {focusOutlineStyles} from '../utils/focusOutline.stylex';import {rtlStyles} from '../utils/rtlStyles';import {themeProps} from '../utils/themeProps';import {normalizeDayOfWeek} from '../utils/dateTypes';+import {formatLocaleTime} from '../utils/timeFormat';import {- formatDisplayTime12h,- formatDisplayTime24h,formatISOTime,isImeKeyEvent,isRenderable,@@ -689,12 +688,9 @@ export function TouchDateTimeField({const timeDisplayValue = useMemo(() => {const displayTime = normalizedValueTime ?? draftTime;return displayTime- ? (hourFormat === '12h' ? formatDisplayTime12h : formatDisplayTime24h)(- displayTime,- hasSeconds,- )+ ? formatLocaleTime(displayTime, locale, hourFormat, hasSeconds): '';- }, [draftTime, normalizedValueTime, hourFormat, hasSeconds]);+ }, [draftTime, normalizedValueTime, locale, hourFormat, hasSeconds]);const timeBoundsForDate = useCallback((date: ISODateString | undefined) => ({diff --git a/packages/core/src/NumberInput/numberParser.ts b/packages/core/src/NumberInput/numberParser.tsindex 978c56cf80..3a6bcca91e 100644--- a/packages/core/src/NumberInput/numberParser.ts+++ b/packages/core/src/NumberInput/numberParser.ts@@ -29,6 +29,9 @@* read off the input: SEPARATOR_CHARS below is a bounded alphabet, the same* shape utils/dateParser.ts uses for its `[-/.]` date separators.*+ * Digit-script folding is shared with utils/timeFormat.ts through+ * utils/unicodeDigits.ts.+ ** SYNC: When modified, update these files to stay in sync:* - /packages/core/src/NumberInput/NumberInput.tsx* - /packages/core/src/NumberInput/numberParser.test.ts@@ -36,6 +39,7 @@*/import type {Locale} from '../i18n';+import {INVISIBLE_CHARS, toAsciiDigits} from '../utils/unicodeDigits';interface LocaleNumberSymbols {group: string;@@ -80,15 +84,9 @@ function getLocaleNumberSymbols(locale: Locale | undefined) {return symbols;}-// Built at runtime rather than written as literals: Babel's-// transform-unicode-property-regex rewrites a `\p{...}` regex LITERAL into an-// enumerated character class, and the copy bundled with Next rejects the-// General_Category short names, failing the sandbox build. Property escapes are-// ES2018 and need no transform in any browser this package supports.-const DECIMAL_DIGIT = new RegExp('\\p{Nd}', 'u');+// Built at runtime rather than written as a literal: see+// utils/unicodeDigits.ts (Babel's property-escape transform).const CURRENCY = new RegExp('\\p{Sc}', 'u');-// Zero-width joiners, bidi isolates and the BOM Excel prepends.-const INVISIBLES = /[\u200B-\u200D\u200E\u200F\u061C\u2066-\u2069\uFEFF]/g;// Hyphen last: inside the character class this builds, a leading one would// open a range.const MINUS_SIGNS = '\u2212\u2012\u2013-';@@ -111,42 +109,6 @@ const NUMBER_BODY = new RegExp(`^[0-9${SEPARATOR_CHARS}]+$`);/** No grouping and at most one full stop: the format `Number()` reads. */const MACHINE_NUMBER = /^(?:\d+\.?\d*|\.\d+)$/;-/**- * Value of any Unicode decimal digit. Each digit script lays its ten digits- * out consecutively, so walking back to the script's zero derives the value- * for Arabic-Indic, Devanagari, full-width and the rest without shipping a- * table of them. Returns null in the one shape the walk cannot resolve: two- * digit blocks adjacent in code space (the mathematical alphanumerics).- */-function digitValue(char: string): number | null {- const codePoint = char.codePointAt(0);- if (codePoint == null) {- return null;- }- for (let zero = codePoint; codePoint - zero < 10; zero--) {- if (!DECIMAL_DIGIT.test(String.fromCodePoint(zero - 1))) {- return codePoint - zero;- }- }- return null;-}--function toAsciiDigits(text: string): string | null {- let out = '';- for (const char of text) {- if (!DECIMAL_DIGIT.test(char)) {- out += char;- continue;- }- const value = digitValue(char);- if (value == null) {- return null;- }- out += String(value);- }- return out;-}-/*** Reduce a digits-and-separators string to a plain machine number under one* candidate reading, or null when it is not well formed under that reading.@@ -302,7 +264,7 @@ export function parseLocaleNumber(locale?: Locale,): number | null {const normalized = toAsciiDigits(- text.normalize('NFKC').replace(INVISIBLES, ''),+ text.normalize('NFKC').replace(INVISIBLE_CHARS, ''),);if (normalized == null) {return null;diff --git a/packages/core/src/TimeInput/NativeTimeInput.test.tsx b/packages/core/src/TimeInput/NativeTimeInput.test.tsxindex b25abd871d..fa6b536170 100644--- a/packages/core/src/TimeInput/NativeTimeInput.test.tsx+++ b/packages/core/src/TimeInput/NativeTimeInput.test.tsx@@ -10,6 +10,7 @@import {afterEach, describe, expect, it, vi} from 'vitest';import {act, fireEvent, render, screen} from '@testing-library/react';import {TimeInput} from './TimeInput';+import {InternationalizationProvider} from '../i18n';import {InputGroup, InputGroupText} from '../InputGroup';import {resetDateSegmentProbe} from '../DateInput/nativeDateSegments';import type {ISOTimeString} from '../utils';@@ -48,6 +49,22 @@ afterEach(() => {});describe('TimeInput nativePicker', () => {+ it("shows the resting value in the locale's hour cycle", () => {+ stubPointer(true);+ render(+ <InternationalizationProvider locale="de-DE">+ <TimeInput+ label="Start time"+ value={'14:30' as ISOTimeString}+ onChange={() => {}}+ />+ </InternationalizationProvider>,+ );+ expect(getNativeTimeInput()).toHaveValue('14:30');+ expect(screen.getByText('14:30')).toBeInTheDocument();+ expect(screen.queryByText('2:30 PM')).toBeNull();+ });+it('uses the browser/OS picker on a coarse pointer by default', () => {stubPointer(true);render(diff --git a/packages/core/src/TimeInput/Presentation.test.tsx b/packages/core/src/TimeInput/Presentation.test.tsxindex 48f6bef723..c4e5628ead 100644--- a/packages/core/src/TimeInput/Presentation.test.tsx+++ b/packages/core/src/TimeInput/Presentation.test.tsx@@ -10,6 +10,8 @@import {afterEach, beforeAll, describe, expect, it, vi} from 'vitest';import {fireEvent, render, screen} from '@testing-library/react';import {TimeInput} from './TimeInput';+import {InternationalizationProvider} from '../i18n';+import type {ISOTimeString} from '../utils';import {resetDateSegmentProbe} from '../DateInput/nativeDateSegments';const HOVER_CAPABLE = /\(\s*hover\s*:\s*hover\s*\)/;@@ -80,6 +82,25 @@ describe('TimeInput presentation', () => {}});+ it("bottom-sheet follows the locale's hour cycle in its text and wheels", () => {+ stubPointer(false);+ render(+ <InternationalizationProvider locale="de-DE">+ <TimeInput+ label="Start"+ presentation="bottom-sheet"+ value={'14:30' as ISOTimeString}+ onChange={() => {}}+ />+ </InternationalizationProvider>,+ );+ const input = screen.getByRole('combobox', {name: 'Start'});+ expect(input).toHaveValue('14:30');+ fireEvent.click(input);+ expect(screen.getByRole('listbox', {name: 'Hour'})).toBeInTheDocument();+ expect(screen.queryByRole('listbox', {name: 'AM/PM'})).toBeNull();+ });+it('bottom-sheet renders the sheet field even on a fine pointer', () => {stubPointer(false);render(diff --git a/packages/core/src/TimeInput/TimeInput.doc.mjs b/packages/core/src/TimeInput/TimeInput.doc.mjsindex 4554cbe21e..419586afd3 100644--- a/packages/core/src/TimeInput/TimeInput.doc.mjs+++ b/packages/core/src/TimeInput/TimeInput.doc.mjs@@ -31,7 +31,7 @@ export const docs = {{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.",+ "Leave hourFormat unset so the field follows the InternationalizationProvider locale's hour cycle (12-hour in en-US, 24-hour in en-GB or de-DE). Set it only when the field itself needs a fixed format, and carry a person's own 12/24-hour preference on the provider locale (e.g. 'en-US-u-hc-h23') rather than on each field.",},{guidance: true,@@ -206,8 +206,8 @@ export const docs = {name: 'hourFormat',type: "'12h' | '24h'",description:- "Controls the display format. '12h' shows AM/PM (e.g. '2:30 PM'); '24h' uses 24-hour notation (e.g. '14:30').",- default: "'12h'",+ "Controls the display format. '12h' shows the locale's day period (e.g. '2:30 PM', '오후 2:30'); '24h' uses 24-hour notation (e.g. '14:30'). When unset, follows the InternationalizationProvider locale's hour cycle: en-US reads 12-hour, en-GB and de-DE read 24-hour. To honor a person's own preference, pass it on the locale tag (e.g. 'en-US-u-hc-h23') rather than per field.",+ default: "the locale's hour cycle",},{name: 'increment',@@ -387,8 +387,8 @@ export const docsZh = {name: 'hourFormat',type: "'12h' | '24h'",description:- "控制显示格式。'12h' 显示 AM/PM(例如 '2:30 PM');'24h' 使用 24 小时制(例如 '14:30')。",- default: "'12h'",+ "控制显示格式。'12h' 使用区域设置的上午/下午用语(例如 '2:30 PM'、'오후 2:30');'24h' 使用 24 小时制(例如 '14:30')。未设置时遵循 InternationalizationProvider 区域设置的小时制:en-US 为 12 小时制,en-GB 和 de-DE 为 24 小时制。要遵循用户自己的偏好,请在区域标签中传入(例如 'en-US-u-hc-h23'),而不是逐个字段设置。",+ default: '区域设置的小时制',},{name: 'increment',@@ -476,7 +476,7 @@ export const docsZh = {{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.",+ "Leave hourFormat unset so the field follows the InternationalizationProvider locale's hour cycle (12-hour in en-US, 24-hour in en-GB or de-DE). Set it only when the field itself needs a fixed format, and carry a person's own 12/24-hour preference on the provider locale (e.g. 'en-US-u-hc-h23') rather than on each field.",},{guidance: true,@@ -565,7 +565,7 @@ export const docsDense = {{guidance: true,description:- 'Choose hour format (12h/24h) to match locale: 12h for US, 24h for international.',+ "Leave hourFormat unset to follow the provider locale's hour cycle; put a person's 12/24h preference on the locale tag (en-US-u-hc-h23), not on each field.",},{guidance: true,@@ -624,7 +624,7 @@ export const docsDense = {hasSeconds: 'Includes seconds in display+parsing.',hasClear: 'Shows clear button when value set+not disabled.',hourFormat:- "Display format. '12h' shows AM/PM; '24h' uses 24-hour notation.",+ "Display format. '12h' shows the locale's day period; '24h' uses 24-hour notation. Unset follows the provider locale's hour cycle (a -u-hc- tag carries a user preference).",increment:'Minutes to add/subtract on arrow up/down. Whole minutes only; a fractional value leaves the time unchanged.',presentation:diff --git a/packages/core/src/TimeInput/TimeInput.spec.md b/packages/core/src/TimeInput/TimeInput.spec.mdindex 04be8e6523..0baf2f0a89 100644--- a/packages/core/src/TimeInput/TimeInput.spec.md+++ b/packages/core/src/TimeInput/TimeInput.spec.md@@ -37,15 +37,15 @@ system_specs: [spec:AST-043, spec:AST-085, spec:AST-086, spec:AST-102]## Contract at a glance-| Area | Contract |-| ----------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |-| Public contract | None changes. TimeInput takes an ISO time `value`, `onChange`, `changeAction`, `isLoading`, `min`, `max`, `hasSeconds`, `hourFormat`, `increment`, `hasClear`, `presentation` (and deprecated `nativePicker`), Field props, size, status, and the input-family part props. |-| Behavior | `presentation` picks the surface: a typed field, the browser time picker, or bottom-sheet wheels, each committing ISO times inside the range through `onChange` and an optional `changeAction`. |-| End-user impact | Desktop users type times in many forms and step with arrows; touch users get the OS picker by default. Keyboard and screen-reader users can reach a disabled field and hear invalid entries and stepped times. |-| Builder impact | None. |-| Compatibility/readiness | Records shipped behavior; no API, default, or DOM change. Caller handlers other than focus, blur, and click still run while disabled, the format hint is fixed English, the clear and Save buttons scale under reduced motion, the grouped sheet field is unnamed by its own label, stepping a draft shows stale text, a focused clear button drops focus when disabled, the sheet surface is pointer-only, the sheet and native surfaces drop focus on clear, the format hint outlasts a disable, the grouped tooltip status describes nothing, time text ignores the locale's digits, separator, and day periods, and typed parsing ignores the locale and commits prefixes; all are listed under Current-state impact. |-| Review checks | Reject a surface other than the one `presentation` names, a commit outside `min`/`max`, an Action skipped by clear, a disabled field that leaves the tab order or changes value, or `nativePicker` winning over `presentation`. |-| Governing rules | `spec:AST-043` FR1–FR4; `family:input-fields` FR3–FR6, FR8–FR11; `spec:AST-085` FR1, FR2, FR4, FR6; `spec:AST-086` FR3, FR4, FR8; `architecture:internationalization` INV1a, INV8; `design:reduced-motion` DR1; `architecture:interaction-modality` INV4. |+| Area | Contract |+| ----------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |+| Public contract | The Hour format default is the provider locale's hour cycle, not a fixed `12h`; no prop, type, or export changes. TimeInput takes an ISO time `value`, `onChange`, `changeAction`, `isLoading`, `min`, `max`, `hasSeconds`, `hourFormat`, `increment`, `hasClear`, `presentation` (and deprecated `nativePicker`), Field props, size, status, and the input-family part props. |+| Behavior | `presentation` picks the surface: a typed field, the browser time picker, or bottom-sheet wheels, each committing ISO times inside the range through `onChange` and an optional `changeAction`. |+| End-user impact | Desktop users type times in many forms and step with arrows; touch users get the OS picker by default. Keyboard and screen-reader users can reach a disabled field and hear invalid entries and stepped times. |+| Builder impact | A caller that relied on the `12h` default under a 24-hour locale passes `hourFormat="12h"` to keep twelve-hour text. A per-user 12/24-hour preference goes on the provider locale as a `-u-hc-` extension (`en-US-u-hc-h23`) rather than on each field. |+| Compatibility/readiness | The `hourFormat` default is the provider locale's hour cycle, which is `12h` for `en`/`en-US` and with no provider; every other released default, API, and DOM shape holds. Caller handlers other than focus, blur, and click still run while disabled, the clear and Save buttons scale under reduced motion, the grouped sheet field is unnamed by its own label, stepping a draft shows stale text, a focused clear button drops focus when disabled, the sheet surface is pointer-only, the sheet and native surfaces drop focus on clear, the format hint outlasts a disable, the grouped tooltip status describes nothing, the sheet's hour, minute, and second wheels use ASCII digits, and typed parsing commits prefixes; all are listed under Current-state impact. |+| Review checks | Reject a surface other than the one `presentation` names, a commit outside `min`/`max`, an Action skipped by clear, a disabled field that leaves the tab order or changes value, or `nativePicker` winning over `presentation`. |+| Governing rules | `spec:AST-043` FR1–FR4; `family:input-fields` FR3–FR6, FR8–FR11; `spec:AST-085` FR1, FR2, FR4, FR6; `spec:AST-086` FR3, FR4, FR8; `architecture:internationalization` INV1a, INV8; `design:reduced-motion` DR1; `architecture:interaction-modality` INV4. |This table is a review projection; the body below is authoritative.@@ -58,11 +58,12 @@ under `family:input-fields`. Consumer usage lives in `TimeInput.doc.mjs`.## Compatibility and migration-- Released default preserved: `yes`; `presentation="adaptive-native"`,- `hourFormat="12h"`, `increment={1}`, no seconds, no clear, `size="md"`,- `statusVariant="attached"`-- Compatibility class: records shipped behavior; no public prop, default,- export, or DOM change+- Released default preserved: `no` for `hourFormat`, which follows the+ provider locale's hour cycle (`12h` for `en` and `en-US`, the released+ default with no provider); `yes` for `presentation="adaptive-native"`,+ `increment={1}`, no seconds, no clear, `size="md"`, `statusVariant="attached"`+- Compatibility class: default change for non-English-US locales; no public+ prop, type, export, or DOM change- Controlled/uncontrolled behavior: controlled; `value` is an ISO time or`undefined`, and the field shows an optimistic value only while a`changeAction` is pending@@ -95,32 +96,32 @@ Consumer migration instructions belong in consumer docs and release notes.## Public concepts-| Concept | Closed values or states | Meaning | Availability by variant/orientation/state | Default | Owner | Stability | Invalid-value behavior |-| ------------- | --------------------------------------------------------------------------------------------- | ------------------------------------ | -------------------------------------------------------------------------------------------------------------------------------------- | ----------------- | --------------------- | ---------- | -------------------------------------------------------------------------------------------------------------------------------------------- |-| Presentation | `text-input`, `popover`, `bottom-sheet`, `native`, `adaptive-bottom-sheet`, `adaptive-native` | Which surface selects the time. | Always. | `adaptive-native` | `spec:AST-043` | Stable | TypeScript rejects other values. |-| Native picker | `touch`, `always`, `never` (deprecated) | Released surface selector. | Ignored when `presentation` is set. | unset | `spec:AST-043` | Deprecated | A development warning names the replacement. |-| Hour format | `12h`, `24h` | Display and wheel hour format. | Typed, native (resting text), and sheet surfaces. | `12h` | `component:TimeInput` | Stable | TypeScript rejects other values. |-| Seconds | off, on | Whether values carry seconds. | Typed and sheet surfaces; keeps adaptive and legacy native off. A forced native surface ignores it and commits hours and minutes only. | off | `component:TimeInput` | Stable | Not applicable. |-| Increment | whole minutes | Arrow-key step. | Typed surface; not 1 keeps adaptive and legacy native off. | `1` | `component:TimeInput` | Stable | A fractional increment steps by nothing: an arrow key re-commits and announces `value`, or commits the current time when the field is empty. |-| Range | `min`, `max` ISO times | Inclusive allowed times. | Every surface. | unbounded | `component:TimeInput` | Stable | Out-of-range entries do not commit. |-| Busy | idle, busy | The value is loading or being saved. | `isLoading`, or while a `changeAction` is pending. | idle | `family:input-fields` | Stable | Not applicable. |+| Concept | Closed values or states | Meaning | Availability by variant/orientation/state | Default | Owner | Stability | Invalid-value behavior |+| ------------- | --------------------------------------------------------------------------------------------- | ------------------------------------ | -------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------- | --------------------- | ---------- | -------------------------------------------------------------------------------------------------------------------------------------------- |+| Presentation | `text-input`, `popover`, `bottom-sheet`, `native`, `adaptive-bottom-sheet`, `adaptive-native` | Which surface selects the time. | Always. | `adaptive-native` | `spec:AST-043` | Stable | TypeScript rejects other values. |+| Native picker | `touch`, `always`, `never` (deprecated) | Released surface selector. | Ignored when `presentation` is set. | unset | `spec:AST-043` | Deprecated | A development warning names the replacement. |+| Hour format | `12h`, `24h` | Display and wheel hour format. | Typed, native (resting text), and sheet surfaces. | The provider locale's hour cycle, including a `-u-hc-` extension on its tag | `component:TimeInput` | Stable | TypeScript rejects other values. |+| Seconds | off, on | Whether values carry seconds. | Typed and sheet surfaces; keeps adaptive and legacy native off. A forced native surface ignores it and commits hours and minutes only. | off | `component:TimeInput` | Stable | Not applicable. |+| Increment | whole minutes | Arrow-key step. | Typed surface; not 1 keeps adaptive and legacy native off. | `1` | `component:TimeInput` | Stable | A fractional increment steps by nothing: an arrow key re-commits and announces `value`, or commits the current time when the field is empty. |+| Range | `min`, `max` ISO times | Inclusive allowed times. | Every surface. | unbounded | `component:TimeInput` | Stable | Out-of-range entries do not commit. |+| Busy | idle, busy | The value is loading or being saved. | `isLoading`, or while a `changeAction` is pending. | idle | `family:input-fields` | Stable | Not applicable. |## Behavioral and layout contract-| ID | Invariant | Basis |-| ---- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------- |-| FR1 | Surface by `presentation` and pointer: `text-input` and `popover` → typed field; `bottom-sheet` → sheet; `native` → native picker on every pointer with no fallback; `adaptive-bottom-sheet` → typed on a fine pointer, sheet on a coarse one; `adaptive-native` → typed on a fine pointer, native on a coarse one, falling back to the typed field when `hasSeconds` or `increment` is not 1. Deprecated `nativePicker` maps `touch` → `adaptive-native`, `always` → native with the same fallbacks, `never` → `text-input`; `presentation` wins when both are set. | `spec:AST-043` FR1–FR4; current tests |-| FR2 | Every surface reports changes as `onChange(isoTime \| undefined)` and then, when supplied, `changeAction` in a transition; while the Action is pending the field shows the proposed value; while `isLoading` or while the shown value differs from `value`, it sets `aria-busy`, shows a decorative Spinner, and announces the busy start once; once the Action settles the field shows `value`. | `family:input-fields` FR5, FR6; `spec:AST-086` FR8; current source |-| FR3 | Typed field: a native text input with a leading clock icon. Typing keeps a draft and commits as soon as the draft parses to an in-range time different from `value`. On blur an empty draft commits `undefined` (when a value exists), a valid draft commits if changed, and an invalid draft reverts. An invalid draft sets `aria-invalid` and fills a persistent assertive region with the localized invalid-time message. Typed times MUST parse in the active locale, and a commit MUST reflect the whole typed time (`architecture:internationalization` INV8). Implementation gap: the parser takes no locale. It recognizes only an English `a`/`p` day period, a `:` separator, and ASCII digits, and it commits as soon as a prefix parses: typing "2.30pm" commits 02:00 from "2" and keeps it on blur; `fi-FI`'s "14.30" keeps 14:00; under `es-ES` "2:30 p. m." commits 02:30 with no warning; and `ja-JP` "午後2:30" and `ar-SA` digits are rejected. | `spec:AST-086` FR3; current tests; `architecture:internationalization` INV8 |-| FR4 | Typed field: ArrowUp and ArrowDown step by `increment` minutes from `value`, or from the current time when empty, commit only when the result is in range, and announce the new time politely (in FR5's display text for the field's hour format, including FR5's digit, separator, and day-period gap). Arrow keys that belong to an IME composition do nothing. The shown text MUST match the committed and announced time. Implementation gap: stepping while a typed draft is pending commits and announces the stepped time but keeps showing the draft, and blur then commits the draft when it parses. | Current tests |-| FR5 | Typed field: the value shows as 12-hour or 24-hour text, with seconds when `hasSeconds`. While focused, enabled, and empty, the placeholder becomes a format hint for the hour format ("e.g., 2:30 PM" or "e.g., 14:30"); otherwise it is `placeholder` or the localized default. The format hint MUST be catalog text (`architecture:internationalization` INV1a). Implementation gap: it is a fixed English string. Implementation gap: a field that becomes disabled while focused keeps showing the hint until blur. On every surface, time text MUST use the locale's digits, separator, and (for twelve-hour text) day-period words (`architecture:internationalization` INV1a, INV8). Implementation gap: every surface's field text and the stepped announcement use ASCII digits, a `:` separator, and a fixed English "AM"/"PM" whatever the locale, and the sheet's hour, minute, and second wheel options use ASCII digits; the sheet's AM/PM wheel uses the catalog's day-period words. | `architecture:internationalization`; current tests |-| FR6 | Native surface: an `<input type="time">` the platform picks with, plus a clock button labelled with the localized open-picker phrase. Native edits outside `min`/`max` do not commit; they set `aria-invalid` and fill the assertive invalid-time region. A pending Action keeps the picker enabled. Clearing does not refocus or reopen the picker. | `spec:AST-043` FR2; current tests |-| FR7 | Sheet surface: a read-only combobox (`aria-haspopup="dialog"`, `aria-expanded`) that opens a BottomSheet of hour, minute, optional second, and (12-hour) meridiem wheels when tapped. Wheel options outside the range are disabled; each wheel change clamps to the range and commits. `isLoading` makes the sheet field inert as well as busy. The wheels MUST be reachable by keyboard (`architecture:interaction-modality` INV4). Implementation gap: Enter, Space, ArrowDown, and Alt+ArrowDown do not open the sheet, and the clock button is out of the tab order, so keyboard users cannot set a time on this surface. | `spec:AST-043` DEC-3; current source and tests; `architecture:interaction-modality` INV4 |-| FR8 | With `hasClear`, a clear button shows while a value is shown and the field is editable. It commits `undefined` through FR2's pipeline, including `changeAction`. On the typed surface it then focuses the input (keyboard: at once; pointer: on the next frame without scrolling). Implementation gap: on the sheet surface, and on the native surface (which does not refocus so the picker does not reopen), it moves focus nowhere, so a keyboard clear leaves focus on the document body. The clear button, and the sheet's Save button, are `component:Button`s, so their press scale MUST NOT apply under reduced motion (`design:reduced-motion` DR1). Implementation gap: both still scale under reduced motion. | `family:input-fields` FR6, FR11; current tests |-| FR9 | TimeInput is disabled when its own `isDisabled` or an enclosing InputGroup's `isDisabled` is true; an enabled group never re-enables a field that disables itself (`spec:AST-085` FR7). Disabled, on every surface: `aria-disabled="true"` on the focusable control, a kept tab stop, no value change by typing, arrows, the picker, or the wheels, a dropped draft, no caller `onClick`, Enter cancelled, the clear button hidden, the control dimmed, and a keyboard focus ring. With `disabledMessage`, a reason tooltip opens on hover and keyboard focus and describes the control. Implementation gap: caller DOM handlers other than focus and blur (`onKeyDown` and the like) still run; only `onClick` is blocked. Implementation gap: when a focused clear button disappears because the field becomes disabled, focus falls to the document body; no destination is named (`spec:AST-085` FR4). | `spec:AST-085` FR1, FR2, FR6; `family:input-fields` FR4; current tests |-| FR10 | Inside InputGroup there is no Field. On the typed and native surfaces, a visually hidden label, description, and status message inside the control name and describe it, the local status icon is suppressed, and a status message is announced through the shared channel (assertive for errors, polite otherwise) when it appears. The sheet surface MUST be named and described the same way. Implementation gap: the grouped sheet field renders no hidden label, description, or status node, so it is named only by the group label, its description and status ids resolve to nothing, and its own status message is not announced (the group's status still describes it). Implementation gap: with `statusVariant="tooltip"`, the grouped typed and native fields render the hidden status message but leave it out of `aria-describedby`, so it is announced once and never describes the control. | `family:input-fields` FR3; `spec:AST-086`; current tests |-| FR11 | Base props reach the semantic control; a caller DOM handler runs after the component's own handler for the same event and cannot cancel built-in behavior. A caller `aria-labelledby` is appended to the field label. `container*` and `control*` reach the Field box and control box; root styling is not accepted. | `family:input-fields` FR10; current tests |-| FR12 | Size and text size (typed and native surfaces; the sheet field sets no font of its own), status presentation, and click-to-focus (typed surface) match `component:TextInput` FR9, FR11, and FR12, including its implementation gaps (the fixed height against `spec:AST-102` FR4, an error status without text, and the color-only `detached` status without a message). The control box carries `astryx-time-input` with `data-size`, `data-status`, and `data-disabled`. | `family:input-fields` FR8, FR9; current tests |+| ID | Invariant | Basis |+| ---- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------- |+| FR1 | Surface by `presentation` and pointer: `text-input` and `popover` → typed field; `bottom-sheet` → sheet; `native` → native picker on every pointer with no fallback; `adaptive-bottom-sheet` → typed on a fine pointer, sheet on a coarse one; `adaptive-native` → typed on a fine pointer, native on a coarse one, falling back to the typed field when `hasSeconds` or `increment` is not 1. Deprecated `nativePicker` maps `touch` → `adaptive-native`, `always` → native with the same fallbacks, `never` → `text-input`; `presentation` wins when both are set. | `spec:AST-043` FR1–FR4; current tests |+| FR2 | Every surface reports changes as `onChange(isoTime \| undefined)` and then, when supplied, `changeAction` in a transition; while the Action is pending the field shows the proposed value; while `isLoading` or while the shown value differs from `value`, it sets `aria-busy`, shows a decorative Spinner, and announces the busy start once; once the Action settles the field shows `value`. | `family:input-fields` FR5, FR6; `spec:AST-086` FR8; current source |+| FR3 | Typed field: a native text input with a leading clock icon. Typing keeps a draft and commits as soon as the draft parses to an in-range time different from `value`. On blur an empty draft commits `undefined` (when a value exists), a valid draft commits if changed, and an invalid draft reverts. An invalid draft sets `aria-invalid` and fills a persistent assertive region with the localized invalid-time message. Typed times MUST parse in the active locale, and a commit MUST reflect the whole typed time (`architecture:internationalization` INV8). The parser reads the locale's digits, hour-minute and minute-second separators, and day-period words on either side of the time, plus English day periods, `:`, and ASCII digits in every locale, so every time FR5 displays reads back as itself. Implementation gap: it commits as soon as a prefix parses: typing "2.30pm" under `en` commits 02:00 from "2" and keeps it on blur. | `spec:AST-086` FR3; current tests; `architecture:internationalization` INV8 |+| FR4 | Typed field: ArrowUp and ArrowDown step by `increment` minutes from `value`, or from the current time when empty, commit only when the result is in range, and announce the new time politely (in FR5's display text for the field's hour format). Arrow keys that belong to an IME composition do nothing. The shown text MUST match the committed and announced time. Implementation gap: stepping while a typed draft is pending commits and announces the stepped time but keeps showing the draft, and blur then commits the draft when it parses. | Current tests |+| FR5 | Typed field: the value shows as 12-hour or 24-hour text, with seconds when `hasSeconds`. The hour format is `hourFormat` when set, else the provider locale's hour cycle (`h11`/`h12` → 12-hour, `h23`/`h24` → 24-hour), so a `-u-hc-` extension on the provider tag carries an app's per-user preference. Every surface receives the same resolved hour format. While focused, enabled, and empty, the placeholder becomes the catalog format hint for that hour format; otherwise it is `placeholder` or the localized default. Implementation gap: a field that becomes disabled while focused keeps showing the hint until blur. On every surface, time text MUST use the locale's digits, separator, and (for twelve-hour text) day-period words (`architecture:internationalization` INV1a, INV8): the typed, native resting, and sheet field text and the stepped announcement come from the shared time formatter. A locale whose twelve-hour reading writes 02:00 and 14:00 alike (no day period) gets English twelve-hour text. Implementation gap: the sheet's hour, minute, and second wheel options use ASCII digits; the sheet's AM/PM wheel uses the catalog's day-period words. | `architecture:internationalization`; current tests |+| FR6 | Native surface: an `<input type="time">` the platform picks with, plus a clock button labelled with the localized open-picker phrase. Native edits outside `min`/`max` do not commit; they set `aria-invalid` and fill the assertive invalid-time region. A pending Action keeps the picker enabled. Clearing does not refocus or reopen the picker. | `spec:AST-043` FR2; current tests |+| FR7 | Sheet surface: a read-only combobox (`aria-haspopup="dialog"`, `aria-expanded`) that opens a BottomSheet of hour, minute, optional second, and (12-hour) meridiem wheels when tapped. Wheel options outside the range are disabled; each wheel change clamps to the range and commits. `isLoading` makes the sheet field inert as well as busy. The wheels MUST be reachable by keyboard (`architecture:interaction-modality` INV4). Implementation gap: Enter, Space, ArrowDown, and Alt+ArrowDown do not open the sheet, and the clock button is out of the tab order, so keyboard users cannot set a time on this surface. | `spec:AST-043` DEC-3; current source and tests; `architecture:interaction-modality` INV4 |+| FR8 | With `hasClear`, a clear button shows while a value is shown and the field is editable. It commits `undefined` through FR2's pipeline, including `changeAction`. On the typed surface it then focuses the input (keyboard: at once; pointer: on the next frame without scrolling). Implementation gap: on the sheet surface, and on the native surface (which does not refocus so the picker does not reopen), it moves focus nowhere, so a keyboard clear leaves focus on the document body. The clear button, and the sheet's Save button, are `component:Button`s, so their press scale MUST NOT apply under reduced motion (`design:reduced-motion` DR1). Implementation gap: both still scale under reduced motion. | `family:input-fields` FR6, FR11; current tests |+| FR9 | TimeInput is disabled when its own `isDisabled` or an enclosing InputGroup's `isDisabled` is true; an enabled group never re-enables a field that disables itself (`spec:AST-085` FR7). Disabled, on every surface: `aria-disabled="true"` on the focusable control, a kept tab stop, no value change by typing, arrows, the picker, or the wheels, a dropped draft, no caller `onClick`, Enter cancelled, the clear button hidden, the control dimmed, and a keyboard focus ring. With `disabledMessage`, a reason tooltip opens on hover and keyboard focus and describes the control. Implementation gap: caller DOM handlers other than focus and blur (`onKeyDown` and the like) still run; only `onClick` is blocked. Implementation gap: when a focused clear button disappears because the field becomes disabled, focus falls to the document body; no destination is named (`spec:AST-085` FR4). | `spec:AST-085` FR1, FR2, FR6; `family:input-fields` FR4; current tests |+| FR10 | Inside InputGroup there is no Field. On the typed and native surfaces, a visually hidden label, description, and status message inside the control name and describe it, the local status icon is suppressed, and a status message is announced through the shared channel (assertive for errors, polite otherwise) when it appears. The sheet surface MUST be named and described the same way. Implementation gap: the grouped sheet field renders no hidden label, description, or status node, so it is named only by the group label, its description and status ids resolve to nothing, and its own status message is not announced (the group's status still describes it). Implementation gap: with `statusVariant="tooltip"`, the grouped typed and native fields render the hidden status message but leave it out of `aria-describedby`, so it is announced once and never describes the control. | `family:input-fields` FR3; `spec:AST-086`; current tests |+| FR11 | Base props reach the semantic control; a caller DOM handler runs after the component's own handler for the same event and cannot cancel built-in behavior. A caller `aria-labelledby` is appended to the field label. `container*` and `control*` reach the Field box and control box; root styling is not accepted. | `family:input-fields` FR10; current tests |+| FR12 | Size and text size (typed and native surfaces; the sheet field sets no font of its own), status presentation, and click-to-focus (typed surface) match `component:TextInput` FR9, FR11, and FR12, including its implementation gaps (the fixed height against `spec:AST-102` FR4, an error status without text, and the color-only `detached` status without a message). The control box carries `astryx-time-input` with `data-size`, `data-status`, and `data-disabled`. | `family:input-fields` FR8, FR9; current tests |### Allowed variation@@ -128,8 +129,7 @@ Consumer migration instructions belong in consumer docs and release notes.and steps.- **AV2 — Accepted typed forms.** The shared time parser decides which typedspellings parse. A parse MUST commit the time the person typed, never a- different one (FR3 gap: prefix commits and locale separators, digits, and day- periods).+ different one (FR3 gap: prefix commits).### Representative states@@ -237,17 +237,14 @@ anatomy-theming map.- **Caller handlers while disabled (FR9).** A disabled TimeInput still runs acaller's DOM handlers other than focus and blur, such as `onKeyDown`, andblocks only `onClick`, against `spec:AST-085` FR2.-- **Format hint (FR5).** The focused-empty format hint is fixed English text,- against `architecture:internationalization` INV1a, and stays shown until blur+- **Format hint (FR5).** The focused-empty format hint stays shown until blurwhen a focused field becomes disabled.-- **Typed parsing (FR3, AV2).** The typed field ignores the locale's day- periods, separator, and digits, and commits a parsed prefix, so a typed time- can commit a different time or be rejected, against+- **Typed parsing (FR3, AV2).** The typed field commits a parsed prefix, so a+ typed time can commit a different time, against`architecture:internationalization` INV8.-- **Time text (FR4, FR5).** Field text on every surface and the stepped-time- announcement use ASCII digits, a `:` separator, and a fixed English "AM"/"PM"- in every locale, and the sheet's hour, minute, and second wheels use ASCII- digits, against `architecture:internationalization` INV1a and INV8.+- **Wheel digits (FR5).** The sheet's hour, minute, and second wheels use ASCII+ digits in every locale, against `architecture:internationalization` INV1a+ and INV8.- **Grouped tooltip status (FR10).** Inside InputGroup with`statusVariant="tooltip"`, the typed and native fields never reference thehidden status message from `aria-describedby`.diff --git a/packages/core/src/TimeInput/TimeInput.test.tsx b/packages/core/src/TimeInput/TimeInput.test.tsxindex 8f869f5790..8a6484916f 100644--- a/packages/core/src/TimeInput/TimeInput.test.tsx+++ b/packages/core/src/TimeInput/TimeInput.test.tsx@@ -829,3 +829,79 @@ describe('TimeInput disabled theme state', () => {expect(root).not.toHaveAttribute('data-disabled');});});++describe('TimeInput locale time text (issue 8992)', () => {+ function renderIn(+ locale: string,+ props: Partial<React.ComponentProps<typeof TimeInput>> = {},+ ) {+ return render(+ <InternationalizationProvider locale={locale}>+ <TimeInput+ label="Time"+ value={'14:30' as ISOTimeString}+ onChange={() => {}}+ presentation="text-input"+ {...props}+ />+ </InternationalizationProvider>,+ );+ }++ it.each([+ ['en-US', '2:30 PM'],+ ['en-GB', '14:30'],+ ['de-DE', '14:30'],+ ['vi-VN', '14:30'],+ ['ko-KR', '오후 2:30'],+ ])(+ 'follows the hour cycle of %s when hourFormat is unset',+ (locale, text) => {+ renderIn(locale);+ expect(screen.getByRole('textbox')).toHaveValue(text);+ },+ );++ it('follows a per-user preference carried on the locale tag', () => {+ renderIn('en-US-u-hc-h23');+ expect(screen.getByRole('textbox')).toHaveValue('14:30');+ });++ it('lets an explicit hourFormat win over the locale', () => {+ renderIn('de-DE', {hourFormat: '12h'});+ expect(screen.getByRole('textbox')).toHaveValue('2:30 PM');+ });++ it("writes the locale's day period instead of a fixed English AM/PM", () => {+ renderIn('ja-JP', {hourFormat: '12h'});+ expect(screen.getByRole('textbox')).toHaveValue('午後2:30');+ });++ it('commits an edit of the localized text', () => {+ const onChange = vi.fn();+ renderIn('ko-KR', {onChange});+ const input = screen.getByRole('textbox');+ fireEvent.focus(input);+ fireEvent.change(input, {target: {value: '오전 9:15'}});+ expect(onChange).toHaveBeenLastCalledWith('09:15');+ });++ it('announces a stepped time in the locale text', async () => {+ const onChange = vi.fn();+ renderIn('de-DE', {onChange});+ fireEvent.keyDown(screen.getByRole('textbox'), {key: 'ArrowUp'});+ expect(onChange).toHaveBeenLastCalledWith('14:31');+ await waitFor(() => {+ expect(politeRegion()).toHaveTextContent('14:31');+ });+ });++ it('shows the catalog format hint for the resolved hour format', () => {+ renderIn('de-DE', {value: undefined});+ fireEvent.focus(screen.getByRole('textbox'));+ expect(screen.getByRole('textbox')).toHaveAttribute(+ 'placeholder',+ 'e.g., 14:30',+ );+ });+});diff --git a/packages/core/src/TimeInput/TimeInput.tsx b/packages/core/src/TimeInput/TimeInput.tsxindex a9cde2261f..ae586664d2 100644--- a/packages/core/src/TimeInput/TimeInput.tsx+++ b/packages/core/src/TimeInput/TimeInput.tsx@@ -52,9 +52,6 @@ import {Spinner} from '../Spinner';import {VisuallyHidden} from '../VisuallyHidden';import {type ISOTimeString,- parseTimeInput,- formatDisplayTime12h,- formatDisplayTime24h,formatISOTime,adjustTime,isImeKeyEvent,@@ -81,7 +78,12 @@ import {InputGroupInternalContext} from '../InputGroup/InputGroupInternalContextimport {groupStyles, inputGroupItemProps} from '../InputGroup/groupStyles';import {useTooltip} from '../Tooltip';import {themeProps} from '../utils/themeProps';-import {useTranslator} from '../i18n';+import {useLocale, useTranslator} from '../i18n';+import {+ formatLocaleTime,+ parseLocaleTime,+ resolveHourFormat,+} from '../utils/timeFormat';import {useMergedRefs} from '../hooks/useMergedRefs';import {NativeTimeSegment} from '../DateTimeInput/NativeTimeSegment';@@ -294,9 +296,13 @@ export interface TimeInputProps extends Omit</*** Hour format for display.- * - '12h': Display as 12-hour with AM/PM (e.g., "2:30 PM")+ * - '12h': Display as 12-hour with the locale's day period (e.g., "2:30 PM")* - '24h': Display as 24-hour (e.g., "14:30")- * @default '12h'+ *+ * When unset, follows the `InternationalizationProvider` locale's hour+ * cycle: `en-US` reads 12-hour, `en-GB` and `de-DE` read 24-hour. A+ * per-user preference rides on the locale tag (`en-US-u-hc-h23`).+ * @default the locale's hour cycle*/hourFormat?: TimeInputHourFormat;@@ -449,6 +455,7 @@ function TimeField({...controlProps} = rest;const t = useTranslator();+ const locale = useLocale();const isEffectivelyRequired = useResolvedRequired({isRequired, isOptional});const placeholder =placeholderFromProps ?? t('@astryx.timeInput.placeholder');@@ -542,9 +549,11 @@ function TimeField({const [pendingInput, setPendingInput] = useState<string | null>(null);const [isFocused, setIsFocused] = useState(false);- // Format function based on hourFormat- const formatDisplayTime =- hourFormat === '12h' ? formatDisplayTime12h : formatDisplayTime24h;+ const formatDisplayTime = useCallback(+ (time: ISOTimeString, includeSeconds: boolean) =>+ formatLocaleTime(time, locale, hourFormat, includeSeconds),+ [locale, hourFormat],+ );// Unified change handler that fires both onChange and changeActionconst fireChange = useCallback(@@ -576,21 +585,23 @@ function TimeField({if (pendingInput === null || !pendingInput.trim()) {return true;}- const parsed = parseTimeInput(pendingInput, hasSeconds);+ const parsed = parseLocaleTime(pendingInput, locale, hasSeconds);if (!parsed) {return false;}// Also check min/max rangereturn isTimeInRange(parsed, min, max);- }, [pendingInput, hasSeconds, min, max]);+ }, [pendingInput, locale, hasSeconds, min, max]);// Placeholder that shows format hint when focused and emptyconst displayPlaceholder = useMemo(() => {if (isFocused && !displayValue) {- return hourFormat === '12h' ? 'e.g., 2:30 PM' : 'e.g., 14:30';+ return hourFormat === '12h'+ ? t('@astryx.dateTimeInput.timeHint12h')+ : t('@astryx.dateTimeInput.timeHint24h');}return placeholder;- }, [isFocused, displayValue, hourFormat, placeholder]);+ }, [isFocused, displayValue, hourFormat, placeholder, t]);// Handle input text change - update immediately if validconst handleInputChange = useCallback(@@ -604,12 +615,12 @@ function TimeField({setPendingInput(newValue);// If the input is valid, update immediately (don't wait for blur)- const parsed = parseTimeInput(newValue, hasSeconds);+ const parsed = parseLocaleTime(newValue, locale, hasSeconds);if (parsed && isTimeInRange(parsed, min, max) && parsed !== value) {fireChange(parsed);}},- [hasSeconds, min, max, value, fireChange, isDisabled],+ [locale, hasSeconds, min, max, value, fireChange, isDisabled],);// Handle focus@@ -646,7 +657,7 @@ function TimeField({return;}- const parsed = parseTimeInput(pendingInput, hasSeconds);+ const parsed = parseLocaleTime(pendingInput, locale, hasSeconds);if (parsed && isTimeInRange(parsed, min, max)) {// Valid time - update if differentif (parsed !== value) {@@ -656,7 +667,7 @@ function TimeField({// Clear pending input - display will revert to formatted valuesetPendingInput(null);},- [pendingInput, isDisabled, value, fireChange, hasSeconds, min, max],+ [pendingInput, isDisabled, value, fireChange, locale, hasSeconds, min, max],);// Handle keyboard navigation on input@@ -950,11 +961,18 @@ export function TimeInput(props: TimeInputProps) {props.nativePicker,'time',);+ const locale = useLocale();const {presentation: _presentation,nativePicker: _nativePicker,- ...rest+ ...surfaceProps} = props;+ // Every surface gets the resolved hour format, so the typed text, the+ // native field's resting text, and the sheet wheels agree.+ const rest = {+ ...surfaceProps,+ hourFormat: resolveHourFormat(locale, props.hourFormat),+ };if (effective === 'native') {// Deprecated `always` keeps released fallbacks (FR2 legacy); only an// explicit `presentation="native"` is forced.diff --git a/packages/core/src/TimeInput/TouchTimeField.tsx b/packages/core/src/TimeInput/TouchTimeField.tsxindex 6c9e986d23..bd8df9dc57 100644--- a/packages/core/src/TimeInput/TouchTimeField.tsx+++ b/packages/core/src/TimeInput/TouchTimeField.tsx@@ -46,7 +46,8 @@ import {useBusyAnnouncement} from '../hooks/useBusyAnnouncement';import {useMergedRefs} from '../hooks/useMergedRefs';import {useResolvedRequired} from '../hooks/useResolvedRequired';import {Icon} from '../Icon';-import {useTranslator} from '../i18n';+import {useLocale, useTranslator} from '../i18n';+import {formatLocaleTime} from '../utils/timeFormat';import {colorVars, sizeVars, spacingVars} from '../theme/tokens.stylex';import {useSize} from '../SizeContext/SizeContext';import {Spinner} from '../Spinner';@@ -57,8 +58,6 @@ import {focusOutlineStyles} from '../utils/focusOutline.stylex';import {themeProps} from '../utils/themeProps';import {clampTime,- formatDisplayTime12h,- formatDisplayTime24h,formatISOTime,getInputARIA,isTimeInRange,@@ -238,6 +237,7 @@ export function TouchTimeField({...controlProps} = rest;const t = useTranslator();+ const locale = useLocale();const isEffectivelyRequired = useResolvedRequired({isRequired, isOptional});const placeholder =placeholderFromProps ?? t('@astryx.timeInput.placeholder');@@ -302,10 +302,8 @@ export function TouchTimeField({[changeAction, isEffectivelyDisabled, onChange, setOptimisticValue],);- const formatDisplayTime =- hourFormat === '12h' ? formatDisplayTime12h : formatDisplayTime24h;const displayValue = optimisticValue- ? formatDisplayTime(optimisticValue, hasSeconds)+ ? formatLocaleTime(optimisticValue, locale, hourFormat, hasSeconds): '';const fallbackTime = useMemo(() => {diff --git a/packages/core/src/utils/timeFormat.test.ts b/packages/core/src/utils/timeFormat.test.tsnew file mode 100644index 0000000000..dda7967b73--- /dev/null+++ b/packages/core/src/utils/timeFormat.test.ts@@ -0,0 +1,204 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file timeFormat.test.ts+ * @input Uses vitest and the timeFormat helpers+ * @output Unit tests for locale hour cycles, locale time text, and parsing it back+ * @position Testing; validates utils/timeFormat.ts+ *+ * SYNC: When timeFormat.ts changes, update tests to match new behavior+ */++import {describe, expect, it} from 'vitest';+import {+ formatLocaleTime,+ parseLocaleTime,+ resolveHourFormat,+ type HourFormat,+} from './timeFormat';+import {parseTimeInput, type ISOTimeString} from './timeParser';++const iso = (time: string) => time as ISOTimeString;++describe('resolveHourFormat', () => {+ it.each([+ ['en', '12h'],+ ['en-US', '12h'],+ ['ko-KR', '12h'],+ ['en-GB', '24h'],+ ['de-DE', '24h'],+ ['vi-VN', '24h'],+ ['fr-FR', '24h'],+ ] as const)('reads the hour cycle of %s as %s', (locale, expected) => {+ expect(resolveHourFormat(locale)).toBe(expected);+ });++ it('honors a -u-hc- preference carried on the locale tag', () => {+ expect(resolveHourFormat('en-US-u-hc-h23')).toBe('24h');+ expect(resolveHourFormat('de-DE-u-hc-h12')).toBe('12h');+ });++ it('lets an explicit hour format win over the locale', () => {+ expect(resolveHourFormat('de-DE', '12h')).toBe('12h');+ expect(resolveHourFormat('en-US', '24h')).toBe('24h');+ });++ it('falls back to twelve-hour for a malformed tag', () => {+ expect(resolveHourFormat('not a locale')).toBe('12h');+ });+});++describe('formatLocaleTime', () => {+ it('keeps the released English text exactly, with a plain space', () => {+ expect(formatLocaleTime(iso('14:30'), 'en', '12h')).toBe('2:30 PM');+ expect(formatLocaleTime(iso('00:05'), 'en', '12h')).toBe('12:05 AM');+ expect(formatLocaleTime(iso('14:30:05'), 'en', '12h', true)).toBe(+ '2:30:05 PM',+ );+ expect(formatLocaleTime(iso('09:05'), 'en', '24h')).toBe('09:05');+ expect(formatLocaleTime(iso('09:05:07'), 'en', '24h', true)).toBe(+ '09:05:07',+ );+ });++ it("uses the locale's day-period words and their position", () => {+ expect(formatLocaleTime(iso('14:30'), 'ko-KR', '12h')).toBe('오후 2:30');+ expect(formatLocaleTime(iso('09:05'), 'zh-CN', '12h')).toBe('上午9:05');+ expect(formatLocaleTime(iso('14:30'), 'es-ES', '12h')).toBe('2:30 p. m.');+ });++ it('writes noon as 12 in a twelve-hour reading, not 0', () => {+ expect(formatLocaleTime(iso('12:30'), 'ja-JP', '12h')).toBe('午後12:30');+ });++ it('writes English twelve-hour text when the locale would drop the day period', () => {+ // fr-CM's twelve-hour reading writes 02:30 and 14:30 both as "2:30".+ expect(formatLocaleTime(iso('14:30'), 'fr-CM', '12h')).toBe('2:30 PM');+ expect(formatLocaleTime(iso('02:30'), 'fr-CM', '12h')).toBe('2:30 AM');+ expect(formatLocaleTime(iso('14:30'), 'fr-CM', '24h')).toBe('14:30');+ });++ it("uses the locale's separator and digits", () => {+ expect(formatLocaleTime(iso('14:30'), 'fi-FI', '24h')).toBe('14.30');+ expect(formatLocaleTime(iso('14:30'), 'ar-EG', '12h')).toBe('٢:٣٠ م');+ });++ it('returns empty text for an empty or malformed time', () => {+ expect(formatLocaleTime(undefined, 'en', '12h')).toBe('');+ expect(formatLocaleTime(iso('25:00'), 'en', '12h')).toBe('');+ });+});++describe('parseLocaleTime', () => {+ const LOCALES = [+ 'en-US',+ 'en-GB',+ 'de-DE',+ 'fi-FI',+ 'fr-CA',+ 'es-ES',+ 'sv-SE',+ 'vi-VN',+ 'ja-JP',+ 'ko-KR',+ 'zh-TW',+ 'ar-EG',+ 'fa-IR',+ 'he-IL',+ // Twelve-hour readings whose separators or surrounding words differ from+ // the twenty-four-hour reading: a dot (as, nds), "h" (oc), a word between+ // the day period and the hour (brx, ee), a word before the hour (dz, nds,+ // tok), and Tibetan digits (dz).+ 'as',+ 'brx',+ 'dz',+ 'ee',+ 'nds',+ 'oc',+ 'tok',+ // A one-letter day period that English input contains ("m" in "pm").+ 'gd',+ // A twelve-hour reading with no day period at all.+ 'fr-CM',+ ];+ const TIMES = ['00:00', '00:30', '09:05', '11:59', '12:00', '12:30', '23:45'];+ const FORMATS: HourFormat[] = ['12h', '24h'];++ it.each(LOCALES)('reads back every time %s writes', locale => {+ for (const hourFormat of FORMATS) {+ for (const time of TIMES) {+ const text = formatLocaleTime(iso(time), locale, hourFormat);+ expect(+ parseLocaleTime(text, locale),+ `${locale} ${hourFormat} "${text}"`,+ ).toBe(time);+ }+ const withSeconds = formatLocaleTime(+ iso('14:30:05'),+ locale,+ hourFormat,+ true,+ );+ expect(parseLocaleTime(withSeconds, locale, true)).toBe('14:30:05');+ }+ });++ it('reads a spaced day period as the half of the day it names', () => {+ // Previously parsed as 02:30: the English matcher missed "p. m.".+ expect(parseLocaleTime('2:30 p. m.', 'es-ES')).toBe('14:30');+ expect(parseLocaleTime('午後2:30', 'ja-JP')).toBe('14:30');+ });++ it('reads twelve-hour text whose pattern differs from the 24-hour one', () => {+ expect(parseLocaleTime('অপৰাহ্ন ২.৩০', 'as')).toBe('14:30');+ expect(parseLocaleTime('ɣetrɔ ga 2:30', 'ee')).toBe('14:30');+ expect(parseLocaleTime('Klock 2.30:05 PM', 'nds', true)).toBe('14:30:05');+ expect(parseLocaleTime('2h30:05 PM', 'oc', true)).toBe('14:30:05');+ });++ it("reads the locale's separator", () => {+ // Previously "14.30" read only its "14" prefix.+ expect(parseLocaleTime('14.30', 'fi-FI')).toBe('14:30');+ expect(parseLocaleTime('14 h 30', 'fr-CA')).toBe('14:30');+ });++ it('does not read a day-period word out of the middle of an English word', () => {+ // gd writes the morning as "m": the "m" of "pm" is not that word.+ expect(parseLocaleTime('2:30 PM', 'gd')).toBe('14:30');+ expect(parseLocaleTime('12:00 PM', 'gd')).toBe('12:00');+ expect(parseLocaleTime('2pm', 'gd')).toBe('14:00');+ expect(parseLocaleTime('2:30 p.m', 'gd')).toBe('14:30');+ expect(parseLocaleTime('12:00 p.m', 'gd')).toBe('12:00');+ expect(parseLocaleTime('2 p.m', 'gd')).toBe('14:00');+ expect(parseLocaleTime('11 a.m', 'gd')).toBe('11:00');+ expect(parseLocaleTime('2:30m', 'gd')).toBe('02:30');+ });++ it('still reads English input in every locale exactly as before', () => {+ const inputs = [+ '2:30 PM',+ '2:30 p.m',+ '2:30 p.m.',+ '12:00 PM',+ '12:00 AM',+ '2pm',+ '2 p.m',+ '11 a.m',+ '14:30',+ '1430',+ ];+ for (const locale of LOCALES) {+ for (const input of inputs) {+ expect(parseLocaleTime(input, locale), `${locale} "${input}"`).toBe(+ parseTimeInput(input),+ );+ }+ }+ });++ it('rejects text no reading fits', () => {+ expect(parseLocaleTime('', 'en-US')).toBeNull();+ expect(parseLocaleTime('25:99', 'de-DE')).toBeNull();+ expect(parseLocaleTime('午後14:30', 'ja-JP')).toBeNull();+ });+});diff --git a/packages/core/src/utils/timeFormat.ts b/packages/core/src/utils/timeFormat.tsnew file mode 100644index 0000000000..0d9cefca8d--- /dev/null+++ b/packages/core/src/utils/timeFormat.ts@@ -0,0 +1,314 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file timeFormat.ts+ * @input An ISO time or typed text, plus the provider's BCP 47 locale+ * @output Exports resolveHourFormat, formatLocaleTime, and parseLocaleTime+ * @position Internal shared helper for TimeInput and DateTimeInput; not part+ * of the public surface+ *+ * Time of day as the locale writes it. The hour cycle, digits, separator, and+ * day-period words all come from Intl rather than a table, so a field reads+ * the same way `Timestamp` does beside it.+ *+ * The hour cycle is the locale's own: `en-US` and `ko-KR` read twelve-hour,+ * `en-GB`, `de-DE`, and `vi-VN` read twenty-four-hour. A `-u-hc-` extension+ * on the provider locale (`en-US-u-hc-h23`) carries an app's per-user+ * preference through the same path, so every Astryx time honors it.+ *+ * The parser reads back what the formatter writes: the locale's digits, its+ * hour-minute separator, and its day-period words, on either side of the time.+ * Whatever is left goes through the shared English-tolerant parser, so "2:30+ * PM" and "14:30" keep working in every locale.+ *+ * SYNC: When modified, update these files to stay in sync:+ * - /packages/core/src/utils/timeFormat.test.ts+ * - /packages/core/src/TimeInput/TimeInput.tsx+ * - /packages/core/src/DateTimeInput/DateTimeInput.tsx+ */++import type {Locale} from '../i18n/types';+import {parseISOTime, parseTimeInput, type ISOTimeString} from './timeParser';+import {INVISIBLE_CHARS, toAsciiDigits} from './unicodeDigits';++export type HourFormat = '12h' | '24h';++interface LocaleTimeSymbols {+ hourFormat: HourFormat;+ /**+ * The text between hour and minute and between minute and second, trimmed:+ * ":" nearly everywhere, "." in fi-FI, "h" and "min" in fr-CA. Read from+ * both readings, because some locales write them differently: `as` writes+ * "১৪:৩০" but "অপৰাহ্ন ২.৩০".+ */+ separators: string[];+ /**+ * Words the locale writes before or after the digits other than the day+ * period, trimmed: "s" after fr-CA seconds, "kl." before nds-DE times, "ga"+ * between an ee day period and its hour. Longest first.+ */+ edgeWords: string[];+ /** Every day-period word the locale writes, longest first. */+ dayPeriods: {word: string; isPM: boolean}[];+ /**+ * The locale's twelve-hour reading writes 02:00 and 14:00 the same (fr-CM+ * writes no day period), so its twelve-hour text is English instead.+ */+ twelveHourIsAmbiguous: boolean;+}++const symbolsByLocale = new Map<string, LocaleTimeSymbols>();++// The space family Intl writes between a time and its day period ("2:30 PM"+// uses U+202F). A typed field shows a plain space so people can edit it.+const SPACES = /[\u00A0\u2007\u202F]/g;+// What may sit on a peeled word's inner side: a digit (digits are already+// ASCII here), whitespace, or nothing.+const WORD_BOUNDARY = /^[\d\s]?$/;++function utcDate(hour: number, minute: number, second: number): Date {+ return new Date(Date.UTC(2000, 0, 1, hour, minute, second));+}++function timeFormatter(+ locale: Locale,+ hourFormat: HourFormat,+ includeSeconds: boolean,+): Intl.DateTimeFormat {+ const options: Intl.DateTimeFormatOptions = {+ hour: hourFormat === '12h' ? 'numeric' : '2-digit',+ minute: '2-digit',+ second: includeSeconds ? '2-digit' : undefined,+ // `hourCycle`, not `hour12`: `hour12: true` resolves to h11 in ja-JP and+ // writes noon as "午後0:30".+ hourCycle: hourFormat === '12h' ? 'h12' : 'h23',+ timeZone: 'UTC',+ };+ try {+ return new Intl.DateTimeFormat(locale, options);+ } catch {+ return new Intl.DateTimeFormat('en', options);+ }+}++function getLocaleTimeSymbols(locale: Locale): LocaleTimeSymbols {+ let symbols = symbolsByLocale.get(locale);+ if (symbols !== undefined) {+ return symbols;+ }++ let hourFormat: HourFormat;+ let resolved: Intl.ResolvedDateTimeFormatOptions;+ try {+ resolved = new Intl.DateTimeFormat(locale, {+ hour: 'numeric',+ }).resolvedOptions();+ } catch {+ // A malformed tag formats as English everywhere else in this module.+ resolved = new Intl.DateTimeFormat('en', {+ hour: 'numeric',+ }).resolvedOptions();+ }+ if (resolved.hourCycle !== undefined) {+ hourFormat =+ resolved.hourCycle === 'h11' || resolved.hourCycle === 'h12'+ ? '12h'+ : '24h';+ } else {+ // Engines that leave hourCycle unresolved still write a day period for a+ // twelve-hour locale when no cycle is forced.+ let ambient: Intl.DateTimeFormat;+ try {+ ambient = new Intl.DateTimeFormat(locale, {hour: 'numeric'});+ } catch {+ ambient = new Intl.DateTimeFormat('en', {hour: 'numeric'});+ }+ hourFormat = ambient+ .formatToParts(utcDate(13, 0, 0))+ .some(part => part.type === 'dayPeriod')+ ? '12h'+ : '24h';+ }++ // Literals of every reading this module writes: twelve- and twenty-four-hour,+ // with and without seconds. A literal between two numbers is a separator;+ // one outside them is an edge word.+ const separatorSet = new Set<string>();+ const edgeSet = new Set<string>();+ for (const cycle of ['12h', '24h'] as const) {+ for (const withSeconds of [false, true]) {+ const parts = timeFormatter(locale, cycle, withSeconds).formatToParts(+ utcDate(13, 30, 5),+ );+ const isNumber = (part: Intl.DateTimeFormatPart) =>+ part.type === 'hour' ||+ part.type === 'minute' ||+ part.type === 'second';+ const first = parts.findIndex(isNumber);+ const last = parts.length - 1 - [...parts].reverse().findIndex(isNumber);+ parts.forEach((part, index) => {+ if (part.type !== 'literal') {+ return;+ }+ const text = normalizeText(part.value).trim();+ if (text === '' || text === ':') {+ return;+ }+ (index > first && index < last ? separatorSet : edgeSet).add(text);+ });+ }+ }+ const separators = [...separatorSet];+ const edgeWords = [...edgeSet].sort((a, b) => b.length - a.length);++ // Every hour, because some locales name several periods across the day+ // (flexible day periods). A word that appears on both sides of noon cannot+ // say which half it means, so it is left out.+ const twelveHour = timeFormatter(locale, '12h', false);+ const sides = new Map<string, Set<boolean>>();+ for (let hour = 0; hour < 24; hour++) {+ const word = twelveHour+ .formatToParts(utcDate(hour, 0, 0))+ .find(part => part.type === 'dayPeriod')?.value;+ if (word === undefined) {+ continue;+ }+ const key = normalizeText(word).trim();+ if (key === '') {+ continue;+ }+ const seen = sides.get(key) ?? new Set<boolean>();+ seen.add(hour >= 12);+ sides.set(key, seen);+ }+ const dayPeriods = [...sides]+ .filter(([, seen]) => seen.size === 1)+ .map(([word, seen]) => ({word, isPM: seen.has(true)}))+ .sort((a, b) => b.word.length - a.word.length);++ const twelveHourIsAmbiguous =+ normalizeText(twelveHour.format(utcDate(2, 0, 0))) ===+ normalizeText(twelveHour.format(utcDate(14, 0, 0)));++ symbols = {+ hourFormat,+ separators,+ edgeWords,+ dayPeriods,+ twelveHourIsAmbiguous,+ };+ symbolsByLocale.set(locale, symbols);+ return symbols;+}++function normalizeText(text: string): string {+ const folded = text+ .normalize('NFKC')+ .replace(INVISIBLE_CHARS, '')+ .replace(SPACES, ' ');+ return (toAsciiDigits(folded) ?? folded).toLowerCase();+}++function escapeRegExp(text: string): string {+ return text.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');+}++/**+ * The hour format a field shows: the caller's explicit choice, else the+ * locale's hour cycle (including a `-u-hc-` extension on the tag).+ */+export function resolveHourFormat(+ locale: Locale,+ hourFormat?: HourFormat,+): HourFormat {+ return hourFormat ?? getLocaleTimeSymbols(locale).hourFormat;+}++/**+ * Formats an ISO time as the locale writes it, in the given hour format.+ * en-US: "14:30" → "2:30 PM"; de-DE 24h: "14:30"; ko-KR 12h: "오후 2:30".+ * Returns '' for an empty or malformed time.+ */+export function formatLocaleTime(+ time: ISOTimeString | undefined,+ locale: Locale,+ hourFormat: HourFormat,+ includeSeconds: boolean = false,+): string {+ if (!time) {+ return '';+ }+ const parsed = parseISOTime(time);+ if (!parsed) {+ return '';+ }+ const formatLocale =+ hourFormat === '12h' && getLocaleTimeSymbols(locale).twelveHourIsAmbiguous+ ? 'en'+ : locale;+ return timeFormatter(formatLocale, hourFormat, includeSeconds)+ .format(utcDate(parsed.hour, parsed.minute, parsed.second))+ .replace(SPACES, ' ');+}++/**+ * Parses typed text into an ISO time, accepting the locale's digits,+ * separator, and day-period words as well as everything `parseTimeInput`+ * accepts. Returns null when no reading fits.+ */+export function parseLocaleTime(+ input: string,+ locale: Locale,+ includeSeconds: boolean = false,+): ISOTimeString | null {+ if (!input) {+ return null;+ }+ const {separators, edgeWords, dayPeriods} = getLocaleTimeSymbols(locale);+ let text = normalizeText(input).trim();++ // Peel the day period and edge words off both ends, in whatever order the+ // locale writes them ("ŋdi ga 2:30", "kl. 2.30 pm").+ let isPM: boolean | null = null;+ // A word counts only when a digit, whitespace, or nothing sits on its inner+ // side, so gd's "m" (morning) is not read out of an English "pm" or "p.m".+ const strip = (word: string) => {+ if (text.startsWith(word) && WORD_BOUNDARY.test(text.charAt(word.length))) {+ text = text.slice(word.length).trim();+ return true;+ }+ if (+ text.endsWith(word) &&+ WORD_BOUNDARY.test(text.charAt(text.length - word.length - 1))+ ) {+ text = text.slice(0, -word.length).trim();+ return true;+ }+ return false;+ };+ for (let peeled = true; peeled;) {+ peeled = false;+ if (isPM === null) {+ const period = dayPeriods.find(({word}) => strip(word));+ if (period !== undefined) {+ isPM = period.isPM;+ peeled = true;+ }+ }+ if (edgeWords.some(strip)) {+ peeled = true;+ }+ }++ for (const separator of separators) {+ text = text.replace(+ new RegExp(`(\\d)\\s*${escapeRegExp(separator)}\\s*(?=\\d)`, 'g'),+ '$1:',+ );+ }++ if (isPM !== null) {+ text = `${text} ${isPM ? 'pm' : 'am'}`;+ }+ return parseTimeInput(text, includeSeconds);+}diff --git a/packages/core/src/utils/unicodeDigits.test.ts b/packages/core/src/utils/unicodeDigits.test.tsnew file mode 100644index 0000000000..5e8709455e--- /dev/null+++ b/packages/core/src/utils/unicodeDigits.test.ts@@ -0,0 +1,44 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file unicodeDigits.test.ts+ * @input Uses vitest and the unicodeDigits helpers+ * @output Unit tests for digit values across scripts+ * @position Testing; validates utils/unicodeDigits.ts+ *+ * SYNC: When unicodeDigits.ts changes, update tests to match new behavior+ */++import {describe, expect, it} from 'vitest';+import {INVISIBLE_CHARS, digitValue, toAsciiDigits} from './unicodeDigits';++describe('digitValue', () => {+ it.each([+ ['7', 7],+ ['٧', 7], // Arabic-Indic+ ['۷', 7], // Extended Arabic-Indic+ ['७', 7], // Devanagari+ ['৭', 7], // Bengali+ ['7', 7], // full-width+ ])('reads %s as %i', (char, value) => {+ expect(digitValue(char)).toBe(value);+ });++ it('returns null for a non-digit', () => {+ expect(digitValue('a')).toBeNull();+ expect(digitValue('')).toBeNull();+ });+});++describe('toAsciiDigits', () => {+ it('rewrites digits and leaves everything else', () => {+ expect(toAsciiDigits('٢:٣٠ م')).toBe('2:30 م');+ expect(toAsciiDigits('१२,३४५.६')).toBe('12,345.6');+ });+});++describe('INVISIBLE_CHARS', () => {+ it('strips bidi marks and zero-width characters', () => {+ expect('\u200F١٢\u061C\uFEFF'.replace(INVISIBLE_CHARS, '')).toBe('١٢');+ });+});diff --git a/packages/core/src/utils/unicodeDigits.ts b/packages/core/src/utils/unicodeDigits.tsnew file mode 100644index 0000000000..b88e0054c1--- /dev/null+++ b/packages/core/src/utils/unicodeDigits.ts@@ -0,0 +1,71 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file unicodeDigits.ts+ * @input Text in any digit script+ * @output Exports INVISIBLE_CHARS, digitValue, and toAsciiDigits+ * @position Internal shared utility for the locale-aware parsers+ * (NumberInput/numberParser.ts, utils/timeFormat.ts); not part of the+ * public surface+ *+ * Locale-independent: a digit's value is a Unicode property, not a locale+ * preference, so this needs no Intl and no locale.+ *+ * SYNC: When modified, update these files to stay in sync:+ * - /packages/core/src/utils/unicodeDigits.test.ts+ */++// Built at runtime rather than written as a literal: Babel's+// transform-unicode-property-regex rewrites a `\p{...}` regex LITERAL into an+// enumerated character class, and the copy bundled with Next rejects the+// General_Category short names, failing the sandbox build. Property escapes are+// ES2018 and need no transform in any browser this package supports.+const DECIMAL_DIGIT = new RegExp('\\p{Nd}', 'u');++/**+ * Zero-width joiners, bidi marks and isolates (which Intl writes around RTL+ * numbers and day periods), and the BOM Excel prepends.+ */+export const INVISIBLE_CHARS =+ /[\u200B-\u200D\u200E\u200F\u061C\u2066-\u2069\uFEFF]/g;++/**+ * Value of any Unicode decimal digit. Each digit script lays its ten digits+ * out consecutively, so walking back to the script's zero derives the value+ * for Arabic-Indic, Devanagari, full-width and the rest without shipping a+ * table of them. Returns null for a non-digit, and in the one shape the walk+ * cannot resolve: two digit blocks adjacent in code space (the mathematical+ * alphanumerics).+ */+export function digitValue(char: string): number | null {+ const codePoint = char.codePointAt(0);+ if (codePoint == null || !DECIMAL_DIGIT.test(char)) {+ return null;+ }+ for (let zero = codePoint; codePoint - zero < 10; zero--) {+ if (!DECIMAL_DIGIT.test(String.fromCodePoint(zero - 1))) {+ return codePoint - zero;+ }+ }+ return null;+}++/**+ * Rewrites every decimal digit as its ASCII digit, leaving other characters+ * alone. Returns null when a digit's value cannot be resolved.+ */+export function toAsciiDigits(text: string): string | null {+ let out = '';+ for (const char of text) {+ if (!DECIMAL_DIGIT.test(char)) {+ out += char;+ continue;+ }+ const value = digitValue(char);+ if (value == null) {+ return null;+ }+ out += String(value);+ }+ return out;+}