Skip to content

fix(useDateFieldState): fix setValue to work when field is empty #8417

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 4 commits into from
Jun 20, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
44 changes: 44 additions & 0 deletions packages/@react-aria/datepicker/stories/useDatePicker.stories.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
/*
* Copyright 2025 Adobe. All rights reserved.
* This file is licensed to you under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. You may obtain a copy
* of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under
* the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
* OF ANY KIND, either express or implied. See the License for the specific language
* governing permissions and limitations under the License.
*/

import {createCalendar, parseDate} from '@internationalized/date';
import {Meta, StoryObj} from '@storybook/react';
import React, {ReactElement, useRef} from 'react';
import {useDateField} from '../src';
import {useDateFieldState} from '@react-stately/datepicker';
import {useLocale} from '@react-aria/i18n';

export function ProgrammaticSetValueExampleRender(): ReactElement {
let {locale} = useLocale();
let state = useDateFieldState({locale, createCalendar});
let ref = useRef<HTMLDivElement>(null);
let {fieldProps} = useDateField({'aria-label': 'Date'}, state, ref);
return (
<div>
<div {...fieldProps} ref={ref} data-testid="field">
{state.segments.map((seg, i) => <span key={i}>{seg.text}</span>)}
</div>
<button onClick={() => state.setValue(parseDate('2020-01-01'))} data-testid="set">Set</button>
</div>
);
}

export default {
title: 'Date and Time/useDatePicker',
excludeStories: ['ProgrammaticSetValueExampleRender']
} as Meta<typeof ProgrammaticSetValueExampleRender>;

type Story = StoryObj<typeof ProgrammaticSetValueExampleRender>;

export const ProgrammaticSetValueExample: Story = {
render: () => <ProgrammaticSetValueExampleRender />
};
32 changes: 32 additions & 0 deletions packages/@react-aria/datepicker/test/useDatePicker.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
/*
* Copyright 2025 Adobe. All rights reserved.
* This file is licensed to you under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. You may obtain a copy
* of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under
* the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
* OF ANY KIND, either express or implied. See the License for the specific language
* governing permissions and limitations under the License.
*/

import {pointerMap, render} from '@react-spectrum/test-utils-internal';
import {ProgrammaticSetValueExampleRender} from '../stories/useDatePicker.stories';
import React, {} from 'react';
import userEvent from '@testing-library/user-event';

describe('useDatePicker', function () {
let user;
beforeAll(() => {
user = userEvent.setup({delay: null, pointerMap});
jest.useFakeTimers();
});

it('should commit programmatically setValue when field is empty', async () => {
let {getByTestId} = render(<ProgrammaticSetValueExampleRender />);

expect(getByTestId('field')).toHaveTextContent('mm/dd/yyyy');
await user.click(getByTestId('set'));
expect(getByTestId('field')).toHaveTextContent('2020');
});
});
13 changes: 12 additions & 1 deletion packages/@react-stately/datepicker/src/useDateFieldState.ts
Original file line number Diff line number Diff line change
Expand Up @@ -260,7 +260,18 @@ export function useDateFieldState<T extends DateValue = DateValue>(props: DateFi
setDate(null);
setPlaceholderDate(createPlaceholderDate(props.placeholderValue, granularity, calendar, defaultTimeZone));
setValidSegments({});
} else if (validKeys.length >= allKeys.length || (validKeys.length === allKeys.length - 1 && allSegments.dayPeriod && !validSegments.dayPeriod && clearedSegment.current !== 'dayPeriod')) {
} else if (
validKeys.length === 0 ||
validKeys.length >= allKeys.length ||
(validKeys.length === allKeys.length - 1 && allSegments.dayPeriod && !validSegments.dayPeriod && clearedSegment.current !== 'dayPeriod')
) {
// If the field was empty (no valid segments) or all segments are completed, commit the new value.
// When committing from an empty state, mark every segment as valid so value is committed.
if (validKeys.length === 0) {
validSegments = {...allSegments};
setValidSegments(validSegments);
}

// The display calendar should not have any effect on the emitted value.
// Emit dates in the same calendar as the original value, if any, otherwise gregorian.
newValue = toCalendar(newValue, v?.calendar || new GregorianCalendar());
Expand Down