Skip to content

Commit dc4370f

Browse files
author
Kubit
committed
Improve hooks useInput and useTrapFocus
1 parent 5066e17 commit dc4370f

File tree

2 files changed

+22
-3
lines changed

2 files changed

+22
-3
lines changed

src/hooks/useInput/useInput.ts

Lines changed: 13 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -121,6 +121,9 @@ export const useInput = (props: ParamsTypeInputHook): ReturnTypeInputHook => {
121121
return;
122122
}
123123
if (eventKeyPressRef.current && props.mask && inputRef?.current && value) {
124+
const popoverElements = document.querySelectorAll(
125+
'[data-calendar], [data-input-dropdown-list], [data-input-search-list]'
126+
);
124127
const { start, end } = eventKeyPressRef.current.cursor;
125128
// if multiple digits are selected, recovery the selected area
126129
const area = Math.abs(start - end);
@@ -138,7 +141,10 @@ export const useInput = (props: ParamsTypeInputHook): ReturnTypeInputHook => {
138141
eventKeyPressRef.current.cursor,
139142
positionRef.current
140143
);
141-
inputRef.current.focus();
144+
145+
if (popoverElements.length !== 0) {
146+
inputRef.current.focus();
147+
}
142148
inputRef.current.setSelectionRange(start + diffStart + position, end - diffEnd + position);
143149
}
144150
}, [value]);
@@ -356,7 +362,12 @@ export const useInput = (props: ParamsTypeInputHook): ReturnTypeInputHook => {
356362
const handlePasteInternal: React.ClipboardEventHandler<HTMLInputElement> = event => {
357363
const clipboardData = event.clipboardData;
358364
const pastedData = clipboardData?.getData('Text');
359-
if (props.ignoreKeys?.some(key => pastedData.includes(key)) || props.disabledCopyAndPaste) {
365+
const newRegex = typeof props.regex === 'string' ? new RegExp(props.regex) : props.regex;
366+
if (
367+
props.ignoreKeys?.some(key => pastedData.includes(key)) ||
368+
props.disabledCopyAndPaste ||
369+
(newRegex && !newRegex?.test(pastedData))
370+
) {
360371
event.preventDefault();
361372
return;
362373
}

src/hooks/useTrapFocus/useTrapFocus.tsx

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -18,10 +18,18 @@ export const useTrapFocus = ({
1818
return;
1919
}
2020
const focusableElements = getFocusableDescendantsV2({ element: ref.current });
21-
// Do nothing if the ref does not contain focusable elements
21+
22+
// When the ref does not contain focusable elements
2223
if (!focusableElements.length) {
24+
// Do not change the current focus if the current focus is inside the ref
25+
// This happens in some element like in actionBottomSheet dropdown
26+
// When the focus is trap, but the options are not focusabled
27+
if (ref.current.contains(document.activeElement)) {
28+
e.preventDefault();
29+
}
2330
return;
2431
}
32+
2533
const firstFocusableElement = focusableElements[0];
2634
const lastFocusableElement = focusableElements[focusableElements.length - 1];
2735

0 commit comments

Comments
 (0)