@engie-group/fluid-design-system-react
Version:
Fluid Design System React
61 lines (58 loc) • 3.07 kB
JavaScript
import { jsxs, jsx } from 'react/jsx-runtime';
import { Root as Slot } from '../../node_modules/.pnpm/@radix-ui_react-slot@1.2.3_@types_react@19.2.6_react@19.2.0/node_modules/@radix-ui/react-slot/dist/index.js';
import { forwardRef, useId, useState, useRef, useEffect } from 'react';
import { Utils } from '../../utils/util.js';
import { NJButton } from '../button/NJButton.js';
import { NJIcon } from '../icon/NJIcon.js';
import { NJIconButton } from '../icon-button/NJIconButton.js';
const rootClass = 'nj-search';
const NJInputSearch = forwardRef((props, forwardedRef) => {
const { onEnterKeyPress, onChange, resetButtonRef, value, buttonOptions, scale, disabled, placeholder, className: hostClass, buttonRef, ...htmlAttributes } = props;
const inputId = useId();
const [isFilled, setIsFilled] = useState(false);
const [controlledValue, setControlledValue] = useState(value ?? '');
const inputRef = useRef(null);
useEffect(() => {
if (value)
setIsFilled(typeof value === 'number' || value.length > 0);
setControlledValue(value ?? '');
}, [value]);
const focusInput = () => {
if (inputRef?.current) {
inputRef?.current.focus();
}
};
const updateControlledValue = (value) => {
setControlledValue(value);
setIsFilled(value.length > 0);
};
const resetInputState = () => {
const newValue = '';
updateControlledValue(newValue);
focusInput();
return newValue;
};
const onClearButtonClick = (e) => {
e.preventDefault();
const value = resetInputState();
onChange?.(e, value);
};
const onChangeValue = (e) => {
const newValue = e.target.value ?? '';
updateControlledValue(newValue);
onChange?.(e, newValue);
};
const onKeyDown = (e) => {
if (e.key === 'Enter') {
if (typeof onEnterKeyPress === 'function')
onEnterKeyPress(e, value);
}
props.onKeyDown?.(e);
};
const className = Utils.classNames(rootClass, {
[`${rootClass}--${scale}`]: !!scale
}, hostClass);
return (jsxs("div", { ...htmlAttributes, className: className, children: [jsxs("div", { className: `${rootClass}__field-wrapper`, children: [jsx("label", { htmlFor: inputId, children: jsx(NJIcon, { name: "search", "aria-label": "searchIcon", className: `${rootClass}__icon` }) }), jsx("input", { ref: Utils.mergeRefs([inputRef, forwardedRef]), id: inputId, className: `${rootClass}__field`, type: 'search', value: controlledValue, onChange: onChangeValue, disabled: disabled, onKeyDown: onKeyDown, placeholder: placeholder }), isFilled && (jsx(NJIconButton, { ref: resetButtonRef, icon: "cancel", "aria-label": "Clear Search", onClick: onClearButtonClick, className: `${rootClass}__clear-button` }))] }), buttonOptions && (jsx(Slot, { className: `${rootClass}__button`, children: jsx(NJButton, { ref: buttonRef, ...buttonOptions }) }))] }));
});
NJInputSearch.displayName = 'NJInputSearch';
export { NJInputSearch };