From 07efa91061f28610a3987fb08f9adc14a87c7927 Mon Sep 17 00:00:00 2001 From: TJ Egan Date: Wed, 17 Jan 2024 06:53:56 -0500 Subject: [PATCH] fix(ExpandableSearch): allow isExpanded state to be controlled (#15544) --- .../ExpandableSearch/ExpandableSearch.tsx | 10 +++++++--- .../src/components/Search/Search.stories.js | 19 ++++++++++++++++++- 2 files changed, 25 insertions(+), 4 deletions(-) diff --git a/packages/react/src/components/ExpandableSearch/ExpandableSearch.tsx b/packages/react/src/components/ExpandableSearch/ExpandableSearch.tsx index 412451f747b6..444935bd87f3 100644 --- a/packages/react/src/components/ExpandableSearch/ExpandableSearch.tsx +++ b/packages/react/src/components/ExpandableSearch/ExpandableSearch.tsx @@ -5,7 +5,7 @@ * LICENSE file in the root directory of this source tree. */ -import React, { useState, useRef } from 'react'; +import React, { useState, useRef, useEffect } from 'react'; import classnames from 'classnames'; import Search, { type SearchProps } from '../Search'; import { usePrefix } from '../../internal/usePrefix'; @@ -31,11 +31,15 @@ function ExpandableSearch({ evt.relatedTarget && evt.relatedTarget.classList.contains(`${prefix}--search-close`); - if (expanded && !relatedTargetIsAllowed && !hasContent) { + if (expanded && !relatedTargetIsAllowed && !hasContent && !isExpanded) { setExpanded(false); } } + useEffect(() => { + setExpanded(!!isExpanded); + }, [isExpanded]); + function handleChange(evt) { setHasContent(evt.target.value !== ''); } @@ -50,7 +54,7 @@ function ExpandableSearch({ evt.stopPropagation(); // escape key only clears if the input is empty, otherwise it clears the input - if (!evt.target?.value) { + if (!evt.target?.value && !isExpanded) { setExpanded(false); } } diff --git a/packages/react/src/components/Search/Search.stories.js b/packages/react/src/components/Search/Search.stories.js index ff8d62f7b17b..8f8d0182f7b8 100644 --- a/packages/react/src/components/Search/Search.stories.js +++ b/packages/react/src/components/Search/Search.stories.js @@ -5,12 +5,13 @@ * LICENSE file in the root directory of this source tree. */ -import React from 'react'; +import React, { useState, useCallback } from 'react'; import { WithLayer } from '../../../.storybook/templates/WithLayer'; import ExpandableSearch from '../ExpandableSearch'; import Search from '.'; +import Button from '../Button'; export default { title: 'Components/Search', @@ -27,6 +28,22 @@ export default { }, }; +export const Test = () => { + const [isExpanded, setExpanded] = useState(false); + + const handleToggleExpandClick = useCallback(() => { + setExpanded(!isExpanded); + }, [isExpanded]); + + return ( + <> +
isExpanded = {isExpanded.toString()}
+ + + + ); +}; + export const Default = () => (