-
Notifications
You must be signed in to change notification settings - Fork 4k
/
flat-term-selector.js
225 lines (206 loc) · 6.54 KB
/
flat-term-selector.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
/**
* External dependencies
*/
import { isEmpty, get, unescape as unescapeString, find, throttle, uniqBy, invoke } from 'lodash';
import { stringify } from 'querystring';
/**
* WordPress dependencies
*/
import { __, _x, sprintf } from '@wordpress/i18n';
import { Component, compose } from '@wordpress/element';
import { FormTokenField, withAPIData } from '@wordpress/components';
import { withSelect, withDispatch } from '@wordpress/data';
import apiRequest from '@wordpress/api-request';
/**
* Module constants
*/
const DEFAULT_QUERY = {
per_page: -1,
orderby: 'count',
order: 'desc',
_fields: 'id,name',
};
const MAX_TERMS_SUGGESTIONS = 20;
const isSameTermName = ( termA, termB ) => termA.toLowerCase() === termB.toLowerCase();
class FlatTermSelector extends Component {
constructor() {
super( ...arguments );
this.onChange = this.onChange.bind( this );
this.searchTerms = throttle( this.searchTerms.bind( this ), 500 );
this.findOrCreateTerm = this.findOrCreateTerm.bind( this );
this.state = {
loading: false,
availableTerms: [],
selectedTerms: [],
};
}
componentDidMount() {
if ( ! isEmpty( this.props.terms ) ) {
this.setState( { loading: false } );
this.initRequest = this.fetchTerms( {
include: this.props.terms.join( ',' ),
per_page: 100,
} );
this.initRequest.then(
() => {
this.setState( { loading: false } );
},
( xhr ) => {
if ( xhr.statusText === 'abort' ) {
return;
}
this.setState( {
loading: false,
} );
}
);
}
this.searchTerms();
}
componentWillUnmount() {
invoke( this.initRequest, [ 'abort' ] );
invoke( this.searchRequest, [ 'abort' ] );
}
componentDidUpdate( prevProps ) {
if ( prevProps.terms !== this.props.terms ) {
this.updateSelectedTerms( this.props.terms );
}
}
fetchTerms( params = {} ) {
const query = { ...DEFAULT_QUERY, ...params };
const basePath = wp.api.getTaxonomyRoute( this.props.slug );
const request = apiRequest( { path: `/wp/v2/${ basePath }?${ stringify( query ) }` } );
request.then( ( terms ) => {
this.setState( ( state ) => ( {
availableTerms: state.availableTerms.concat(
terms.filter( ( term ) => ! find( state.availableTerms, ( availableTerm ) => availableTerm.id === term.id ) )
),
} ) );
this.updateSelectedTerms( this.props.terms );
} );
return request;
}
updateSelectedTerms( terms = [] ) {
const selectedTerms = terms.reduce( ( result, termId ) => {
const termObject = find( this.state.availableTerms, ( term ) => term.id === termId );
if ( termObject ) {
result.push( termObject.name );
}
return result;
}, [] );
this.setState( {
selectedTerms,
} );
}
findOrCreateTerm( termName ) {
return new Promise( ( resolve, reject ) => {
// Tries to create a term or fetch it if it already exists
const basePath = wp.api.getTaxonomyRoute( this.props.slug );
apiRequest( {
path: `/wp/v2/${ basePath }`,
method: 'POST',
data: { name: termName },
} ).then( resolve, ( xhr ) => {
const errorCode = xhr.responseJSON && xhr.responseJSON.code;
if ( errorCode === 'term_exists' ) {
// search the new category created since last fetch
this.addRequest = apiRequest( {
path: `/wp/v2/${ basePath }?${ stringify( { ...DEFAULT_QUERY, search: termName } ) }`,
} );
return this.addRequest.then( ( searchResult ) => {
resolve( find( searchResult, ( result ) => isSameTermName( result.name, termName ) ) );
}, reject );
}
reject( xhr );
} );
} );
}
onChange( termNames ) {
const uniqueTerms = uniqBy( termNames, ( term ) => term.toLowerCase() );
this.setState( { selectedTerms: uniqueTerms } );
const newTermNames = uniqueTerms.filter( ( termName ) =>
! find( this.state.availableTerms, ( term ) => isSameTermName( term.name, termName ) )
);
const termNamesToIds = ( names, availableTerms ) => {
return names
.map( ( termName ) =>
find( availableTerms, ( term ) => isSameTermName( term.name, termName ) ).id
);
};
if ( newTermNames.length === 0 ) {
return this.props.onUpdateTerms( termNamesToIds( uniqueTerms, this.state.availableTerms ), this.props.restBase );
}
Promise
.all( newTermNames.map( this.findOrCreateTerm ) )
.then( ( newTerms ) => {
const newAvailableTerms = this.state.availableTerms.concat( newTerms );
this.setState( { availableTerms: newAvailableTerms } );
return this.props.onUpdateTerms( termNamesToIds( uniqueTerms, newAvailableTerms ), this.props.restBase );
} );
}
searchTerms( search = '' ) {
invoke( this.searchRequest, [ 'abort' ] );
this.searchRequest = this.fetchTerms( { search } );
}
render() {
const { slug, taxonomy, hasAssignAction } = this.props;
if ( ! hasAssignAction ) {
return null;
}
const { loading, availableTerms, selectedTerms } = this.state;
const termNames = availableTerms.map( ( term ) => term.name );
const newTermPlaceholderLabel = get(
taxonomy,
[ 'data', 'labels', 'add_new_item' ],
slug === 'post_tag' ? __( 'Add New Tag' ) : __( 'Add New Term' )
);
const singularName = get(
taxonomy,
[ 'data', 'labels', 'singular_name' ],
slug === 'post_tag' ? __( 'Tag' ) : __( 'Term' )
);
const termAddedLabel = sprintf( _x( '%s added', 'term' ), singularName );
const termRemovedLabel = sprintf( _x( '%s removed', 'term' ), singularName );
const removeTermLabel = sprintf( _x( 'Remove %s', 'term' ), singularName );
return (
<FormTokenField
value={ selectedTerms }
displayTransform={ unescapeString }
suggestions={ termNames }
onChange={ this.onChange }
onInputChange={ this.searchTerms }
maxSuggestions={ MAX_TERMS_SUGGESTIONS }
disabled={ loading }
placeholder={ newTermPlaceholderLabel }
messages={ {
added: termAddedLabel,
removed: termRemovedLabel,
remove: removeTermLabel,
} }
/>
);
}
}
export default compose(
withAPIData( ( props ) => {
const { slug } = props;
return {
taxonomy: `/wp/v2/taxonomies/${ slug }?context=edit`,
};
} ),
withSelect( ( select, ownProps ) => {
const { getCurrentPost } = select( 'core/editor' );
return {
hasCreateAction: get( getCurrentPost(), [ '_links', 'wp:action-create-' + ownProps.restBase ], false ),
hasAssignAction: get( getCurrentPost(), [ '_links', 'wp:action-assign-' + ownProps.restBase ], false ),
terms: select( 'core/editor' ).getEditedPostAttribute( ownProps.restBase ),
};
} ),
withDispatch( ( dispatch ) => {
return {
onUpdateTerms( terms, restBase ) {
dispatch( 'core/editor' ).editPost( { [ restBase ]: terms } );
},
};
} )
)( FlatTermSelector );