Skip to content

Commit

Permalink
MaybeTagsPanel visibility
Browse files Browse the repository at this point in the history
We want the panel to be shown after the user adds a tag in
the pre-publish panel, so we can't rely on the props.hasTag value.
We need to derived it once it is fetched.
  • Loading branch information
oandregal committed Aug 1, 2018
1 parent f402272 commit 860ea4a
Showing 1 changed file with 40 additions and 4 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
* WordPress dependencies
*/
import { __ } from '@wordpress/i18n';
import { Component } from '@wordpress/element';
import { compose } from '@wordpress/compose';
import { withSelect } from '@wordpress/data';
import { Dashicon, PanelBody } from '@wordpress/components';
Expand All @@ -18,12 +19,47 @@ const TagsPanel = () => <PanelBody initialOpen={ true } title={ [
<FlatTermSelector slug={ 'post_tag' } />
</PanelBody>;

const MaybeTagsPanel = ( { isPostTypeSupported, hasTags } ) => {
if ( ! isPostTypeSupported || hasTags ) {
class MaybeTagsPanel extends Component {
constructor( props ) {
super( props );
this.state = {
hadTags: props.hasTags,
};
}

/*
* We use state.hadTags to track whether the post had tags when this
* component was first mounted.
*
* We can't rely on the props.hasTags value to do this check
* because when the user adds a tag to a post that didn't have one,
* the props.hasTags is going to change from false to true,
* forcing a re-render of this component and hiding it when it was previosly shown.
*
* We take advantage of the fact that the props.hasTags value is undefined
* if tags weren't fetched yet, otherwise it will be true of false.
*
*/
static getDerivedStateFromProps( props, state ) {
const { hadTags: currentHadTags } = state;
const { hasTags } = props;
if ( currentHadTags === undefined && hasTags !== undefined ) {
return {
hadTags: hasTags,
};
}
return null;
}
return ( <TagsPanel /> );
};

render() {
const { isPostTypeSupported } = this.props;
const { hadTags } = this.state;
if ( ! isPostTypeSupported || hadTags ) {
return null;
}
return ( <TagsPanel /> );
}
}

export default compose( [
withSelect( ( select ) => {
Expand Down

0 comments on commit 860ea4a

Please sign in to comment.