Skip to content

Commit

Permalink
Block Editor: LinkControl: Allow onChange parent to manage focus
Browse files Browse the repository at this point in the history
  • Loading branch information
aduth committed Feb 1, 2020
1 parent 06bd266 commit f3be670
Show file tree
Hide file tree
Showing 2 changed files with 53 additions and 3 deletions.
4 changes: 2 additions & 2 deletions packages/block-editor/src/components/link-control/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -292,8 +292,8 @@ function LinkControl( {
) }
suggestion={ suggestion }
onClick={ () => {
stopEditing();
onChange( { ...value, ...suggestion } );
stopEditing();
} }
isSelected={ index === selectedSuggestion }
isURL={ manualLinkEntryTypes.includes(
Expand All @@ -318,8 +318,8 @@ function LinkControl( {
value={ inputValue }
onChange={ onInputChange }
onSelect={ ( suggestion ) => {
stopEditing();
onChange( { ...value, ...suggestion } );
stopEditing();
} }
renderSuggestions={ renderSearchResults }
fetchSuggestions={ getSearchHandler }
Expand Down
52 changes: 51 additions & 1 deletion packages/block-editor/src/components/link-control/test/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import { first, last, nth } from 'lodash';
/**
* WordPress dependencies
*/
import { useState } from '@wordpress/element';
import { useState, useRef } from '@wordpress/element';
import { UP, DOWN, ENTER } from '@wordpress/keycodes';
/**
* Internal dependencies
Expand Down Expand Up @@ -766,6 +766,56 @@ describe( 'Selecting links', () => {
}
);
} );

it( 'does not forcefully regain focus if onChange handler had ', () => {
// Regression: Previously, there had been issues where if `onChange`
// would programmatically shift focus, LinkControl would try to force it
// back, based on its internal logic to determine whether it had focus
// when finishing an edit occuring _before_ `onChange` having been run.
//
// See: https://github.com/WordPress/gutenberg/pull/19462

const LinkControlConsumer = () => {
const focusTarget = useRef();

return (
<>
<div tabIndex={ -1 } data-expected ref={ focusTarget } />
<LinkControl
onChange={ () => focusTarget.current.focus() }
/>
</>
);
};

act( () => {
render( <LinkControlConsumer />, container );
} );

// Change value.
const form = container.querySelector( 'form' );
const searchInput = container.querySelector(
'input[aria-label="URL"]'
);

// Simulate searching for a term
act( () => {
Simulate.change( searchInput, {
target: { value: 'https://example.com' },
} );
} );
act( () => {
Simulate.keyDown( searchInput, { keyCode: ENTER } );
} );
act( () => {
Simulate.submit( form );
} );

const isExpectedFocusTarget = document.activeElement.hasAttribute(
'data-expected'
);
expect( isExpectedFocusTarget ).toBe( true );
} );
} );

describe( 'Addition Settings UI', () => {
Expand Down

0 comments on commit f3be670

Please sign in to comment.