-
Notifications
You must be signed in to change notification settings - Fork 4.2k
/
menu.js
550 lines (499 loc) · 15.7 KB
/
menu.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
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
/**
* External dependencies
*/
import {
filter,
find,
findIndex,
flow,
groupBy,
isEmpty,
map,
some,
sortBy,
without,
includes,
deburr,
} from 'lodash';
import scrollIntoView from 'dom-scroll-into-view';
import classnames from 'classnames';
/**
* WordPress dependencies
*/
import { __, _n, _x, sprintf } from '@wordpress/i18n';
import { Component, createRef } from '@wordpress/element';
import {
PanelBody,
withSpokenMessages,
Tip,
} from '@wordpress/components';
import {
getCategories,
isReusableBlock,
createBlock,
isUnmodifiedDefaultBlock,
getBlockType,
} from '@wordpress/blocks';
import { withDispatch, withSelect } from '@wordpress/data';
import { withInstanceId, compose, withSafeTimeout } from '@wordpress/compose';
import { LEFT, RIGHT, UP, DOWN, BACKSPACE, ENTER } from '@wordpress/keycodes';
import { addQueryArgs } from '@wordpress/url';
/**
* Internal dependencies
*/
import BlockPreview from '../block-preview';
import BlockTypesList from '../block-types-list';
import BlockCard from '../block-card';
import ChildBlocks from './child-blocks';
import __experimentalInserterMenuExtension from '../inserter-menu-extension';
const MAX_SUGGESTED_ITEMS = 9;
const stopKeyPropagation = ( event ) => event.stopPropagation();
/**
* Filters an item list given a search term.
*
* @param {Array} items Item list
* @param {string} searchTerm Search term.
*
* @return {Array} Filtered item list.
*/
export const searchItems = ( items, searchTerm ) => {
const normalizedSearchTerm = normalizeTerm( searchTerm );
const matchSearch = ( string ) => normalizeTerm( string ).indexOf( normalizedSearchTerm ) !== -1;
const categories = getCategories();
return items.filter( ( item ) => {
const itemCategory = find( categories, { slug: item.category } );
return matchSearch( item.title ) || some( item.keywords, matchSearch ) || ( itemCategory && matchSearch( itemCategory.title ) );
} );
};
/**
* Converts the search term into a normalized term.
*
* @param {string} term The search term to normalize.
*
* @return {string} The normalized search term.
*/
export const normalizeTerm = ( term ) => {
// Disregard diacritics.
// Input: "média"
term = deburr( term );
// Accommodate leading slash, matching autocomplete expectations.
// Input: "/media"
term = term.replace( /^\//, '' );
// Lowercase.
// Input: "MEDIA"
term = term.toLowerCase();
// Strip leading and trailing whitespace.
// Input: " media "
term = term.trim();
return term;
};
export class InserterMenu extends Component {
constructor() {
super( ...arguments );
this.state = {
childItems: [],
filterValue: '',
hoveredItem: null,
suggestedItems: [],
reusableItems: [],
itemsPerCategory: {},
openPanels: [ 'suggested' ],
};
this.onChangeSearchInput = this.onChangeSearchInput.bind( this );
this.onHover = this.onHover.bind( this );
this.panels = {};
this.inserterResults = createRef();
}
componentDidMount() {
// This could be replaced by a resolver.
this.props.fetchReusableBlocks();
this.filter();
}
componentDidUpdate( prevProps ) {
if ( prevProps.items !== this.props.items ) {
this.filter( this.state.filterValue );
}
}
onChangeSearchInput( event ) {
this.filter( event.target.value );
}
onHover( item ) {
this.setState( {
hoveredItem: item,
} );
const { showInsertionPoint, hideInsertionPoint } = this.props;
if ( item ) {
showInsertionPoint();
} else {
hideInsertionPoint();
}
}
bindPanel( name ) {
return ( ref ) => {
this.panels[ name ] = ref;
};
}
onTogglePanel( panel ) {
return () => {
const isOpened = this.state.openPanels.indexOf( panel ) !== -1;
if ( isOpened ) {
this.setState( {
openPanels: without( this.state.openPanels, panel ),
} );
} else {
this.setState( {
openPanels: [
...this.state.openPanels,
panel,
],
} );
this.props.setTimeout( () => {
// We need a generic way to access the panel's container
scrollIntoView( this.panels[ panel ], this.inserterResults.current, {
alignWithTop: true,
} );
} );
}
};
}
filterOpenPanels( filterValue, itemsPerCategory, filteredItems, reusableItems ) {
if ( filterValue === this.state.filterValue ) {
return this.state.openPanels;
}
if ( ! filterValue ) {
return [ 'suggested' ];
}
let openPanels = [];
if ( reusableItems.length > 0 ) {
openPanels.push( 'reusable' );
}
if ( filteredItems.length > 0 ) {
openPanels = openPanels.concat(
Object.keys( itemsPerCategory )
);
}
return openPanels;
}
filter( filterValue = '' ) {
const { debouncedSpeak, items, rootChildBlocks } = this.props;
const filteredItems = searchItems( items, filterValue );
const childItems = filter( filteredItems, ( { name } ) => includes( rootChildBlocks, name ) );
let suggestedItems = [];
if ( ! filterValue ) {
const maxSuggestedItems = this.props.maxSuggestedItems || MAX_SUGGESTED_ITEMS;
suggestedItems = filter( items, ( item ) => item.utility > 0 ).slice( 0, maxSuggestedItems );
}
const reusableItems = filter( filteredItems, { category: 'reusable' } );
const getCategoryIndex = ( item ) => {
return findIndex( getCategories(), ( category ) => category.slug === item.category );
};
const itemsPerCategory = flow(
( itemList ) => filter( itemList, ( item ) => item.category !== 'reusable' ),
( itemList ) => sortBy( itemList, getCategoryIndex ),
( itemList ) => groupBy( itemList, 'category' )
)( filteredItems );
this.setState( {
hoveredItem: null,
childItems,
filterValue,
suggestedItems,
reusableItems,
itemsPerCategory,
openPanels: this.filterOpenPanels(
filterValue,
itemsPerCategory,
filteredItems,
reusableItems
),
} );
const resultCount = Object.keys( itemsPerCategory ).reduce( ( accumulator, currentCategorySlug ) => {
return accumulator + itemsPerCategory[ currentCategorySlug ].length;
}, 0 );
const resultsFoundMessage = sprintf(
_n( '%d result found.', '%d results found.', resultCount ),
resultCount
);
debouncedSpeak( resultsFoundMessage );
}
onKeyDown( event ) {
if ( includes( [ LEFT, DOWN, RIGHT, UP, BACKSPACE, ENTER ], event.keyCode ) ) {
// Stop the key event from propagating up to ObserveTyping.startTypingInTextField.
event.stopPropagation();
}
}
render() {
const { instanceId, onSelect, rootClientId, showInserterHelpPanel } = this.props;
const {
childItems,
hoveredItem,
itemsPerCategory,
openPanels,
reusableItems,
suggestedItems,
filterValue,
} = this.state;
const isPanelOpen = ( panel ) => openPanels.indexOf( panel ) !== -1;
const hasItems = ! isEmpty( suggestedItems ) || ! isEmpty( reusableItems ) || ! isEmpty( itemsPerCategory );
const hoveredItemBlockType = hoveredItem ? getBlockType( hoveredItem.name ) : null;
const hasHelpPanel = hasItems && showInserterHelpPanel;
// Disable reason (no-autofocus): The inserter menu is a modal display, not one which
// is always visible, and one which already incurs this behavior of autoFocus via
// Popover's focusOnMount.
// Disable reason (no-static-element-interactions): Navigational key-presses within
// the menu are prevented from triggering WritingFlow and ObserveTyping interactions.
/* eslint-disable jsx-a11y/no-autofocus, jsx-a11y/no-static-element-interactions */
return (
<div
className={ classnames( 'editor-inserter__menu block-editor-inserter__menu', {
'has-help-panel': hasHelpPanel,
} ) }
onKeyPress={ stopKeyPropagation }
onKeyDown={ this.onKeyDown }
>
<div className="block-editor-inserter__main-area">
<label htmlFor={ `block-editor-inserter__search-${ instanceId }` } className="screen-reader-text">
{ __( 'Search for a block' ) }
</label>
<input
id={ `block-editor-inserter__search-${ instanceId }` }
type="search"
placeholder={ __( 'Search for a block' ) }
className="editor-inserter__search block-editor-inserter__search"
autoFocus
onChange={ this.onChangeSearchInput }
/>
<div
className="editor-inserter__results block-editor-inserter__results"
ref={ this.inserterResults }
tabIndex="0"
role="region"
aria-label={ __( 'Available block types' ) }
>
<ChildBlocks
rootClientId={ rootClientId }
items={ childItems }
onSelect={ onSelect }
onHover={ this.onHover }
/>
{ !! suggestedItems.length &&
<PanelBody
title={ _x( 'Most Used', 'blocks' ) }
opened={ isPanelOpen( 'suggested' ) }
onToggle={ this.onTogglePanel( 'suggested' ) }
ref={ this.bindPanel( 'suggested' ) }
>
<BlockTypesList items={ suggestedItems } onSelect={ onSelect } onHover={ this.onHover } />
</PanelBody>
}
{ map( getCategories(), ( category ) => {
const categoryItems = itemsPerCategory[ category.slug ];
if ( ! categoryItems || ! categoryItems.length ) {
return null;
}
return (
<PanelBody
key={ category.slug }
title={ category.title }
icon={ category.icon }
opened={ isPanelOpen( category.slug ) }
onToggle={ this.onTogglePanel( category.slug ) }
ref={ this.bindPanel( category.slug ) }
>
<BlockTypesList items={ categoryItems } onSelect={ onSelect } onHover={ this.onHover } />
</PanelBody>
);
} ) }
{ !! reusableItems.length && (
<PanelBody
className="editor-inserter__reusable-blocks-panel block-editor-inserter__reusable-blocks-panel"
title={ __( 'Reusable' ) }
opened={ isPanelOpen( 'reusable' ) }
onToggle={ this.onTogglePanel( 'reusable' ) }
icon="controls-repeat"
ref={ this.bindPanel( 'reusable' ) }
>
<BlockTypesList items={ reusableItems } onSelect={ onSelect } onHover={ this.onHover } />
<a
className="editor-inserter__manage-reusable-blocks block-editor-inserter__manage-reusable-blocks"
href={ addQueryArgs( 'edit.php', { post_type: 'wp_block' } ) }
>
{ __( 'Manage All Reusable Blocks' ) }
</a>
</PanelBody>
) }
<__experimentalInserterMenuExtension.Slot
fillProps={ {
onSelect,
onHover: this.onHover,
filterValue,
hasItems,
} }
>
{ ( fills ) => {
if ( fills.length ) {
return fills;
}
if ( ! hasItems ) {
return (
<p className="editor-inserter__no-results block-editor-inserter__no-results">{ __( 'No blocks found.' ) }</p>
);
}
return null;
} }
</__experimentalInserterMenuExtension.Slot>
</div>
</div>
{ hasHelpPanel && (
<div className="block-editor-inserter__menu-help-panel">
{ hoveredItem && (
<>
{ ! isReusableBlock( hoveredItem ) && (
<BlockCard blockType={ hoveredItemBlockType } />
) }
{ ( isReusableBlock( hoveredItem ) || hoveredItemBlockType.example ) && (
<div className="block-editor-inserter__preview">
<div className="block-editor-inserter__preview-content">
<BlockPreview
viewportWidth={ 500 }
blocks={ createBlock(
hoveredItem.name,
hoveredItemBlockType.example ? hoveredItemBlockType.example.attributes : hoveredItem.initialAttributes,
hoveredItemBlockType.example ? hoveredItemBlockType.example.innerBlocks : undefined
) }
/>
</div>
</div>
) }
</>
) }
{ ! hoveredItem && (
<div className="block-editor-inserter__menu-help-panel-no-block">
<div className="block-editor-inserter__menu-help-panel-no-block-text">
<div className="block-editor-inserter__menu-help-panel-title">{ __( 'Content Blocks' ) }</div>
<p>
{ __(
'Welcome to the wonderful world of blocks! Blocks are the basis of all content within the editor.'
) }
</p>
<p>
{ __(
'There are blocks available for all kinds of content: insert text, headings, images, lists, videos, tables, and lots more.'
) }
</p>
<p>
{ __(
'Browse through the library to learn more about what each block does.'
) }
</p>
</div>
<Tip>
{ __(
'While writing, you can press "/" to quickly insert new blocks.'
) }
</Tip>
</div>
) }
</div>
) }
</div>
);
/* eslint-enable jsx-a11y/no-autofocus, jsx-a11y/no-static-element-interactions */
}
}
export default compose(
withSelect( ( select, { clientId, isAppender, rootClientId, showInserterHelpPanel } ) => {
const {
getInserterItems,
getBlockName,
getBlockRootClientId,
getBlockSelectionEnd,
getSettings,
} = select( 'core/block-editor' );
const {
getChildBlockNames,
} = select( 'core/blocks' );
let destinationRootClientId = rootClientId;
if ( ! destinationRootClientId && ! clientId && ! isAppender ) {
const end = getBlockSelectionEnd();
if ( end ) {
destinationRootClientId = getBlockRootClientId( end ) || undefined;
}
}
const destinationRootBlockName = getBlockName( destinationRootClientId );
return {
rootChildBlocks: getChildBlockNames( destinationRootBlockName ),
items: getInserterItems( destinationRootClientId ),
showInserterHelpPanel: showInserterHelpPanel && getSettings().showInserterHelpPanel,
destinationRootClientId,
};
} ),
withDispatch( ( dispatch, ownProps, { select } ) => {
const {
showInsertionPoint,
hideInsertionPoint,
} = dispatch( 'core/block-editor' );
// This should be an external action provided in the editor settings.
const {
__experimentalFetchReusableBlocks: fetchReusableBlocks,
} = dispatch( 'core/editor' );
// To avoid duplication, getInsertionIndex is extracted and used in two event handlers
// This breaks the withDispatch not containing any logic rule.
// Since it's a function only called when the event handlers are called,
// it's fine to extract it.
// eslint-disable-next-line no-restricted-syntax
function getInsertionIndex() {
const {
getBlockIndex,
getBlockSelectionEnd,
getBlockOrder,
} = select( 'core/block-editor' );
const { clientId, destinationRootClientId, isAppender } = ownProps;
// If the clientId is defined, we insert at the position of the block.
if ( clientId ) {
return getBlockIndex( clientId, destinationRootClientId );
}
// If there a selected block, we insert after the selected block.
const end = getBlockSelectionEnd();
if ( ! isAppender && end ) {
return getBlockIndex( end, destinationRootClientId ) + 1;
}
// Otherwise, we insert at the end of the current rootClientId
return getBlockOrder( destinationRootClientId ).length;
}
return {
fetchReusableBlocks,
showInsertionPoint() {
const index = getInsertionIndex();
showInsertionPoint( ownProps.destinationRootClientId, index );
},
hideInsertionPoint,
onSelect( item ) {
const {
replaceBlocks,
insertBlock,
} = dispatch( 'core/block-editor' );
const {
getSelectedBlock,
} = select( 'core/block-editor' );
const { isAppender } = ownProps;
const { name, initialAttributes } = item;
const selectedBlock = getSelectedBlock();
const insertedBlock = createBlock( name, initialAttributes );
if ( ! isAppender && selectedBlock && isUnmodifiedDefaultBlock( selectedBlock ) ) {
replaceBlocks( selectedBlock.clientId, insertedBlock );
} else {
insertBlock(
insertedBlock,
getInsertionIndex(),
ownProps.destinationRootClientId
);
}
ownProps.onSelect();
return insertedBlock;
},
};
} ),
withSpokenMessages,
withInstanceId,
withSafeTimeout
)( InserterMenu );