Skip to content

Commit

Permalink
[@mantine/core] fix: NumberInput no jump to end when pressing backspa…
Browse files Browse the repository at this point in the history
…ce on pos 0
  • Loading branch information
jvllmr committed Apr 14, 2024
1 parent afc9929 commit 6b09863
Showing 1 changed file with 16 additions and 1 deletion.
Original file line number Diff line number Diff line change
Expand Up @@ -190,6 +190,7 @@ export const NumberInput = factory<NumberInputFactory>((_props, ref) => {
allowDecimal,
decimalScale,
onKeyDown,
onKeyDownCapture,
handlersRef,
startValue,
disabled,
Expand Down Expand Up @@ -255,7 +256,7 @@ export const NumberInput = factory<NumberInputFactory>((_props, ref) => {
};

const adjustCursor = (position?: number) => {
if (inputRef.current && position) {
if (inputRef.current && typeof position !== 'undefined') {
inputRef.current.setSelectionRange(position, position);
}
};
Expand Down Expand Up @@ -328,6 +329,19 @@ export const NumberInput = factory<NumberInputFactory>((_props, ref) => {
}
};

const handleKeyDownCapture = (event: React.KeyboardEvent<HTMLInputElement>) => {
onKeyDownCapture?.(event);
// prevent cursor jumping to end of input when pressing backspace on pos 0
// https://github.com/mantinedev/mantine/issues/6056
if (event.key === 'Backspace') {
const input = inputRef.current!;
if (input.selectionStart === 0 && input.selectionStart === input.selectionEnd) {
event.preventDefault();
setTimeout(() => adjustCursor(0), 0);
}
}
};

assignRef(handlersRef, { increment: incrementRef.current, decrement: decrementRef.current });

const onStepHandleChange = (isIncrement: boolean) => {
Expand Down Expand Up @@ -425,6 +439,7 @@ export const NumberInput = factory<NumberInputFactory>((_props, ref) => {
__staticSelector="NumberInput"
decimalScale={allowDecimal ? decimalScale : 0}
onKeyDown={handleKeyDown}
onKeyDownCapture={handleKeyDownCapture}
rightSectionPointerEvents={rightSectionPointerEvents ?? (disabled ? 'none' : undefined)}
rightSectionWidth={rightSectionWidth ?? `var(--ni-right-section-width-${size || 'sm'})`}
allowLeadingZeros={allowLeadingZeros}
Expand Down

0 comments on commit 6b09863

Please sign in to comment.