Skip to content

Commit f5eed7a

Browse files
authored
fix(DateField): correctly check sections constraints on user input (#206)
1 parent 12f2693 commit f5eed7a

File tree

1 file changed

+25
-10
lines changed

1 file changed

+25
-10
lines changed

src/components/DateField/hooks/useBaseDateFieldState.ts

Lines changed: 25 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -346,25 +346,37 @@ export function useBaseDateFieldState<T = DateTime>(
346346
}
347347

348348
const section = this.sections[sectionIndex];
349+
const isLastSection = section.nextEditableSection === sectionIndex;
349350
let newValue = enteredKeys.current + key;
350351

351352
const onInputNumber = (numberValue: number) => {
352353
let sectionValue = section.type === 'month' ? numberValue - 1 : numberValue;
354+
const sectionMaxValue = section.maxValue ?? 0;
353355
const allowsZero = section.minValue === 0;
356+
let shouldResetUserInput;
354357
if (
358+
// 12-hour clock format with AM/PM
355359
section.type === 'hour' &&
356-
(section.minValue === 12 || section.maxValue === 11)
360+
(sectionMaxValue === 11 || section.minValue === 12)
357361
) {
358-
if (numberValue > 12) {
362+
if (sectionValue > 12) {
359363
sectionValue = Number(key);
364+
newValue = key;
360365
}
361-
if (section.minValue === 12 && sectionValue > 1) {
366+
if (sectionValue === 0) {
367+
sectionValue = -Infinity;
368+
}
369+
if (sectionValue === 12) {
370+
sectionValue = 0;
371+
}
372+
if (section.minValue === 12) {
362373
sectionValue += 12;
363374
}
364-
} else if (sectionValue > (section.maxValue ?? 0)) {
375+
shouldResetUserInput = Number(newValue + '0') > 12;
376+
} else if (sectionValue > sectionMaxValue) {
365377
sectionValue = Number(key) - (section.type === 'month' ? 1 : 0);
366378
newValue = key;
367-
if (sectionValue > (section.maxValue ?? 0)) {
379+
if (sectionValue > sectionMaxValue) {
368380
enteredKeys.current = '';
369381
return;
370382
}
@@ -375,16 +387,19 @@ export function useBaseDateFieldState<T = DateTime>(
375387
setSection(sectionIndex, sectionValue);
376388
}
377389

378-
if (
379-
Number(numberValue + '0') > (section.maxValue ?? 0) ||
380-
newValue.length >= String(section.maxValue).length
381-
) {
390+
if (shouldResetUserInput === undefined) {
391+
shouldResetUserInput = Number(newValue + '0') > sectionMaxValue;
392+
}
393+
const isMaxLength = newValue.length >= String(sectionMaxValue).length;
394+
if (shouldResetUserInput) {
382395
enteredKeys.current = '';
383396
if (shouldSetValue) {
384397
this.focusNextSection();
385398
}
399+
} else if (isMaxLength && shouldSetValue && !isLastSection) {
400+
this.focusNextSection();
386401
} else {
387-
enteredKeys.current = newValue === '0' && !allowsZero ? '' : newValue;
402+
enteredKeys.current = newValue;
388403
}
389404
};
390405

0 commit comments

Comments
 (0)