You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
49 lines
1.1 KiB
49 lines
1.1 KiB
import type { ChangeEvent } from 'react'
|
|
import { useState } from 'react'
|
|
|
|
import isNaN from 'lodash/isNaN'
|
|
|
|
import type { EpisodeDuration } from '../../types'
|
|
|
|
const LIMITS = {
|
|
max: 30,
|
|
min: 1,
|
|
}
|
|
|
|
const isValidDuration = (value: number) => (
|
|
isFinite(value)
|
|
&& value >= LIMITS.min
|
|
&& value <= LIMITS.max
|
|
)
|
|
|
|
export type Props = {
|
|
onChange: (duration: EpisodeDuration) => void,
|
|
value: EpisodeDuration,
|
|
}
|
|
|
|
export const useInputHandlers = ({ onChange, value: initialValue }: Props) => {
|
|
const [duration, setDuration] = useState(initialValue)
|
|
const handleChange = (key: 'before' | 'after') => (
|
|
(e: ChangeEvent<HTMLInputElement>) => {
|
|
const seconds = Number(e.target.value)
|
|
setDuration({
|
|
...duration,
|
|
[key]: isNaN(seconds) ? '' : seconds,
|
|
})
|
|
}
|
|
)
|
|
|
|
const handleBlur = () => {
|
|
const { after, before } = duration
|
|
if (isValidDuration(before) && isValidDuration(after)) {
|
|
onChange(duration)
|
|
} else {
|
|
setDuration(initialValue)
|
|
}
|
|
}
|
|
return {
|
|
duration,
|
|
handleBlur,
|
|
handleChange,
|
|
}
|
|
}
|
|
|