-
Notifications
You must be signed in to change notification settings - Fork 4.2k
/
index.tsx
743 lines (650 loc) · 18.8 KB
/
index.tsx
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
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
/**
* External dependencies
*/
import classnames from 'classnames';
import type { KeyboardEvent, MouseEvent, TouchEvent } from 'react';
/**
* WordPress dependencies
*/
import { useEffect, useRef, useState } from '@wordpress/element';
import { __, _n, sprintf } from '@wordpress/i18n';
import { useDebounce, useInstanceId, usePrevious } from '@wordpress/compose';
import { speak } from '@wordpress/a11y';
import isShallowEqual from '@wordpress/is-shallow-equal';
/**
* Internal dependencies
*/
import Token from './token';
import TokenInput from './token-input';
import { TokensAndInputWrapperFlex } from './styles';
import SuggestionsList from './suggestions-list';
import type { FormTokenFieldProps, TokenItem } from './types';
import { FlexItem } from '../flex';
import {
StyledHelp,
StyledLabel,
} from '../base-control/styles/base-control-styles';
import { Spacer } from '../spacer';
const identity = ( value: string ) => value;
/**
* A `FormTokenField` is a field similar to the tags and categories fields in the interim editor chrome,
* or the "to" field in Mail on OS X. Tokens can be entered by typing them or selecting them from a list of suggested tokens.
*
* Up to one hundred suggestions that match what the user has typed so far will be shown from which the user can pick from (auto-complete).
* Tokens are separated by the "," character. Suggestions can be selected with the up or down arrows and added with the tab or enter key.
*
* The `value` property is handled in a manner similar to controlled form components.
* See [Forms](http://facebook.github.io/react/docs/forms.html) in the React Documentation for more information.
*/
export function FormTokenField( props: FormTokenFieldProps ) {
const {
autoCapitalize,
autoComplete,
maxLength,
placeholder,
label = __( 'Add item' ),
className,
suggestions = [],
maxSuggestions = 100,
value = [],
displayTransform = identity,
saveTransform = ( token ) => token.trim(),
onChange = () => {},
onInputChange = () => {},
onFocus = undefined,
isBorderless = false,
disabled = false,
tokenizeOnSpace = false,
messages = {
added: __( 'Item added.' ),
removed: __( 'Item removed.' ),
remove: __( 'Remove item' ),
__experimentalInvalid: __( 'Invalid item' ),
},
__experimentalRenderItem,
__experimentalExpandOnFocus = false,
__experimentalValidateInput = () => true,
__experimentalShowHowTo = true,
__next36pxDefaultSize = false,
__experimentalAutoSelectFirstMatch = false,
__nextHasNoMarginBottom = false,
} = props;
const instanceId = useInstanceId( FormTokenField );
// We reset to these initial values again in the onBlur
const [ incompleteTokenValue, setIncompleteTokenValue ] = useState( '' );
const [ inputOffsetFromEnd, setInputOffsetFromEnd ] = useState( 0 );
const [ isActive, setIsActive ] = useState( false );
const [ isExpanded, setIsExpanded ] = useState( false );
const [ selectedSuggestionIndex, setSelectedSuggestionIndex ] =
useState( -1 );
const [ selectedSuggestionScroll, setSelectedSuggestionScroll ] =
useState( false );
const prevSuggestions = usePrevious< string[] >( suggestions );
const prevValue = usePrevious< ( string | TokenItem )[] >( value );
const input = useRef< HTMLInputElement >( null );
const tokensAndInput = useRef< HTMLInputElement >( null );
const debouncedSpeak = useDebounce( speak, 500 );
useEffect( () => {
// Make sure to focus the input when the isActive state is true.
if ( isActive && ! hasFocus() ) {
focus();
}
}, [ isActive ] );
useEffect( () => {
const suggestionsDidUpdate = ! isShallowEqual(
suggestions,
prevSuggestions || []
);
if ( suggestionsDidUpdate || value !== prevValue ) {
updateSuggestions( suggestionsDidUpdate );
}
// TODO: updateSuggestions() should first be refactored so its actual deps are clearer.
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [ suggestions, prevSuggestions, value, prevValue ] );
useEffect( () => {
updateSuggestions();
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [ incompleteTokenValue ] );
useEffect( () => {
updateSuggestions();
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [ __experimentalAutoSelectFirstMatch ] );
if ( disabled && isActive ) {
setIsActive( false );
setIncompleteTokenValue( '' );
}
function focus() {
input.current?.focus();
}
function hasFocus() {
return input.current === input.current?.ownerDocument.activeElement;
}
function onFocusHandler( event: FocusEvent ) {
// If focus is on the input or on the container, set the isActive state to true.
if ( hasFocus() || event.target === tokensAndInput.current ) {
setIsActive( true );
setIsExpanded( __experimentalExpandOnFocus || isExpanded );
} else {
/*
* Otherwise, focus is on one of the token "remove" buttons and we
* set the isActive state to false to prevent the input to be
* re-focused, see componentDidUpdate().
*/
setIsActive( false );
}
if ( 'function' === typeof onFocus ) {
onFocus( event );
}
}
function onBlur() {
if (
inputHasValidValue() &&
__experimentalValidateInput( incompleteTokenValue )
) {
setIsActive( false );
} else {
// Reset to initial state
setIncompleteTokenValue( '' );
setInputOffsetFromEnd( 0 );
setIsActive( false );
setIsExpanded( false );
setSelectedSuggestionIndex( -1 );
setSelectedSuggestionScroll( false );
}
}
function onKeyDown( event: KeyboardEvent ) {
let preventDefault = false;
if (
event.defaultPrevented ||
// Ignore keydowns from IMEs
event.nativeEvent.isComposing ||
// Workaround for Mac Safari where the final Enter/Backspace of an IME composition
// is `isComposing=false`, even though it's technically still part of the composition.
// These can only be detected by keyCode.
event.keyCode === 229
) {
return;
}
switch ( event.key ) {
case 'Backspace':
preventDefault = handleDeleteKey( deleteTokenBeforeInput );
break;
case 'Enter':
preventDefault = addCurrentToken();
break;
case 'ArrowLeft':
preventDefault = handleLeftArrowKey();
break;
case 'ArrowUp':
preventDefault = handleUpArrowKey();
break;
case 'ArrowRight':
preventDefault = handleRightArrowKey();
break;
case 'ArrowDown':
preventDefault = handleDownArrowKey();
break;
case 'Delete':
preventDefault = handleDeleteKey( deleteTokenAfterInput );
break;
case 'Space':
if ( tokenizeOnSpace ) {
preventDefault = addCurrentToken();
}
break;
case 'Escape':
preventDefault = handleEscapeKey( event );
break;
default:
break;
}
if ( preventDefault ) {
event.preventDefault();
}
}
function onKeyPress( event: KeyboardEvent ) {
let preventDefault = false;
switch ( event.key ) {
case ',':
preventDefault = handleCommaKey();
break;
default:
break;
}
if ( preventDefault ) {
event.preventDefault();
}
}
function onContainerTouched( event: MouseEvent | TouchEvent ) {
// Prevent clicking/touching the tokensAndInput container from blurring
// the input and adding the current token.
if ( event.target === tokensAndInput.current && isActive ) {
event.preventDefault();
}
}
function onTokenClickRemove( event: { value: string } ) {
deleteToken( event.value );
focus();
}
function onSuggestionHovered( suggestion: string ) {
const index = getMatchingSuggestions().indexOf( suggestion );
if ( index >= 0 ) {
setSelectedSuggestionIndex( index );
setSelectedSuggestionScroll( false );
}
}
function onSuggestionSelected( suggestion: string ) {
addNewToken( suggestion );
}
function onInputChangeHandler( event: { value: string } ) {
const text = event.value;
const separator = tokenizeOnSpace ? /[ ,\t]+/ : /[,\t]+/;
const items = text.split( separator );
const tokenValue = items[ items.length - 1 ] || '';
if ( items.length > 1 ) {
addNewTokens( items.slice( 0, -1 ) );
}
setIncompleteTokenValue( tokenValue );
onInputChange( tokenValue );
}
function handleDeleteKey( _deleteToken: () => void ) {
let preventDefault = false;
if ( hasFocus() && isInputEmpty() ) {
_deleteToken();
preventDefault = true;
}
return preventDefault;
}
function handleLeftArrowKey() {
let preventDefault = false;
if ( isInputEmpty() ) {
moveInputBeforePreviousToken();
preventDefault = true;
}
return preventDefault;
}
function handleRightArrowKey() {
let preventDefault = false;
if ( isInputEmpty() ) {
moveInputAfterNextToken();
preventDefault = true;
}
return preventDefault;
}
function handleUpArrowKey() {
setSelectedSuggestionIndex( ( index ) => {
return (
( index === 0
? getMatchingSuggestions(
incompleteTokenValue,
suggestions,
value,
maxSuggestions,
saveTransform
).length
: index ) - 1
);
} );
setSelectedSuggestionScroll( true );
return true; // PreventDefault.
}
function handleDownArrowKey() {
setSelectedSuggestionIndex( ( index ) => {
return (
( index + 1 ) %
getMatchingSuggestions(
incompleteTokenValue,
suggestions,
value,
maxSuggestions,
saveTransform
).length
);
} );
setSelectedSuggestionScroll( true );
return true; // PreventDefault.
}
function handleEscapeKey( event: KeyboardEvent ) {
if ( event.target instanceof HTMLInputElement ) {
setIncompleteTokenValue( event.target.value );
setIsExpanded( false );
setSelectedSuggestionIndex( -1 );
setSelectedSuggestionScroll( false );
}
return true; // PreventDefault.
}
function handleCommaKey() {
if ( inputHasValidValue() ) {
addNewToken( incompleteTokenValue );
}
return true; // PreventDefault.
}
function moveInputToIndex( index: number ) {
setInputOffsetFromEnd( value.length - Math.max( index, -1 ) - 1 );
}
function moveInputBeforePreviousToken() {
setInputOffsetFromEnd( ( prevInputOffsetFromEnd ) => {
return Math.min( prevInputOffsetFromEnd + 1, value.length );
} );
}
function moveInputAfterNextToken() {
setInputOffsetFromEnd( ( prevInputOffsetFromEnd ) => {
return Math.max( prevInputOffsetFromEnd - 1, 0 );
} );
}
function deleteTokenBeforeInput() {
const index = getIndexOfInput() - 1;
if ( index > -1 ) {
deleteToken( value[ index ] );
}
}
function deleteTokenAfterInput() {
const index = getIndexOfInput();
if ( index < value.length ) {
deleteToken( value[ index ] );
// Update input offset since it's the offset from the last token.
moveInputToIndex( index );
}
}
function addCurrentToken() {
let preventDefault = false;
const selectedSuggestion = getSelectedSuggestion();
if ( selectedSuggestion ) {
addNewToken( selectedSuggestion );
preventDefault = true;
} else if ( inputHasValidValue() ) {
addNewToken( incompleteTokenValue );
preventDefault = true;
}
return preventDefault;
}
function addNewTokens( tokens: string[] ) {
const tokensToAdd = [
...new Set(
tokens
.map( saveTransform )
.filter( Boolean )
.filter( ( token ) => ! valueContainsToken( token ) )
),
];
if ( tokensToAdd.length > 0 ) {
const newValue = [ ...value ];
newValue.splice( getIndexOfInput(), 0, ...tokensToAdd );
onChange( newValue );
}
}
function addNewToken( token: string ) {
if ( ! __experimentalValidateInput( token ) ) {
speak( messages.__experimentalInvalid, 'assertive' );
return;
}
addNewTokens( [ token ] );
speak( messages.added, 'assertive' );
setIncompleteTokenValue( '' );
setSelectedSuggestionIndex( -1 );
setSelectedSuggestionScroll( false );
setIsExpanded( ! __experimentalExpandOnFocus );
if ( isActive ) {
focus();
}
}
function deleteToken( token: string | TokenItem ) {
const newTokens = value.filter( ( item ) => {
return getTokenValue( item ) !== getTokenValue( token );
} );
onChange( newTokens );
speak( messages.removed, 'assertive' );
}
function getTokenValue( token: { value: string } | string ) {
if ( 'object' === typeof token ) {
return token.value;
}
return token;
}
function getMatchingSuggestions(
searchValue = incompleteTokenValue,
_suggestions = suggestions,
_value = value,
_maxSuggestions = maxSuggestions,
_saveTransform = saveTransform
) {
let match = _saveTransform( searchValue );
const startsWithMatch: string[] = [];
const containsMatch: string[] = [];
const normalizedValue = _value.map( ( item ) => {
if ( typeof item === 'string' ) {
return item;
}
return item.value;
} );
if ( match.length === 0 ) {
_suggestions = _suggestions.filter(
( suggestion ) => ! normalizedValue.includes( suggestion )
);
} else {
match = match.toLocaleLowerCase();
_suggestions.forEach( ( suggestion ) => {
const index = suggestion.toLocaleLowerCase().indexOf( match );
if ( normalizedValue.indexOf( suggestion ) === -1 ) {
if ( index === 0 ) {
startsWithMatch.push( suggestion );
} else if ( index > 0 ) {
containsMatch.push( suggestion );
}
}
} );
_suggestions = startsWithMatch.concat( containsMatch );
}
return _suggestions.slice( 0, _maxSuggestions );
}
function getSelectedSuggestion() {
if ( selectedSuggestionIndex !== -1 ) {
return getMatchingSuggestions()[ selectedSuggestionIndex ];
}
return undefined;
}
function valueContainsToken( token: string ) {
return value.some( ( item ) => {
return getTokenValue( token ) === getTokenValue( item );
} );
}
function getIndexOfInput() {
return value.length - inputOffsetFromEnd;
}
function isInputEmpty() {
return incompleteTokenValue.length === 0;
}
function inputHasValidValue() {
return saveTransform( incompleteTokenValue ).length > 0;
}
function updateSuggestions( resetSelectedSuggestion = true ) {
const inputHasMinimumChars = incompleteTokenValue.trim().length > 1;
const matchingSuggestions =
getMatchingSuggestions( incompleteTokenValue );
const hasMatchingSuggestions = matchingSuggestions.length > 0;
const shouldExpandIfFocuses = hasFocus() && __experimentalExpandOnFocus;
setIsExpanded(
shouldExpandIfFocuses ||
( inputHasMinimumChars && hasMatchingSuggestions )
);
if ( resetSelectedSuggestion ) {
if (
__experimentalAutoSelectFirstMatch &&
inputHasMinimumChars &&
hasMatchingSuggestions
) {
setSelectedSuggestionIndex( 0 );
setSelectedSuggestionScroll( true );
} else {
setSelectedSuggestionIndex( -1 );
setSelectedSuggestionScroll( false );
}
}
if ( inputHasMinimumChars ) {
const message = hasMatchingSuggestions
? sprintf(
/* translators: %d: number of results. */
_n(
'%d result found, use up and down arrow keys to navigate.',
'%d results found, use up and down arrow keys to navigate.',
matchingSuggestions.length
),
matchingSuggestions.length
)
: __( 'No results.' );
debouncedSpeak( message, 'assertive' );
}
}
function renderTokensAndInput() {
const components = value.map( renderToken );
components.splice( getIndexOfInput(), 0, renderInput() );
return components;
}
function renderToken(
token: string | TokenItem,
index: number,
tokens: ( string | TokenItem )[]
) {
const _value = getTokenValue( token );
const status = typeof token !== 'string' ? token.status : undefined;
const termPosition = index + 1;
const termsCount = tokens.length;
return (
<FlexItem key={ 'token-' + _value }>
<Token
value={ _value }
status={ status }
title={
typeof token !== 'string' ? token.title : undefined
}
displayTransform={ displayTransform }
onClickRemove={ onTokenClickRemove }
isBorderless={
( typeof token !== 'string' && token.isBorderless ) ||
isBorderless
}
onMouseEnter={
typeof token !== 'string'
? token.onMouseEnter
: undefined
}
onMouseLeave={
typeof token !== 'string'
? token.onMouseLeave
: undefined
}
disabled={ 'error' !== status && disabled }
messages={ messages }
termsCount={ termsCount }
termPosition={ termPosition }
/>
</FlexItem>
);
}
function renderInput() {
const inputProps = {
instanceId,
autoCapitalize,
autoComplete,
placeholder: value.length === 0 ? placeholder : '',
key: 'input',
disabled,
value: incompleteTokenValue,
onBlur,
isExpanded,
selectedSuggestionIndex,
};
return (
<TokenInput
{ ...inputProps }
onChange={
! ( maxLength && value.length >= maxLength )
? onInputChangeHandler
: undefined
}
ref={ input }
/>
);
}
const classes = classnames(
className,
'components-form-token-field__input-container',
{
'is-active': isActive,
'is-disabled': disabled,
}
);
let tokenFieldProps = {
className: 'components-form-token-field',
tabIndex: -1,
};
const matchingSuggestions = getMatchingSuggestions();
if ( ! disabled ) {
tokenFieldProps = Object.assign( {}, tokenFieldProps, {
onKeyDown,
onKeyPress,
onFocus: onFocusHandler,
} );
}
// Disable reason: There is no appropriate role which describes the
// input container intended accessible usability.
// TODO: Refactor click detection to use blur to stop propagation.
/* eslint-disable jsx-a11y/no-static-element-interactions */
return (
<div { ...tokenFieldProps }>
<StyledLabel
htmlFor={ `components-form-token-input-${ instanceId }` }
className="components-form-token-field__label"
>
{ label }
</StyledLabel>
<div
ref={ tokensAndInput }
className={ classes }
tabIndex={ -1 }
onMouseDown={ onContainerTouched }
onTouchStart={ onContainerTouched }
>
<TokensAndInputWrapperFlex
justify="flex-start"
align="center"
gap={ 1 }
wrap={ true }
__next36pxDefaultSize={ __next36pxDefaultSize }
hasTokens={ !! value.length }
>
{ renderTokensAndInput() }
</TokensAndInputWrapperFlex>
{ isExpanded && (
<SuggestionsList
instanceId={ instanceId }
match={ saveTransform( incompleteTokenValue ) }
displayTransform={ displayTransform }
suggestions={ matchingSuggestions }
selectedIndex={ selectedSuggestionIndex }
scrollIntoView={ selectedSuggestionScroll }
onHover={ onSuggestionHovered }
onSelect={ onSuggestionSelected }
__experimentalRenderItem={ __experimentalRenderItem }
/>
) }
</div>
{ ! __nextHasNoMarginBottom && <Spacer marginBottom={ 2 } /> }
{ __experimentalShowHowTo && (
<StyledHelp
id={ `components-form-token-suggestions-howto-${ instanceId }` }
className="components-form-token-field__help"
__nextHasNoMarginBottom={ __nextHasNoMarginBottom }
>
{ tokenizeOnSpace
? __(
'Separate with commas, spaces, or the Enter key.'
)
: __( 'Separate with commas or the Enter key.' ) }
</StyledHelp>
) }
</div>
);
/* eslint-enable jsx-a11y/no-static-element-interactions */
}
export default FormTokenField;