Skip to content

Commit

Permalink
replace type assertion with instanceof check
Browse files Browse the repository at this point in the history
  • Loading branch information
firehawk89 committed Jan 28, 2024
1 parent bb61c12 commit 52ce497
Showing 1 changed file with 26 additions and 23 deletions.
49 changes: 26 additions & 23 deletions src/components/pages/auth/otp-input.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -39,15 +39,15 @@ const OtpInput: FC<OtpInputProps> = ({

const focusNext = (target: HTMLInputElement) => {
const { nextElementSibling } = target
if (nextElementSibling) {
;(nextElementSibling as HTMLInputElement).focus()
if (nextElementSibling instanceof HTMLInputElement) {
nextElementSibling.focus()
}
}

const focusPrev = (target: HTMLInputElement) => {
const { previousElementSibling } = target
if (previousElementSibling) {
;(previousElementSibling as HTMLInputElement).focus()
if (previousElementSibling instanceof HTMLInputElement) {
previousElementSibling.focus()
}
}

Expand All @@ -67,8 +67,8 @@ const OtpInput: FC<OtpInputProps> = ({

if (
!isTargetValueDigit &&
nextElementSibling &&
(nextElementSibling as HTMLInputElement).value !== ''
nextElementSibling instanceof HTMLInputElement &&
nextElementSibling.value !== ''
) {
return
}
Expand Down Expand Up @@ -98,36 +98,39 @@ const OtpInput: FC<OtpInputProps> = ({

const handleKeyDown = (e: KeyboardEvent<HTMLInputElement>) => {
const { key, target } = e
const { value } = target as HTMLInputElement

if (key === 'ArrowRight' || key === 'ArrowDown') {
e.preventDefault()
return focusNext(target as HTMLInputElement)
}
if (target instanceof HTMLInputElement) {
const { value } = target

if (key === 'ArrowLeft' || key === 'ArrowUp') {
e.preventDefault()
return focusPrev(target as HTMLInputElement)
}
if (key === 'ArrowRight' || key === 'ArrowDown') {
e.preventDefault()
return focusNext(target)
}

;(target as HTMLInputElement).setSelectionRange(0, value.length)
if (key === 'ArrowLeft' || key === 'ArrowUp') {
e.preventDefault()
return focusPrev(target)
}

if (key !== 'Backspace' || value !== '') {
return
}
target.setSelectionRange(0, value.length)

focusPrev(target as HTMLInputElement)
if (key !== 'Backspace' || value !== '') {
return
}

focusPrev(target)
}
}

const handleFocus = (e: FocusEvent<HTMLInputElement>) => {
const { target } = e
const { previousElementSibling, value } = target

if (
previousElementSibling &&
(previousElementSibling as HTMLInputElement).value === ''
previousElementSibling instanceof HTMLInputElement &&
previousElementSibling.value === ''
) {
return (previousElementSibling as HTMLInputElement).focus()
return previousElementSibling.focus()
}

target.setSelectionRange(0, value.length)
Expand Down

0 comments on commit 52ce497

Please sign in to comment.