Skip to content

Commit

Permalink
Prevent clicks on multi-input from bubbling to container (#615, #650)
Browse files Browse the repository at this point in the history
  • Loading branch information
ericgio committed Jul 9, 2021
1 parent 81b3ea2 commit 1dd39d8
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 2 deletions.
17 changes: 16 additions & 1 deletion src/__tests__/components/TypeaheadInputMulti.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import TypeaheadInputMulti from '../../components/TypeaheadInputMulti';
import options from '../data';

import {
fireEvent,
getHint,
getInput,
getTokens,
Expand Down Expand Up @@ -78,7 +79,7 @@ describe('<TypeaheadInputMulti>', () => {

// No need to test the logic for `shouldSelectHint` here; just make sure
// it's passed through to the `Hint` component and called.
screen.getByRole('textbox').focus();
getInput(screen).focus();
userEvent.tab();
expect(shouldSelectHint).toHaveBeenCalledTimes(1);
});
Expand Down Expand Up @@ -106,6 +107,20 @@ describe('<TypeaheadInputMulti>', () => {
expect(disabledInput).not.toHaveFocus();
});

it('prevents clicks on the input from bubbling', () => {
const onClick = jest.fn();
render(<TestComponent context={{ text: 'calif' }} props={{ onClick }} />);

const input = getInput(screen);
input.selectionStart = 2;
// userEvent.click triggers the wrong behavior for some reason.
fireEvent.click(input);

// Cursor shouldn't move when the input is clicked once.
expect(onClick).toHaveBeenCalledTimes(1);
expect(input.selectionStart).toBe(2);
});

it('calls the keydown handler', () => {
const onKeyDown = jest.fn();
render(<TestComponent props={{ onKeyDown }} />);
Expand Down
11 changes: 10 additions & 1 deletion src/components/TypeaheadInputMulti.js
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,7 @@ class TypeaheadInputMulti extends React.Component<Props> {
<Input
{...props}
className={inputClassName}
onClick={this._handleClick}
onKeyDown={this._handleKeyDown}
placeholder={selected.length ? '' : placeholder}
ref={this.getInputRef}
Expand All @@ -80,6 +81,13 @@ class TypeaheadInputMulti extends React.Component<Props> {
this.props.inputRef(input);
}

_handleClick = (e: SyntheticEvent<HTMLInputElement>) => {
// Prevent clicks on the input from bubbling up to the container,
// which then re-focuses the input.
e.stopPropagation();
this.props.onClick(e);
}

/**
* Forward click or focus events on the container element to the input.
*/
Expand All @@ -92,11 +100,12 @@ class TypeaheadInputMulti extends React.Component<Props> {

// Move cursor to the end if the user clicks outside the actual input.
const inputNode = this._input;

if (!inputNode) {
return;
}

if (e.currentTarget !== inputNode && isSelectable(inputNode)) {
if (isSelectable(inputNode)) {
inputNode.selectionStart = inputNode.value.length;
}

Expand Down

0 comments on commit 1dd39d8

Please sign in to comment.