Skip to content

Commit fa46b0c

Browse files
committed
refactor: extract handleManualClear to reduce code duplication
- Extracted duplicate logic into reusable handleManualClear function - Added JSDoc comment explaining the function's purpose - Added inline comment explaining why event.preventDefault() is called - Improved code maintainability and testability
1 parent 88c80f2 commit fa46b0c

File tree

1 file changed

+23
-21
lines changed

1 file changed

+23
-21
lines changed

src/PickerInput/Selector/Input.tsx

Lines changed: 23 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -212,20 +212,32 @@ const Input = React.forwardRef<InputRef, InputProps>((props, ref) => {
212212
});
213213

214214
// ======================= Keyboard =======================
215+
/**
216+
* Handle manual clear when user selects all text and presses Delete/Backspace
217+
* @returns true if input was cleared, false otherwise
218+
*/
219+
const handleManualClear = (event: React.KeyboardEvent<HTMLInputElement>): boolean => {
220+
const inputElement = inputRef.current;
221+
if (
222+
inputElement &&
223+
inputElement.selectionStart === 0 &&
224+
inputElement.selectionEnd === inputValue.length &&
225+
inputValue.length > 0
226+
) {
227+
onChange('');
228+
setInputValue('');
229+
// Prevent default browser behavior (e.g., navigation) after clearing
230+
event.preventDefault();
231+
return true;
232+
}
233+
return false;
234+
};
235+
215236
const onSharedKeyDown: React.KeyboardEventHandler<HTMLInputElement> = (event) => {
216237
const { key } = event;
217238

218239
if ((key === 'Backspace' || key === 'Delete') && !format) {
219-
const inputElement = inputRef.current;
220-
if (
221-
inputElement &&
222-
inputElement.selectionStart === 0 &&
223-
inputElement.selectionEnd === inputValue.length &&
224-
inputValue.length > 0
225-
) {
226-
onChange('');
227-
setInputValue('');
228-
event.preventDefault();
240+
if (handleManualClear(event)) {
229241
return;
230242
}
231243
}
@@ -281,22 +293,12 @@ const Input = React.forwardRef<InputRef, InputProps>((props, ref) => {
281293
// =============== Remove ===============
282294
case 'Backspace':
283295
case 'Delete':
284-
const inputElement = inputRef.current;
285-
if (
286-
inputElement &&
287-
inputElement.selectionStart === 0 &&
288-
inputElement.selectionEnd === inputValue.length &&
289-
inputValue.length > 0
290-
) {
291-
onChange('');
292-
setInputValue('');
293-
event.preventDefault();
296+
if (handleManualClear(event)) {
294297
return;
295298
}
296299
nextCellText = '';
297300
nextFillText = cellFormat;
298301
break;
299-
300302
// =============== Arrows ===============
301303
// Left key
302304
case 'ArrowLeft':

0 commit comments

Comments
 (0)