ol-form-control.tsx 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. import { forwardRef } from 'react'
  2. import { Form } from 'react-bootstrap-5'
  3. import { FormControl as BS3FormControl } from 'react-bootstrap'
  4. import BootstrapVersionSwitcher from '@/features/ui/components/bootstrap-5/bootstrap-version-switcher'
  5. type OLFormControlProps = React.ComponentProps<(typeof Form)['Control']> & {
  6. bs3Props?: Record<string, unknown>
  7. }
  8. const OLFormControl = forwardRef<HTMLInputElement, OLFormControlProps>(
  9. (props, ref) => {
  10. const { bs3Props, ...rest } = props
  11. let bs3FormControlProps: React.ComponentProps<typeof BS3FormControl> = {
  12. id: rest.id,
  13. className: rest.className,
  14. style: rest.style,
  15. type: rest.type,
  16. value: rest.value,
  17. required: rest.required,
  18. disabled: rest.disabled,
  19. placeholder: rest.placeholder,
  20. readOnly: rest.readOnly,
  21. autoComplete: rest.autoComplete,
  22. minLength: rest.minLength,
  23. maxLength: rest.maxLength,
  24. onChange: rest.onChange as (e: React.ChangeEvent<unknown>) => void,
  25. onKeyDown: rest.onKeyDown as (e: React.KeyboardEvent<unknown>) => void,
  26. onFocus: rest.onFocus as (e: React.FocusEvent<unknown>) => void,
  27. onInvalid: rest.onInvalid as (e: React.InvalidEvent<unknown>) => void,
  28. inputRef: (inputElement: HTMLInputElement) => {
  29. if (typeof ref === 'function') {
  30. ref(inputElement)
  31. } else if (ref) {
  32. ref.current = inputElement
  33. }
  34. },
  35. ...bs3Props,
  36. }
  37. // get all `aria-*` and `data-*` attributes
  38. const extraProps = Object.entries(rest).reduce(
  39. (acc, [key, value]) => {
  40. if (key.startsWith('aria-') || key.startsWith('data-')) {
  41. acc[key] = value
  42. }
  43. return acc
  44. },
  45. {} as Record<string, string>
  46. )
  47. bs3FormControlProps = {
  48. ...bs3FormControlProps,
  49. ...extraProps,
  50. 'data-ol-dirty': rest['data-ol-dirty'],
  51. } as typeof bs3FormControlProps & Record<string, unknown>
  52. return (
  53. <BootstrapVersionSwitcher
  54. bs3={<BS3FormControl {...bs3FormControlProps} />}
  55. bs5={<Form.Control ref={ref} {...rest} />}
  56. />
  57. )
  58. }
  59. )
  60. OLFormControl.displayName = 'OLFormControl'
  61. export default OLFormControl