-
Notifications
You must be signed in to change notification settings - Fork 4.2k
/
flat-term-selector.js
283 lines (252 loc) · 6.76 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
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
/**
* WordPress dependencies
*/
import { __, _x, sprintf } from '@wordpress/i18n';
import { useEffect, useMemo, useState } from '@wordpress/element';
import { FormTokenField, withFilters } from '@wordpress/components';
import { useSelect, useDispatch } from '@wordpress/data';
import { store as coreStore } from '@wordpress/core-data';
import { useDebounce } from '@wordpress/compose';
import { speak } from '@wordpress/a11y';
import { store as noticesStore } from '@wordpress/notices';
/**
* Internal dependencies
*/
import { store as editorStore } from '../../store';
import { unescapeString, unescapeTerm } from '../../utils/terms';
import MostUsedTerms from './most-used-terms';
/**
* Shared reference to an empty array for cases where it is important to avoid
* returning a new array reference on every invocation.
*
* @type {Array<any>}
*/
const EMPTY_ARRAY = [];
/**
* Module constants
*/
const MAX_TERMS_SUGGESTIONS = 20;
const DEFAULT_QUERY = {
per_page: MAX_TERMS_SUGGESTIONS,
_fields: 'id,name',
context: 'view',
};
const isSameTermName = ( termA, termB ) =>
unescapeString( termA ).toLowerCase() ===
unescapeString( termB ).toLowerCase();
const termNamesToIds = ( names, terms ) => {
return names.map(
( termName ) =>
terms.find( ( term ) => isSameTermName( term.name, termName ) ).id
);
};
export function FlatTermSelector( { slug } ) {
const [ values, setValues ] = useState( [] );
const [ search, setSearch ] = useState( '' );
const debouncedSearch = useDebounce( setSearch, 500 );
const {
terms,
termIds,
taxonomy,
hasAssignAction,
hasCreateAction,
hasResolvedTerms,
} = useSelect(
( select ) => {
const { getCurrentPost, getEditedPostAttribute } =
select( editorStore );
const { getEntityRecords, getTaxonomy, hasFinishedResolution } =
select( coreStore );
const post = getCurrentPost();
const _taxonomy = getTaxonomy( slug );
const _termIds = _taxonomy
? getEditedPostAttribute( _taxonomy.rest_base )
: EMPTY_ARRAY;
const query = {
...DEFAULT_QUERY,
include: _termIds.join( ',' ),
per_page: -1,
};
return {
hasCreateAction: _taxonomy
? post._links?.[
'wp:action-create-' + _taxonomy.rest_base
] ?? false
: false,
hasAssignAction: _taxonomy
? post._links?.[
'wp:action-assign-' + _taxonomy.rest_base
] ?? false
: false,
taxonomy: _taxonomy,
termIds: _termIds,
terms: _termIds.length
? getEntityRecords( 'taxonomy', slug, query )
: EMPTY_ARRAY,
hasResolvedTerms: hasFinishedResolution( 'getEntityRecords', [
'taxonomy',
slug,
query,
] ),
};
},
[ slug ]
);
const { searchResults } = useSelect(
( select ) => {
const { getEntityRecords } = select( coreStore );
return {
searchResults: !! search
? getEntityRecords( 'taxonomy', slug, {
...DEFAULT_QUERY,
search,
} )
: EMPTY_ARRAY,
};
},
[ search, slug ]
);
// Update terms state only after the selectors are resolved.
// We're using this to avoid terms temporarily disappearing on slow networks
// while core data makes REST API requests.
useEffect( () => {
if ( hasResolvedTerms ) {
const newValues = ( terms ?? [] ).map( ( term ) =>
unescapeString( term.name )
);
setValues( newValues );
}
}, [ terms, hasResolvedTerms ] );
const suggestions = useMemo( () => {
return ( searchResults ?? [] ).map( ( term ) =>
unescapeString( term.name )
);
}, [ searchResults ] );
const { editPost } = useDispatch( editorStore );
const { saveEntityRecord } = useDispatch( coreStore );
const { createErrorNotice } = useDispatch( noticesStore );
if ( ! hasAssignAction ) {
return null;
}
async function findOrCreateTerm( term ) {
try {
const newTerm = await saveEntityRecord( 'taxonomy', slug, term, {
throwOnError: true,
} );
return unescapeTerm( newTerm );
} catch ( error ) {
if ( error.code !== 'term_exists' ) {
throw error;
}
return {
id: error.data.term_id,
name: term.name,
};
}
}
function onUpdateTerms( newTermIds ) {
editPost( { [ taxonomy.rest_base ]: newTermIds } );
}
function onChange( termNames ) {
const availableTerms = [
...( terms ?? [] ),
...( searchResults ?? [] ),
];
const uniqueTerms = termNames.reduce( ( acc, name ) => {
if (
! acc.some( ( n ) => n.toLowerCase() === name.toLowerCase() )
) {
acc.push( name );
}
return acc;
}, [] );
const newTermNames = uniqueTerms.filter(
( termName ) =>
! availableTerms.find( ( term ) =>
isSameTermName( term.name, termName )
)
);
// Optimistically update term values.
// The selector will always re-fetch terms later.
setValues( uniqueTerms );
if ( newTermNames.length === 0 ) {
return onUpdateTerms(
termNamesToIds( uniqueTerms, availableTerms )
);
}
if ( ! hasCreateAction ) {
return;
}
Promise.all(
newTermNames.map( ( termName ) =>
findOrCreateTerm( { name: termName } )
)
)
.then( ( newTerms ) => {
const newAvailableTerms = availableTerms.concat( newTerms );
return onUpdateTerms(
termNamesToIds( uniqueTerms, newAvailableTerms )
);
} )
.catch( ( error ) => {
createErrorNotice( error.message, {
type: 'snackbar',
} );
} );
}
function appendTerm( newTerm ) {
if ( termIds.includes( newTerm.id ) ) {
return;
}
const newTermIds = [ ...termIds, newTerm.id ];
const defaultName = slug === 'post_tag' ? __( 'Tag' ) : __( 'Term' );
const termAddedMessage = sprintf(
/* translators: %s: term name. */
_x( '%s added', 'term' ),
taxonomy?.labels?.singular_name ?? defaultName
);
speak( termAddedMessage, 'assertive' );
onUpdateTerms( newTermIds );
}
const newTermLabel =
taxonomy?.labels?.add_new_item ??
( slug === 'post_tag' ? __( 'Add new tag' ) : __( 'Add new Term' ) );
const singularName =
taxonomy?.labels?.singular_name ??
( slug === 'post_tag' ? __( 'Tag' ) : __( 'Term' ) );
const termAddedLabel = sprintf(
/* translators: %s: term name. */
_x( '%s added', 'term' ),
singularName
);
const termRemovedLabel = sprintf(
/* translators: %s: term name. */
_x( '%s removed', 'term' ),
singularName
);
const removeTermLabel = sprintf(
/* translators: %s: term name. */
_x( 'Remove %s', 'term' ),
singularName
);
return (
<>
<FormTokenField
__next40pxDefaultSize
value={ values }
suggestions={ suggestions }
onChange={ onChange }
onInputChange={ debouncedSearch }
maxSuggestions={ MAX_TERMS_SUGGESTIONS }
label={ newTermLabel }
messages={ {
added: termAddedLabel,
removed: termRemovedLabel,
remove: removeTermLabel,
} }
/>
<MostUsedTerms taxonomy={ taxonomy } onSelect={ appendTerm } />
</>
);
}
export default withFilters( 'editor.PostTaxonomyType' )( FlatTermSelector );