-
Notifications
You must be signed in to change notification settings - Fork 4.3k
/
Copy pathindex.js
664 lines (598 loc) · 19.8 KB
/
index.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
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
/**
* External dependencies
*/
import classnames from 'classnames';
import { escapeRegExp, find, filter, map, debounce } from 'lodash';
/**
* WordPress dependencies
*/
import { Component, compose, renderToString } from '@wordpress/element';
import { keycodes } from '@wordpress/utils';
import { __, _n, sprintf } from '@wordpress/i18n';
/**
* Internal dependencies
*/
import './style.scss';
import { isDeprecatedCompleter, toCompatibleCompleter } from './completer-compat';
import withFocusOutside from '../higher-order/with-focus-outside';
import Button from '../button';
import Popover from '../popover';
import withInstanceId from '../higher-order/with-instance-id';
import withSpokenMessages from '../higher-order/with-spoken-messages';
const { ENTER, ESCAPE, UP, DOWN, LEFT, RIGHT, SPACE } = keycodes;
/**
* A raw completer option.
* @typedef {*} CompleterOption
*/
/**
* @callback FnGetOptions
*
* @returns {(CompleterOption[]|Promise.<CompleterOption[]>)} The completer options or a promise for them.
*/
/**
* @callback FnGetOptionKeywords
* @param {CompleterOption} option a completer option.
*
* @returns {string[]} list of key words to search.
*/
/**
* @callback FnGetOptionLabel
* @param {CompleterOption} option a completer option.
*
* @returns {(string|Array.<(string|Component)>)} list of react components to render.
*/
/**
* @callback FnAllowNode
* @param {Node} textNode check if the completer can handle this text node.
*
* @returns {boolean} true if the completer can handle this text node.
*/
/**
* @callback FnAllowContext
* @param {Range} before the range before the auto complete trigger and query.
* @param {Range} after the range after the autocomplete trigger and query.
*
* @returns {boolean} true if the completer can handle these ranges.
*/
/**
* @typedef {Object} OptionCompletion
* @property {('insert-at-caret', 'replace')} action the intended placement of the completion.
* @property {OptionCompletionValue} value the completion value.
*/
/**
* A completion value.
* @typedef {(String|WPElement|Object)} OptionCompletionValue
*/
/**
* @callback FnGetOptionCompletion
* @param {CompleterOption} value the value of the completer option.
* @param {Range} range the nodes included in the autocomplete trigger and query.
* @param {String} query the text value of the autocomplete query.
*
* @returns {(OptionCompletion|OptionCompletionValue)} the completion for the given option. If an
* OptionCompletionValue is returned, the
* completion action defaults to `insert-at-caret`.
*/
/**
* @typedef {Object} Completer
* @property {String} name a way to identify a completer, useful for selective overriding.
* @property {?String} className A class to apply to the popup menu.
* @property {String} triggerPrefix the prefix that will display the menu.
* @property {(CompleterOption[]|FnGetOptions)} options the completer options or a function to get them.
* @property {?FnGetOptionKeywords} getOptionKeywords get the keywords for a given option.
* @property {FnGetOptionLabel} getOptionLabel get the label for a given option.
* @property {?FnAllowNode} allowNode filter the allowed text nodes in the autocomplete.
* @property {?FnAllowContext} allowContext filter the context under which the autocomplete activates.
* @property {FnGetOptionCompletion} getOptionCompletion get the completion associated with a given option.
*/
/**
* Recursively select the firstChild until hitting a leaf node.
*
* @param {Node} node The node to find the recursive first child.
*
* @return {Node} The first leaf-node >= node in the ordering.
*/
function descendFirst( node ) {
let n = node;
while ( n.firstChild ) {
n = n.firstChild;
}
return n;
}
/**
* Recursively select the lastChild until hitting a leaf node.
*
* @param {Node} node The node to find the recursive last child.
*
* @return {Node} The first leaf-node <= node in the ordering.
*/
function descendLast( node ) {
let n = node;
while ( n.lastChild ) {
n = n.lastChild;
}
return n;
}
/**
* Is the node a text node.
*
* @param {?Node} node The node to check.
*
* @return {boolean} True if the node is a text node.
*/
function isTextNode( node ) {
return node !== null && node.nodeType === 3;
}
/**
* Return the node only if it is a text node, otherwise return null.
*
* @param {?Node} node The node to filter.
*
* @return {?Node} The node or null if it is not a text node.
*/
function onlyTextNode( node ) {
return isTextNode( node ) ? node : null;
}
/**
* Find the index of the last charater in the text that is whitespace.
*
* @param {string} text The text to search.
*
* @return {number} The last index of a white space character in the text or -1.
*/
function lastIndexOfSpace( text ) {
for ( let i = text.length - 1; i >= 0; i-- ) {
if ( /\s/.test( text.charAt( i ) ) ) {
return i;
}
}
return -1;
}
function filterOptions( search, options = [], maxResults = 10 ) {
const filtered = [];
for ( let i = 0; i < options.length; i++ ) {
const option = options[ i ];
// Merge label into keywords
let { keywords = [] } = option;
if ( 'string' === typeof option.label ) {
keywords = [ ...keywords, option.label ];
}
const isMatch = keywords.some( ( keyword ) => search.test( keyword ) );
if ( ! isMatch ) {
continue;
}
filtered.push( option );
// Abort early if max reached
if ( filtered.length === maxResults ) {
break;
}
}
return filtered;
}
export class Autocomplete extends Component {
static getInitialState() {
return {
search: /./,
selectedIndex: 0,
suppress: undefined,
open: undefined,
query: undefined,
range: undefined,
filteredOptions: [],
};
}
/*
* NOTE: This is necessary for backwards compatibility with the
* previous completer interface. Once we no longer support the
* old interface, we should be able to use the `completers` prop
* directly.
*/
static getDerivedStateFromProps( nextProps, prevState ) {
const { completers: nextCompleters } = nextProps;
const { lastAppliedCompleters } = prevState;
if ( nextCompleters !== lastAppliedCompleters ) {
let completers = nextCompleters;
if ( completers.some( isDeprecatedCompleter ) ) {
completers = completers.map( completer => {
return isDeprecatedCompleter( completer ) ?
toCompatibleCompleter( completer ) :
completer;
} );
}
return {
completers,
lastAppliedCompleters: nextCompleters,
};
}
return null;
}
constructor() {
super( ...arguments );
this.bindNode = this.bindNode.bind( this );
this.select = this.select.bind( this );
this.reset = this.reset.bind( this );
this.resetWhenSuppressed = this.resetWhenSuppressed.bind( this );
this.search = this.search.bind( this );
this.handleKeyDown = this.handleKeyDown.bind( this );
this.getWordRect = this.getWordRect.bind( this );
this.debouncedLoadOptions = debounce( this.loadOptions, 250 );
this.state = this.constructor.getInitialState();
}
bindNode( node ) {
this.node = node;
}
insertCompletion( range, replacement ) {
const container = document.createElement( 'div' );
container.innerHTML = renderToString( replacement );
while ( container.firstChild ) {
const child = container.firstChild;
container.removeChild( child );
range.insertNode( child );
range.setStartAfter( child );
}
range.deleteContents();
}
select( option ) {
const { onReplace } = this.props;
const { open, range, query } = this.state;
const { getOptionCompletion } = open || {};
this.reset();
if ( getOptionCompletion ) {
const completion = getOptionCompletion( option.value, range, query );
const { action, value } =
( undefined === completion.action || undefined === completion.value ) ?
{ action: 'insert-at-caret', value: completion } :
completion;
if ( 'replace' === action ) {
onReplace( [ value ] );
} else if ( 'insert-at-caret' === action ) {
this.insertCompletion( range, value );
} else if ( 'backcompat' === action ) {
// NOTE: This block should be removed once we no longer support the old completer interface.
const onSelect = value;
const deprecatedOptionObject = option.value;
const selectionResult = onSelect( deprecatedOptionObject.value, range, query );
if ( selectionResult !== undefined ) {
this.insertCompletion( range, selectionResult );
}
}
}
}
reset() {
this.setState( this.constructor.getInitialState() );
}
resetWhenSuppressed() {
const { open, suppress } = this.state;
if ( open && suppress === open.idx ) {
this.reset();
}
}
handleFocusOutside() {
this.reset();
}
// this method is separate so it can be overrided in tests
getCursor( container ) {
const selection = window.getSelection();
if ( selection.isCollapsed ) {
if ( 'production' !== process.env.NODE_ENV ) {
if ( ! container.contains( selection.anchorNode ) ) {
throw new Error( 'Invalid assumption: expected selection to be within the autocomplete container' );
}
}
return {
node: selection.anchorNode,
offset: selection.anchorOffset,
};
}
return null;
}
// this method is separate so it can be overrided in tests
createRange( startNode, startOffset, endNode, endOffset ) {
const range = document.createRange();
range.setStart( startNode, startOffset );
range.setEnd( endNode, endOffset );
return range;
}
announce( filteredOptions ) {
const { debouncedSpeak } = this.props;
if ( ! debouncedSpeak ) {
return;
}
if ( !! filteredOptions.length ) {
debouncedSpeak( sprintf( _n(
'%d result found, use up and down arrow keys to navigate.',
'%d results found, use up and down arrow keys to navigate.',
filteredOptions.length
), filteredOptions.length ), 'assertive' );
} else {
debouncedSpeak( __( 'No results.' ), 'assertive' );
}
}
/**
* Load options for an autocompleter.
*
* @param {Completer} completer The autocompleter.
* @param {string} query The query, if any.
*/
loadOptions( completer, query ) {
const { options } = completer;
/*
* We support both synchronous and asynchronous retrieval of completer options
* but internally treat all as async so we maintain a single, consistent code path.
*/
Promise.resolve(
typeof options === 'function' ? options( query ) : options
).then( optionsData => {
const keyedOptions = optionsData.map( ( optionData, optionIndex ) => ( {
key: `${ completer.idx }-${ optionIndex }`,
value: optionData,
label: completer.getOptionLabel( optionData ),
keywords: completer.getOptionKeywords ? completer.getOptionKeywords( optionData ) : [],
} ) );
const filteredOptions = filterOptions( this.state.search, keyedOptions );
const selectedIndex = filteredOptions.length === this.state.filteredOptions.length ? this.state.selectedIndex : 0;
this.setState( {
[ 'options_' + completer.idx ]: keyedOptions,
filteredOptions,
selectedIndex,
} );
this.announce( filteredOptions );
} );
}
findMatch( container, cursor, allCompleters, wasOpen ) {
const allowAnything = () => true;
let endTextNode;
let endIndex;
// search backwards to find the first preceeding space or non-text node.
if ( isTextNode( cursor.node ) ) { // TEXT node
endTextNode = cursor.node;
endIndex = cursor.offset;
} else if ( cursor.offset === 0 ) {
endTextNode = onlyTextNode( descendFirst( cursor.node ) );
endIndex = 0;
} else {
endTextNode = onlyTextNode( descendLast( cursor.node.childNodes[ cursor.offset - 1 ] ) );
endIndex = endTextNode ? endTextNode.nodeValue.length : 0;
}
if ( endTextNode === null ) {
return null;
}
// store the index of a completer in the object so we can use it to reference the options
let completers = map( allCompleters, ( completer, idx ) => ( { ...completer, idx } ) );
if ( wasOpen ) {
// put the open completer at the start so it has priority
completers = [
wasOpen,
...filter( completers, ( completer ) => completer.idx !== wasOpen.idx ),
];
}
// filter the completers to those that could handle this node
completers = filter( completers,
( { allowNode = allowAnything } ) => allowNode( endTextNode, container ) );
// exit early if nothing can handle it
if ( completers.length === 0 ) {
return null;
}
let startTextNode = endTextNode;
let text = endTextNode.nodeValue.substring( 0, endIndex );
let pos = lastIndexOfSpace( text );
while ( pos === -1 ) {
const prev = onlyTextNode( startTextNode.previousSibling );
if ( prev === null ) {
break;
}
// filter the completers to those that could handle this node
completers = filter( completers,
( { allowNode = allowAnything } ) => allowNode( endTextNode, container ) );
// exit early if nothing can handle it
if ( completers.length === 0 ) {
return null;
}
startTextNode = prev;
text = prev.nodeValue + text;
pos = lastIndexOfSpace( prev.nodeValue );
}
// exit early if nothing can handle it
if ( text.length <= pos + 1 ) {
return null;
}
// find a completer that matches
const open = find( completers, ( { triggerPrefix = '', allowContext = allowAnything } ) => {
if ( text.substr( pos + 1, triggerPrefix.length ) !== triggerPrefix ) {
return false;
}
const before = this.createRange( container, 0, startTextNode, pos + 1 );
const after = this.createRange( endTextNode, endIndex, container, container.childNodes.length );
return allowContext( before, after );
} );
// exit if no completers match
if ( ! open ) {
return null;
}
const { triggerPrefix = '' } = open;
const range = this.createRange( startTextNode, pos + 1, endTextNode, endIndex );
const query = text.substr( pos + 1 + triggerPrefix.length );
return { open, range, query };
}
search( event ) {
const { completers, open: wasOpen, suppress: wasSuppress, query: wasQuery } = this.state;
const container = event.target;
// ensure that the cursor location is unambiguous
const cursor = this.getCursor( container );
if ( ! cursor ) {
return;
}
// look for the trigger prefix and search query just before the cursor location
const match = this.findMatch( container, cursor, completers, wasOpen );
const { open, query, range } = match || {};
// asynchronously load the options for the open completer
if ( open && ( ! wasOpen || open.idx !== wasOpen.idx || query !== wasQuery ) ) {
if ( open.isDebounced ) {
this.debouncedLoadOptions( open, query );
} else {
this.loadOptions( open, query );
}
}
// create a regular expression to filter the options
const search = open ? new RegExp( '(?:\\b|\\s|^)' + escapeRegExp( query ), 'i' ) : /./;
// filter the options we already have
const filteredOptions = open ? filterOptions( search, this.state[ 'options_' + open.idx ] ) : [];
// check if we should still suppress the popover
const suppress = ( open && wasSuppress === open.idx ) ? wasSuppress : undefined;
// update the state
if ( wasOpen || open ) {
this.setState( { selectedIndex: 0, filteredOptions, suppress, search, open, query, range } );
}
// announce the count of filtered options but only if they have loaded
if ( open && this.state[ 'options_' + open.idx ] ) {
this.announce( filteredOptions );
}
}
handleKeyDown( event ) {
const { open, suppress, selectedIndex, filteredOptions } = this.state;
if ( ! open ) {
return;
}
if ( suppress === open.idx ) {
switch ( event.keyCode ) {
// cancel popup suppression on CTRL+SPACE
case SPACE:
const { ctrlKey, shiftKey, altKey, metaKey } = event;
if ( ctrlKey && ! ( shiftKey || altKey || metaKey ) ) {
this.setState( { suppress: undefined } );
event.preventDefault();
event.stopPropagation();
}
break;
// reset on cursor movement
case UP:
case DOWN:
case LEFT:
case RIGHT:
this.reset();
}
return;
}
if ( filteredOptions.length === 0 ) {
return;
}
let nextSelectedIndex;
switch ( event.keyCode ) {
case UP:
nextSelectedIndex = ( selectedIndex === 0 ? filteredOptions.length : selectedIndex ) - 1;
this.setState( { selectedIndex: nextSelectedIndex } );
break;
case DOWN:
nextSelectedIndex = ( selectedIndex + 1 ) % filteredOptions.length;
this.setState( { selectedIndex: nextSelectedIndex } );
break;
case ESCAPE:
this.setState( { suppress: open.idx } );
break;
case ENTER:
this.select( filteredOptions[ selectedIndex ] );
break;
case LEFT:
case RIGHT:
this.reset();
return;
default:
return;
}
// Any handled keycode should prevent original behavior. This relies on
// the early return in the default case.
event.preventDefault();
event.stopPropagation();
}
getWordRect( { isLeft, isRight } ) {
const { range } = this.state;
if ( ! range ) {
return;
}
if ( isLeft ) {
const rects = range.getClientRects();
return rects[ 0 ];
} else if ( isRight ) {
const rects = range.getClientRects();
return rects[ rects.length - 1 ];
}
return range.getBoundingClientRect();
}
toggleKeyEvents( isListening ) {
// This exists because we must capture ENTER key presses before RichText.
// It seems that react fires the simulated capturing events after the
// native browser event has already bubbled so we can't stopPropagation
// and avoid RichText getting the event from TinyMCE, hence we must
// register a native event handler.
const handler = isListening ? 'addEventListener' : 'removeEventListener';
this.node[ handler ]( 'keydown', this.handleKeyDown, true );
}
componentDidUpdate( prevProps, prevState ) {
const { open } = this.state;
const { open: prevOpen } = prevState;
if ( ( ! open ) !== ( ! prevOpen ) ) {
this.toggleKeyEvents( ! ! open );
}
}
componentWillUnmount() {
this.toggleKeyEvents( false );
this.debouncedLoadOptions.cancel();
}
render() {
const { children, instanceId } = this.props;
const { open, suppress, selectedIndex, filteredOptions } = this.state;
const { key: selectedKey = '' } = filteredOptions[ selectedIndex ] || {};
const { className, idx } = open || {};
const isExpanded = suppress !== idx && filteredOptions.length > 0;
const listBoxId = isExpanded ? `components-autocomplete-listbox-${ instanceId }` : null;
const activeId = isExpanded ? `components-autocomplete-item-${ instanceId }-${ selectedKey }` : null;
// Disable reason: Clicking the editor should reset the autocomplete when the menu is suppressed
/* eslint-disable jsx-a11y/no-static-element-interactions, jsx-a11y/onclick-has-role, jsx-a11y/click-events-have-key-events */
return (
<div
ref={ this.bindNode }
onInput={ this.search }
onClick={ this.resetWhenSuppressed }
className="components-autocomplete"
>
{ children( { isExpanded, listBoxId, activeId } ) }
{ isExpanded && (
<Popover
focusOnMount={ false }
onClose={ this.reset }
position="top right"
className="components-autocomplete__popover"
getAnchorRect={ this.getWordRect }
>
<div
id={ listBoxId }
role="listbox"
className="components-autocomplete__results"
>
{ isExpanded && map( filteredOptions, ( option, index ) => (
<Button
key={ option.key }
id={ `components-autocomplete-item-${ instanceId }-${ option.key }` }
role="option"
aria-selected={ index === selectedIndex }
className={ classnames( 'components-autocomplete__result', className, {
'is-selected': index === selectedIndex,
} ) }
onClick={ () => this.select( option ) }
>
{ option.label }
</Button>
) ) }
</div>
</Popover>
) }
</div>
);
/* eslint-enable jsx-a11y/no-static-element-interactions, jsx-a11y/onclick-has-role, jsx-a11y/click-events-have-key-events */
}
}
export default compose( [
withSpokenMessages,
withInstanceId,
withFocusOutside, // this MUST be the innermost HOC as it calls handleFocusOutside
] )( Autocomplete );