Skip to content

fix: Constrain day on blur #8385

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

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
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
2 changes: 1 addition & 1 deletion packages/@internationalized/date/src/manipulation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -115,7 +115,7 @@ function balanceDay(date: Mutable<AnyCalendarDate>) {

function constrainMonthDay(date: Mutable<AnyCalendarDate>) {
date.month = Math.max(1, Math.min(date.calendar.getMonthsInYear(date), date.month));
date.day = Math.max(1, Math.min(date.calendar.getDaysInMonth(date), date.day));
date.day = Math.max(1, Math.min(31, date.day));
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't think the util should be loose on the constraint given the name of the function, instead, wherever it is we need it to be loose, we should do this. This way it's obvious when we are truly constraining to a valid date vs dealing with partial information.

}

export function constrain(date: Mutable<AnyCalendarDate>): void {
Expand Down
6 changes: 6 additions & 0 deletions packages/@react-aria/datepicker/src/useDateSegment.ts
Original file line number Diff line number Diff line change
Expand Up @@ -275,6 +275,11 @@ export function useDateSegment(segment: DateSegment, state: DateFieldState, ref:
selection?.collapse(ref.current);
};


const onBlur = () => {
state.constrain()
}

let documentRef = useRef(typeof document !== 'undefined' ? document : null);
useEvent(documentRef, 'selectionchange', () => {
// Enforce that the selection is collapsed when inside a date segment.
Expand Down Expand Up @@ -420,6 +425,7 @@ export function useDateSegment(segment: DateSegment, state: DateFieldState, ref:
onPointerDown(e) {
e.stopPropagation();
},
onBlur,
onMouseDown(e) {
e.stopPropagation();
}
Expand Down
59 changes: 58 additions & 1 deletion packages/@react-spectrum/datepicker/test/DateField.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
* governing permissions and limitations under the License.
*/

import {act, pointerMap, render as render_, within} from '@react-spectrum/test-utils-internal';
import {act, pointerMap, fireEvent, render as render_, within} from '@react-spectrum/test-utils-internal';
import {Button} from '@react-spectrum/button';
import {CalendarDate, CalendarDateTime, ZonedDateTime} from '@internationalized/date';
import {DateField} from '../';
Expand All @@ -20,6 +20,12 @@ import React from 'react';
import {theme} from '@react-spectrum/theme-default';
import userEvent from '@testing-library/user-event';

function beforeInput(target, key) {
// JSDOM doesn't support the beforeinput event
let e = new InputEvent('beforeinput', {cancelable: true, data: key, inputType: 'insertText'});
fireEvent(target, e);
}

function render(el) {
if (el.type === Provider) {
return render_(el);
Expand Down Expand Up @@ -674,4 +680,55 @@ describe('DateField', function () {
});
});
});

describe("validation", () => {
it("Should limit day to 31", async () => {
let onChange = jest.fn();
let { getByTestId } = render(
<DateField
label="Date"
value={new CalendarDate(2019, 2, 3)}
onChange={onChange}
/>,
);

let segment = getByTestId("day");
act(() => {
segment.focus();
});
beforeInput(segment, "32");
expect(onChange).toHaveBeenCalledWith(new CalendarDate(2019, 2, 31));
});
it.only("Constrain day on blur", async () => {
let onChange = jest.fn();
let { getByTestId } = render(
<DateField label="Date" onChange={onChange} />,
);

let segment;

segment = getByTestId("year");
act(() => {
segment.focus();
});
beforeInput(segment, "2025");

segment = getByTestId("month");
act(() => {
segment.focus();
});
beforeInput(segment, "2");

segment = getByTestId("day");
act(() => {
segment.focus();
});
beforeInput(segment, "29");

act(() => document.activeElement.blur());

expect(onChange).toHaveBeenCalledWith(new CalendarDate(2025, 2, 28));
});
});

});
36 changes: 33 additions & 3 deletions packages/@react-stately/datepicker/src/useDateFieldState.ts
Original file line number Diff line number Diff line change
Expand Up @@ -95,7 +95,8 @@ export interface DateFieldState extends FormValidationState {
/** Formats the current date value using the given options. */
formatValue(fieldOptions: FieldOptions): string,
/** Gets a formatter based on state's props. */
getDateFormatter(locale: string, formatOptions: FormatterOptions): DateFormatter
getDateFormatter(locale: string, formatOptions: FormatterOptions): DateFormatter,
constrain(): void,
}

const EDITABLE_SEGMENTS = {
Expand Down Expand Up @@ -190,6 +191,7 @@ export function useDateFieldState<T extends DateValue = DateValue>(props: DateFi
() => createPlaceholderDate(props.placeholderValue, granularity, calendar, defaultTimeZone)
);


let val = calendarValue || placeholderDate;
let showEra = calendar.identifier === 'gregory' && val.era === 'BC';
let formatOpts = useMemo(() => ({
Expand Down Expand Up @@ -419,6 +421,19 @@ export function useDateFieldState<T extends DateValue = DateValue>(props: DateFi
let newOptions = {...formatOpts, ...formatOptions};
let newFormatOptions = getFormatOptions({}, newOptions);
return new DateFormatter(locale, newFormatOptions);
},
constrain() {
setValidSegments(validSegments => {
let validKeys = Object.keys(validSegments);
let allKeys = Object.keys(allSegments);

if (validKeys.length >= allKeys.length || (validKeys.length === allKeys.length - 1 && allSegments.dayPeriod && !validSegments.dayPeriod)) {
const value = Math.max(1, Math.min( displayValue.calendar.getDaysInMonth(displayValue),displayValue.day));
console.log(value)
setValue(setSegment(displayValue, "day", value, resolvedOptions))
}
return validSegments
})
}
};
}
Expand All @@ -437,9 +452,24 @@ function processSegments(dateValue, validSegments, dateFormatter, resolvedOption
let isPlaceholder = EDITABLE_SEGMENTS[type] && !validSegments[type];
let placeholder = EDITABLE_SEGMENTS[type] ? getPlaceholder(type, segment.value, locale) : null;

let numberFormatter = new Intl.NumberFormat(locale, {
useGrouping: false
});

let twoDigitFormatter = new Intl.NumberFormat(locale, {
useGrouping: false,
minimumIntegerDigits: 2
})

let segmentValue
if(segment.type === "day") segmentValue = displayValue.day
else if(segment.type === "month") segmentValue = displayValue.month

let value = segment.type === "day" || segment.type === "month" ? twoDigitFormatter.format(segmentValue) : segment.value

let dateSegment = {
type,
text: isPlaceholder ? placeholder : segment.value,
text: isPlaceholder ? placeholder : value,
...getSegmentLimits(displayValue, type, resolvedOptions),
isPlaceholder,
placeholder,
Expand Down Expand Up @@ -517,7 +547,7 @@ function getSegmentLimits(date: DateValue, type: string, options: Intl.ResolvedD
return {
value: date.day,
minValue: getMinimumDayInMonth(date),
maxValue: date.calendar.getDaysInMonth(date)
maxValue: 31
};
}

Expand Down