Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Refocus SearchField input field on clear button click #953

Merged
merged 4 commits into from
Dec 10, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/spicy-needles-shave.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@aws-amplify/ui-react": patch
---

Refocus `SearchField` input field on clear button click
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
import * as React from 'react';
import { renderHook } from '@testing-library/react-hooks';
import { useComposeRefsCallback } from '../useComposeRefsCallback';

const externalRef = React.createRef<HTMLInputElement>();
const internalRef = React.createRef<HTMLInputElement>();

let externalRefCallbackNode: HTMLInputElement;
const externalRefCallback = (node: HTMLInputElement) => {
externalRefCallbackNode = node;
};

describe('useComposeRefsCallback', () => {
it('should compose both internal RefObject and external RefObject', () => {
const callback = renderHook(() =>
useComposeRefsCallback({ externalRef, internalRef })
);

const inputNode = document.createElement('input');
callback.result.current(inputNode);

expect(internalRef.current).toBe(inputNode);
expect(externalRef.current).toBe(inputNode);
});

it('should compose both internal RefObject and external callback', () => {
const callback = renderHook(() =>
useComposeRefsCallback({ externalRef: externalRefCallback, internalRef })
);

const inputNode = document.createElement('input');
callback.result.current(inputNode);

expect(internalRef.current).toBe(inputNode);
expect(externalRefCallbackNode).toBe(inputNode);
});
});
27 changes: 27 additions & 0 deletions packages/react/src/hooks/useComposeRefsCallback.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
import * as React from 'react';

export interface UseComposeRefsCallbackProps<RefType> {
externalRef: React.ForwardedRef<RefType>;
internalRef: React.MutableRefObject<RefType>;
}

export type UseComposeRefsCallbackReturn<RefType> = (node: RefType) => void;

/**
* Creates ref callback to compose together external and internal refs
*/
export const useComposeRefsCallback = <RefType,>({
externalRef,
internalRef,
}: UseComposeRefsCallbackProps<RefType>): UseComposeRefsCallbackReturn<RefType> => {
return React.useCallback((node) => {
// Handle callback ref
if (typeof externalRef === 'function') {
externalRef(node);
} else if (externalRef != null) {
externalRef.current = node;
}

internalRef.current = node;
}, []);
};
74 changes: 5 additions & 69 deletions packages/react/src/primitives/SearchField/SearchField.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,74 +3,11 @@ import * as React from 'react';

import { ComponentClassNames } from '../shared/constants';
import { FieldClearButton } from '../Field';
import { isFunction, strHasLength } from '../shared/utils';
import { strHasLength } from '../shared/utils';
import { SearchFieldButton } from './SearchFieldButton';
import { SearchFieldProps, Primitive } from '../types';
import { TextField } from '../TextField';

const ESCAPE_KEY = 'Escape';
const ENTER_KEY = 'Enter';
const DEFAULT_KEYS = [ESCAPE_KEY, ENTER_KEY];

export const useSearchField = ({
onSubmit,
onClear,
}: Partial<SearchFieldProps>) => {
const [value, setValue] = React.useState<string>('');

const onClearHandler = React.useCallback(() => {
setValue('');

if (isFunction(onClear)) {
onClear();
}
}, [setValue, onClear]);

const onSubmitHandler = React.useCallback(
(value: string) => {
if (isFunction(onSubmit)) {
onSubmit(value);
}
},
[onSubmit]
);

const onKeyDown = React.useCallback(
(event) => {
const key = event.key;

if (DEFAULT_KEYS.includes(key)) {
event.preventDefault();
}

if (key === ESCAPE_KEY) {
onClearHandler();
} else if (key === ENTER_KEY) {
onSubmitHandler(value);
}
},
[value, onClearHandler, onSubmitHandler]
);

const onInput = React.useCallback(
(event) => {
setValue(event.target.value);
},
[setValue]
);

const onClick = React.useCallback(() => {
onSubmitHandler(value);
}, [onSubmitHandler, value]);

return {
value,
onClearHandler,
onKeyDown,
onInput,
onClick,
};
};
import { useSearchField } from './useSearchField';

const SearchFieldPrimitive: Primitive<SearchFieldProps, 'input'> = (
{
Expand All @@ -86,9 +23,8 @@ const SearchFieldPrimitive: Primitive<SearchFieldProps, 'input'> = (
},
ref
) => {
const { value, onClearHandler, onInput, onKeyDown, onClick } = useSearchField(
{ onSubmit, onClear }
);
const { value, onClearHandler, onInput, onKeyDown, onClick, composedRefs } =
useSearchField({ onSubmit, onClear, externalRef: ref });

return (
<TextField
Expand All @@ -115,7 +51,7 @@ const SearchFieldPrimitive: Primitive<SearchFieldProps, 'input'> = (
size={size}
/>
}
ref={ref}
ref={composedRefs}
size={size}
value={value}
{...rest}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,26 @@ describe('SearchField component', () => {
expect(searchButtonRef.current.nodeName).toBe('BUTTON');
});

it('should forward callback ref to DOM element', async () => {
let ref: HTMLInputElement;

const setRef = (node) => (ref = node);

render(
<SearchField
className="custom-class"
label={label}
name="q"
ref={setRef}
testId={testId}
/>
);

await screen.findByRole('button');

expect(ref.nodeName).toBe('INPUT');
});

it('should be text input type', async () => {
render(<SearchField label={label} name="q" />);

Expand Down Expand Up @@ -137,7 +157,7 @@ describe('SearchField component', () => {
});

describe(' - clear button', () => {
it('should clear text when clicked', async () => {
it('should clear text and refocus input when clicked', async () => {
render(<SearchField label={label} name="q" />);

const searchField = (await screen.findByLabelText(
Expand All @@ -150,6 +170,7 @@ describe('SearchField component', () => {
expect(searchField).toHaveValue(searchQuery);
userEvent.click(clearButton);
expect(searchField).toHaveValue('');
expect(searchField).toHaveFocus();
});
});
});
75 changes: 75 additions & 0 deletions packages/react/src/primitives/SearchField/useSearchField.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
import * as React from 'react';

import { isFunction } from '../shared/utils';
import { UseSearchFieldProps } from '../types';
import { useComposeRefsCallback } from '../../hooks/useComposeRefsCallback';

const ESCAPE_KEY = 'Escape';
const ENTER_KEY = 'Enter';
const DEFAULT_KEYS = new Set([ESCAPE_KEY, ENTER_KEY]);

export const useSearchField = ({
onSubmit,
onClear,
externalRef,
}: UseSearchFieldProps) => {
const [value, setValue] = React.useState<string>('');
const internalRef = React.useRef<HTMLInputElement>(null);
const composedRefs = useComposeRefsCallback({ externalRef, internalRef });

const onClearHandler = React.useCallback(() => {
setValue('');
internalRef?.current?.focus();
if (isFunction(onClear)) {
onClear();
}
}, [setValue, onClear]);

const onSubmitHandler = React.useCallback(
(value: string) => {
if (isFunction(onSubmit)) {
onSubmit(value);
}
},
[onSubmit]
);

const onKeyDown = React.useCallback(
(event) => {
const { key } = event;

if (!DEFAULT_KEYS.has(key)) {
return;
}

event.preventDefault();

if (key === ESCAPE_KEY) {
onClearHandler();
} else if (key === ENTER_KEY) {
onSubmitHandler(value);
}
},
[value, onClearHandler, onSubmitHandler]
);

const onInput = React.useCallback(
(event) => {
setValue(event.target.value);
},
[setValue]
);

const onClick = React.useCallback(() => {
onSubmitHandler(value);
}, [onSubmitHandler, value]);

return {
value,
onClearHandler,
onKeyDown,
onInput,
onClick,
composedRefs,
};
};
4 changes: 4 additions & 0 deletions packages/react/src/primitives/types/searchField.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,3 +27,7 @@ export interface SearchFieldProps extends TextInputFieldProps {

export interface SearchFieldButtonProps
extends Partial<FieldGroupIconButtonProps> {}

export type UseSearchFieldProps = Partial<SearchFieldProps> & {
externalRef?: React.ForwardedRef<HTMLInputElement>;
};