import React, { Ref, useContext, useMemo, ReactNode, CSSProperties, useRef, useCallback, } from 'react'; import classnames from 'classnames'; import { FieldSetColumnContext } from './FieldSet'; import { createFC } from './common'; import { TooltipContent } from './TooltipContent'; /** * */ export type FormElementProps = { id?: string; className?: string; controlId?: string; label?: string; required?: boolean; error?: boolean | string | { message: string }; errorId?: string; readOnly?: boolean; cols?: number; dropdown?: JSX.Element; elementRef?: Ref; style?: CSSProperties; children?: ReactNode; tooltip?: ReactNode; tooltipIcon?: string; }; /** * */ export const FormElement = createFC< FormElementProps, { isFormElement: boolean } >( (props) => { const { id, className, controlId, cols = 1, elementRef, label, required, error, errorId, dropdown, children, readOnly, tooltip, tooltipIcon, } = props; const controlElRef = useRef(null); const { totalCols } = useContext(FieldSetColumnContext); const errorMessage = error ? typeof error === 'string' ? error : typeof error === 'object' ? error.message : undefined : undefined; const formElementClassNames = classnames( 'slds-form-element', readOnly ? 'slds-form-element_readonly' : null, error ? 'slds-has-error' : null, typeof totalCols === 'number' ? `slds-size_${cols}-of-${totalCols}` : null, className ); const onClickLabel = useCallback(() => { if (controlElRef.current) { const inputEl = controlElRef.current.querySelector( 'input,select,button' ); inputEl?.focus(); } }, []); const emptyCtx = useMemo(() => ({}), []); const LabelTag = readOnly ? 'span' : 'label'; return (
{label ? ( {required ? ( ) : undefined} {label} ) : null} {tooltip ? ( {tooltip} ) : null}
{readOnly ? (
{children}
) : ( children )} {dropdown} {errorMessage ? ( {errorMessage} ) : undefined}
); }, { isFormElement: true } );