import * as React from 'react'; import classNames from 'classnames'; import Col, { ColProps } from '../grid/col'; import { FormLabelAlign } from './interface'; import { FormContext, FormContextProps } from './context'; import { RequiredMark } from './Form'; import { useLocaleReceiver } from '../locale-provider/LocaleReceiver'; import defaultLocale from '../locale/default'; export interface FormItemLabelProps { colon?: boolean; htmlFor?: string; label?: React.ReactNode; labelAlign?: FormLabelAlign; labelCol?: ColProps; requiredMark?: RequiredMark; } const FormItemLabel: React.FC = ({ prefixCls, label, htmlFor, labelCol, labelAlign, colon, required, requiredMark, }) => { const [formLocale] = useLocaleReceiver('Form'); if (!label) return null; return ( {({ vertical, labelAlign: contextLabelAlign, labelCol: contextLabelCol, colon: contextColon, }: FormContextProps) => { const mergedLabelCol: ColProps = labelCol || contextLabelCol || {}; const mergedLabelAlign: FormLabelAlign | undefined = labelAlign || contextLabelAlign; const labelClsBasic = `${prefixCls}-item-label`; const labelColClassName = classNames( labelClsBasic, mergedLabelAlign === 'left' && `${labelClsBasic}-left`, mergedLabelCol.className, ); let labelChildren = label; // Keep label is original where there should have no colon const computedColon = colon === true || (contextColon !== false && colon !== false); const haveColon = computedColon && !vertical; // Remove duplicated user input colon if (haveColon && typeof label === 'string' && (label as string).trim() !== '') { labelChildren = (label as string).replace(/[:|:]\s*$/, ''); } // Add required mark if optional if (requiredMark === 'optional' && !required) { labelChildren = ( <> {labelChildren} {formLocale?.optional || defaultLocale.Form?.optional} ); } const labelClassName = classNames({ [`${prefixCls}-item-required`]: required, [`${prefixCls}-item-required-mark-optional`]: requiredMark === 'optional', [`${prefixCls}-item-no-colon`]: !computedColon, }); return ( ); }} ); }; export default FormItemLabel;