Skip to content
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

[@mantine/core]: PinInput - some improvements #5704

Merged
merged 6 commits into from
Feb 9, 2024
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
32 changes: 32 additions & 0 deletions packages/@mantine/core/src/components/PinInput/PinInput.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,19 @@ describe('@mantine/core/PinInput', () => {
expect(container.querySelectorAll('.mantine-PinInput-input')).toHaveLength(5);
});

it('onChange is called after typing', () => {
const spy = jest.fn();
const { container } = render(<PinInput type="number" length={6} onChange={spy} />);

fireEvent.input(container.querySelectorAll('.mantine-PinInput-input')[1], {
target: {
value: '1',
},
});

expect(spy).toHaveBeenCalled();
});

it('onComplete is called on last input', () => {
const spy = jest.fn();
const { container } = render(<PinInput {...defaultProps} onComplete={spy} />);
Expand All @@ -43,6 +56,11 @@ describe('@mantine/core/PinInput', () => {
expect(spy).toHaveBeenCalledWith('1111');
});

it('focus first input on mount with `autoFocus` property', () => {
const { container } = render(<PinInput length={6} autoFocus />);
expect(container.querySelectorAll('.mantine-PinInput-input')[0]).toHaveFocus();
});

it('stay focused on last element on initial backspace press', async () => {
const { container } = render(<PinInput {...defaultProps} length={5} />);
expect(container.querySelectorAll('.mantine-PinInput-input')).toHaveLength(5);
Expand Down Expand Up @@ -89,4 +107,18 @@ describe('@mantine/core/PinInput', () => {
fireEvent.change(element, { target: { value: expectedValue } });
expect(spy).toHaveBeenCalledWith(expectedValue);
});

it('display only one character in an input', () => {
const { container } = render(<PinInput length={6} />);
expect(
(container.querySelectorAll('.mantine-PinInput-input')[0] as HTMLInputElement).value.length
).toBeLessThan(2);
});

it('display only one character in an input with `defaultValue` property', () => {
const { container } = render(<PinInput length={6} defaultValue="123456" />);
expect(
(container.querySelectorAll('.mantine-PinInput-input')[2] as HTMLInputElement).value.length
).toBe(1);
});
});
68 changes: 49 additions & 19 deletions packages/@mantine/core/src/components/PinInput/PinInput.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -200,17 +200,24 @@ export const PinInput = factory<PinInputFactory>((props, ref) => {

const [focusedIndex, setFocusedIndex] = useState(-1);

const [_value, setValues] = useUncontrolled({
value,
defaultValue,
finalValue: '',
onChange,
const [_value, setValues] = useUncontrolled<string[]>({
value: value ? createPinArray(length ?? 0, value) : undefined,
defaultValue: defaultValue?.split('').slice(0, length ?? 0),
finalValue: createPinArray(length ?? 0, ''),
onChange:
typeof onChange === 'function'
? (val) => {
onChange(val.join('').trim());
}
: undefined,
});
const _valueToString = _value.join('').trim();

const inputsRef = useRef<Array<HTMLInputElement>>([]);

const validate = (code: string) => {
const re = type instanceof RegExp ? type : type && type in regex ? regex[type] : null;

return re?.test(code);
};

Expand All @@ -230,9 +237,9 @@ export const PinInput = factory<PinInputFactory>((props, ref) => {
};

const setFieldValue = (val: string, index: number) => {
const values = [...createPinArray(length ?? 0, _value)];
const values = [..._value];
values[index] = val;
setValues(values.join(''));
setValues(values);
};

const handleChange = (event: React.ChangeEvent<HTMLInputElement>, index: number) => {
Expand All @@ -250,21 +257,39 @@ export const PinInput = factory<PinInputFactory>((props, ref) => {
setFieldValue('', index);
}
} else if (isValid) {
setValues(inputValue);
setValues(createPinArray(length ?? 0, inputValue));
}
};

const handleKeyDown = (event: React.KeyboardEvent<HTMLInputElement>, index: number) => {
if (event.key === 'ArrowLeft') {
const { ctrlKey, key, shiftKey, target } = event;
const inputValue = (target as HTMLInputElement).value;

if (inputMode === 'numeric') {
const canTypeSign =
key === 'Backspace' ||
key === 'Tab' ||
key === 'Control' ||
key === 'Delete' ||
(ctrlKey && key === 'v')
? true
: !Number.isNaN(Number(key));

if (!canTypeSign) {
event.preventDefault();
}
}

if (key === 'ArrowLeft' || (shiftKey && key === 'Tab')) {
event.preventDefault();
focusInputField('prev', index);
} else if (event.key === 'ArrowRight') {
} else if (key === 'ArrowRight' || key === 'Tab' || key === ' ') {
event.preventDefault();
focusInputField('next', index);
} else if (event.key === 'Delete') {
} else if (key === 'Delete') {
event.preventDefault();
setFieldValue('', index);
} else if (event.key === 'Backspace') {
} else if (key === 'Backspace') {
event.preventDefault();
setFieldValue('', index);
if (length === index + 1) {
Expand All @@ -274,6 +299,9 @@ export const PinInput = factory<PinInputFactory>((props, ref) => {
} else {
focusInputField('prev', index);
}
} else if (inputValue.length > 0 && key === _value[index]) {
event.preventDefault();
focusInputField('next', index);
}
};

Expand All @@ -288,19 +316,21 @@ export const PinInput = factory<PinInputFactory>((props, ref) => {

const handlePaste = (event: React.ClipboardEvent<HTMLInputElement>) => {
event.preventDefault();
const copyValue = event.clipboardData.getData('Text');
const copyValue = event.clipboardData.getData('text/plain').replace(/[\n\r\s]+/g, '');
const isValid = validate(copyValue.trim());

if (isValid) {
setValues(copyValue);
const copyValueToPinArray = createPinArray(length ?? 0, copyValue);
setValues(copyValueToPinArray);
focusInputField('next', copyValueToPinArray.length - 1);
}
};

useEffect(() => {
if (_value.length !== length) return;
if (_valueToString.length !== length) return;

onComplete?.(_value);
}, [_value]);
onComplete?.(_valueToString);
}, [length, onComplete, _valueToString]);

return (
<>
Expand All @@ -315,7 +345,7 @@ export const PinInput = factory<PinInputFactory>((props, ref) => {
variant={variant}
__size={size}
>
{createPinArray(length ?? 0, _value).map((char, index) => (
{_value.map((char: string, index: number) => (
<Input
component="input"
{...getStyles('pinInput', {
Expand Down Expand Up @@ -356,7 +386,7 @@ export const PinInput = factory<PinInputFactory>((props, ref) => {
))}
</Group>

<input type="hidden" name={name} form={form} value={_value} {...hiddenInputProps} />
<input type="hidden" name={name} form={form} value={_valueToString} {...hiddenInputProps} />
</>
);
});
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,8 @@ describe('@mantine/core/PinInput/create-pin-array', () => {
expect(createPinArray(2, 'abcd')).toStrictEqual(['a', 'b']);
expect(createPinArray(2, 'a')).toStrictEqual(['a', '']);
expect(createPinArray(4, 'abcd')).toStrictEqual(['a', 'b', 'c', 'd']);
expect(createPinArray(5, 'ab de')).toStrictEqual(['a', 'b', '', 'd', 'e']);
expect(createPinArray(5, 'abc')).toStrictEqual(['a', 'b', 'c', '', '']);
});

it('returns empty array if length is less than 1', () => {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ export function createPinArray(length: number, value: string): string[] {
if (value) {
const splitted = value.trim().split('');
for (let i = 0; i < Math.min(length, splitted.length); i += 1) {
values[i] = splitted[i];
values[i] = splitted[i] === ' ' ? '' : splitted[i];
}
}

Expand Down
Loading