-
Notifications
You must be signed in to change notification settings - Fork 4.3k
/
Copy pathhierarchical-term-selector.js
330 lines (309 loc) · 9.24 KB
/
hierarchical-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
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
/**
* External dependencies
*/
import { get, unescape as unescapeString, without, find, some, invoke } from 'lodash';
import { stringify } from 'querystring';
/**
* WordPress dependencies
*/
import { __, _x, sprintf } from '@wordpress/i18n';
import { Component } from '@wordpress/element';
import { TreeSelect, withAPIData, withSpokenMessages, Button } from '@wordpress/components';
import { withSelect, withDispatch } from '@wordpress/data';
import { withInstanceId, compose } from '@wordpress/compose';
import apiFetch from '@wordpress/api-fetch';
/**
* Internal dependencies
*/
import { buildTermsTree } from '../../utils/terms';
/**
* Module Constants
*/
const DEFAULT_QUERY = {
per_page: -1,
orderby: 'count',
order: 'desc',
_fields: 'id,name,parent',
};
class HierarchicalTermSelector extends Component {
constructor() {
super( ...arguments );
this.findTerm = this.findTerm.bind( this );
this.onChange = this.onChange.bind( this );
this.onChangeFormName = this.onChangeFormName.bind( this );
this.onChangeFormParent = this.onChangeFormParent.bind( this );
this.onAddTerm = this.onAddTerm.bind( this );
this.onToggleForm = this.onToggleForm.bind( this );
this.state = {
loading: true,
availableTermsTree: [],
availableTerms: [],
adding: false,
formName: '',
formParent: '',
showForm: false,
};
}
onChange( event ) {
const { onUpdateTerms, terms = [], restBase } = this.props;
const termId = parseInt( event.target.value, 10 );
const hasTerm = terms.indexOf( termId ) !== -1;
const newTerms = hasTerm ?
without( terms, termId ) :
[ ...terms, termId ];
onUpdateTerms( newTerms, restBase );
}
onChangeFormName( event ) {
const newValue = event.target.value.trim() === '' ? '' : event.target.value;
this.setState( { formName: newValue } );
}
onChangeFormParent( newParent ) {
this.setState( { formParent: newParent } );
}
onToggleForm() {
this.setState( ( state ) => ( {
showForm: ! state.showForm,
} ) );
}
findTerm( terms, parent, name ) {
return find( terms, ( term ) => {
return ( ( ! term.parent && ! parent ) || parseInt( term.parent ) === parseInt( parent ) ) &&
term.name.toLowerCase() === name.toLowerCase();
} );
}
onAddTerm( event ) {
event.preventDefault();
const { onUpdateTerms, restBase, terms, slug } = this.props;
const { formName, formParent, adding, availableTerms } = this.state;
if ( formName === '' || adding ) {
return;
}
// check if the term we are adding already exists
const existingTerm = this.findTerm( availableTerms, formParent, formName );
if ( existingTerm ) {
// if the term we are adding exists but is not selected select it
if ( ! some( terms, ( term ) => term === existingTerm.id ) ) {
onUpdateTerms( [ ...terms, existingTerm.id ], restBase );
}
this.setState( {
formName: '',
formParent: '',
} );
return;
}
this.setState( {
adding: true,
} );
const basePath = wp.api.getTaxonomyRoute( this.props.slug );
this.addRequest = apiFetch( {
path: `/wp/v2/${ basePath }`,
method: 'POST',
data: {
name: formName,
parent: formParent ? formParent : undefined,
},
} );
// Tries to create a term or fetch it if it already exists
const findOrCreatePromise = this.addRequest
.catch( ( error ) => {
const errorCode = error.code;
if ( errorCode === 'term_exists' ) {
// search the new category created since last fetch
this.addRequest = apiFetch( {
path: `/wp/v2/${ basePath }?${ stringify( { ...DEFAULT_QUERY, parent: formParent || 0, search: formName } ) }`,
} );
return this.addRequest
.then( ( searchResult ) => {
return this.findTerm( searchResult, formParent, formName );
} );
}
return Promise.reject( error );
} );
findOrCreatePromise
.then( ( term ) => {
const hasTerm = !! find( this.state.availableTerms, ( availableTerm ) => availableTerm.id === term.id );
const newAvailableTerms = hasTerm ? this.state.availableTerms : [ term, ...this.state.availableTerms ];
const termAddedMessage = sprintf(
_x( '%s added', 'term' ),
get(
this.props.taxonomy,
[ 'data', 'labels', 'singular_name' ],
slug === 'category' ? __( 'Category' ) : __( 'Term' )
)
);
this.props.speak( termAddedMessage, 'assertive' );
this.addRequest = null;
this.setState( {
adding: false,
formName: '',
formParent: '',
availableTerms: newAvailableTerms,
availableTermsTree: buildTermsTree( newAvailableTerms ),
} );
onUpdateTerms( [ ...terms, term.id ], restBase );
}, ( xhr ) => {
if ( xhr.statusText === 'abort' ) {
return;
}
this.addRequest = null;
this.setState( {
adding: false,
} );
} );
}
componentDidMount() {
const basePath = wp.api.getTaxonomyRoute( this.props.slug );
this.fetchRequest = apiFetch( { path: `/wp/v2/${ basePath }?${ stringify( DEFAULT_QUERY ) }` } );
this.fetchRequest.then(
( terms ) => { // resolve
const availableTermsTree = buildTermsTree( terms );
this.fetchRequest = null;
this.setState( {
loading: false,
availableTermsTree,
availableTerms: terms,
} );
},
( xhr ) => { // reject
if ( xhr.statusText === 'abort' ) {
return;
}
this.fetchRequest = null;
this.setState( {
loading: false,
} );
}
);
}
componentWillUnmount() {
invoke( this.fetchRequest, [ 'abort' ] );
invoke( this.addRequest, [ 'abort' ] );
}
renderTerms( renderedTerms ) {
const { terms = [] } = this.props;
return renderedTerms.map( ( term ) => {
const id = `editor-post-taxonomies-hierarchical-term-${ term.id }`;
return (
<div key={ term.id } className="editor-post-taxonomies__hierarchical-terms-choice">
<input
id={ id }
className="editor-post-taxonomies__hierarchical-terms-input"
type="checkbox"
checked={ terms.indexOf( term.id ) !== -1 }
value={ term.id }
onChange={ this.onChange }
/>
<label htmlFor={ id }>{ unescapeString( term.name ) }</label>
{ !! term.children.length && (
<div className="editor-post-taxonomies__hierarchical-terms-subchoices">
{ this.renderTerms( term.children ) }
</div>
) }
</div>
);
} );
}
render() {
const { slug, taxonomy, instanceId, hasCreateAction, hasAssignAction } = this.props;
if ( ! hasAssignAction ) {
return null;
}
const { availableTermsTree, availableTerms, formName, formParent, loading, showForm } = this.state;
const labelWithFallback = ( labelProperty, fallbackIsCategory, fallbackIsNotCategory ) => get(
taxonomy,
[ 'data', 'labels', labelProperty ],
slug === 'category' ? fallbackIsCategory : fallbackIsNotCategory
);
const newTermButtonLabel = labelWithFallback(
'add_new_item',
__( 'Add new category' ),
__( 'Add new term' )
);
const newTermLabel = labelWithFallback(
'new_item_name',
__( 'Add new category' ),
__( 'Add new term' )
);
const parentSelectLabel = labelWithFallback(
'parent_item',
__( 'Parent Category' ),
__( 'Parent Term' )
);
const noParentOption = `— ${ parentSelectLabel } —`;
const newTermSubmitLabel = newTermButtonLabel;
const inputId = `editor-post-taxonomies__hierarchical-terms-input-${ instanceId }`;
/* eslint-disable jsx-a11y/no-onchange */
return [
...this.renderTerms( availableTermsTree ),
! loading && hasCreateAction && (
<Button
key="term-add-button"
onClick={ this.onToggleForm }
className="editor-post-taxonomies__hierarchical-terms-add"
aria-expanded={ showForm }
isLink
>
{ newTermButtonLabel }
</Button>
),
showForm && (
<form onSubmit={ this.onAddTerm } key="hierarchical-terms-form">
<label
htmlFor={ inputId }
className="editor-post-taxonomies__hierarchical-terms-label"
>
{ newTermLabel }
</label>
<input
type="text"
id={ inputId }
className="editor-post-taxonomies__hierarchical-terms-input"
value={ formName }
onChange={ this.onChangeFormName }
required
/>
{ !! availableTerms.length &&
<TreeSelect
label={ parentSelectLabel }
noOptionLabel={ noParentOption }
onChange={ this.onChangeFormParent }
selectedId={ formParent }
tree={ availableTermsTree }
/>
}
<Button
isDefault
type="submit"
className="editor-post-taxonomies__hierarchical-terms-submit"
>
{ newTermSubmitLabel }
</Button>
</form>
),
];
/* eslint-enable jsx-a11y/no-onchange */
}
}
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 ) => ( {
onUpdateTerms( terms, restBase ) {
dispatch( 'core/editor' ).editPost( { [ restBase ]: terms } );
},
} ) ),
withSpokenMessages,
withInstanceId,
] )( HierarchicalTermSelector );