An open source design system that's fully customizable and agent ready
TypeScript
fix(DateInput): show the native control's own segments while it is typed into (#5456)
Xinzi Zhou75e726c5ff61
diff --git a/.changeset/date-input-native-segments-visible.md b/.changeset/date-input-native-segments-visible.mdnew file mode 100644index 0000000000..e6528e50b9--- /dev/null+++ b/.changeset/date-input-native-segments-visible.md@@ -0,0 +1,7 @@+---+'@astryxdesign/core': patch+---++[fix] DateInput's native surface (`nativePicker`) now shows the engine's own date segments while the control has focus, instead of painting over them. On iOS and Android `<input type="date">` is a single untypable run, so DateInput's formatted text can cover it; on desktop engines — and in Chrome's touch simulator — it is a row of editable `mm`/`dd`/`yyyy` fields, and covering those hid the digits being typed. `format` reapplies on blur.++@imdreamrunnerdiff --git a/packages/core/src/DateInput/NativeDateField.test.tsx b/packages/core/src/DateInput/NativeDateField.test.tsxindex 67f03d96fa..39b1908add 100644--- a/packages/core/src/DateInput/NativeDateField.test.tsx+++ b/packages/core/src/DateInput/NativeDateField.test.tsx@@ -22,8 +22,32 @@import {describe, it, expect, vi, beforeEach, afterEach} from 'vitest';import {render, screen, fireEvent} from '@testing-library/react';import {DateInput} from './DateInput';+import type * as NativeDateSegments from './nativeDateSegments';+import {+ hasEditableDateSegments,+ resetDateSegmentProbe,+} from './nativeDateSegments';import {InternationalizationProvider} from '../i18n';+/**+ * Lets a test say which kind of `<input type="date">` the engine draws.+ * `null` (the default) runs the real probe, so every other test in this file+ * exercises the shipping path: jsdom lays nothing out, so the probe reports+ * `'unknown'` and the coarse pointer resolves it to picker-only.+ */+const {segmentState} = vi.hoisted(() => ({+ segmentState: {editable: null as boolean | null},+}));++vi.mock('./nativeDateSegments', async importOriginal => {+ const actual = await importOriginal<typeof NativeDateSegments>();+ return {+ ...actual,+ hasEditableDateSegments: (isTouchPointer: boolean) =>+ segmentState.editable ?? actual.hasEditableDateSegments(isTouchPointer),+ };+});+const HOVER_CAPABLE = /\(\s*hover\s*:\s*hover\s*\)/;/**@@ -87,6 +111,8 @@ beforeEach(() => {afterEach(() => {vi.unstubAllGlobals();vi.restoreAllMocks();+ segmentState.editable = null;+ resetDateSegmentProbe();});describe('DateInput nativePicker', () => {@@ -173,9 +199,7 @@ describe('DateInput nativePicker', () => {it('fires onChange with undefined when the control is emptied', () => {stubPointer(true);const onChange = vi.fn();- render(- <DateInput label="Date" value="2026-03-21" onChange={onChange} />,- );+ render(<DateInput label="Date" value="2026-03-21" onChange={onChange} />);fireEvent.change(getInput(), {target: {value: ''}});@@ -191,9 +215,7 @@ describe('DateInput nativePicker', () => {// sees the real one.stubPointer(true);const onChange = vi.fn();- render(- <DateInput label="Date" value="2026-03-21" onChange={onChange} />,- );+ render(<DateInput label="Date" value="2026-03-21" onChange={onChange} />);const input = getInput();input.value = '2026-03-09';@@ -205,9 +227,7 @@ describe('DateInput nativePicker', () => {it('fires one change when both commit paths see the same edit', () => {stubPointer(true);const onChange = vi.fn();- render(- <DateInput label="Date" value="2026-03-21" onChange={onChange} />,- );+ render(<DateInput label="Date" value="2026-03-21" onChange={onChange} />);fireEvent.change(getInput(), {target: {value: '2026-03-09'}});@@ -225,9 +245,7 @@ describe('DateInput nativePicker', () => {const input = getInput();fireEvent.focus(input);- rerender(- <DateInput label="Date" value="2026-12-25" onChange={() => {}} />,- );+ rerender(<DateInput label="Date" value="2026-12-25" onChange={() => {}} />);expect(input).toHaveValue('2026-03-21');});@@ -240,9 +258,7 @@ describe('DateInput nativePicker', () => {const input = getInput();fireEvent.focus(input);- rerender(- <DateInput label="Date" value="2026-12-25" onChange={() => {}} />,- );+ rerender(<DateInput label="Date" value="2026-12-25" onChange={() => {}} />);fireEvent.blur(input);expect(input).toHaveValue('2026-12-25');@@ -391,9 +407,7 @@ describe('DateInput nativePicker', () => {it('keeps painting the value while the picker is open', () => {// The OS picker has no segments to reveal, so `format` holds throughout.stubPointer(true);- render(- <DateInput label="Date" value="2026-01-25" onChange={() => {}} />,- );+ render(<DateInput label="Date" value="2026-01-25" onChange={() => {}} />);fireEvent.focus(getInput());@@ -402,14 +416,10 @@ describe('DateInput nativePicker', () => {it('shows the placeholder when empty, and drops it when filled', () => {stubPointer(true);- const {rerender} = render(- <DateInput label="Date" onChange={() => {}} />,- );+ const {rerender} = render(<DateInput label="Date" onChange={() => {}} />);expect(screen.getByText('Select a date')).toBeInTheDocument();- rerender(- <DateInput label="Date" value="2026-01-25" onChange={() => {}} />,- );+ rerender(<DateInput label="Date" value="2026-01-25" onChange={() => {}} />);expect(screen.queryByText('Select a date')).toBeNull();});@@ -418,9 +428,7 @@ describe('DateInput nativePicker', () => {// The input still holds the value and carries the label, so announcing// the overlay too would double-speak.stubPointer(true);- render(- <DateInput label="Date" value="2026-01-25" onChange={() => {}} />,- );+ render(<DateInput label="Date" value="2026-01-25" onChange={() => {}} />);expect(screen.getByText('January 25, 2026')).toHaveAttribute('aria-hidden',@@ -430,9 +438,7 @@ describe('DateInput nativePicker', () => {it('hides the engine\u2019s own text under the overlay', () => {stubPointer(true);- render(- <DateInput label="Date" value="2026-01-25" onChange={() => {}} />,- );+ render(<DateInput label="Date" value="2026-01-25" onChange={() => {}} />);const rules = rulesFor(getInput());// One transparent colour covers Chromium's `::-webkit-datetime-edit` and@@ -562,4 +568,68 @@ describe('DateInput nativePicker', () => {expect(input).toHaveAttribute('aria-required', 'true');expect(ref).toHaveBeenCalledWith(expect.any(HTMLInputElement));});++ // ===========================================================================+ // Engines that draw editable segments+ //+ // Chrome's touch simulator, a Windows tablet and a ChromeOS convertible all+ // render `<input type="date">` as typable fields while reporting a coarse+ // pointer. See ./nativeDateSegments.+ // ===========================================================================++ it('reveals the engine’s own segments while an editable control has focus', () => {+ // Measured in Chrome: with the overlay up, typing paints nothing but a+ // selection highlight drifting across the placeholder.+ segmentState.editable = true;+ stubPointer(true);+ render(<DateInput label="Date" value="2026-01-25" onChange={() => {}} />);++ expect(screen.getByText('January 25, 2026')).toBeInTheDocument();++ fireEvent.focus(getInput());++ expect(screen.queryByText('January 25, 2026')).toBeNull();+ // `-webkit-text-fill-color` is what wins inside a date control, and+ // unlike a bare `color:` cannot be confused with the wrapper's+ // `background-color: transparent`.+ expect(rulesFor(getInput())).not.toContain(+ '-webkit-text-fill-color: transparent',+ );+ });++ it('paints the formatted date again once the segments lose focus', () => {+ segmentState.editable = true;+ stubPointer(true);+ render(<DateInput label="Date" value="2026-01-25" onChange={() => {}} />);++ fireEvent.focus(getInput());+ fireEvent.blur(getInput());++ expect(screen.getByText('January 25, 2026')).toBeInTheDocument();+ expect(rulesFor(getInput())).toContain(+ '-webkit-text-fill-color: transparent',+ );+ });++ it('stands aside for the engine’s placeholder while empty and focused', () => {+ // `mm/dd/yyyy` says which order to type in, which ours cannot.+ segmentState.editable = true;+ stubPointer(true);+ render(<DateInput label="Date" onChange={() => {}} />);++ expect(screen.getByText('Select a date')).toBeInTheDocument();++ fireEvent.focus(getInput());++ expect(screen.queryByText('Select a date')).toBeNull();+ });++ it('resolves an unprobeable engine with the pointer', () => {+ // jsdom lays nothing out, so neither pseudo can be measured — the same+ // answer Firefox gives, which exposes neither.+ resetDateSegmentProbe();++ expect(hasEditableDateSegments(true)).toBe(false);+ expect(hasEditableDateSegments(false)).toBe(true);+ });});diff --git a/packages/core/src/DateInput/NativeDateField.tsx b/packages/core/src/DateInput/NativeDateField.tsxindex 8a8094c6a9..ae5d87c09e 100644--- a/packages/core/src/DateInput/NativeDateField.tsx+++ b/packages/core/src/DateInput/NativeDateField.tsx@@ -4,7 +4,7 @@/*** @file NativeDateField.tsx- * @input Uses React, Field, Icon, InputClearButton, Spinner, useCalendarConstraints+ * @input Uses React, Field, Icon, InputClearButton, Spinner, useCalendarConstraints, hasEditableDateSegments* @output Exports NativeDateField — the OS-picker touch surface* @position One of DateInput's three surfaces. `DateInput` picks the pointer* field on a mouse and, on touch, either `TouchDateField` (the default) or@@ -22,13 +22,15 @@* SYNC: When modified, update these files to stay in sync:* - /packages/core/src/DateInput/DateInput.tsx (the `nativePicker` prop)* - /packages/core/src/DateInput/DateInput.doc.mjs (prop table)- * - /packages/core/src/DateInput/DateInputNative.test.tsx (tests)+ * - /packages/core/src/DateInput/nativeDateSegments.ts (the engine probe)+ * - /packages/core/src/DateInput/NativeDateField.test.tsx (tests)*/import {useCallback, useEffect, useId, useRef, useState} from 'react';import * as stylex from '@stylexjs/stylex';import {useCalendarConstraints} from '../Calendar';import type {DateInputProps} from './DateInput';+import {hasEditableDateSegments} from './nativeDateSegments';import {Field,InputClearButton,@@ -38,6 +40,7 @@ import {inputWrapperStyles,} from '../Field';import {useInputStatusIcon, useMergedRefs} from '../hooks';+import {useMediaQuery} from '../hooks/useMediaQuery';import {useResolvedRequired} from '../hooks/useResolvedRequired';import {Icon} from '../Icon';import {useLocale, useTranslator} from '../i18n';@@ -254,6 +257,8 @@ export function NativeDateField({const placeholder =placeholderFromProps ?? t('@astryx.dateInput.placeholder');const size = useSize(sizeProp, 'md');+ // Only breaks a tie the engine probe cannot: see ./nativeDateSegments.+ const isTouchPointer = useMediaQuery('(pointer: coarse)');const id = useId();const inputLabelID = useId();@@ -301,6 +306,10 @@ export function NativeDateField({// Whether the control has focus — which, on a touch device, means its// picker is open.const [isFocused, setIsFocused] = useState(false);+ // Whether the engine draws this control as editable segments rather than a+ // picker-only run. Latched on focus rather than read during render: the+ // probe touches the DOM, and unfocused the answer changes nothing.+ const [isSegmentEditable, setIsSegmentEditable] = useState(false);// The raw value the control last reported and we acted on, so the same edit// arriving through both commit paths only fires one change.const lastCommitRef = useRef<string | null>(null);@@ -328,10 +337,14 @@ export function NativeDateField({);// This field paints the closed control's text itself, which is what keeps- // `format` and `placeholder` applying: the OS picker has no segments to- // edit, so our text holds even while the picker is open, and tracks it live.+ // `format` and `placeholder` applying: a picker-only control has no+ // segments to edit, so our text holds even while the picker is open, and+ // tracks it live. An editable control is the opposite case — its text IS+ // the edit surface, and it reports no `value` until every segment is+ // filled, so the overlay has nothing to paint mid-edit — so step aside for+ // as long as it has focus. See ./nativeDateSegments.const overlayText = nativeValue ? formatValue(nativeValue) : placeholder;- const showsOverlay = !!overlayText;+ const showsOverlay = !!overlayText && !(isFocused && isSegmentEditable);const commitValue = useCallback((newValue: string) => {@@ -434,6 +447,11 @@ export function NativeDateField({}}, [isFocused, nativeValue]);+ const handleFocus = useCallback(() => {+ setIsSegmentEditable(hasEditableDateSegments(isTouchPointer));+ setIsFocused(true);+ }, [isTouchPointer]);+const handleBlur = useCallback(() => {const domValue = inputRef.current?.value;setIsFocused(false);@@ -533,7 +551,7 @@ export function NativeDateField({// mount — see `initialValueRef` and the sync effect above.defaultValue={initialValueRef.current ?? ''}onChange={handleChange}- onFocus={() => setIsFocused(true)}+ onFocus={handleFocus}onBlur={handleBlur}min={min}max={max}diff --git a/packages/core/src/DateInput/nativeDateSegments.ts b/packages/core/src/DateInput/nativeDateSegments.tsnew file mode 100644index 0000000000..bc118a83a9--- /dev/null+++ b/packages/core/src/DateInput/nativeDateSegments.ts@@ -0,0 +1,127 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++'use client';++/**+ * @file nativeDateSegments.ts+ * @input Uses the DOM only+ * @output Exports hasEditableDateSegments, resetDateSegmentProbe+ * @position Internal helper for NativeDateField; answers "can the user type+ * into this engine's `<input type="date">`?"+ *+ * `<input type="date">` is two different controls wearing one tag name: a+ * single untypable run the OS picker drives (iOS, Android), or a row of+ * editable `mm`/`dd`/`yyyy` fields (desktop engines). Hiding the first costs+ * nothing; hiding the second hides what the user is editing.+ *+ * Neither obvious test tells them apart. The pointer is wrong on Chrome's+ * touch simulator, a Windows tablet and a ChromeOS convertible, which report+ * a coarse pointer while Blink still renders segments. And measured, iOS and+ * Chromium BOTH accept every `-webkit-datetime-*` selector, so+ * `CSS.supports('selector(...)')` only proves the parser knows the name. What+ * separates them is which pseudo is a real box, so this measures that.+ *+ * SYNC: When modified, update these files to stay in sync:+ * - /packages/core/src/DateInput/NativeDateField.tsx (the caller)+ * - /packages/core/src/DateInput/NativeDateField.test.tsx (tests)+ */++/** Marks the throwaway probe element for the probe stylesheet. */+const PROBE_ATTR = 'data-astryx-date-probe';++/** How much padding the probe adds, in px. Large enough to beat rounding. */+const PROBE_PADDING = 100;++type EngineKind = 'segmented' | 'picker-only' | 'unknown';++let cachedEngine: EngineKind | null = null;++/** Whether padding this pseudo-element moves the control's box. */+function pseudoIsRealBox(+ input: HTMLInputElement,+ style: HTMLStyleElement,+ pseudo: string,+ baseWidth: number,+): boolean {+ style.textContent = `[${PROBE_ATTR}]${pseudo}{padding-inline-start:${PROBE_PADDING}px !important}`;+ // Reading geometry flushes style and layout, so this already reflects it.+ return input.getBoundingClientRect().width > baseWidth + PROBE_PADDING / 2;+}++/**+ * Classifies the engine's date control. Cached: the answer is a build-time+ * property of the browser, not of the field or the pointer in use.+ */+function probeEngine(): EngineKind {+ if (cachedEngine !== null) {+ return cachedEngine;+ }+ if (typeof document === 'undefined' || !document.body) {+ return 'unknown';+ }++ const input = document.createElement('input');+ input.setAttribute('type', 'date');+ input.setAttribute(PROBE_ATTR, '');+ // Off-screen, and immune to the page's own `input` rules: the probe reads a+ // width DELTA, so anything pinning the width would swallow the signal.+ input.style.cssText =+ 'position:fixed;top:-9999px;left:0;width:auto;min-width:0;max-width:none;' ++ 'padding:0;border:0;font-size:16px;box-sizing:content-box;';++ const style = document.createElement('style');++ let kind: EngineKind = 'unknown';+ try {+ document.body.appendChild(input);+ document.head.appendChild(style);+ const base = input.getBoundingClientRect().width;+ if (pseudoIsRealBox(input, style, '::-webkit-datetime-edit', base)) {+ // Chromium's editable field row, and WebKit's on macOS/GTK. Probe the+ // container: the individual field pseudos overflow it rather than+ // expand it, so they do not move the box even in Chromium.+ kind = 'segmented';+ } else if (+ pseudoIsRealBox(input, style, '::-webkit-date-and-time-value', base)+ ) {+ // The single, untypable run iOS Safari and Chrome on Android paint.+ kind = 'picker-only';+ }+ } catch {+ // A hostile CSSOM leaves the answer unknown, resolved by the pointer.+ } finally {+ input.remove();+ style.remove();+ }++ cachedEngine = kind;+ return kind;+}++/**+ * Whether the user can type into this engine's `<input type="date">`.+ *+ * Firefox exposes neither pseudo-element, so it — and any future engine —+ * comes back `'unknown'` and the pointer breaks the tie. That is the right+ * fallback precisely where the probe is blind: the pointer is wrong for+ * Chromium because Blink's answer is fixed at build time and contradicts it,+ * and an engine we cannot see is not in that position. It lands Firefox on+ * the desktop (segmented) and on Android (picker-only) correctly.+ *+ * @param isTouchPointer Whether `(pointer: coarse)` matches.+ * @internal Exported for tests.+ */+export function hasEditableDateSegments(isTouchPointer: boolean): boolean {+ const engine = probeEngine();+ return engine === 'unknown' ? !isTouchPointer : engine === 'segmented';+}++/**+ * Drops the cached classification.+ *+ * @internal Exists for tests, which render against several engines in one+ * document.+ */+export function resetDateSegmentProbe(): void {+ cachedEngine = null;+}