'use client'; import classnames from 'classnames'; import React, { useId, useState } from 'react'; import MdHelpButton from '../help/MdHelpButton'; import MdHelpText from '../help/MdHelpText'; import MdIconButton from '../iconButton/MdIconButton'; import MdIconSearch from '../icons-material/MdIconSearch'; interface Labels { helpTextFor?: string; searchButton?: string; } export interface MdInputSearchProps extends React.InputHTMLAttributes { label?: string; labels?: Labels; supportText?: string; helpText?: string; outerWrapperClass?: string; button?: boolean; mode?: 'small' | 'medium' | 'large'; onSearch: (term: string) => void; } export const MdInputSearch = React.forwardRef( ( { label, labels = {}, id, supportText, helpText, outerWrapperClass = '', className = '', mode = 'medium', button = true, onSearch, ...otherProps }, ref, ) => { const [helpOpen, setHelpOpen] = useState(false); const uuid = useId(); const inputId = id && id !== '' ? id : uuid; const defaultLabels: Required = { helpTextFor: 'Hjelpetekst for', searchButton: 'Søk', }; const mergedLabels: Required = { ...defaultLabels, ...labels }; const classNames = classnames( 'md-inputsearch', { 'md-inputsearch--small': mode === 'small', 'md-inputsearch--large': mode === 'large', 'md-inputsearch--button': button, 'md-inputsearch--has-prefix': !button, }, className, ); const wrapperClassNames = classnames('md-inputsearch__wrapper', { 'md-inputsearch__wrapper--small': mode === 'small', 'md-inputsearch__wrapper--large': mode === 'large', }); const outerWrapperClasses = classnames( 'md-inputsearch__outer-wrapper', { 'md-inputsearch__outer-wrapper--small': mode === 'small', 'md-inputsearch__outer-wrapper--large': mode === 'large', }, outerWrapperClass, ); // Build aria-describedby in order of priority: help → support const ariaDescribedBy = [ helpText && helpText !== '' && `md-inputsearch_help-text_${inputId}`, supportText && supportText !== '' && `md-inputsearch_support_${inputId}`, ] .filter(Boolean) .join(' ') || undefined; const showLabel = (label && label !== '') || (helpText && helpText !== ''); return (
{showLabel && (
{label && label !== '' && } {helpText && helpText !== '' && (
{ setHelpOpen(!helpOpen); }} expanded={helpOpen} />
)}
{helpText && helpText !== '' && (
{helpText}
)}
)}
{ e.preventDefault(); const input = e.currentTarget.querySelector('input'); const searchValue = input?.value || ''; onSearch(searchValue); }} > {!button && ( )} {button && ( )}
{supportText && supportText !== '' && (
{supportText}
)}
); }, ); MdInputSearch.displayName = 'MdInputSearch'; export default MdInputSearch;