-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat(components): add debounced-textfield (#3)
* feat: add a debounced-textfield componet * feat: add a debounced-textfield componet * feat: add a debounced-textfield componet * feat: add a debounced-textfield componet
- Loading branch information
Showing
2 changed files
with
50 additions
and
4 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,45 @@ | ||
import type { ChangeEventHandler, FC, FocusEventHandler, ReactNode } from 'react' | ||
|
||
import { TextField } from '@radix-ui/themes' | ||
import { useCallback, useState } from 'react' | ||
|
||
interface WithOnBlurValueProps { | ||
onBlurValueChange?: (text: string) => undefined | void | ||
} | ||
|
||
interface WithOnBlurValueRequiredProps { | ||
children?: ReactNode | ||
onBlur?: FocusEventHandler<HTMLInputElement> | ||
onChange?: ChangeEventHandler<HTMLInputElement> | ||
value?: number | string | ||
} | ||
|
||
const withOnBlurValue = <P extends WithOnBlurValueRequiredProps>(Component: FC<P>): FC<P & WithOnBlurValueProps> => ({ | ||
onBlur, | ||
onBlurValueChange, | ||
onChange, | ||
value, | ||
...rest | ||
}) => { | ||
const [indeterminate, setIndeterminate] = useState<typeof value>(undefined) | ||
const [prevValue, setPrevValue] = useState(value) | ||
if (prevValue !== value) { | ||
setPrevValue(value) | ||
setIndeterminate(undefined) | ||
} | ||
const _onBlur = useCallback<Exclude<typeof onBlur, undefined>>((e) => { | ||
onBlur?.(e) | ||
if (indeterminate !== undefined) { | ||
onBlurValueChange?.(indeterminate.toString()) | ||
setIndeterminate(undefined) | ||
} | ||
}, [onBlur, onBlurValueChange, indeterminate, setIndeterminate]) | ||
const _onChange = useCallback<Exclude<typeof onChange, undefined>>((e) => { | ||
onChange?.(e) | ||
setIndeterminate(e.currentTarget.value) | ||
}, [onChange, setIndeterminate]) | ||
const p = { onBlur: _onBlur, onChange: _onChange, value: indeterminate ?? value, ...rest } | ||
return <Component {...p as P} /> | ||
} | ||
|
||
export const DebouncedTextField = withOnBlurValue(TextField.Root) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters