UNPKG

@equinor/eds-core-react

Version:

The React implementation of the Equinor Design System

83 lines (80 loc) 2.67 kB
import { forwardRef, useRef, useState, useEffect, useMemo } from 'react'; import styled from 'styled-components'; import { search, close } from '@equinor/eds-icons'; import { Button } from '../Button/index.js'; import { Icon } from '../Icon/index.js'; import { mergeRefs, setReactInputValue } from '@equinor/eds-utils'; import { jsx, Fragment } from 'react/jsx-runtime'; import { InputWrapper } from '../InputWrapper/InputWrapper.js'; import { Input } from '../Input/Input.js'; const SearchInput = styled(Input).withConfig({ displayName: "Search__SearchInput", componentId: "sc-v8l23u-0" })(["input{&[type='search']::-webkit-search-decoration,&[type='search']::-webkit-search-cancel-button,&[type='search']::-webkit-search-results-button,&[type='search']::-webkit-search-results-decoration{-webkit-appearance:none;}}"]); const InsideButton = styled(Button).withConfig({ displayName: "Search__InsideButton", componentId: "sc-v8l23u-1" })(["height:24px;width:24px;"]); const Search = /*#__PURE__*/forwardRef(function Search({ onChange, style, className, ...rest }, ref) { const inputRef = useRef(null); const [showClear, setShowClear] = useState(Boolean(rest.defaultValue)); useEffect(() => { if (rest.disabled) { setShowClear(false); } else if (rest.value) { setShowClear(Boolean(rest.value)); } }, [rest.value, rest.disabled]); const clearInputValue = () => { const input = inputRef.current; const clearedValue = ''; setReactInputValue(input, clearedValue); }; const handleOnChange = e => { setShowClear(Boolean(e.currentTarget.value)); }; const combinedRef = useMemo(() => mergeRefs(inputRef, ref), [inputRef, ref]); return /*#__PURE__*/jsx(InputWrapper, { role: "search", style: style, className: className, children: /*#__PURE__*/jsx(SearchInput, { onChange: e => { handleOnChange(e); if (onChange) { onChange(e); } }, ref: combinedRef, leftAdornmentsWidth: 24 + 8, leftAdornments: /*#__PURE__*/jsx(Icon, { data: search, "aria-hidden": true, size: 18 }), rightAdornmentsWidth: 24 + 8, rightAdornments: /*#__PURE__*/jsx(Fragment, { children: showClear && /*#__PURE__*/jsx(InsideButton, { "aria-label": 'clear search', title: "clear", variant: "ghost_icon", onClick: e => { e.stopPropagation(); clearInputValue(); }, children: /*#__PURE__*/jsx(Icon, { data: close, size: 16 }) }) }), ...rest }) }); }); export { Search };