import { useId } from 'react'
import * as React from 'react'
import {
Input as UIInput,
InputNumeric as UIInputNumeric,
InputTime as UIInputTime,
} from '@planview/pv-uikit'
import type {
InputProps as UIInputProps,
InputNumericProps as UIInputNumericProps,
InputTimeProps as UIInputTimeProps,
} from '@planview/pv-uikit'
import Field from '../field'
import type { CounterProps } from '../utils/limit-counter'
import { useCounterLogic } from '../hooks/useCounterLogic'
type BaseInputProps
= Omit
&
Pick<
React.ComponentPropsWithRef,
'label' | 'error' | 'withAsterisk' | 'labelPosition' | 'warning'
> &
CounterProps
const asFormComponent = >(
ElementType: typeof UIInput | typeof UIInputNumeric | typeof UIInputTime,
displayName: string
): React.FC
=> {
const Component: React.FC
= ({
id: incomingId,
label,
labelPosition,
error,
warning,
withAsterisk,
defaultValue,
value,
onChange,
showCounter,
maxLength: maxLengthIncoming,
limit,
...inputProps
}) => {
const internalId = `pv-form-${useId()}`
const id = incomingId || internalId
const [uncontrolledLength, setUncontrolledLength] = React.useState(
defaultValue?.length || 0
)
const changeHandler = React.useCallback(
(changedVal: string, e?: React.ChangeEvent) => {
setUncontrolledLength(changedVal.length)
onChange?.(changedVal, e)
},
[onChange]
)
const length = value?.length || uncontrolledLength
const {
maxLength,
count,
fieldError,
handleBeforeInput,
handleBlur,
handleFocus,
handlePaste,
} = useCounterLogic({
length,
maxLength: maxLengthIncoming,
showCounter,
limit,
onBeforeInput: inputProps.nativeProps?.onBeforeInput,
onPaste: inputProps.nativeProps?.onPaste,
onFocus: inputProps.onFocus,
onBlur: inputProps.onBlur,
})
return (
{(fieldProps) => (
)}
)
}
Component.displayName = displayName
return Component
}
export type InputProps = BaseInputProps
/**
* Implementation combines [Form Field specification](https://design.planview.com/components/forms/form-field)
* with [Input specification](https://design.planview.com/components/forms/input).
*
* `import { Input } from '@planview/pv-form'`
*/
const Input = asFormComponent(UIInput, 'Input')
export type InputNumericProps = BaseInputProps
/**
* Implementation combines [Form Field specification](https://design.planview.com/components/forms/form-field)
* with [Input Number specification](https://design.planview.com/components/forms/input-numeric).
*
* `import { InputNumeric } from '@planview/pv-form'`
*/
const InputNumeric = asFormComponent(
UIInputNumeric,
'InputNumeric'
)
export type InputTimeProps = BaseInputProps>
/**
* Implementation combines [Form Field specification](https://design.planview.com/components/forms/form-field)
* with [Input Time specification](https://design.planview.com/components/forms/input-time).
*
* `import { InputTime } from '@planview/pv-form'`
*/
const InputTime = asFormComponent(UIInputTime, 'InputTime')
export { Input, InputNumeric, InputTime }
export default Input