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

Fix FormTokenField rendering #14819

Merged
merged 3 commits into from
Jul 31, 2019
Merged
Show file tree
Hide file tree
Changes from 2 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
67 changes: 41 additions & 26 deletions packages/components/src/form-token-field/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -48,13 +48,20 @@ class FormTokenField extends Component {
this.onInputChange = this.onInputChange.bind( this );
this.bindInput = this.bindInput.bind( this );
this.bindTokensAndInput = this.bindTokensAndInput.bind( this );
this.updateSuggestions = this.updateSuggestions.bind( this );
}

componentDidUpdate() {
componentDidUpdate( prevProps ) {
// Make sure to focus the input when the isActive state is true.
if ( this.state.isActive && ! this.input.hasFocus() ) {
this.input.focus();
}

const { suggestions, value } = this.props;
const suggestionsDidUpdate = suggestions !== prevProps.suggestions;
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This probably updates more than you're expecting it to, at least based on the shape of suggestions being an array, and the array being generated as a new value on each render.

Essentially, it comes down to:

const a = [ 'foo' ];
const b = [ 'foo' ];
console.log( a === b );
// false

Related: http://adripofjavascript.com/blog/drips/object-equality-in-javascript.html

At least in how this is used by FlatTermSelector, the array is a result of Array#map, so would be a new value on each render:

const termNames = availableTerms.map( ( term ) => term.name );

The map() method creates a new array with the results of calling a provided function on every element in the calling array.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map

Options:

  • Accept the fact that it renders more than we expect it to, but that it might benefit from some reuse if the references stay the same
  • Abandon any attempt to avoid updating and always update suggestions
  • Consider instead equality of members for sameness (@wordpress/is-shallow-equal). There is a small performance overhead to this, if it's worth considering the costliness vs. updateSuggestions (or whether updateSuggestions must only be called when in-fact it changes)

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hey @aduth - thanks for the feedback, and sorry for the super late reply. I missed this comment (and only read the review one further down). 🤦‍♂

You are absolutely right, and I now implemented isShallowEqual to compare suggestions. 👍

Is this PR all good now? (Build and tests are still pasing.) 🙂

if ( suggestionsDidUpdate || value !== prevProps.value ) {
this.updateSuggestions( suggestionsDidUpdate );
}
}

static getDerivedStateFromProps( props, state ) {
Expand Down Expand Up @@ -193,38 +200,14 @@ class FormTokenField extends Component {
const separator = this.props.tokenizeOnSpace ? /[ ,\t]+/ : /[,\t]+/;
const items = text.split( separator );
const tokenValue = last( items ) || '';
const inputHasMinimumChars = tokenValue.trim().length > 1;
const matchingSuggestions = this.getMatchingSuggestions( tokenValue );
const hasVisibleSuggestions = inputHasMinimumChars && !! matchingSuggestions.length;

if ( items.length > 1 ) {
this.addNewTokens( items.slice( 0, -1 ) );
}

this.setState( {
incompleteTokenValue: tokenValue,
selectedSuggestionIndex: -1,
selectedSuggestionScroll: false,
isExpanded: false,
} );
this.setState( { incompleteTokenValue: tokenValue }, this.updateSuggestions );
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Technically we could avoid this.updateSuggestions as the callback here and consolidate instead to componentDidUpdate (which can also detect the state change).


this.props.onInputChange( tokenValue );

if ( inputHasMinimumChars ) {
this.setState( {
isExpanded: hasVisibleSuggestions,
} );

if ( !! matchingSuggestions.length ) {
this.props.debouncedSpeak( sprintf( _n(
'%d result found, use up and down arrow keys to navigate.',
'%d results found, use up and down arrow keys to navigate.',
matchingSuggestions.length
), matchingSuggestions.length ), 'assertive' );
} else {
this.props.debouncedSpeak( __( 'No results.' ), 'assertive' );
}
}
}

handleDeleteKey( deleteToken ) {
Expand Down Expand Up @@ -467,6 +450,38 @@ class FormTokenField extends Component {
return this.props.saveTransform( this.state.incompleteTokenValue ).length > 0;
}

updateSuggestions( resetSelectedSuggestion = true ) {
const { incompleteTokenValue } = this.state;

const inputHasMinimumChars = incompleteTokenValue.trim().length > 1;
const matchingSuggestions = this.getMatchingSuggestions( incompleteTokenValue );
const hasMatchingSuggestions = matchingSuggestions.length > 0;

const newState = {
isExpanded: inputHasMinimumChars && hasMatchingSuggestions,
};
if ( resetSelectedSuggestion ) {
newState.selectedSuggestionIndex = -1;
newState.selectedSuggestionScroll = false;
}

this.setState( newState );

if ( inputHasMinimumChars ) {
const { debouncedSpeak } = this.props;

const message = hasMatchingSuggestions ?
sprintf( _n(
'%d result found, use up and down arrow keys to navigate.',
'%d results found, use up and down arrow keys to navigate.',
matchingSuggestions.length
), matchingSuggestions.length ) :
__( 'No results.' );

debouncedSpeak( message, 'assertive' );
}
}

renderTokensAndInput() {
const components = map( this.props.value, this.renderToken );
components.splice( this.getIndexOfInput(), 0, this.renderInput() );
Expand Down
20 changes: 20 additions & 0 deletions packages/components/src/form-token-field/test/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -237,6 +237,26 @@ describe( 'FormTokenField', function() {
expect( getSelectedSuggestion() ).toBe( null );
expect( getTokensHTML() ).toEqual( [ 'foo', 'bar', 'with' ] );
} );

it( 'should re-render when suggestions prop has changed', function() {
wrapper.setState( {
tokenSuggestions: [],
isExpanded: true,
} );
expect( getSuggestionsText() ).toEqual( [] );
setText( 'so' );
expect( getSuggestionsText() ).toEqual( [] );

wrapper.setState( {
tokenSuggestions: fixtures.specialSuggestions.default,
} );
expect( getSuggestionsText() ).toEqual( fixtures.matchingSuggestions.so );

wrapper.setState( {
tokenSuggestions: [],
} );
expect( getSuggestionsText() ).toEqual( [] );
} );
} );

describe( 'adding tokens', function() {
Expand Down
5 changes: 5 additions & 0 deletions packages/components/src/form-token-field/test/lib/fixtures.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,11 @@ export default {
htmlUnescaped: [ 'a   b', 'i <3 tags', '1&2&3&4' ],
},
specialSuggestions: {
default: [
'the', 'of', 'and', 'to', 'a', 'in', 'for', 'is', 'on', 'that', 'by', 'this', 'with', 'i', 'you', 'it',
'not', 'or', 'be', 'are', 'from', 'at', 'as', 'your', 'all', 'have', 'new', 'more', 'an', 'was', 'we',
'associate', 'snake', 'pipes', 'sound',
],
textEscaped: [ '<3', 'Stuff & Things', 'Tags & Stuff', 'Tags & Stuff 2' ],
textUnescaped: [ '<3', 'Stuff & Things', 'Tags & Stuff', 'Tags & Stuff 2' ],
matchAmpersandUnescaped: [
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,13 +11,10 @@ import { Component } from '@wordpress/element';
/**
* Internal dependencies
*/
import fixtures from './fixtures';
import TokenField from '../../';

const suggestions = [
'the', 'of', 'and', 'to', 'a', 'in', 'for', 'is', 'on', 'that', 'by', 'this', 'with', 'i', 'you', 'it',
'not', 'or', 'be', 'are', 'from', 'at', 'as', 'your', 'all', 'have', 'new', 'more', 'an', 'was', 'we',
'associate', 'snake', 'pipes', 'sound',
];
const { specialSuggestions: { default: suggestions } } = fixtures;

function unescapeAndFormatSpaces( str ) {
const nbsp = String.fromCharCode( 160 );
Expand Down