From ded041d8566994f3b1abb16b6a6bce57329a8a87 Mon Sep 17 00:00:00 2001 From: Christopher Chedeau Date: Mon, 2 Nov 2026 21:48:21 -0800 Subject: [PATCH 1/3] feat(Wheel): turn a wheel onto a row from script, for the time wheels The time wheels turn a column by themselves when another column's change moves its value, so the Wheel offers that turn on its ref: `spinTo(index)` (`WheelHandle`). Under a finger the wheel turns onto the row on the tap spin, then commits it as a rest would; under a fine pointer the scrolling column commits the row at once, and the new value scrolls it there. Each reports whether the row was committed: a disabled row or an index outside the rows resolves false at once, and a finger, another turn or the wheel's unmounting cutting the turn short resolves false. --- .changeset/wheel-spin.md | 7 ++ .../core/src/DateInput/PickerWheel.test.tsx | 109 +++++++++++++++++- packages/core/src/DateInput/PickerWheel.tsx | 39 ++++++- packages/core/src/DateInput/Wheel.test.tsx | 25 +++- packages/core/src/DateInput/Wheel.tsx | 32 ++++- packages/core/src/DateInput/wheelOptions.ts | 33 +++++- 6 files changed, 235 insertions(+), 10 deletions(-) create mode 100644 .changeset/wheel-spin.md diff --git a/.changeset/wheel-spin.md b/.changeset/wheel-spin.md new file mode 100644 index 0000000000000..53054f4b17f8c --- /dev/null +++ b/.changeset/wheel-spin.md @@ -0,0 +1,7 @@ +--- +'@astryxdesign/core': patch +--- + +[chore] Internal: the picker wheel turns from script, for the time columns that use it. Under a finger, `spinTo` on the wheel's ref turns it onto a row on the tap spin, then commits it as a rest would; under a fine pointer it commits the row at once. Either way it reports whether that row was committed: it refuses a disabled row and an index outside the rows, and a turn the wheel's unmounting cuts short reports that it did not arrive. Nothing public changes: the wheel is not exported from the package entry point. + +@vjeux diff --git a/packages/core/src/DateInput/PickerWheel.test.tsx b/packages/core/src/DateInput/PickerWheel.test.tsx index 1e28d6db38a92..677e7ce9b164f 100644 --- a/packages/core/src/DateInput/PickerWheel.test.tsx +++ b/packages/core/src/DateInput/PickerWheel.test.tsx @@ -14,7 +14,7 @@ */ import {act, fireEvent, render, screen} from '@testing-library/react'; -import {Profiler, useState} from 'react'; +import {Profiler, createRef, useState} from 'react'; import { afterAll, afterEach, @@ -31,6 +31,7 @@ import {fontWeightVars} from '../theme/tokens.stylex'; import {PickerWheel} from './PickerWheel'; import { WHEEL_ROW_HEIGHT, + type WheelHandle, type WheelOption, type WheelProps, } from './wheelOptions'; @@ -1133,6 +1134,21 @@ describe('PickerWheel — under reduced motion', () => { expect(onChange).toHaveBeenLastCalledWith(9); }); + it('fades for a spin', async () => { + const ref = createRef(); + const {onChange} = renderWheel({ref}); + let arrived: boolean | undefined; + act(() => { + void ref.current!.spinTo(15).then(value => { + arrived = value; + }); + }); + await advanceAsync(FADE_MS); + expect(arrived).toBe(true); + expect(onChange).toHaveBeenLastCalledWith(15); + expectFadesOnly(); + }); + it('fades for a tap and a key', async () => { const {column, onChange} = renderWheel(); const below = CENTRE + ROW; @@ -1150,6 +1166,97 @@ describe('PickerWheel — under reduced motion', () => { }); describe('PickerWheel — mechanics for its owners', () => { + it('spins to a row on request and commits it there', async () => { + const ref = createRef(); + const {onChange} = renderWheel({ref}); + let arrived: boolean | undefined; + act(() => { + void ref.current!.spinTo(15).then(value => { + arrived = value; + }); + }); + advance(310); + await act(async () => {}); + expect(arrived).toBe(true); + expect(onChange).toHaveBeenCalledWith(15); + }); + + it('turns nothing and reports false for a spin onto a disabled row or outside the rows', async () => { + // As the scrolling column answers. + const ref = createRef(); + const {option, onChange} = renderWheel({ref}); + for (const index of [3, 24, -1]) { + let arrived: boolean | undefined; + act(() => { + void ref.current!.spinTo(index).then(value => { + arrived = value; + }); + }); + await act(async () => {}); + expect(arrived, `spinTo(${index})`).toBe(false); + } + advance(1000); + expect(onChange).not.toHaveBeenCalled(); + expect(distanceOf(option('10'))).toBeCloseTo(0, 4); + }); + + it('reports false for a spin still turning when the wheel goes away', async () => { + const ref = createRef(); + const {unmount} = renderWheel({ref}); + const spin = ref.current!.spinTo(15); + advance(100); + unmount(); + await expect(spin).resolves.toBe(false); + }); + + it('reports a spin a finger interrupted', async () => { + const ref = createRef(); + const {column} = renderWheel({ref}); + let arrived: boolean | undefined; + act(() => { + void ref.current!.spinTo(15).then(value => { + arrived = value; + }); + }); + advance(100); + touch('touchstart', column, 100); + await act(async () => {}); + expect(arrived).toBe(false); + }); + + it('keeps a spin going when its owner re-renders the rows mid-turn', async () => { + const ref = createRef(); + const {rerender, onChange} = renderWheel({ + ref, + options: MINUTES, + value: 15, + label: 'Minute', + }); + let arrived: boolean | undefined; + act(() => { + void ref.current!.spinTo(30).then(value => { + arrived = value; + }); + }); + advance(100); + // The owner commits a time on its bound: the minutes before 30 are + // disabled now. The same row nodes come back, so the turn goes on. + rerender( + ({ + ...option, + isDisabled: option.value < 30, + }))} + value={30} + onChange={onChange} + />, + ); + advance(250); + await act(async () => {}); + expect(arrived).toBe(true); + }); it('keeps a finger that lands on it from an enclosing sheet', () => { // A sheet arms its pull-down on its body's pointerdown. const onPointerDown = vi.fn(); diff --git a/packages/core/src/DateInput/PickerWheel.tsx b/packages/core/src/DateInput/PickerWheel.tsx index 9fdade2a45ea5..b868710834ca8 100644 --- a/packages/core/src/DateInput/PickerWheel.tsx +++ b/packages/core/src/DateInput/PickerWheel.tsx @@ -4,7 +4,8 @@ /** * @file PickerWheel.tsx - * @input Wheel's props (wheelOptions.ts): options, value and change callback + * @input Wheel's props (wheelOptions.ts): options, value and change callback; + * optionally a ref for programmatic turns * @output PickerWheel: one picker column that moves like UIPickerView * @position Internal component; the Wheel under a finger (Wheel.tsx picks it) * @@ -15,7 +16,14 @@ * DateInputTouch.test.tsx, DateInput.doc.mjs and TimeInput.doc.mjs. */ -import {useCallback, useEffect, useMemo, useRef, useState} from 'react'; +import { + useCallback, + useEffect, + useImperativeHandle, + useMemo, + useRef, + useState, +} from 'react'; import * as stylex from '@stylexjs/stylex'; import {scrollTypeOf} from '../gestures/GestureHost'; import {PanGestureRecognizer} from '../gestures/PanGestureRecognizer'; @@ -50,6 +58,7 @@ import { type WheelLayout, } from './wheelPhysics'; import { + canSpinTo, endIndex, nearestEnabledIndex, steppedIndex, @@ -197,6 +206,7 @@ export function PickerWheel({ value, onChange, isActive = true, + ref, }: WheelProps) { const columnRef = useRef(null); const rowsRef = useRef(null); @@ -584,6 +594,31 @@ export function PickerWheel({ isPointerKept: true, }); + // A spin turns only onto an enabled row (canSpinTo). So its arrival commits + // that row, and nothing turns on past it. It reports the row it was asked + // for, as the scrolling column does. + const spinTo = useCallback( + async (index: number): Promise => + new Promise(resolve => { + if (!canSpinTo(latestRef.current.options, index)) { + resolve(false); + return; + } + const offset = motion.offset(); + move(turnCurve(columnRef.current, offset, index * ROW_HEIGHT), { + onEnd: (outcome, end) => { + if (outcome === 'arrived') { + arrive(end); + } + resolve(outcome === 'arrived'); + }, + }); + }), + [motion, move, arrive], + ); + + useImperativeHandle(ref, () => ({spinTo}), [spinTo]); + const turnToPosition = useCallback( (position: number, offset: number) => { const current = latestRef.current; diff --git a/packages/core/src/DateInput/Wheel.test.tsx b/packages/core/src/DateInput/Wheel.test.tsx index e7fbb5a047bcf..b86a6ec2ab3c8 100644 --- a/packages/core/src/DateInput/Wheel.test.tsx +++ b/packages/core/src/DateInput/Wheel.test.tsx @@ -12,7 +12,7 @@ * touch suites */ -import {useState} from 'react'; +import {createRef, useState} from 'react'; import {act, fireEvent, render, screen} from '@testing-library/react'; import {afterEach, beforeAll, describe, expect, it, vi} from 'vitest'; import {fakeAnimate} from '../motion/__tests__/fakeWebAnimation'; @@ -20,6 +20,7 @@ import { nearestEnabledIndex, ScrollWheel, Wheel, + type WheelHandle, type WheelOption, } from './Wheel'; import {SCROLL_QUIET_MS} from './useScrollSettle'; @@ -650,11 +651,18 @@ describe('Wheel — by pointer', () => { } function renderPicker() { + const ref = createRef(); const onChange = vi.fn(); const view = render( - , + , ); - return {...view, onChange}; + return {...view, ref, onChange}; } it.each([ @@ -682,6 +690,17 @@ describe('Wheel — by pointer', () => { screen.getByRole('listbox', {name: 'Hour'}).parentElement?.parentElement, ).toBe(container); }); + + it('commits a spin at once under a fine pointer', async () => { + stubDevice({ios: false, coarse: false}); + expect(window.matchMedia('(pointer: coarse)').matches).toBe(false); + const {ref, onChange} = renderPicker(); + await expect(ref.current?.spinTo(14)).resolves.toBe(true); + expect(onChange).toHaveBeenCalledWith(14); + // A disabled row is not a place to rest. + await expect(ref.current?.spinTo(3)).resolves.toBe(false); + expect(onChange).toHaveBeenCalledTimes(1); + }); }); describe('Wheel — markup', () => { diff --git a/packages/core/src/DateInput/Wheel.tsx b/packages/core/src/DateInput/Wheel.tsx index aab65a8f7c5e5..53e713e0d1317 100644 --- a/packages/core/src/DateInput/Wheel.tsx +++ b/packages/core/src/DateInput/Wheel.tsx @@ -4,7 +4,8 @@ /** * @file Wheel.tsx - * @input Option list, selected value and change callback + * @input Option list, selected value and change callback; a ref for + * programmatic turns * @output Exports Wheel (one picker column), ScrollWheel (the scrolling * column) and the shared types of wheelOptions.ts * @position Internal component; consumed by MonthYearWheels.tsx, @@ -27,7 +28,13 @@ * - /packages/core/src/DateInput/DateInputTouch.test.tsx */ -import {useCallback, useEffect, useRef, useState} from 'react'; +import { + useCallback, + useEffect, + useImperativeHandle, + useRef, + useState, +} from 'react'; import * as stylex from '@stylexjs/stylex'; import { colorVars, @@ -51,6 +58,7 @@ import {usePointerDragScroll} from './usePointerDragScroll'; import {useScrollSettle} from './useScrollSettle'; import {useWheelListbox} from './useWheelListbox'; import { + canSpinTo, endIndex, nearestEnabledIndex, steppedIndex, @@ -59,6 +67,7 @@ import { export { nearestEnabledIndex, + type WheelHandle, type WheelOption, type WheelProps, } from './wheelOptions'; @@ -299,7 +308,26 @@ export function ScrollWheel({ value, onChange, isActive = true, + ref, }: WheelProps) { + // A spin commits the row at once. The new value then scrolls the column + // there, as any new value does. + useImperativeHandle( + ref, + () => ({ + spinTo: async index => { + if (!canSpinTo(options, index)) { + return false; + } + const option = options[index]; + if (option.value !== value) { + onChange(option.value); + } + return true; + }, + }), + [options, value, onChange], + ); const scrollerRef = useRef(null); const selectedIndex = Math.max( 0, diff --git a/packages/core/src/DateInput/wheelOptions.ts b/packages/core/src/DateInput/wheelOptions.ts index e77d93c47a965..087eae129c28c 100644 --- a/packages/core/src/DateInput/wheelOptions.ts +++ b/packages/core/src/DateInput/wheelOptions.ts @@ -3,8 +3,8 @@ /** * @file wheelOptions.ts * @input Nothing; types, the row height and pure functions - * @output WheelOption, WheelProps, WHEEL_ROW_HEIGHT, nearestEnabledIndex, - * steppedIndex and endIndex: what both wheels share + * @output WheelOption, WheelProps, WheelHandle, WHEEL_ROW_HEIGHT, canSpinTo, + * nearestEnabledIndex, steppedIndex and endIndex: what both wheels share * @position Internal; read by Wheel.tsx (which re-exports all of it) and * PickerWheel.tsx * @@ -13,6 +13,8 @@ * - /packages/core/src/DateInput/PickerWheel.tsx */ +import type {Ref} from 'react'; + /** * The row height, px (`dateInputTouchSizes.wheelItemSize`): the pitch of both * columns' rows, and the unit of the touch wheel's offset. @@ -37,6 +39,19 @@ export interface WheelOption { order?: number; } +/** What a Wheel's `ref` exposes. */ +export interface WheelHandle { + /** + * Turn the wheel onto `index` (an index into `options`) on the tap spin, then + * commit it as a rest would. Resolves true once that row is the committed + * one, false if a finger or another turn interrupted it or the wheel went + * away first. An index outside `options` or a disabled row resolves false at + * once, and nothing turns. Under a fine pointer the row commits at once. The + * column then scrolls to it as for any new value, on the same rule. + */ + spinTo(index: number): Promise; +} + export interface WheelProps { /** Accessible name for the column, e.g. "Month". */ label: string; @@ -53,6 +68,20 @@ export interface WheelProps { * motion. */ isActive?: boolean; + /** Programmatic turns: `spinTo(index)`. */ + ref?: Ref; +} + +/** + * Whether `spinTo(index)` may turn onto `index`: an enabled row of `options`. + * The touch wheel and the scrolling column answer a spin by the same rule. + */ +export function canSpinTo( + options: ReadonlyArray, + index: number, +): boolean { + const option = options[index]; + return option != null && !option.isDisabled; } /** From 9bf92ce4a7ce5050cc3a42a44bcab633e4e17404 Mon Sep 17 00:00:00 2001 From: Christopher Chedeau Date: Mon, 2 Nov 2026 21:48:21 -0800 Subject: [PATCH 2/3] fix(TimeInput, DateTimeInput): under a finger the AM/PM wheel follows the hour, as UIDatePicker's does Under a finger the TimeInput and DateTimeInput sheets render TimeWheels, through the pickers' touch layer (datePickerTouch.ts). The half of the day changes only when the hour's move passes between 11 and 12: 11 AM turned to 12 gives 12 PM, and the AM/PM column turns onto the new half on the wheel's own spin (component:DateInput FR14). The hour column does not loop, so 12 counts as next to 1: 12 PM turned to 1 stays 1 PM, and 1 PM turned to 9 stays 9 PM. A column that comes to rest past min or max goes on to the nearest time inside them and commits it there, the other columns turning onto it; an untouched time outside the bounds stays as it is. A turn the wheels start by themselves is not a person's rest: its arrival commits nothing, even when the owner kept the old time. With a mouse the sheets keep today's independent columns. The columns do not loop, and the minute wheel lists every minute. --- .changeset/clamp-time-whole-minute.md | 7 + .changeset/time-wheels-follow-uidatepicker.md | 12 + apps/storybook/stories/TimeInput.stories.tsx | 17 + .../no-comment-provenance.baseline.json | 2 - .../core/src/DateInput/datePickerTouch.ts | 15 + .../src/DateTimeInput/TouchDateTimeField.tsx | 272 +++---- .../core/src/TimeInput/TimeWheels.test.tsx | 277 +++++++ packages/core/src/TimeInput/TimeWheels.tsx | 218 ++++++ .../src/TimeInput/TimeWheelsTouch.test.tsx | 291 +++++++ .../core/src/TimeInput/TouchTimeField.tsx | 250 +++--- .../TimeWheels.interaction.browser.spec.ts | 740 ++++++++++++++++++ .../core/src/TimeInput/timeWheelRules.test.ts | 315 ++++++++ packages/core/src/TimeInput/timeWheelRules.ts | 352 +++++++++ packages/core/src/utils/timeParser.test.ts | 22 + packages/core/src/utils/timeParser.ts | 43 +- 15 files changed, 2493 insertions(+), 340 deletions(-) create mode 100644 .changeset/clamp-time-whole-minute.md create mode 100644 .changeset/time-wheels-follow-uidatepicker.md create mode 100644 packages/core/src/DateInput/datePickerTouch.ts create mode 100644 packages/core/src/TimeInput/TimeWheels.test.tsx create mode 100644 packages/core/src/TimeInput/TimeWheels.tsx create mode 100644 packages/core/src/TimeInput/TimeWheelsTouch.test.tsx create mode 100644 packages/core/src/TimeInput/__tests__/TimeWheels.interaction.browser.spec.ts create mode 100644 packages/core/src/TimeInput/timeWheelRules.test.ts create mode 100644 packages/core/src/TimeInput/timeWheelRules.ts diff --git a/.changeset/clamp-time-whole-minute.md b/.changeset/clamp-time-whole-minute.md new file mode 100644 index 0000000000000..2deca626cd48e --- /dev/null +++ b/.changeset/clamp-time-whole-minute.md @@ -0,0 +1,7 @@ +--- +'@astryxdesign/core': patch +--- + +[fix] `clampTime` without seconds now gives the nearest whole minute inside a bound that falls between minutes. Before, `clampTime('08:00', '09:00:30')` gave `09:00`, a time outside the range. + +@vjeux diff --git a/.changeset/time-wheels-follow-uidatepicker.md b/.changeset/time-wheels-follow-uidatepicker.md new file mode 100644 index 0000000000000..7cc5d7c699a13 --- /dev/null +++ b/.changeset/time-wheels-follow-uidatepicker.md @@ -0,0 +1,12 @@ +--- +'@astryxdesign/core': patch +--- + +[fix] Under a finger, the time wheels in the TimeInput and DateTimeInput bottom sheets now follow iOS's date picker: + +- The AM/PM column follows the hour. Turning the hour from 11 to 12 now gives 12 PM, not 12 AM, and the AM/PM column turns onto PM. From 12 PM to 1 it stays PM. +- A bound that falls between whole minutes, such as `min="09:00:30"` without a seconds column, now commits the nearest whole minute inside it, with a finger as with a mouse. + +With a mouse, each column still turns on its own. + +@vjeux diff --git a/apps/storybook/stories/TimeInput.stories.tsx b/apps/storybook/stories/TimeInput.stories.tsx index 842e390fcffa1..70818eb243197 100644 --- a/apps/storybook/stories/TimeInput.stories.tsx +++ b/apps/storybook/stories/TimeInput.stories.tsx @@ -245,6 +245,23 @@ export const BottomSheetWithMinMax: Story = { }, }; +/** + * The bottom-sheet wheels as iOS's date picker turns them: from 11:58 AM, one + * row down on the hour gives 12:58 PM and the AM/PM column turns with it. + */ +export const BottomSheetWheels: Story = { + render: args => { + const [value, setValue] = useState( + '11:58' as ISOTimeString, + ); + return ; + }, + args: { + label: 'Alarm', + presentation: 'bottom-sheet', + }, +}; + export const WithIncrement: Story = { render: args => { const [value, setValue] = useState( diff --git a/internal/eslint-plugin-astryx/no-comment-provenance.baseline.json b/internal/eslint-plugin-astryx/no-comment-provenance.baseline.json index 28de171077173..3f19cf8bebdbf 100644 --- a/internal/eslint-plugin-astryx/no-comment-provenance.baseline.json +++ b/internal/eslint-plugin-astryx/no-comment-provenance.baseline.json @@ -1110,10 +1110,8 @@ "spec:AST-086" ], "packages/core/src/TimeInput/TouchTimeField.tsx": [ - "DEC-3", "FR2", "FR8", - "spec:AST-043", "spec:AST-086" ], "packages/core/src/Timestamp/Timestamp.tsx": [ diff --git a/packages/core/src/DateInput/datePickerTouch.ts b/packages/core/src/DateInput/datePickerTouch.ts new file mode 100644 index 0000000000000..8cfcf73839865 --- /dev/null +++ b/packages/core/src/DateInput/datePickerTouch.ts @@ -0,0 +1,15 @@ +// Copyright (c) Meta Platforms, Inc. and affiliates. + +/** + * @file datePickerTouch.ts + * @input The date and time pickers' touch-only pieces + * @output Re-exports what the date and time sheets use only under a finger: + * TimeWheels + * @position The pickers' touch layer. The sheets import touch behaviour from + * here only, so a desktop build can replace this one module. + * + * SYNC: When modified, update TouchTimeField.tsx and TouchDateTimeField.tsx. + */ + +export {TimeWheels} from '../TimeInput/TimeWheels'; +export type {TimeWheelsProps} from '../TimeInput/TimeWheels'; diff --git a/packages/core/src/DateTimeInput/TouchDateTimeField.tsx b/packages/core/src/DateTimeInput/TouchDateTimeField.tsx index ea83b9c752f6f..9005f2f31f114 100644 --- a/packages/core/src/DateTimeInput/TouchDateTimeField.tsx +++ b/packages/core/src/DateTimeInput/TouchDateTimeField.tsx @@ -4,7 +4,7 @@ /** * @file TouchDateTimeField.tsx - * @input Uses React, Field, BottomSheet, SegmentedControl, DateInput month picker primitives, Wheel, StyleX intrinsic flex layout + * @input Uses React, Field, BottomSheet, SegmentedControl, DateInput month picker primitives, Wheel and the pickers' touch layer (TimeWheels), the touch presentation, StyleX intrinsic flex layout * @output Exports TouchDateTimeField — the coarse-pointer surface behind DateTimeInput * @position Internal component; consumed by DateTimeInput.tsx * @@ -75,7 +75,6 @@ import { formatISOTime, isImeKeyEvent, isRenderable, - isTimeInRange, clampTime, mergeProps, parseISOTime, @@ -97,6 +96,17 @@ import { } from '../DateInput/MonthScroller'; import {MonthYearWheels} from '../DateInput/MonthYearWheels'; import {Wheel, type WheelOption} from '../DateInput/Wheel'; +import {TimeWheels} from '../DateInput/datePickerTouch'; +import { + hour12From24, + hour24From12, + hourRowsInHalf, + meridiemRows, + minuteRows, + secondRows, + wheelBounds, +} from '../TimeInput/timeWheelRules'; +import {useTouchPresentation} from '../utils/touchPresentation'; import { dateInputTouchGeometry, dateInputTouchSizes, @@ -406,45 +416,6 @@ function normalizeISOTime( return parsed ? formatISOTime(parsed, hasSeconds) : undefined; } -function timeToSeconds(time: ISOTimeString | undefined): number | null { - if (time === undefined) { - return null; - } - const parsed = parseISOTime(time); - return parsed == null - ? null - : parsed.hour * 3600 + parsed.minute * 60 + parsed.second; -} - -function twoDigits(value: number): string { - return String(value).padStart(2, '0'); -} - -function hour12From24(hour: number): number { - return hour === 0 ? 12 : hour > 12 ? hour - 12 : hour; -} - -function hour24From12(hour: number, meridiem: number): number { - if (meridiem === 0) { - return hour === 12 ? 0 : hour; - } - return hour === 12 ? 12 : hour + 12; -} - -function rangeOverlaps( - startSecond: number, - endSecond: number, - min: ISOTimeString | undefined, - max: ISOTimeString | undefined, -): boolean { - const minSecond = timeToSeconds(min); - const maxSecond = timeToSeconds(max); - return ( - (minSecond == null || endSecond >= minSecond) && - (maxSecond == null || startSecond <= maxSecond) - ); -} - type TouchDateTimePanel = 'date' | 'time'; export function TouchDateTimeField({ @@ -584,6 +555,7 @@ export function TouchDateTimeField({ ); const [activePanel, setActivePanel] = useState('date'); const [isWheelOpen, setIsWheelOpen] = useState(false); + const {isTouch} = useTouchPresentation(); const [draftTime, setDraftTime] = useState(() => normalizeISOTime(splitDateTime(value).time, hasSeconds), ); @@ -852,108 +824,32 @@ export function TouchDateTimeField({ ); const timeBounds = timeBoundsForDate(valueParts.date); - const hourOptions: WheelOption[] = useMemo(() => { - if (hourFormat === '24h') { - return Array.from({length: 24}, (_, hour) => ({ - value: hour, - label: twoDigits(hour), - isDisabled: !rangeOverlaps( - hour * 3600, - hour * 3600 + 3599, - timeBounds.min, - timeBounds.max, - ), - })); - } - const meridiem = parsedWheelTime.hour < 12 ? 0 : 1; - // In 12-hour mode the hour column is interpreted inside the active AM/PM - // half, so disabled rows describe reachability within that half only. - return Array.from({length: 12}, (_, index) => { - const hour = index + 1; - const hour24 = hour24From12(hour, meridiem); - return { - value: hour, - label: String(hour), - // Keys step in time order: 12 PM comes before 1 PM. - order: hour24, - isDisabled: !rangeOverlaps( - hour24 * 3600, - hour24 * 3600 + 3599, - timeBounds.min, - timeBounds.max, - ), - }; - }); - }, [hourFormat, parsedWheelTime.hour, timeBounds.min, timeBounds.max]); - + const bounds = useMemo( + () => wheelBounds(timeBounds.min, timeBounds.max), + [timeBounds.min, timeBounds.max], + ); + const hourOptions: WheelOption[] = useMemo( + () => hourRowsInHalf(parsedWheelTime.hour, hourFormat, bounds), + [bounds, hourFormat, parsedWheelTime.hour], + ); const minuteOptions: WheelOption[] = useMemo( - () => - Array.from({length: 60}, (_, minute) => { - const start = parsedWheelTime.hour * 3600 + minute * 60; - return { - value: minute, - label: twoDigits(minute), - isDisabled: !rangeOverlaps( - start, - start + (hasSeconds ? 59 : 0), - timeBounds.min, - timeBounds.max, - ), - }; - }), - [hasSeconds, parsedWheelTime.hour, timeBounds.min, timeBounds.max], + () => minuteRows(parsedWheelTime.hour, hasSeconds, bounds), + [bounds, hasSeconds, parsedWheelTime.hour], ); - const secondOptions: WheelOption[] = useMemo( - () => - Array.from({length: 60}, (_, second) => ({ - value: second, - label: twoDigits(second), - isDisabled: !isTimeInRange( - formatISOTime( - { - hour: parsedWheelTime.hour, - minute: parsedWheelTime.minute, - second, - }, - true, - ), - timeBounds.min, - timeBounds.max, - ), - })), - [ - parsedWheelTime.hour, - parsedWheelTime.minute, - timeBounds.min, - timeBounds.max, - ], + () => secondRows(parsedWheelTime.hour, parsedWheelTime.minute, bounds), + [bounds, parsedWheelTime.hour, parsedWheelTime.minute], ); - const meridiemOptions: WheelOption[] = useMemo( - () => [ - { - value: 0, - label: t('@astryx.dateTimeInput.meridiemAM'), - isDisabled: !rangeOverlaps( - 0, - 11 * 3600 + 3599, - timeBounds.min, - timeBounds.max, - ), - }, - { - value: 1, - label: t('@astryx.dateTimeInput.meridiemPM'), - isDisabled: !rangeOverlaps( - 12 * 3600, - 23 * 3600 + 3599, - timeBounds.min, - timeBounds.max, - ), - }, - ], - [t, timeBounds.min, timeBounds.max], + () => + meridiemRows( + { + am: t('@astryx.dateTimeInput.meridiemAM'), + pm: t('@astryx.dateTimeInput.meridiemPM'), + }, + bounds, + ), + [bounds, t], ); const handleVisibleMonthChange = useCallback( @@ -1225,49 +1121,69 @@ export function TouchDateTimeField({ activePanel !== 'time' && styles.touchPanelHidden, )}>
- - commitWheelTime( - hourFormat === '24h' - ? composeWheelTime({hour24: hour}) - : composeWheelTime({hour12: hour}), - ) - } - /> - commitWheelTime(composeWheelTime({minute}))} - /> - {hasSeconds && ( - commitWheelTime(composeWheelTime({second}))} - /> - )} - {hourFormat === '12h' && ( - - commitWheelTime(composeWheelTime({meridiem})) + onCommit={time => + commitWheelTime(formatISOTime(time, hasSeconds)) } /> + ) : ( + <> + + commitWheelTime( + hourFormat === '24h' + ? composeWheelTime({hour24: hour}) + : composeWheelTime({hour12: hour}), + ) + } + /> + + commitWheelTime(composeWheelTime({minute})) + } + /> + {hasSeconds && ( + + commitWheelTime(composeWheelTime({second})) + } + /> + )} + {hourFormat === '12h' && ( + + commitWheelTime(composeWheelTime({meridiem})) + } + /> + )} + )}
diff --git a/packages/core/src/TimeInput/TimeWheels.test.tsx b/packages/core/src/TimeInput/TimeWheels.test.tsx new file mode 100644 index 0000000000000..28c1b855fb55d --- /dev/null +++ b/packages/core/src/TimeInput/TimeWheels.test.tsx @@ -0,0 +1,277 @@ +// Copyright (c) Meta Platforms, Inc. and affiliates. + +/** + * @file TimeWheels.test.tsx + * @input vitest, @testing-library/react, TimeWheels + * @output Checks UIDatePicker's time wheels as one picker: the AM/PM column + * follows the hour and turns (never jumps) onto its new row, the hour + * column keeps the half of the day unless a rest passes between 11 and 12, + * and a time past a bound commits as the bound with the other columns + * turning onto it + * @position Testing; the pure rules are timeWheelRules.test.ts. TimeWheels + * are the wheels under a finger, so the tests run under one, where the + * Wheel is UIPickerView's + */ + +import {act, fireEvent, render, screen, within} from '@testing-library/react'; +import {useState} from 'react'; +import { + afterAll, + afterEach, + beforeAll, + beforeEach, + describe, + expect, + it, + vi, +} from 'vitest'; +import type {ISOTimeString} from '../utils'; +import {TimeWheels} from './TimeWheels'; +import type {TimeParts} from './timeWheelRules'; + +// One fake clock for the whole file, as the Wheel's own tests: the gesture +// system keeps one timeline per document. +beforeAll(() => { + vi.useFakeTimers({ + toFake: [ + 'setTimeout', + 'clearTimeout', + 'performance', + 'Date', + 'requestAnimationFrame', + 'cancelAnimationFrame', + ], + }); +}); + +// A finger: TouchTimeField renders TimeWheels under one. +beforeEach(() => { + vi.stubGlobal('matchMedia', (query: string) => ({ + // A finger, with no reduced-motion preference: the policy's combined + // query names the pointer too, so the preference is checked first. + matches: + !query.includes('prefers-reduced-motion') && + /pointer:\s*coarse/.test(query), + media: query, + onchange: null, + addListener: () => {}, + removeListener: () => {}, + addEventListener: () => {}, + removeEventListener: () => {}, + dispatchEvent: () => false, + })); +}); + +afterEach(() => { + vi.advanceTimersByTime(10_000); + vi.unstubAllGlobals(); +}); + +afterAll(() => { + vi.useRealTimers(); +}); + +function advance(ms: number) { + act(() => { + vi.advanceTimersByTime(ms); + }); +} + +function Harness({ + initial, + hourFormat = '12h', + hasSeconds = false, + min, + max, + onCommit, +}: { + initial: TimeParts; + hourFormat?: '12h' | '24h'; + hasSeconds?: boolean; + min?: ISOTimeString; + max?: ISOTimeString; + onCommit: (time: TimeParts) => void; +}) { + const [time, setTime] = useState(initial); + return ( + { + onCommit(next); + setTime(next); + }} + /> + ); +} + +function renderWheels(props: Omit[0], 'onCommit'>) { + const onCommit = vi.fn(); + render(); + return {onCommit}; +} + +const column = (name: string) => screen.getByRole('listbox', {name}); + +/** The label of the row at rest under the band. */ +function restingLabel(name: string): string | null { + const list = column(name); + const id = list.getAttribute('aria-activedescendant'); + return id == null ? null : (document.getElementById(id)?.textContent ?? null); +} + +const at = (hour: number, minute: number): TimeParts => ({ + hour, + minute, + second: 0, +}); + +describe('TimeWheels — the AM/PM column follows the hour', () => { + it('turns AM to PM when the hour goes from 11 to 12, turning the AM/PM column', () => { + const {onCommit} = renderWheels({initial: at(11, 58)}); + fireEvent.keyDown(column('Hour'), {key: 'ArrowDown'}); + expect(onCommit).toHaveBeenLastCalledWith(at(12, 58)); + // The column turns onto PM (its curve is sampled in the browser spec). + advance(400); + expect(restingLabel('AM/PM')).toBe('PM'); + expect( + within(column('AM/PM')).getByRole('option', {name: 'PM'}), + ).toHaveAttribute('aria-selected', 'true'); + }); + + it('turns PM back to AM from 12 to 11', () => { + const {onCommit} = renderWheels({initial: at(12, 58)}); + fireEvent.keyDown(column('Hour'), {key: 'ArrowUp'}); + expect(onCommit).toHaveBeenLastCalledWith(at(11, 58)); + advance(550); + expect(restingLabel('AM/PM')).toBe('AM'); + }); + + it('turns PM to AM from 11 PM to 12, midnight', () => { + const {onCommit} = renderWheels({initial: at(23, 15)}); + // In time order no hour follows 11 PM, so a key cannot make this turn. + fireEvent.click(within(column('Hour')).getByRole('option', {name: '12'})); + expect(onCommit).toHaveBeenLastCalledWith(at(0, 15)); + advance(550); + expect(restingLabel('Hour')).toBe('12'); + expect(restingLabel('AM/PM')).toBe('AM'); + }); + + it('keeps the half of the day from 1 to 2', () => { + const {onCommit} = renderWheels({initial: at(13, 58)}); + fireEvent.keyDown(column('Hour'), {key: 'ArrowDown'}); + expect(onCommit).toHaveBeenLastCalledWith(at(14, 58)); + advance(550); + expect(restingLabel('AM/PM')).toBe('PM'); + }); + + it('keeps PM from 12 to 1', () => { + const {onCommit} = renderWheels({initial: at(12, 58)}); + fireEvent.keyDown(column('Hour'), {key: 'ArrowDown'}); + expect(onCommit).toHaveBeenLastCalledWith(at(13, 58)); + advance(550); + expect(restingLabel('Hour')).toBe('1'); + expect(restingLabel('AM/PM')).toBe('PM'); + }); + + it('keeps PM from 1 back to 12', () => { + const {onCommit} = renderWheels({initial: at(13, 58)}); + fireEvent.keyDown(column('Hour'), {key: 'ArrowUp'}); + expect(onCommit).toHaveBeenLastCalledWith(at(12, 58)); + advance(550); + expect(restingLabel('Hour')).toBe('12'); + expect(restingLabel('AM/PM')).toBe('PM'); + }); + + it('keeps PM from 1 forward to 9, a rest that does not pass between 11 and 12', () => { + const {onCommit} = renderWheels({initial: at(13, 58)}); + fireEvent.click(within(column('Hour')).getByRole('option', {name: '9'})); + expect(onCommit).toHaveBeenLastCalledWith(at(21, 58)); + advance(550); + expect(restingLabel('Hour')).toBe('9'); + expect(restingLabel('AM/PM')).toBe('PM'); + }); + + it('leaves the hour on its row when the AM/PM column turns', () => { + const {onCommit} = renderWheels({initial: at(9, 30)}); + fireEvent.keyDown(column('AM/PM'), {key: 'ArrowDown'}); + expect(onCommit).toHaveBeenLastCalledWith(at(21, 30)); + advance(550); + expect(restingLabel('Hour')).toBe('9'); + }); + + it('commits nothing when the AM/PM turn it started arrives and the owner kept the old time', () => { + // An owner that refuses the commit keeps passing 11:58 AM. + const onCommit = vi.fn(); + render( + , + ); + fireEvent.keyDown(column('Hour'), {key: 'ArrowDown'}); + expect(onCommit).toHaveBeenLastCalledWith(at(12, 58)); + advance(550); + expect(onCommit).not.toHaveBeenCalledWith(at(23, 58)); + }); +}); + +describe('TimeWheels — minutes', () => { + it('change only the minutes', () => { + const {onCommit} = renderWheels({initial: at(12, 58)}); + fireEvent.keyDown(column('Minute'), {key: 'ArrowDown'}); + expect(onCommit).toHaveBeenLastCalledWith(at(12, 59)); + advance(550); + expect(restingLabel('Hour')).toBe('12'); + }); +}); + +describe('TimeWheels — bounds', () => { + it('commit a time past a bound as the bound, turning the other columns onto it', () => { + const {onCommit} = renderWheels({ + initial: at(10, 15), + min: '09:30' as ISOTimeString, + }); + fireEvent.keyDown(column('Hour'), {key: 'ArrowUp'}); + expect(onCommit).toHaveBeenLastCalledWith(at(9, 30)); + // The minutes turn onto the bound with the hour. + advance(400); + expect(restingLabel('Hour')).toBe('9'); + expect(restingLabel('Minute')).toBe('30'); + }); + + it('bring an AM/PM turn past the maximum back onto it', () => { + const {onCommit} = renderWheels({ + initial: at(11, 30), + min: '09:00' as ISOTimeString, + max: '17:00' as ISOTimeString, + }); + fireEvent.keyDown(column('AM/PM'), {key: 'ArrowDown'}); + expect(onCommit).toHaveBeenLastCalledWith(at(17, 0)); + advance(550); + expect(restingLabel('Hour')).toBe('5'); + expect(restingLabel('Minute')).toBe('00'); + expect(restingLabel('AM/PM')).toBe('PM'); + }); + + it('show an untouched time outside the bounds as it is, and commit nothing', () => { + // Opening the sheet never changes the value: an 8:00 under a 9:00 + // minimum stays 8:00 on the wheels, on its disabled rows. + const {onCommit} = renderWheels({ + initial: at(8, 0), + min: '09:00' as ISOTimeString, + }); + advance(600); + expect(restingLabel('Hour')).toBe('8'); + expect(restingLabel('Minute')).toBe('00'); + expect(restingLabel('AM/PM')).toBe('AM'); + expect(onCommit).not.toHaveBeenCalled(); + }); +}); diff --git a/packages/core/src/TimeInput/TimeWheels.tsx b/packages/core/src/TimeInput/TimeWheels.tsx new file mode 100644 index 0000000000000..c939217418e06 --- /dev/null +++ b/packages/core/src/TimeInput/TimeWheels.tsx @@ -0,0 +1,218 @@ +// Copyright (c) Meta Platforms, Inc. and affiliates. + +'use client'; + +/** + * @file TimeWheels.tsx + * @input A time of day, the hour format, the bounds and a commit callback + * @output Exports TimeWheels: UIDatePicker's `.time` wheels as one picker + * @position Internal component; the wheels under a finger in the TimeInput + * sheet and DateTimeInput's time panel. timeWheelRules.ts holds the rules. + * + * A column that moves by itself turns on the Wheel's own spin (`spinTo`). The + * spin starts before the commit, so the new value finds the column moving. + * + * SYNC: When modified, update TimeWheels.test.tsx, timeWheelRules.ts, + * TimeInput.doc.mjs and DateTimeInput.doc.mjs. + */ + +import {useMemo, useRef} from 'react'; +import {Wheel, type WheelHandle} from '../DateInput/Wheel'; +import type {ISOTimeString} from '../utils/timeParser'; +import { + columnValue, + columnsToTurn, + displayedTime, + restingTime, + hourRows, + meridiemOf, + meridiemRows, + minuteRows, + secondRows, + turnColumn, + wheelBounds, + type TimeColumn, + type TimeParts, + type TimeRow, +} from './timeWheelRules'; +import { + registerEnglishFallback, + useComponentTranslator, +} from '../i18n/useComponentTranslator'; +import english from '../i18n/generated-english/TimeInput/TimeWheels.generated'; + +registerEnglishFallback(english); + +export interface TimeWheelsProps { + /** The time the wheels show. */ + time: TimeParts; + /** 12-hour (with an AM/PM column) or 24-hour time. */ + hourFormat: '12h' | '24h'; + /** Whether a seconds column shows. */ + hasSeconds: boolean; + /** Earliest time that may commit. */ + min?: ISOTimeString; + /** Latest time that may commit. */ + max?: ISOTimeString; + /** False while the wheels are hidden. */ + isActive: boolean; + /** Called with the committed time, already inside the bounds. */ + onCommit: (time: TimeParts) => void; +} + +function sameTime(a: TimeParts, b: TimeParts): boolean { + return a.hour === b.hour && a.minute === b.minute && a.second === b.second; +} + +/** + * UIDatePicker's time wheels. + * + * @example + * ``` + * + * ``` + */ +export function TimeWheels({ + time, + hourFormat, + hasSeconds, + min, + max, + isActive, + onCommit, +}: TimeWheelsProps) { + const t = useComponentTranslator(); + const bounds = useMemo(() => wheelBounds(min, max), [min, max]); + const shown = displayedTime(time, hasSeconds); + + const hourOptions = useMemo( + () => hourRows(shown.hour, hourFormat, bounds), + [shown.hour, hourFormat, bounds], + ); + const minuteOptions = useMemo( + () => minuteRows(shown.hour, hasSeconds, bounds), + [shown.hour, hasSeconds, bounds], + ); + const secondOptions = useMemo( + () => secondRows(shown.hour, shown.minute, bounds), + [shown.hour, shown.minute, bounds], + ); + const meridiemOptions = useMemo( + () => + meridiemRows( + { + am: t('@astryx.dateTimeInput.meridiemAM'), + pm: t('@astryx.dateTimeInput.meridiemPM'), + }, + bounds, + ), + [t, bounds], + ); + + const hourRef = useRef(null); + const minuteRef = useRef(null); + const secondRef = useRef(null); + const meridiemRef = useRef(null); + + const rows: Record = { + hour: hourOptions, + minute: minuteOptions, + second: secondOptions, + meridiem: meridiemOptions, + }; + // The rows the columns turn onto by themselves (`spinTo`), each with the id of + // its turn. A turn's arrival is not a person's rest, so it commits nothing, + // even when the owner kept the old time. + const spinsRef = useRef< + Partial> + >({}); + const nextSpinIdRef = useRef(0); + + const restOn = (column: TimeColumn) => (value: number) => { + if (spinsRef.current[column]?.value === value) { + return; + } + const from = shown; + // What commits is the row the wheels come to rest on: past a bound, the + // nearest time inside it that has a row (datePicker.wheels.restPastBound). + const next = restingTime( + turnColumn(from, column, value, hourFormat), + hasSeconds, + bounds, + ); + const handles: Record = { + hour: hourRef.current, + minute: minuteRef.current, + second: secondRef.current, + meridiem: meridiemRef.current, + }; + // Turn the other columns first, so the commit's new value finds them + // already moving (a Wheel never parks a moving column). + for (const turn of columnsToTurn(from, column, value, next, { + hourFormat, + hasSeconds, + })) { + const index = rows[turn.column].findIndex( + row => row.value === turn.value, + ); + const handle = handles[turn.column]; + if (index >= 0 && handle != null) { + nextSpinIdRef.current += 1; + const id = nextSpinIdRef.current; + spinsRef.current[turn.column] = {value: turn.value, id}; + void handle.spinTo(index).finally(() => { + if (spinsRef.current[turn.column]?.id === id) { + spinsRef.current[turn.column] = undefined; + } + }); + } + } + if (!sameTime(next, from)) { + onCommit(next); + } + }; + + return ( + <> + + + {hasSeconds && ( + + )} + {hourFormat === '12h' && ( + + )} + + ); +} + +TimeWheels.displayName = 'TimeWheels'; diff --git a/packages/core/src/TimeInput/TimeWheelsTouch.test.tsx b/packages/core/src/TimeInput/TimeWheelsTouch.test.tsx new file mode 100644 index 0000000000000..8c7ff18b42602 --- /dev/null +++ b/packages/core/src/TimeInput/TimeWheelsTouch.test.tsx @@ -0,0 +1,291 @@ +// Copyright (c) Meta Platforms, Inc. and affiliates. + +/** + * @file TimeWheelsTouch.test.tsx + * @input Uses vitest, Testing Library, TimeInput and DateTimeInput + * @output Tests that the bottom sheet's time wheels follow UIDatePicker under + * a finger, on iOS WebKit and on Android alike: the AM/PM column follows the + * hour; under a mouse each scrolling column turns on its own + * @position Testing; the touch gate of TouchTimeField and TouchDateTimeField + */ + +import {useState} from 'react'; +import {afterEach, beforeAll, describe, expect, it, vi} from 'vitest'; +import {fireEvent, render, screen, within} from '@testing-library/react'; +import {TimeInput} from './TimeInput'; +import {DateTimeInput} from '../DateTimeInput/DateTimeInput'; +import {IOS_SUPPORTS_QUERY} from '../utils/touchPresentation'; +import type {ISODateTimeString} from '../DateTimeInput/DateTimeInput'; +import type {ISOTimeString} from '../utils'; + +class MockResizeObserver { + observe() {} + unobserve() {} + disconnect() {} +} + +/** + * A device: a finger or a mouse, and whether the engine is iOS WebKit. The + * sheet's behaviour depends only on the pointer; the engine is stubbed to + * show that an iPhone and an Android finger get the same wheels. + */ +function stubDevice({ + isCoarse, + isIosWebKit, +}: { + isCoarse: boolean; + isIosWebKit: boolean; +}): void { + vi.stubGlobal('matchMedia', (query: string) => ({ + // No reduced-motion preference; the policy's combined query names the + // pointer too, so the preference is checked first. + matches: query.includes('prefers-reduced-motion') + ? false + : /pointer:\s*coarse/.test(query) + ? isCoarse + : /pointer:\s*fine/.test(query) + ? !isCoarse + : false, + media: query, + onchange: null, + addListener: () => {}, + removeListener: () => {}, + addEventListener: () => {}, + removeEventListener: () => {}, + dispatchEvent: () => false, + })); + vi.stubGlobal('CSS', { + supports: (condition: string) => + isIosWebKit && condition === IOS_SUPPORTS_QUERY, + }); + vi.stubGlobal('ResizeObserver', MockResizeObserver); +} + +const IOS = {isCoarse: true, isIosWebKit: true}; +const ANDROID = {isCoarse: true, isIosWebKit: false}; +const MOUSE = {isCoarse: false, isIosWebKit: false}; + +beforeAll(() => { + window.scrollTo = vi.fn(); + Element.prototype.scrollTo = vi.fn(); + Element.prototype.scrollIntoView = vi.fn(); + HTMLDialogElement.prototype.showModal = vi.fn(function ( + this: HTMLDialogElement, + ) { + this.open = true; + }); + HTMLDialogElement.prototype.close = vi.fn(function (this: HTMLDialogElement) { + this.open = false; + }); +}); + +afterEach(() => { + vi.unstubAllGlobals(); + vi.restoreAllMocks(); +}); + +function ControlledTime({ + initial, + onChange, +}: { + initial: ISOTimeString; + onChange: (value: ISOTimeString | undefined) => void; +}) { + const [value, setValue] = useState(initial); + return ( + { + onChange(next); + setValue(next); + }} + /> + ); +} + +function openTimeSheet() { + fireEvent.click(screen.getByRole('combobox', {name: 'Alarm'})); + return { + hour: screen.getByRole('listbox', {name: 'Hour'}), + minute: screen.getByRole('listbox', {name: 'Minute'}), + }; +} + +describe('TimeInput sheet wheels under a finger and a mouse', () => { + it.each([ + ['an iPhone', IOS], + ['an Android', ANDROID], + ])('turns AM to PM from 11 to 12 under %s finger', (_, device) => { + stubDevice(device); + const onChange = vi.fn(); + render( + , + ); + fireEvent.keyDown(openTimeSheet().hour, {key: 'ArrowDown'}); + expect(onChange).toHaveBeenLastCalledWith('12:58'); + }); + + it('keeps each column on its own under a mouse', () => { + stubDevice(MOUSE); + expect(matchMedia('(pointer: coarse)').matches).toBe(false); + const onChange = vi.fn(); + render( + , + ); + // In time order no AM hour follows 11 AM, so a click turns the column. + const {hour} = openTimeSheet(); + fireEvent.click(within(hour).getByRole('option', {name: '12'})); + expect(onChange).toHaveBeenLastCalledWith('00:58'); + }); +}); + +describe('a bound between whole minutes', () => { + it.each([ + ['an iPhone', IOS], + ['a mouse', MOUSE], + ])('commits the nearest whole minute inside it, with %s', (_, device) => { + stubDevice(device); + const onChange = vi.fn(); + render( + , + ); + const {hour} = openTimeSheet(); + fireEvent.click(within(hour).getByRole('option', {name: '9'})); + expect(onChange).toHaveBeenLastCalledWith('09:01'); + }); +}); + +describe('opening a bounded sheet never changes an untouched value', () => { + it.each([ + ['an iPhone', IOS], + ['an Android', ANDROID], + ])( + 'TimeInput under %s finger: 8:00 under a 9:00 minimum stays 8:00, and an empty field stays empty', + (_, device) => { + stubDevice(device); + const onChange = vi.fn(); + const {unmount} = render( + , + ); + const {hour} = openTimeSheet(); + expect( + document.getElementById(hour.getAttribute('aria-activedescendant')!) + ?.textContent, + ).toBe('8'); + expect(onChange).not.toHaveBeenCalled(); + unmount(); + + render( + , + ); + openTimeSheet(); + expect(onChange).not.toHaveBeenCalled(); + expect(screen.getByRole('combobox', {name: 'Alarm'})).toHaveValue(''); + }, + ); + + it('DateTimeInput: a time before the minimum stays, and an empty field stays empty', () => { + stubDevice(ANDROID); + const onChange = vi.fn(); + const {unmount} = render( + , + ); + const hour = openTimePanel(); + expect( + document.getElementById(hour.getAttribute('aria-activedescendant')!) + ?.textContent, + ).toBe('8'); + expect(onChange).not.toHaveBeenCalled(); + unmount(); + + render( + , + ); + openTimePanel(); + expect(onChange).not.toHaveBeenCalled(); + }); +}); + +function ControlledDateTime({ + initial = '2026-03-15T11:58' as ISODateTimeString, + onChange, +}: { + initial?: ISODateTimeString; + onChange: (value: ISODateTimeString | undefined) => void; +}) { + const [value, setValue] = useState(initial); + return ( + { + onChange(next); + setValue(next); + }} + /> + ); +} + +function openTimePanel() { + fireEvent.click(screen.getAllByRole('button', {name: /^Open /})[0]); + fireEvent.click(screen.getByRole('radio', {name: 'Time'})); + return screen.getByRole('listbox', {name: 'Hour'}); +} + +describe('DateTimeInput sheet wheels under a finger and a mouse', () => { + it.each([ + ['an iPhone', IOS], + ['an Android', ANDROID], + ])('turns AM to PM from 11 to 12 under %s finger', (_, device) => { + stubDevice(device); + const onChange = vi.fn(); + render(); + fireEvent.keyDown(openTimePanel(), {key: 'ArrowDown'}); + expect(onChange).toHaveBeenLastCalledWith('2026-03-15T12:58'); + }); + + it('keeps each column on its own under a mouse', () => { + stubDevice(MOUSE); + expect(matchMedia('(pointer: coarse)').matches).toBe(false); + const onChange = vi.fn(); + render(); + // In time order no AM hour follows 11 AM, so a click turns the column. + fireEvent.click(within(openTimePanel()).getByRole('option', {name: '12'})); + expect(onChange).toHaveBeenLastCalledWith('2026-03-15T00:58'); + }); +}); diff --git a/packages/core/src/TimeInput/TouchTimeField.tsx b/packages/core/src/TimeInput/TouchTimeField.tsx index 75ed25806b6b4..52938dfb7a42f 100644 --- a/packages/core/src/TimeInput/TouchTimeField.tsx +++ b/packages/core/src/TimeInput/TouchTimeField.tsx @@ -4,11 +4,11 @@ /** * @file TouchTimeField.tsx - * @input Uses React, Field, BottomSheet, Wheel, DateInput touch geometry - * tokens, and shared time utilities + * @input Uses React, Field, BottomSheet, the wheels (TimeWheels under a finger, + * Wheel with a mouse), DateInput touch geometry tokens and time utilities * @output Exports TouchTimeField — the bottom-sheet surface behind TimeInput * @position Internal component; consumed by TimeInput.tsx for `presentation` - * sheet surfaces (`spec:AST-043` DEC-3: the time half of DateTimeInput's sheet) + * sheet surfaces * * SYNC: When modified, update these files to stay in sync: * - /packages/core/src/TimeInput/TimeInput.tsx @@ -54,6 +54,7 @@ import {useSize} from '../SizeContext/SizeContext'; import {Spinner} from '../Spinner'; import {useTooltip} from '../Tooltip'; import {Wheel, type WheelOption} from '../DateInput/Wheel'; +import {useTouchPresentation} from '../utils/touchPresentation'; import {dateInputTouchGeometry} from '../DateInput/tokens.stylex'; import {focusOutlineStyles} from '../utils/focusOutline.stylex'; import {themeProps} from '../utils/themeProps'; @@ -68,6 +69,16 @@ import { } from '../utils'; import {chainEventHandlers} from '../utils/chainEventHandlers'; import type {TimeInputProps} from './TimeInput'; +import {TimeWheels} from '../DateInput/datePickerTouch'; +import { + hour12From24, + hour24From12, + hourRowsInHalf, + meridiemRows, + minuteRows, + secondRows, + wheelBounds, +} from './timeWheelRules'; import { registerEnglishFallback, useComponentTranslator, @@ -141,45 +152,6 @@ const styles = stylex.create({ }, }); -function twoDigits(value: number): string { - return String(value).padStart(2, '0'); -} - -function hour12From24(hour: number): number { - return hour === 0 ? 12 : hour > 12 ? hour - 12 : hour; -} - -function hour24From12(hour: number, meridiem: number): number { - if (meridiem === 0) { - return hour === 12 ? 0 : hour; - } - return hour === 12 ? 12 : hour + 12; -} - -function timeToSeconds(time: ISOTimeString | undefined): number | null { - if (time == null) { - return null; - } - const parsed = parseISOTime(time); - return parsed == null - ? null - : parsed.hour * 3600 + parsed.minute * 60 + parsed.second; -} - -function rangeOverlaps( - startSecond: number, - endSecond: number, - min: ISOTimeString | undefined, - max: ISOTimeString | undefined, -): boolean { - const minSecond = timeToSeconds(min); - const maxSecond = timeToSeconds(max); - return ( - (minSecond == null || endSecond >= minSecond) && - (maxSecond == null || startSecond <= maxSecond) - ); -} - /** * The Astryx bottom-sheet time surface: a read-only closed field that opens * hour/minute(/second/meridiem) wheels in a BottomSheet. Wheels commit live, @@ -249,6 +221,7 @@ export function TouchTimeField({ const mergedInputRef = useMergedRefs(ref, inputRef); const inputGroup = useInputGroup(); const [isSheetOpen, setIsSheetOpen] = useState(false); + const {isTouch} = useTouchPresentation(); const [, startTransition] = useTransition(); const [optimisticValue, setOptimisticValue] = useOptimistic(value); const isBusy = isLoading || optimisticValue !== value; @@ -363,86 +336,29 @@ export function TouchTimeField({ [fireChange, hasSeconds, max, min, optimisticValue], ); - const hourOptions: WheelOption[] = useMemo(() => { - if (hourFormat === '24h') { - return Array.from({length: 24}, (_, hour) => ({ - value: hour, - label: twoDigits(hour), - isDisabled: !rangeOverlaps(hour * 3600, hour * 3600 + 3599, min, max), - })); - } - const meridiem = parsedWheelTime.hour < 12 ? 0 : 1; - return Array.from({length: 12}, (_, index) => { - const hour = index + 1; - const hour24 = hour24From12(hour, meridiem); - return { - value: hour, - label: String(hour), - // Keys step in time order: 12 PM comes before 1 PM. - order: hour24, - isDisabled: !rangeOverlaps( - hour24 * 3600, - hour24 * 3600 + 3599, - min, - max, - ), - }; - }); - }, [hourFormat, max, min, parsedWheelTime.hour]); - + const bounds = useMemo(() => wheelBounds(min, max), [min, max]); + const hourOptions: WheelOption[] = useMemo( + () => hourRowsInHalf(parsedWheelTime.hour, hourFormat, bounds), + [bounds, hourFormat, parsedWheelTime.hour], + ); const minuteOptions: WheelOption[] = useMemo( - () => - Array.from({length: 60}, (_, minute) => { - const start = parsedWheelTime.hour * 3600 + minute * 60; - return { - value: minute, - label: twoDigits(minute), - isDisabled: !rangeOverlaps( - start, - start + (hasSeconds ? 59 : 0), - min, - max, - ), - }; - }), - [hasSeconds, max, min, parsedWheelTime.hour], + () => minuteRows(parsedWheelTime.hour, hasSeconds, bounds), + [bounds, hasSeconds, parsedWheelTime.hour], ); - const secondOptions: WheelOption[] = useMemo( - () => - Array.from({length: 60}, (_, second) => ({ - value: second, - label: twoDigits(second), - isDisabled: !isTimeInRange( - formatISOTime( - { - hour: parsedWheelTime.hour, - minute: parsedWheelTime.minute, - second, - }, - true, - ), - min, - max, - ), - })), - [max, min, parsedWheelTime.hour, parsedWheelTime.minute], + () => secondRows(parsedWheelTime.hour, parsedWheelTime.minute, bounds), + [bounds, parsedWheelTime.hour, parsedWheelTime.minute], ); - const meridiemOptions: WheelOption[] = useMemo( - () => [ - { - value: 0, - label: t('@astryx.dateTimeInput.meridiemAM'), - isDisabled: !rangeOverlaps(0, 11 * 3600 + 3599, min, max), - }, - { - value: 1, - label: t('@astryx.dateTimeInput.meridiemPM'), - isDisabled: !rangeOverlaps(12 * 3600, 23 * 3600 + 3599, min, max), - }, - ], - [max, min, t], + () => + meridiemRows( + { + am: t('@astryx.dateTimeInput.meridiemAM'), + pm: t('@astryx.dateTimeInput.meridiemPM'), + }, + bounds, + ), + [bounds, t], ); const openSheet = useCallback(() => { @@ -541,49 +457,69 @@ export function TouchTimeField({ padding={0}>
- - commitWheelTime( - hourFormat === '24h' - ? composeWheelTime({hour24: hour}) - : composeWheelTime({hour12: hour}), - ) - } - /> - commitWheelTime(composeWheelTime({minute}))} - /> - {hasSeconds && ( - commitWheelTime(composeWheelTime({second}))} - /> - )} - {hourFormat === '12h' && ( - - commitWheelTime(composeWheelTime({meridiem})) + onCommit={time => + commitWheelTime(formatISOTime(time, hasSeconds)) } /> + ) : ( + <> + + commitWheelTime( + hourFormat === '24h' + ? composeWheelTime({hour24: hour}) + : composeWheelTime({hour12: hour}), + ) + } + /> + + commitWheelTime(composeWheelTime({minute})) + } + /> + {hasSeconds && ( + + commitWheelTime(composeWheelTime({second})) + } + /> + )} + {hourFormat === '12h' && ( + + commitWheelTime(composeWheelTime({meridiem})) + } + /> + )} + )}
diff --git a/packages/core/src/TimeInput/__tests__/TimeWheels.interaction.browser.spec.ts b/packages/core/src/TimeInput/__tests__/TimeWheels.interaction.browser.spec.ts new file mode 100644 index 0000000000000..5bd655b422f8f --- /dev/null +++ b/packages/core/src/TimeInput/__tests__/TimeWheels.interaction.browser.spec.ts @@ -0,0 +1,740 @@ +// Copyright (c) Meta Platforms, Inc. and affiliates. + +/** + * @file TimeWheels.interaction.browser.spec.ts + * @input The built "Bottom Sheet Wheels" TimeInput story, real touch input + * and the interaction harness + * @output Interaction proofs for the sheet's time wheels under a finger, in + * Chromium and WebKit: an hour drag from 11 to 12 turns AM to PM on the + * AM/PM column's own spin; the turn advances through a blocked main thread; + * it cross-fades under Reduce Motion; a finger stops it mid-turn. With a + * mouse, 11 to 12 stays AM. + * @position Interaction tests of TimeWheels.tsx, run by + * `pnpm test:interaction` + */ + +import { + expect, + test, + type Locator, + type Page, +} from '@astryxdesign/a11y-spec/playwright'; +import { + blockMainThread, + busyWindowProof, + compareCurve, + drag, + installTimerGate, + openStory, + startScreencast, + Storyboard, + tap as press, + thawTimers, + timeline, + touchDriver, + waitForRest, + withStorybook, + writeEvidence, + type CastFrame, + type TouchDriver, + type TrackedFrame, +} from '@astryxdesign/interaction-harness'; +import {cubicBezier} from '../../motion/bezier'; +import {picker} from '../../motion/uikit/picker'; +import {timing} from '../../motion/uikit/timing'; +import {WHEEL_ROW_HEIGHT} from '../../DateInput/wheelOptions'; + +const storybook = withStorybook(test); + +const TURN_MS = picker.tapSpin.durationMs; +const move = cubicBezier(timing.curves.move); +/** The column turn's oracle: the wheel's spin, `timing.curves.move` over `picker.tapSpin`. */ +const spin = (t: number) => (t >= TURN_MS ? 1 : move(Math.max(t, 0) / TURN_MS)); + +interface OpenWheels { + driver: TouchDriver; + sheet: Locator; + hour: Locator; + meridiem: Locator; +} + +async function openWheels(page: Page, story: string): Promise { + await openStory(page, storybook(), story); + const driver = await touchDriver(page); + const opener = page.getByRole('button', {name: /^Open /}).first(); + const box = await opener.boundingBox(); + if (box == null) { + throw new Error('no field'); + } + await driver.tap({x: box.x + box.width / 2, y: box.y + box.height / 2}); + const hour = page.getByRole('listbox', {name: 'Hour'}); + await expect(hour).toBeVisible(); + const sheet = page.getByRole('dialog').first(); + await waitForRest(sheet); + return { + driver, + sheet, + hour, + meridiem: page.getByRole('listbox', {name: 'AM/PM'}), + }; +} + +/** The label of the row at rest under the band. */ +async function restingLabel(column: Locator): Promise { + return column.evaluate(element => { + const id = element.getAttribute('aria-activedescendant'); + return id == null + ? null + : (document.getElementById(id)?.textContent ?? null); + }); +} + +/** Records, in the page, the touches the hour column receives. */ +async function logHourTouches(hour: Locator) { + await hour.evaluate(column => { + const seen: [string, number][] = []; + (window as unknown as {hourTouches: typeof seen}).hourTouches = seen; + for (const type of ['touchstart', 'touchmove', 'touchend']) { + column.addEventListener( + type, + event => seen.push([type, Math.round(event.timeStamp)]), + {capture: true, passive: true}, + ); + } + }); +} + +/** + * Waits for the hour to rest and requires it on 12. A drag that did not turn it + * exactly one row fails here. The failure shows its touches as the page + * received them. It does not wait for an AM/PM turn that never comes. + * + * WebKit's injected touches carry no timestamps. Under a 3-CPU cap with 16 + * workers, a report-only profile, they reach the page in bursts. Three moves + * come within 2 ms, then none for 60 ms or more. So the release reads as a + * fling, and the hour turns several rows. It rested on 5 to 8 in 5 of 10 runs. + * This check names that limit of WebKit's real-time input. The required CI + * WebKit profile and Chromium pass. + */ +async function expectHourOn12(hour: Locator) { + await waitForRest(hour); + // Under Reduce Motion the release lands with no motion for waitForRest to + // follow, so the rest it sees can come before the commit. Wait for the + // commit itself. + const label = await expect + .poll(async () => restingLabel(hour), {timeout: 2_000}) + .toBe('12') + .then( + () => '12', + async () => restingLabel(hour), + ); + if (label !== '12') { + const touches = await hour + .page() + .evaluate( + () => + (window as unknown as {hourTouches: [string, number][]}).hourTouches, + ); + throw new Error( + `the drag did not turn the hour one row (it rests on ${label}); its touches as the page received them: ${JSON.stringify(touches)}`, + ); + } +} + +/** Turns the hour from 11 to 12 and waits for it to rest there. */ +async function turnHourTo12(driver: TouchDriver, hour: Locator) { + await logHourTouches(hour); + await turnOneRowDown(driver, hour); + await expectHourOn12(hour); +} + +/** A slow drag that rests before the lift: one row up, no fling. */ +async function turnOneRowDown(driver: TouchDriver, column: Locator) { + const box = await column.boundingBox(); + if (box == null) { + throw new Error('no column'); + } + const from = {x: box.x + box.width / 2, y: box.y + box.height / 2}; + // One row plus the pan's hysteresis. + await driver.play( + drag( + from, + {x: from.x, y: from.y - (WHEEL_ROW_HEIGHT + 10)}, + {durationMs: 300, restMs: 150}, + ), + ); +} + +/** The strip holding a column's rows moves by one row pitch per row. */ +const stripOf = (column: Locator) => column.locator('[data-wheel-strip]'); + +/** + * Resolves once the page has caught `column`'s next turn as it was created. In + * the task that creates the turn's animations, it holds the gated timers and + * pauses the animations. The Wheel ends a turn from one of those timers. So a + * sampler that comes late still finds the turn at its start. Needs + * installTimerGate first. + */ +async function catchTurn(column: Locator): Promise { + await column.evaluate( + async element => + new Promise(resolve => { + const observer = new MutationObserver(() => { + const animations = element.getAnimations({subtree: true}); + if (animations.length === 0) { + return; + } + observer.disconnect(); + const gate = ( + window as unknown as {__harnessTimerGate?: {frozen: boolean}} + ).__harnessTimerGate; + if (gate == null) { + throw new Error('catchTurn: call installTimerGate first'); + } + gate.frozen = true; + for (const animation of animations) { + animation.pause(); + } + resolve(); + }); + // The Wheel writes the turn's end offset inline in the task that + // creates its animations; the callback runs right after that task. + observer.observe(element, { + attributes: true, + attributeFilter: ['style'], + subtree: true, + }); + }), + ); +} + +test('the AM/PM column follows the hour from 11 to 12 on UIDatePicker’s turn', async ({ + page, +}) => { + const {driver, hour, meridiem} = await openWheels( + page, + 'core-timeinput--bottom-sheet-wheels', + ); + expect(await restingLabel(hour)).toBe('11'); + expect(await restingLabel(meridiem)).toBe('AM'); + + // The Wheel ends a turn from a timer at the curve's duration: hold it with + // the animations while they are sampled. + await installTimerGate(page); + // The hour commits at rest; the AM/PM column then turns by itself. The + // page catches that turn as it is created (see catchTurn). So the hold + // below finds it, however late a loaded machine's round trips are. A wait + // from the harness found the 0.3 s turn already ended. + const caught = catchTurn(meridiem); + await turnHourTo12(driver, hour); + await caught; + // Sampled in the page: the turn's animations seek together to each time, + // and the strip's presented offset is read there. + const ys = await meridiem.evaluate( + (column, times) => { + const strip = column.querySelector('[data-wheel-strip]'); + const animations = column.getAnimations({subtree: true}); + if (strip == null || animations.length === 0) { + throw new Error('no turn to sample'); + } + return times.map(t => { + for (const animation of animations) { + animation.currentTime = t; + } + return { + t, + value: strip.getBoundingClientRect().top, + }; + }); + }, + timeline(TURN_MS, 1000 / 60), + ); + const start = ys[0].value; + const end = ys[ys.length - 1].value; + expect(Math.abs(end - start)).toBeCloseTo(WHEEL_ROW_HEIGHT, 0); + const progress = ys.map(({t, value}) => ({ + t, + value: (value - start) / (end - start), + })); + const fit = compareCurve(progress, spin, 0.02); + expect(fit.pass, JSON.stringify(fit.worst)).toBe(true); + // The held end timer finishes the turn, as it would have at 0.3 s. + await thawTimers(page); + await waitForRest(meridiem); + + await expect.poll(async () => restingLabel(hour)).toBe('12'); + await expect.poll(async () => restingLabel(meridiem)).toBe('PM'); + await expect(page.getByRole('dialog').first()).toBeVisible(); +}); + +/** + * The vertical centre of the text in a column's box, per frame. The labels on + * the drum and in the band move with the column. So this centre moves as the + * column turns. + */ +async function textCentres( + page: Page, + frames: ReadonlyArray, + rect: {x: number; y: number; width: number; height: number}, +): Promise { + const scratch = await page.context().newPage(); + try { + const out: TrackedFrame[] = []; + for (let i = 0; i < frames.length; i += 12) { + const batch = frames.slice(i, i + 12); + const centres = await scratch.evaluate( + async ({items, box}) => { + const results: (number | null)[] = []; + for (const item of items) { + const blob = await ( + await fetch(`data:image/${item.format};base64,${item.data}`) + ).blob(); + const bitmap = await createImageBitmap(blob); + const scale = bitmap.width / item.viewportWidth; + const canvas = new OffscreenCanvas(bitmap.width, bitmap.height); + const context = canvas.getContext('2d'); + if (context == null) { + throw new Error('no 2d context'); + } + context.drawImage(bitmap, 0, 0); + const x = Math.round(box.x * scale); + const y = Math.round(box.y * scale); + const w = Math.round(box.width * scale); + const h = Math.round(box.height * scale); + const {data} = context.getImageData(x, y, w, h); + let weight = 0; + let sum = 0; + for (let row = 0; row < h; row += 1) { + for (let col = 0; col < w; col += 1) { + const o = (row * w + col) * 4; + // Ink: how far below white, summed over the channels. + const ink = Math.max( + 0, + 600 - data[o] - data[o + 1] - data[o + 2], + ); + weight += ink; + sum += ink * row; + } + } + results.push(weight === 0 ? null : sum / weight / scale); + } + return results; + }, + { + items: batch.map(f => ({ + data: f.data, + format: f.format, + viewportWidth: f.viewportWidth, + })), + box: rect, + }, + ); + centres.forEach((centre, k) => + out.push({ + t: batch[k].t, + box: + centre == null ? null : {x: 0, y: centre * 10, width: 0, height: 0}, + pixels: 1, + }), + ); + } + return out; + } finally { + await scratch.close(); + } +} + +test('the AM/PM turn keeps advancing every frame through a blocked main thread', async ({ + page, + browserName, +}, testInfo) => { + test.skip( + browserName === 'webkit', + "WebKit's screencast clock is not the page's (frames arrive ~100 ms off), so a 0.3 s turn cannot be placed inside the block; Mobile Safari on the iOS simulator is this proof's WebKit evidence", + ); + const {driver, hour, meridiem} = await openWheels( + page, + 'core-timeinput--bottom-sheet-wheels', + ); + const rect = await meridiem.boundingBox(); + if (rect == null) { + throw new Error('no AM/PM column'); + } + const cast = await startScreencast(page); + await page.waitForTimeout(300); + await turnOneRowDown(driver, hour); + // The page blocks itself once the AM/PM column has turned for 32 ms. + const busy = await blockMainThread(page, 600, { + during: stripOf(meridiem), + minProgressMs: 32, + }); + await page.waitForTimeout(500); + const tracked = await textCentres(page, await cast.stop(), rect); + // Judged until the turn's end (the text centre in tenths of a px). + const spanned = {...busy, to: Math.min(busy.to, busy.from + TURN_MS - 32)}; + const proof = busyWindowProof(tracked, spanned, { + axis: 'y', + settledWithin: 5, + }); + await writeEvidence( + 'busy-main-thread/timewheels-meridiem-turn', + { + [`${testInfo.project.name}.json`]: JSON.stringify( + { + busy, + proof, + frames: tracked.map(f => ({ + t: +(f.t - busy.from).toFixed(1), + y: f.box == null ? null : +(f.box.y / 10).toFixed(2), + })), + }, + null, + 1, + ), + }, + testInfo, + ); + testInfo.annotations.push({ + type: 'busy-main-thread', + description: proof.summary, + }); + expect(proof.verdict.failures, proof.summary).toEqual([]); + await expect.poll(async () => restingLabel(meridiem)).toBe('PM'); +}); + +test('Reduced Motion: the AM/PM column cross-fades onto PM instead of turning', async ({ + page, +}) => { + // design:reduced-motion DR2: nothing travels. The column's drawing dips in + // opacity for 200 ms or less. Its rows hold where they are until the dip's + // middle. Then they step onto their rows: the wheel's landing. + await page.emulateMedia({reducedMotion: 'reduce'}); + const {driver, hour, meridiem} = await openWheels( + page, + 'core-timeinput--bottom-sheet-wheels', + ); + // Caught as it is created (catchTurn), because the cross-fade is 200 ms or + // less. Read after the hour came to rest, it had ended on a loaded machine. + await installTimerGate(page); + const caught = catchTurn(meridiem); + await turnHourTo12(driver, hour); + await caught; + const animations = await meridiem.evaluate(root => + root.getAnimations({subtree: true}).map(animation => { + const effect = animation.effect as KeyframeEffect; + // The animator holds a curve's end state in a long tail after the + // curve, so the harness reads where the curve itself ends. + const curveEnd = ( + window as unknown as {__harnessCurveEnd?: (a: Animation) => number} + ).__harnessCurveEnd; + return { + curveMs: + curveEnd == null + ? Number(effect.getTiming().duration) + : curveEnd(animation), + keyframes: effect.getKeyframes().map(frame => ({ + offset: frame.computedOffset, + // The animator moves the strip with `translate`; either property + // is a move. + motion: + frame.translate != null + ? String(frame.translate) + : frame.transform != null + ? String(frame.transform) + : null, + properties: Object.keys(frame).filter( + key => + !['offset', 'easing', 'composite', 'computedOffset'].includes( + key, + ), + ), + })), + duration: Number(effect.getTiming().duration), + }; + }), + ); + const fades = animations.filter(animation => + animation.keyframes.every( + frame => + !frame.properties.includes('transform') && + !frame.properties.includes('translate'), + ), + ); + expect(fades.length).toBeGreaterThan(0); + for (const fade of fades) { + expect([ + ...new Set(fade.keyframes.flatMap(frame => frame.properties)), + ]).toEqual(['opacity']); + expect(fade.curveMs).toBeLessThanOrEqual(200); + } + const fadeMs = Math.max(...fades.map(fade => fade.curveMs)); + for (const landing of animations.filter( + animation => !fades.includes(animation), + )) { + // The origin held, then the destination, stepping at the dip's middle. + expect(landing.keyframes).toHaveLength(4); + const [origin, held, landed, end] = landing.keyframes; + expect(held.motion).toBe(origin.motion); + expect(landed.offset).toBe(held.offset); + expect(end.motion).toBe(landed.motion); + expect(held.offset * landing.duration).toBeCloseTo(fadeMs / 2, 0); + } + // The held end timer finishes the turn, as it would have. + await thawTimers(page); + await expect.poll(async () => restingLabel(meridiem)).toBe('PM'); +}); + +/** + * A finger lands on the AM/PM column early in its 0.3 s turn. The column stops + * where it was at the touch's time. The lift rests it on the nearer row. + * + * Chromium's injected touches carry the timestamps they are given. The Wheel + * stops a turn where it was at the touch's time. So the touch lands 100 ms into + * the turn, however late a loaded machine delivers it. That is before the + * turn's middle, so AM is the nearer row. The gated timers hold from the turn's + * start until the touch is in. So the turn cannot end before the touch arrives. + * A busy device does the same: it holds a touch's event but keeps its time. + * Dispatched at the moment the harness saw the turn running instead, the touch + * landed past the turn's end on a loaded machine. + * + * WebKit's injected touches carry no timestamps: the page sees the real + * dispatch time. There the touch lands when the harness sends it, after the + * turn has run 20 ms. The lift rests on whichever row is nearer. Under a 3-CPU + * cap with 16 workers, a report-only profile, the press came after the turn + * ended in 2 of 10 runs. The hour's drag missed its row in more runs (see + * expectHourOn12). Both are limits of WebKit's real-time input. The required CI + * WebKit profile and Chromium pass. + */ +test('a finger on the AM/PM column mid-turn stops it; the lift rests it on the nearest row', async ({ + page, + browserName, +}) => { + const {driver, hour, meridiem} = await openWheels( + page, + 'core-timeinput--bottom-sheet-wheels', + ); + const field = page.locator('input').first(); + const offsetOf = async () => + stripOf(meridiem).evaluate(element => element.getBoundingClientRect().top); + // Where the strip rests on AM, and on PM one row on. + const restAM = await offsetOf(); + const restPM = restAM - WHEEL_ROW_HEIGHT; + // Read before the turn: nothing about the column's box moves with it. + const box = await meridiem.boundingBox(); + if (box == null) { + throw new Error('no AM/PM column'); + } + const at = {x: box.x + box.width / 2, y: box.y + box.height / 2}; + // The strip's offset on each of the page's own frames, for 200 ms after a + // touch arrives on the AM/PM column. The hour's drag does not count, and a + // held timer gate never holds these frames. + const caught = meridiem.evaluate( + async column => + new Promise(resolve => { + const element = column.querySelector('[data-wheel-strip]'); + if (element == null) { + throw new Error('no AM/PM strip'); + } + const frame = + ( + window as unknown as { + __harnessTimerGate?: {frame: typeof requestAnimationFrame}; + } + ).__harnessTimerGate?.frame ?? requestAnimationFrame; + column.addEventListener( + 'touchstart', + () => { + const ys: number[] = []; + const t0 = performance.now(); + const tick = () => { + ys.push(element.getBoundingClientRect().top); + if (performance.now() - t0 < 200) { + frame(tick); + } else { + resolve(ys); + } + }; + frame(tick); + }, + {capture: true, once: true}, + ); + }), + ); + if (browserName === 'chromium') { + await installTimerGate(page); + // Armed before the drag. As the turn is created, the page holds the gated + // timers, the turn's end among them. So the turn cannot end before the + // touch is in. The page reports the turn's start on the epoch clock of the + // touch's timestamp. + const turnStart = stripOf(meridiem).evaluate( + async element => + new Promise(resolve => { + const gate = ( + window as unknown as { + __harnessTimerGate: { + frozen: boolean; + frame?: typeof requestAnimationFrame; + }; + } + ).__harnessTimerGate; + const frame = gate.frame ?? requestAnimationFrame; + const observer = new MutationObserver(() => { + if (element.getAnimations().length === 0) { + return; + } + observer.disconnect(); + gate.frozen = true; + const check = () => { + const animation = element + .getAnimations() + .find(candidate => candidate.startTime != null); + if (animation == null) { + frame(check); + return; + } + resolve(performance.timeOrigin + Number(animation.startTime)); + }; + check(); + }); + observer.observe(element, { + attributes: true, + attributeFilter: ['style'], + }); + }), + ); + await turnHourTo12(driver, hour); + const startedAt = await turnStart; + const cdp = await page.context().newCDPSession(page); + const points = [ + {x: at.x, y: at.y, id: 1, radiusX: 1, radiusY: 1, force: 1}, + ]; + await cdp.send('Input.dispatchTouchEvent', { + type: 'touchStart', + touchPoints: points, + timestamp: (startedAt + 100) / 1000, + }); + await thawTimers(page); + // Held in place for 250 ms, then the lift. + await page.waitForTimeout(250); + await cdp.send('Input.dispatchTouchEvent', { + type: 'touchEnd', + touchPoints: [], + timestamp: Date.now() / 1000, + }); + await cdp.detach(); + } else { + await logHourTouches(hour); + // Early in the turn, while AM is still the nearer row; watched from + // before the drag. + const running = stripOf(meridiem).evaluate( + async element => + new Promise(resolve => { + const check = () => { + const isRunning = element + .getAnimations() + .some(a => Number(a.currentTime ?? 0) >= 20); + if (isRunning) { + resolve(); + } else { + requestAnimationFrame(check); + } + }; + check(); + }), + ); + await turnOneRowDown(driver, hour); + // The turn starts once the hour rests on 12; a drag that left it on + // another row fails at once (expectHourOn12). + await Promise.race([ + running, + expectHourOn12(hour).then(async () => new Promise(() => {})), + ]); + // A press held in place for 250 ms, then the lift. + await driver.play(press(at, {holdMs: 250})); + } + const held = await caught; + // Stopped where the finger caught it: still at most 1 px of drift. + const tail = held.slice(Math.floor(held.length / 2)); + expect(Math.max(...tail) - Math.min(...tail)).toBeLessThan(1); + // Caught mid-turn, strictly between the two rows. + const caughtAt = tail[tail.length - 1]; + const context = JSON.stringify({restAM, restPM, held}); + expect(caughtAt, context).toBeLessThan(restAM - 0.1); + expect(caughtAt, context).toBeGreaterThan(restPM + 0.1); + const nearer = + Math.abs(caughtAt - restAM) <= Math.abs(caughtAt - restPM) ? 'AM' : 'PM'; + if (browserName === 'chromium') { + // 100 ms into the turn, before its middle. + expect(nearer, context).toBe('AM'); + } + await waitForRest(meridiem); + await expect.poll(async () => restingLabel(meridiem)).toBe(nearer); + await expect(field).toHaveValue(`12:58 ${nearer}`); +}); + +test.describe('with a mouse', () => { + test.use({hasTouch: false, isMobile: false}); + + test('with a mouse each column turns on its own: 11 to 12 stays AM', async ({ + page, + }) => { + await openStory(page, storybook(), 'core-timeinput--bottom-sheet-wheels'); + expect( + await page.evaluate(() => matchMedia('(pointer: coarse)').matches), + ).toBe(false); + await page + .getByRole('button', {name: /^Open /}) + .first() + .click(); + const hour = page.getByRole('listbox', {name: 'Hour'}); + await expect(hour).toBeVisible(); + // In time order no AM hour follows 11 AM, so a click turns the column. + await hour.getByRole('option', {name: '12'}).click(); + await expect(page.locator('input').first()).toHaveValue('12:58 AM'); + expect(await restingLabel(page.getByRole('listbox', {name: 'AM/PM'}))).toBe( + 'AM', + ); + }); +}); + +test( + 'storyboard: the AM/PM column turns after the hour', + {tag: '@storyboard'}, + async ({page}, testInfo) => { + const {driver, sheet, hour, meridiem} = await openWheels( + page, + 'core-timeinput--bottom-sheet-wheels', + ); + // Caught as it is created (catchTurn), so a late harness still films the + // turn from its start. Held after waitForAnimation instead, the 0.3 s turn + // had ended on a loaded machine. + await installTimerGate(page); + const caught = catchTurn(meridiem); + await turnHourTo12(driver, hour); + await caught; + const clip = (await sheet.boundingBox()) ?? undefined; + const storyboard = new Storyboard(page, { + name: 'timewheels-meridiem-follows-hour', + clip, + columns: 6, + cellScale: 0.4, + }); + for (const t of timeline(TURN_MS, 1000 / 30)) { + const y = await meridiem.evaluate((column, time) => { + for (const animation of column.getAnimations({subtree: true})) { + animation.currentTime = time; + } + const strip = column.querySelector('[data-wheel-strip]'); + // The animator writes the strip's `translate`, which `transform` + // does not report: its drawn top, from the box. + return strip == null + ? NaN + : Number(strip.getBoundingClientRect().top.toFixed(2)); + }, t); + await storyboard.capture(`t=${+t.toFixed(1)} ms`, t, {y}); + } + await storyboard.write(testInfo); + // The held end timer finishes the turn. + await thawTimers(page); + }, +); diff --git a/packages/core/src/TimeInput/timeWheelRules.test.ts b/packages/core/src/TimeInput/timeWheelRules.test.ts new file mode 100644 index 0000000000000..112f0e994a26d --- /dev/null +++ b/packages/core/src/TimeInput/timeWheelRules.test.ts @@ -0,0 +1,315 @@ +// Copyright (c) Meta Platforms, Inc. and affiliates. + +/** + * @file timeWheelRules.test.ts + * @input vitest, the time wheels' pure rules + * @output Checks UIDatePicker's time-wheel rules as timeWheelRules.ts encodes + * them on columns that do not loop: the hour column's turn across + * 11 ↔ 12, the bounds, and which columns turn with a change + * @position Testing; the component around these rules is TimeWheels.test.tsx + */ + +import {describe, expect, it} from 'vitest'; +import { + columnsToTurn, + displayedTime, + restingTime, + hour12From24, + hour24From12, + hourAfterTurn, + hourRows, + hourRowsInHalf, + meridiemRows, + minuteRows, + secondRows, + turnColumn, + wheelBounds, + type TimeBounds, + type TimeParts, +} from './timeWheelRules'; +import type {ISOTimeString} from '../utils/timeParser'; + +const at = (hour: number, minute: number, second = 0): TimeParts => ({ + hour, + minute, + second, +}); +const UNBOUNDED: TimeBounds = {min: null, max: null}; +const NINE_TO_FIVE: TimeBounds = {min: 9 * 3600, max: 17 * 3600}; + +describe('displayedTime', () => { + it('keeps the seconds when the picker shows them, and drops them when it does not', () => { + expect(displayedTime(at(10, 45, 30), true)).toEqual(at(10, 45, 30)); + expect(displayedTime(at(10, 45, 30), false)).toEqual(at(10, 45)); + }); + + it('shows a time outside the bounds as it is: opening never moves it', () => { + expect(displayedTime(at(8, 50), false)).toEqual(at(8, 50)); + }); +}); + +describe('the 12-hour clock', () => { + it('converts 12 AM, 12 PM and 1 PM both ways', () => { + expect([0, 12, 13].map(hour12From24)).toEqual([12, 12, 1]); + expect(hour24From12(12, 0)).toBe(0); + expect(hour24From12(12, 1)).toBe(12); + expect(hour24From12(1, 1)).toBe(13); + }); +}); + +describe('the hour column', () => { + it('turns AM to PM across 11 → 12 and back', () => { + // UIKit: 11:58 AM, hour +1 → 12:58 PM. + expect(hourAfterTurn(11, 12, '12h')).toBe(12); + expect(hourAfterTurn(12, 11, '12h')).toBe(11); + expect(hourAfterTurn(23, 12, '12h')).toBe(0); + expect(hourAfterTurn(0, 11, '12h')).toBe(23); + }); + + it('keeps the half of the day for a move among 1 to 11', () => { + expect(hourAfterTurn(13, 5, '12h')).toBe(17); + expect(hourAfterTurn(13, 9, '12h')).toBe(21); + expect(hourAfterTurn(10, 8, '12h')).toBe(8); + expect(hourAfterTurn(11, 3, '12h')).toBe(3); + expect(hourAfterTurn(15, 11, '12h')).toBe(23); + }); + + it('counts 12 as next to 1: a move between 12 and 1 to 6 keeps the half of the day', () => { + expect(hourAfterTurn(12, 1, '12h')).toBe(13); + expect(hourAfterTurn(13, 12, '12h')).toBe(12); + expect(hourAfterTurn(12, 6, '12h')).toBe(18); + expect(hourAfterTurn(18, 12, '12h')).toBe(12); + expect(hourAfterTurn(0, 1, '12h')).toBe(1); + expect(hourAfterTurn(1, 12, '12h')).toBe(0); + }); + + it('flips the half of the day for a move between 12 and 7 to 11, which passes between 11 and 12', () => { + expect(hourAfterTurn(12, 7, '12h')).toBe(7); + expect(hourAfterTurn(19, 12, '12h')).toBe(0); + expect(hourAfterTurn(0, 9, '12h')).toBe(21); + expect(hourAfterTurn(9, 12, '12h')).toBe(12); + }); + + it('is the hour itself in 24-hour time', () => { + expect(hourAfterTurn(11, 23, '24h')).toBe(23); + }); + + it('labels 12-hour rows 1 to 12 and disables the hours a turn would make outside the bounds', () => { + const rows = hourRows(11, '12h', NINE_TO_FIVE); + expect(rows.map(row => row.label)).toEqual([ + '1', + '2', + '3', + '4', + '5', + '6', + '7', + '8', + '9', + '10', + '11', + '12', + ]); + // From 11 AM: 1 to 11 stay AM (1 to 8 AM are outside), and 12 is noon. + expect(rows.filter(row => row.isDisabled).map(row => row.label)).toEqual([ + '1', + '2', + '3', + '4', + '5', + '6', + '7', + '8', + ]); + }); + + it('labels 24-hour rows 00 to 23', () => { + const rows = hourRows(11, '24h', NINE_TO_FIVE); + expect(rows[0].label).toBe('00'); + expect(rows[23].label).toBe('23'); + expect(rows[8].isDisabled).toBe(true); + expect(rows[9].isDisabled).toBe(false); + expect(rows[17].isDisabled).toBe(false); + expect(rows[18].isDisabled).toBe(true); + }); +}); + +describe('the mouse columns', () => { + it('keep a 12-hour row in the half of the day the time is in', () => { + // From 10 AM, rows 1 to 8 and 12 stand for AM hours outside 9:00–17:00. + const morning = hourRowsInHalf(10, '12h', NINE_TO_FIVE); + expect( + morning.filter(row => !row.isDisabled).map(row => row.label), + ).toEqual(['9', '10', '11']); + // From 2 PM, rows 12 and 1 to 5 stand for PM hours inside them. + const afternoon = hourRowsInHalf(14, '12h', NINE_TO_FIVE); + expect( + afternoon.filter(row => !row.isDisabled).map(row => row.label), + ).toEqual(['1', '2', '3', '4', '5', '12']); + }); + + it('order 12 PM before 1 PM, so keys follow the full time', () => { + const afternoon = hourRowsInHalf(17, '12h', NINE_TO_FIVE); + const order = (label: string) => + afternoon.find(row => row.label === label)?.order; + expect(order('12')).toBe(12); + expect(order('1')).toBe(13); + expect(order('11')).toBe(23); + const morning = hourRowsInHalf(9, '12h', NINE_TO_FIVE); + expect(morning.find(row => row.label === '12')?.order).toBe(0); + // Under a finger each row holds the hour a turn onto it makes. + const fromNoon = hourRows(12, '12h', NINE_TO_FIVE); + expect(fromNoon.find(row => row.label === '11')?.order).toBe(11); + expect(fromNoon.find(row => row.label === '1')?.order).toBe(13); + }); + + it('match the finger rows in 24-hour time', () => { + expect(hourRowsInHalf(11, '24h', NINE_TO_FIVE)).toEqual( + hourRows(11, '24h', NINE_TO_FIVE), + ); + }); + + it('read the bounds from the field’s min and max', () => { + expect( + wheelBounds('09:00' as ISOTimeString, '17:00:30' as ISOTimeString), + ).toEqual({ + min: 9 * 3600, + max: 17 * 3600 + 30, + }); + expect(wheelBounds(undefined, undefined)).toEqual(UNBOUNDED); + }); + + it('disable the seconds and the halves of the day outside the bounds', () => { + const seconds = secondRows( + 17, + 0, + wheelBounds('09:00' as ISOTimeString, '17:00:30' as ISOTimeString), + ); + expect(seconds[30].isDisabled).toBe(false); + expect(seconds[31].isDisabled).toBe(true); + const halves = meridiemRows( + {am: 'AM', pm: 'PM'}, + wheelBounds('13:00' as ISOTimeString, undefined), + ); + expect(halves.map(row => row.isDisabled)).toEqual([true, false]); + }); +}); + +describe('the minute column', () => { + it('shows every minute', () => { + const rows = minuteRows(10, false, UNBOUNDED); + expect(rows).toHaveLength(60); + expect(rows[0].label).toBe('00'); + expect(rows[59].label).toBe('59'); + }); + + it('changes only the minutes', () => { + expect(turnColumn(at(12, 58), 'minute', 2, '12h')).toEqual(at(12, 2)); + }); +}); + +describe('turnColumn', () => { + it('moves the hour by twelve for an AM/PM turn', () => { + expect(turnColumn(at(11, 30), 'meridiem', 1, '12h')).toEqual(at(23, 30)); + expect(turnColumn(at(23, 30), 'meridiem', 0, '12h')).toEqual(at(11, 30)); + expect(turnColumn(at(12, 0), 'meridiem', 0, '12h')).toEqual(at(0, 0)); + }); +}); + +describe('restingTime (restPastBound)', () => { + it('keeps a time inside the bounds', () => { + expect(restingTime(at(12, 30), false, NINE_TO_FIVE)).toEqual(at(12, 30)); + }); + + it('goes on past a bound to the bound', () => { + expect(restingTime(at(7, 0), false, NINE_TO_FIVE)).toEqual(at(9, 0)); + expect(restingTime(at(18, 15), false, NINE_TO_FIVE)).toEqual(at(17, 0)); + }); + + it('keeps a bound with seconds when the picker shows seconds, and the nearest whole minute inside it when it does not', () => { + const min = {min: 9 * 3600 + 30, max: null}; + expect(restingTime(at(8, 0), true, min)).toEqual(at(9, 0, 30)); + expect(restingTime(at(8, 0), false, min)).toEqual(at(9, 1)); + const max = {min: null, max: 16 * 3600 + 55 * 60 + 30}; + expect(restingTime(at(17, 30), false, max)).toEqual(at(16, 55)); + }); + + it('drops seconds the picker does not show before it clamps', () => { + const min = {min: 10 * 3600 + 30, max: null}; + expect(restingTime(at(10, 0, 45), false, min)).toEqual(at(10, 1)); + expect(restingTime(at(12, 30, 45), false, NINE_TO_FIVE)).toEqual( + at(12, 30), + ); + }); +}); + +describe('columnsToTurn', () => { + const twelveHour = {hourFormat: '12h', hasSeconds: false} as const; + + it('turns the AM/PM column after the hour crossed 11 → 12', () => { + const from = at(11, 58); + const committed = turnColumn(from, 'hour', 12, '12h'); + expect(columnsToTurn(from, 'hour', 12, committed, twelveHour)).toEqual([ + {column: 'meridiem', value: 1}, + ]); + }); + + it('turns nothing after a rest from 12 to 1, which keeps PM', () => { + const from = at(12, 58); + const committed = turnColumn(from, 'hour', 1, '12h'); + expect(committed).toEqual(at(13, 58)); + expect(columnsToTurn(from, 'hour', 1, committed, twelveHour)).toEqual([]); + }); + + it('turns nothing after a rest from 1 back to 12, which keeps PM', () => { + const from = at(13, 58); + const committed = turnColumn(from, 'hour', 12, '12h'); + expect(committed).toEqual(at(12, 58)); + expect(columnsToTurn(from, 'hour', 12, committed, twelveHour)).toEqual([]); + }); + + it('turns nothing for an hour that kept its half of the day', () => { + const from = at(13, 58); + const committed = turnColumn(from, 'hour', 2, '12h'); + expect(committed).toEqual(at(14, 58)); + expect(columnsToTurn(from, 'hour', 2, committed, twelveHour)).toEqual([]); + }); + + it('leaves the hour where it is for an AM/PM turn', () => { + const from = at(11, 30); + const committed = turnColumn(from, 'meridiem', 1, '12h'); + expect(columnsToTurn(from, 'meridiem', 1, committed, twelveHour)).toEqual( + [], + ); + }); + + it('turns every column whose row a bound changed', () => { + // 10:15 with the hour turned to 9 and a 9:30 minimum: the minutes turn to + // 30. + const bounds = {min: 9 * 3600 + 30 * 60, max: null}; + const from = at(10, 15); + const committed = restingTime( + turnColumn(from, 'hour', 9, '12h'), + true, + bounds, + ); + expect(committed).toEqual(at(9, 30)); + expect(columnsToTurn(from, 'hour', 9, committed, twelveHour)).toEqual([ + {column: 'minute', value: 30}, + ]); + }); + + it('turns the hour and minutes onto the maximum after an AM/PM turn past it', () => { + const from = at(11, 30); + const committed = restingTime( + turnColumn(from, 'meridiem', 1, '12h'), + true, + NINE_TO_FIVE, + ); + expect(committed).toEqual(at(17, 0)); + expect(columnsToTurn(from, 'meridiem', 1, committed, twelveHour)).toEqual([ + {column: 'hour', value: 5}, + {column: 'minute', value: 0}, + ]); + }); +}); diff --git a/packages/core/src/TimeInput/timeWheelRules.ts b/packages/core/src/TimeInput/timeWheelRules.ts new file mode 100644 index 0000000000000..90ff23df4d776 --- /dev/null +++ b/packages/core/src/TimeInput/timeWheelRules.ts @@ -0,0 +1,352 @@ +// Copyright (c) Meta Platforms, Inc. and affiliates. + +/** + * @file timeWheelRules.ts + * @input A time of day, the hour format and the bounds + * @output Pure rules of UIDatePicker's time wheels: the columns' rows, the + * time a turned column makes, and which other columns turn with it + * @position Internal helper of the TimeInput and DateTimeInput sheets: the + * rows of both their finger and their mouse wheels + * + * The columns do not loop. Each rule follows a leaf of motion/uikit/ + * datePicker.ts `wheels`. Pure functions keep the rules testable without a + * layout engine. + * + * SYNC: When modified, update timeWheelRules.test.ts and TimeWheels.tsx. + */ + +import { + clampTime, + formatISOTime, + parseISOTime, + type ISOTimeString, +} from '../utils/timeParser'; + +/** A time of day, 24-hour. */ +export interface TimeParts { + hour: number; + minute: number; + second: number; +} + +/** A time wheel column. */ +export type TimeColumn = 'hour' | 'minute' | 'second' | 'meridiem'; + +/** One row of a column: the value it stands for and its label. */ +export interface TimeRow { + value: number; + label: string; + isDisabled: boolean; + /** + * Where the row falls when a key steps the column. An hour row holds the hour + * it stands for, so a key follows the full time: 12 PM comes before 1 PM. + */ + order?: number; +} + +/** Inclusive bounds in seconds since midnight; `null` is unbounded. */ +export interface TimeBounds { + min: number | null; + max: number | null; +} + +const SECONDS_PER_DAY = 24 * 3600; + +function secondsOfISO(time: ISOTimeString | undefined): number | null { + if (time == null) { + return null; + } + const parsed = parseISOTime(time); + return parsed == null + ? null + : parsed.hour * 3600 + parsed.minute * 60 + parsed.second; +} + +/** The bounds of a field's `min` and `max` times. */ +export function wheelBounds( + min: ISOTimeString | undefined, + max: ISOTimeString | undefined, +): TimeBounds { + return {min: secondsOfISO(min), max: secondsOfISO(max)}; +} + +/** Whether the hour falls in the PM half (1) or the AM half (0). */ +export function meridiemOf(hour: number): 0 | 1 { + return hour < 12 ? 0 : 1; +} + +/** The 12-hour clock's label for a 24-hour hour: 0 → 12, 13 → 1. */ +export function hour12From24(hour: number): number { + const h = hour % 12; + return h === 0 ? 12 : h; +} + +/** The 24-hour hour for a 12-hour hour in a half of the day: 12 AM → 0. */ +export function hour24From12(hour: number, meridiem: number): number { + return (hour % 12) + (meridiem === 1 ? 12 : 0); +} + +function partsOf(seconds: number): TimeParts { + const s = ((seconds % SECONDS_PER_DAY) + SECONDS_PER_DAY) % SECONDS_PER_DAY; + return { + hour: Math.floor(s / 3600), + minute: Math.floor((s % 3600) / 60), + second: s % 60, + }; +} + +/** Whether [start, end] (seconds) overlaps the bounds. */ +function overlaps(start: number, end: number, bounds: TimeBounds): boolean { + return ( + (bounds.min == null || end >= bounds.min) && + (bounds.max == null || start <= bounds.max) + ); +} + +/** + * The time the wheels show for `time`: its seconds kept when the picker has a + * seconds column and dropped when it has none. A time outside the bounds is + * shown as it is, on its disabled rows: opening the sheet never moves an + * untouched value. + */ +export function displayedTime(time: TimeParts, hasSeconds: boolean): TimeParts { + return {...time, second: hasSeconds ? time.second : 0}; +} + +/** + * The time a column's rest commits when it would make `time`: the nearest + * time inside the bounds that the columns have a row for. Past a bound, that + * is the bound itself, or, with no seconds column, the nearest whole minute + * inside it (a 16:55:30 maximum: 16:55). Inside the bounds, `time` itself. + */ +export function restingTime( + time: TimeParts, + hasSeconds: boolean, + bounds: TimeBounds, +): TimeParts { + const boundAt = (seconds: number | null) => + seconds == null ? undefined : formatISOTime(partsOf(seconds), true); + const resting = clampTime( + formatISOTime(time, hasSeconds), + boundAt(bounds.min), + boundAt(bounds.max), + hasSeconds, + ); + return parseISOTime(resting) ?? time; +} + +/** + * The hour the hour column makes when it comes to rest on `row` from the row + * that showed `from` (24-hour). In 24-hour time the row is the hour. In 12-hour + * time the half of the day changes only when the move passes between 11 and 12. + * The column (1 … 12) does not loop, so 12 counts as next to 1. A move between + * 12 and 1 to 6 keeps the half of the day. A move between 12 and 7 to 11 + * changes it. + * + * @example + * ``` + * hourAfterTurn(11, 12, '12h'); // 12: 11 AM → 12 PM + * hourAfterTurn(12, 1, '12h'); // 13: 12 PM → 1 PM + * hourAfterTurn(13, 9, '12h'); // 21: 1 PM → 9 PM + * ``` + */ +export function hourAfterTurn( + from: number, + row: number, + hourFormat: '12h' | '24h', +): number { + if (hourFormat === '24h') { + return row; + } + const shown = hour12From24(from); + if (row === shown) { + return from; + } + const half = meridiemOf(from); + const passes11And12 = + (shown === 12 && row >= 7) || (row === 12 && shown >= 7); + return hour24From12(row, passes11And12 ? 1 - half : half); +} + +function hourRowsFor( + hourFormat: '12h' | '24h', + hourOf: (row: number) => number, + bounds: TimeBounds, +): TimeRow[] { + const rows = + hourFormat === '24h' + ? Array.from({length: 24}, (_, hour) => hour) + : Array.from({length: 12}, (_, index) => index + 1); + return rows.map(row => { + const hour = hourOf(row); + return { + value: row, + label: hourFormat === '24h' ? String(row).padStart(2, '0') : String(row), + isDisabled: !overlaps(hour * 3600, hour * 3600 + 3599, bounds), + order: hour, + }; + }); +} + +/** + * The hour column under a finger. In 24-hour time its rows are 00 … 23. In + * 12-hour time they are 1 … 12, each row standing for the hour a turn onto it + * from `from` makes (`hourAfterTurn`). A row is disabled when no minute of that + * hour is inside the bounds. + */ +export function hourRows( + from: number, + hourFormat: '12h' | '24h', + bounds: TimeBounds, +): TimeRow[] { + return hourRowsFor( + hourFormat, + row => hourAfterTurn(from, row, hourFormat), + bounds, + ); +} + +/** + * The hour column under a mouse, whose columns turn one at a time. A 12-hour + * row stands for its hour in the half of the day that `from` is in. + */ +export function hourRowsInHalf( + from: number, + hourFormat: '12h' | '24h', + bounds: TimeBounds, +): TimeRow[] { + const half = meridiemOf(from); + return hourRowsFor( + hourFormat, + row => (hourFormat === '24h' ? row : hour24From12(row, half)), + bounds, + ); +} + +/** + * The minute column for `hour`: every minute. A row is disabled when it is + * outside the bounds (its whole minute, when the picker shows seconds). + */ +export function minuteRows( + hour: number, + hasSeconds: boolean, + bounds: TimeBounds, +): TimeRow[] { + return Array.from({length: 60}, (_, minute): TimeRow => { + const start = hour * 3600 + minute * 60; + return { + value: minute, + label: String(minute).padStart(2, '0'), + isDisabled: !overlaps(start, start + (hasSeconds ? 59 : 0), bounds), + }; + }); +} + +/** The second column for `hour`:`minute`. */ +export function secondRows( + hour: number, + minute: number, + bounds: TimeBounds, +): TimeRow[] { + return Array.from({length: 60}, (_, second): TimeRow => { + const at = hour * 3600 + minute * 60 + second; + return { + value: second, + label: String(second).padStart(2, '0'), + isDisabled: !overlaps(at, at, bounds), + }; + }); +} + +/** The AM/PM column: a half is disabled when none of its hours is in bounds. */ +export function meridiemRows( + labels: {am: string; pm: string}, + bounds: TimeBounds, +): TimeRow[] { + return [ + { + value: 0, + label: labels.am, + isDisabled: !overlaps(0, 12 * 3600 - 1, bounds), + }, + { + value: 1, + label: labels.pm, + isDisabled: !overlaps(12 * 3600, SECONDS_PER_DAY - 1, bounds), + }, + ]; +} + +/** + * The time made by turning `column` to `value` (its row's value) from `from` + * (the time the wheels show). Only that column changes, and the AM/PM column + * moves the hour by twelve. + */ +export function turnColumn( + from: TimeParts, + column: TimeColumn, + value: number, + hourFormat: '12h' | '24h', +): TimeParts { + switch (column) { + case 'hour': + return {...from, hour: hourAfterTurn(from.hour, value, hourFormat)}; + case 'minute': + return {...from, minute: value}; + case 'second': + return {...from, second: value}; + case 'meridiem': + return {...from, hour: hour24From12(hour12From24(from.hour), value)}; + } +} + +/** What a column shows for a time: its row's value. */ +export function columnValue( + time: TimeParts, + column: TimeColumn, + hourFormat: '12h' | '24h', +): number { + switch (column) { + case 'hour': + return hourFormat === '24h' ? time.hour : hour12From24(time.hour); + case 'minute': + return time.minute; + case 'second': + return time.second; + case 'meridiem': + return meridiemOf(time.hour); + } +} + +/** + * The columns that must turn after `column` came to rest on `value`. That is + * every column whose row for the committed time differs from the row it shows + * now. The column that moved shows `value`; the others show `from`. An hour + * that crossed 11 ↔ 12 turns the AM/PM column; a time brought back onto a bound + * turns every column whose row changed. + */ +export function columnsToTurn( + from: TimeParts, + column: TimeColumn, + value: number, + committed: TimeParts, + options: {hourFormat: '12h' | '24h'; hasSeconds: boolean}, +): {column: TimeColumn; value: number}[] { + const columns: TimeColumn[] = ['hour', 'minute']; + if (options.hasSeconds) { + columns.push('second'); + } + if (options.hourFormat === '12h') { + columns.push('meridiem'); + } + const turns: {column: TimeColumn; value: number}[] = []; + for (const each of columns) { + const shown = + each === column ? value : columnValue(from, each, options.hourFormat); + const target = columnValue(committed, each, options.hourFormat); + if (shown !== target) { + turns.push({column: each, value: target}); + } + } + return turns; +} diff --git a/packages/core/src/utils/timeParser.test.ts b/packages/core/src/utils/timeParser.test.ts index 56cda4d3fa51f..3c586f83c98d8 100644 --- a/packages/core/src/utils/timeParser.test.ts +++ b/packages/core/src/utils/timeParser.test.ts @@ -19,6 +19,7 @@ import { compareTime, isTimeInRange, adjustTime, + clampTime, type ISOTimeString, } from './timeParser'; @@ -293,3 +294,24 @@ describe('adjustTime', () => { expect(adjustTime('00:30' as ISOTimeString, -60)).toBe('23:30'); }); }); + +describe('clampTime', () => { + const t = (value: string) => value as ISOTimeString; + + it('brings a time outside the bounds onto the bound', () => { + expect(clampTime(t('08:00'), t('09:00'))).toBe('09:00'); + expect(clampTime(t('18:00'), undefined, t('17:00'))).toBe('17:00'); + expect(clampTime(t('12:00'), t('09:00'), t('17:00'))).toBe('12:00'); + }); + + it('keeps a bound with seconds when the time shows seconds', () => { + expect(clampTime(t('08:00:00'), t('09:00:30'), undefined, true)).toBe( + '09:00:30', + ); + }); + + it('without seconds, gives the nearest whole minute inside a bound between minutes', () => { + expect(clampTime(t('08:00'), t('09:00:30'))).toBe('09:01'); + expect(clampTime(t('18:00'), undefined, t('17:00:30'))).toBe('17:00'); + }); +}); diff --git a/packages/core/src/utils/timeParser.ts b/packages/core/src/utils/timeParser.ts index b52f2ddc593f7..3a3fb0035193d 100644 --- a/packages/core/src/utils/timeParser.ts +++ b/packages/core/src/utils/timeParser.ts @@ -341,7 +341,8 @@ export function isTimeInRange( } /** - * Clamps a time to a min/max range. + * Clamps a time to a min/max range. Without seconds, a bound that falls + * between whole minutes gives the nearest whole minute inside the range. */ export function clampTime( time: ISOTimeString, @@ -357,19 +358,55 @@ export function clampTime( if (min && compareTime(time, min) < 0) { const parsedMin = parseISOTime(min); if (parsedMin) { - return formatISOTime(parsedMin, includeSeconds); + return formatISOTime( + onWholeMinute(parsedMin, 1, includeSeconds, max), + includeSeconds, + ); } } if (max && compareTime(time, max) > 0) { const parsedMax = parseISOTime(max); if (parsedMax) { - return formatISOTime(parsedMax, includeSeconds); + return formatISOTime( + onWholeMinute(parsedMax, -1, includeSeconds, min), + includeSeconds, + ); } } return time; } +/** + * A bound as a time without seconds reaches it: the next whole minute up from + * a minimum, or the whole minute down from a maximum. With no whole minute + * before the other bound, the bound stays as it is. + */ +function onWholeMinute( + bound: ParsedTime, + direction: 1 | -1, + includeSeconds: boolean, + other: ISOTimeString | undefined, +): ParsedTime { + if (includeSeconds || bound.second === 0) { + return bound; + } + const minutes = bound.hour * 60 + bound.minute + (direction === 1 ? 1 : 0); + if (minutes > 23 * 60 + 59) { + return bound; + } + const rounded = { + hour: Math.floor(minutes / 60), + minute: minutes % 60, + second: 0, + }; + const order = compareTime(formatISOTime(rounded, true), other); + if (other && (direction === 1 ? order > 0 : order < 0)) { + return bound; + } + return rounded; +} + /** * Adjusts a time by adding/subtracting minutes. * From e51ebcc9aeebe58d92c8060c99454beee6476780 Mon Sep 17 00:00:00 2001 From: Christopher Chedeau Date: Mon, 2 Nov 2026 21:48:21 -0800 Subject: [PATCH 3/3] spec(TimeInput): the AM/PM wheel follows the hour on the non-looping column MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit TimeInput FR7 records the rule the spec owners asked for at the B4 head. On the non-looping hour column, 12 counts as next to 1. Moving between 12 and 1–6 keeps the half of the day; any other move flips it when it passes between 11 and 12. It cites DateInput FR14's turn-onto rule, and the FR7 verification row names the tests. --- .../components/TimeInput/TimeInput.spec.md | 55 ++++++++++--------- 1 file changed, 28 insertions(+), 27 deletions(-) diff --git a/docs/specs/components/TimeInput/TimeInput.spec.md b/docs/specs/components/TimeInput/TimeInput.spec.md index 24c04c9017631..5c47ff1184cd0 100644 --- a/docs/specs/components/TimeInput/TimeInput.spec.md +++ b/docs/specs/components/TimeInput/TimeInput.spec.md @@ -109,20 +109,20 @@ Consumer migration instructions belong in consumer docs and release notes. ## 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). 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 `` 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 `` 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. Under a coarse primary pointer, in 12-hour time, the meridiem wheel MUST follow the hour wheel. On the non-looping hour column, 12 counts as next to 1. Moving between 12 and 1–6 keeps the half of the day; any other move flips it when it passes between 11 and 12, and the meridiem wheel turns onto the new half (`component:DateInput` FR14). Under a fine pointer each wheel changes only its own part of the time. `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; UIDatePicker on the iOS 26.2 simulator; `component:DateInput` FR14 | +| 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 @@ -203,19 +203,20 @@ anatomy-theming map. ## Verification map -| Contract | Verification | Representative states | Mutation or failure expectation | Audit section | -| -------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------- | -| FR1, ORD1 | `Presentation.test.tsx`; `NativeTimeInput.test.tsx` mode cases | Each value × pointer; deprecated mapping; both props | A substituted surface, a lost fallback, or `nativePicker` winning fails. Evidence gap: no real-browser check of the surface per pointer, as `spec:AST-043` asks. No test covers `presentation="popover"`. | `audit:TimeInput/behavior` | -| FR3–FR5, AR2 | `TimeInput.test.tsx` typing, blur, invalid, stepping, IME, and format cases, including "shows the catalog format hint for the resolved hour format" (24-hour) | 12h, 24h, seconds; invalid and out of range | A commit of an invalid time, a missing alert, or a step during IME fails. Evidence gap: no test asserts the 12-hour format hint, stepping from the current time when empty, or a step that would leave the range. No test steps while a draft is pending. | `audit:TimeInput/behavior` | -| FR6 | `NativeTimeInput.test.tsx` | Coarse default; range; pending Action; clear; clock button | An out-of-range native commit, or a reopened picker after clear, fails. | `audit:TimeInput/behavior` | -| FR7, ORD3, AR4 | `Presentation.test.tsx` sheet cases | Forced and adaptive sheet; disabled | A sheet field that is not inert while disabled fails. Evidence gap: no test opens the sheet by keyboard or asserts the clock button's tab order. No test disables an out-of-range wheel option or clamps a wheel change. | `audit:TimeInput/behavior` | -| FR8 | `TimeInput.test.tsx` clear cases; `NativeTimeInput.test.tsx` clear case | With value; empty | A clear on an empty field, or no `undefined`, fails. Evidence gap: no test asserts the focus move after clear on either surface, `changeAction` on clear, or a clear or Save press under reduced motion. | `audit:TimeInput/behavior` | -| FR9, AR3 | `TimeInput.test.tsx` disabled suites; `NativeTimeInput.test.tsx` and `Presentation.test.tsx` disabled cases; `InputGroup.test.tsx` disabled-propagation cases | Each surface; with reason; draft in progress | A lost tab stop, a value change, or a caller `onClick` fails. Evidence gap: no test asserts that caller `onKeyDown` and similar handlers still run while disabled (the FR9 gap). | `audit:TimeInput/accessibility` | -| FR10 | `TimeInput.test.tsx` InputGroup suite | Grouped with description and status | A duplicate label, a visible status icon, or a missed announcement fails. Evidence gap: no test groups the sheet surface. | `audit:TimeInput/accessibility` | -| FR11 | `TimeInput.fr10.test.tsx` | Each surface; handler composition | A base prop off the control, or a caller handler that cancels built-ins, fails. | `audit:TimeInput/api` | -| FR12 | `TimeInput.test.tsx` status and theme-state cases | Status; disabled | A missing state attribute fails. Evidence gap: no test asserts `data-size` or `data-status`. | `audit:TimeInput/theming` | -| FR2, ORD2 | Evidence gap: no TimeInput test of the pending Action's optimistic value | — | — | `audit:TimeInput/behavior` | -| AR1, PR1 | Covered by the FR10 and FR11 rows for naming. Evidence gap: no test asserts the single coarse-pointer query that decides the surface | — | — | `audit:TimeInput/behavior` | +| Contract | Verification | Representative states | Mutation or failure expectation | Audit section | +| -------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------- | +| FR1, ORD1 | `Presentation.test.tsx`; `NativeTimeInput.test.tsx` mode cases | Each value × pointer; deprecated mapping; both props | A substituted surface, a lost fallback, or `nativePicker` winning fails. Evidence gap: no real-browser check of the surface per pointer, as `spec:AST-043` asks. No test covers `presentation="popover"`. | `audit:TimeInput/behavior` | +| FR3–FR5, AR2 | `TimeInput.test.tsx` typing, blur, invalid, stepping, IME, and format cases, including "shows the catalog format hint for the resolved hour format" (24-hour) | 12h, 24h, seconds; invalid and out of range | A commit of an invalid time, a missing alert, or a step during IME fails. Evidence gap: no test asserts the 12-hour format hint, stepping from the current time when empty, or a step that would leave the range. No test steps while a draft is pending. | `audit:TimeInput/behavior` | +| FR6 | `NativeTimeInput.test.tsx` | Coarse default; range; pending Action; clear; clock button | An out-of-range native commit, or a reopened picker after clear, fails. | `audit:TimeInput/behavior` | +| FR7, ORD3, AR4 | `Presentation.test.tsx` sheet cases | Forced and adaptive sheet; disabled | A sheet field that is not inert while disabled fails. Evidence gap: no test opens the sheet by keyboard or asserts the clock button's tab order. No test disables an out-of-range wheel option or clamps a wheel change. | `audit:TimeInput/behavior` | +| FR7 | `TimeWheels.test.tsx` "turns AM to PM when the hour goes from 11 to 12, turning the AM/PM column", "turns PM back to AM from 12 to 11", "turns PM to AM from 11 PM to 12, midnight", "keeps the half of the day from 1 to 2", "keeps PM from 12 to 1", "keeps PM from 1 back to 12", "keeps PM from 1 forward to 9, a rest that does not pass between 11 and 12", "leaves the hour on its row when the AM/PM column turns"; `timeWheelRules.test.ts` hour-column and `columnsToTurn` cases; `TimeWheelsTouch.test.tsx` "turns AM to PM from 11 to 12 under %s finger" (TimeInput and DateTimeInput, an iPhone and an Android) and "keeps each column on its own under a mouse"; `TimeWheels.interaction.browser.spec.ts` "the AM/PM column follows the hour from 11 to 12 on UIDatePicker’s turn", "with a mouse each column turns on its own: 11 to 12 stays AM" | 12-hour time: 11 to 12 and back, 11 PM to 12, 1 to 2, 12 to 1 and back, 1 to 9; a finger and a mouse | An hour across 11 and 12 that keeps its half of the day, a move between 12 and 1–6 that flips it, a meridiem wheel that jumps instead of turning, or a mouse sheet whose hour moves the meridiem fails. | `audit:TimeInput/behavior` | +| FR8 | `TimeInput.test.tsx` clear cases; `NativeTimeInput.test.tsx` clear case | With value; empty | A clear on an empty field, or no `undefined`, fails. Evidence gap: no test asserts the focus move after clear on either surface, `changeAction` on clear, or a clear or Save press under reduced motion. | `audit:TimeInput/behavior` | +| FR9, AR3 | `TimeInput.test.tsx` disabled suites; `NativeTimeInput.test.tsx` and `Presentation.test.tsx` disabled cases; `InputGroup.test.tsx` disabled-propagation cases | Each surface; with reason; draft in progress | A lost tab stop, a value change, or a caller `onClick` fails. Evidence gap: no test asserts that caller `onKeyDown` and similar handlers still run while disabled (the FR9 gap). | `audit:TimeInput/accessibility` | +| FR10 | `TimeInput.test.tsx` InputGroup suite | Grouped with description and status | A duplicate label, a visible status icon, or a missed announcement fails. Evidence gap: no test groups the sheet surface. | `audit:TimeInput/accessibility` | +| FR11 | `TimeInput.fr10.test.tsx` | Each surface; handler composition | A base prop off the control, or a caller handler that cancels built-ins, fails. | `audit:TimeInput/api` | +| FR12 | `TimeInput.test.tsx` status and theme-state cases | Status; disabled | A missing state attribute fails. Evidence gap: no test asserts `data-size` or `data-status`. | `audit:TimeInput/theming` | +| FR2, ORD2 | Evidence gap: no TimeInput test of the pending Action's optimistic value | — | — | `audit:TimeInput/behavior` | +| AR1, PR1 | Covered by the FR10 and FR11 rows for naming. Evidence gap: no test asserts the single coarse-pointer query that decides the surface | — | — | `audit:TimeInput/behavior` | ## Current-state impact