'use client'; import classnames from 'classnames'; import React, { useId, useState } from 'react'; import MdHelpButton from '../help/MdHelpButton'; import MdHelpText from '../help/MdHelpText'; import MdCheckbox from './MdCheckbox'; import type { ChangeEvent } from 'react'; interface Labels { helpTextFor?: string; } /** * 3.0.0: Replaces previous type MdCheckboxGroupOptionProps. */ export interface MdCheckboxGroupOption { value: string; text?: string; disabled?: boolean; } export interface MdCheckboxGroupProps { options?: MdCheckboxGroupOption[]; selectedOptions?: MdCheckboxGroupOption[]; label?: string; labels?: Labels; id?: string; disabled?: boolean; direction?: 'horizontal' | 'vertical' | 'grid'; columns?: number; className?: string; error?: boolean; /** * v6.0.0: Added `errorText` prop to display error messages, this is now required to set error state. */ errorText?: string; helpText?: string; onChange?(_e: ChangeEvent): void; onBlur?(_e: React.FocusEvent): void; onFocus?(_e: React.FocusEvent): void; } export const MdCheckboxGroup: React.FunctionComponent = ({ options = [], selectedOptions, label, id, disabled = false, direction, columns = 2, className = '', error = false, errorText, helpText, onChange, onFocus, onBlur, labels = {}, ...otherProps }: MdCheckboxGroupProps) => { const uuid = useId(); const checkboxGroupId = id || uuid; const [helpOpen, setHelpOpen] = useState(false); const defaultLabels: Required = { helpTextFor: 'Hjelpetekst for', }; const mergedLabels: Required = { ...defaultLabels, ...labels }; const classNames = classnames( 'md-checkboxgroup', { 'md-checkboxgroup--disabled': !!disabled, }, className, ); const optionsClassNames = classnames('md-checkboxgroup__options', { 'md-checkboxgroup__options--vertical': direction === 'vertical', 'md-checkboxgroup__options--grid': direction === 'grid', }); const optionIsSelected = (option: MdCheckboxGroupOption) => { if (selectedOptions) { const find = selectedOptions.find(item => { return item.value === option.value; }); return find !== undefined; } return false; }; const handleChange = (e: ChangeEvent) => { if (onChange) { onChange(e); } }; const handleFocus = (e: React.FocusEvent) => { if (onFocus) { onFocus(e); } }; const handleBlur = (e: React.FocusEvent) => { if (onBlur) { onBlur(e); } }; const showLabel = (label && label !== '') || (helpText && helpText !== ''); return (
{showLabel && (
{label && label !== '' &&
{label}
} {helpText && helpText !== '' && ( { return setHelpOpen(!helpOpen); }} expanded={helpOpen} /> )}
{helpText && helpText !== '' && (
{helpText}
)}
)}
{options.map(option => { return ( ); })}
{error && errorText && errorText !== '' &&
{errorText}
}
); }; export default MdCheckboxGroup;