Skip to content

Commit

Permalink
fix(ExpandableSearch): allow isExpanded state to be controlled (#15544)
Browse files Browse the repository at this point in the history
  • Loading branch information
tw15egan committed Jan 17, 2024
1 parent d895119 commit 07efa91
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 4 deletions.
Expand Up @@ -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';
Expand All @@ -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 !== '');
}
Expand All @@ -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);
}
}
Expand Down
19 changes: 18 additions & 1 deletion packages/react/src/components/Search/Search.stories.js
Expand Up @@ -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',
Expand All @@ -27,6 +28,22 @@ export default {
},
};

export const Test = () => {
const [isExpanded, setExpanded] = useState(false);

const handleToggleExpandClick = useCallback(() => {
setExpanded(!isExpanded);
}, [isExpanded]);

return (
<>
<div>isExpanded = {isExpanded.toString()}</div>
<ExpandableSearch isExpanded={isExpanded} />
<Button onClick={handleToggleExpandClick}>Toggle Expand</Button>
</>
);
};

export const Default = () => (
<Search
size="lg"
Expand Down

0 comments on commit 07efa91

Please sign in to comment.