import type { ForwardedRef } from 'react'; import React, { useEffect, useId, useRef, useState } from 'react'; import { forwardRef } from '../../../utils/forwardRef'; import type { FormRowProps } from '../../FormRow/FormRow'; import { FormRow } from '../../FormRow/FormRow'; import type { FormRowHelperTextOwnProps } from '../../FormRow/FormRowHelperText'; import { IconButton } from '../../IconButton/IconButton'; import type { SingleSelectProps } from '../../Inputs/SingleSelect/SingleSelect'; import { SingleSelect } from '../../Inputs/SingleSelect/SingleSelect'; import { TextInput } from '../../Inputs/TextInput/TextInput'; interface SelectAddFieldInheritedProps extends Partial, Omit { label: string; } export interface SelectAddFieldProps extends Omit, 'error' | 'warning' | 'mode' | 'onQueryBlur' | 'onQueryChange' | 'onQueryFocus'>, SelectAddFieldInheritedProps {} export const SelectAddField = Object.assign( forwardRef(function SelectAddField( { error, hint, id, justify, value, label, required, tooltip, warning, options, width, onChange, labelHidden, ...rest }: SelectAddFieldProps, forwardedRef: ForwardedRef ) { const internalId = useId(); const inputId = id ?? `selectAdd${internalId}`; const [isAdding, setIsAdding] = useState(false); const [inputValue, setInputValue] = useState(''); const [selectValue, setSelectValue] = useState(value ?? ''); const inputRef = useRef(null); useEffect(() => { if (isAdding && inputRef.current) { inputRef.current.focus(); } }, [isAdding]); const handleAddClick = (e: React.MouseEvent) => { e.preventDefault(); setIsAdding(true); onChange?.(inputValue); }; const handleCancelClick = (e: React.MouseEvent) => { e.preventDefault(); setIsAdding(false); onChange?.(selectValue); }; const handleInputChange = (value: string) => { setInputValue(value); onChange?.(value); }; const handleSelectChange = (option: string) => { setSelectValue(option); onChange?.(option); }; const selectElement = React.cloneElement( handleSelectChange(value ?? '')} options={options} error={!!error} warning={!!warning} label={label} width={width} {...rest} />, isAdding ? { hidden: true } : {} ); return (
{!isAdding && selectElement} {isAdding && ( )}
{isAdding ? ( ) : ( )}
); }), { Option: SingleSelect.Option, } );