/
index.tsx
2260 lines (1778 loc) · 64.6 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
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* eslint jest/expect-expect: ["warn", { "assertFunctionNames": ["expect", "expectTokensToBeInTheDocument", "expectTokensNotToBeInTheDocument", "expectVisibleSuggestionsToBe", "expectEscapedProperly"] }] */
/**
* External dependencies
*/
import {
render,
screen,
within,
getDefaultNormalizer,
waitFor,
} from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import type { ComponentProps } from 'react';
/**
* WordPress dependencies
*/
import { useState } from '@wordpress/element';
/**
* Internal dependencies
*/
import FormTokenField from '../';
const FormTokenFieldWithState = ( {
onChange,
value,
initialValue = [],
...props
}: ComponentProps< typeof FormTokenField > & {
initialValue?: ComponentProps< typeof FormTokenField >[ 'value' ];
} ) => {
const [ selectedValue, setSelectedValue ] =
useState< ComponentProps< typeof FormTokenField >[ 'value' ] >(
initialValue
);
return (
<FormTokenField
{ ...props }
value={ selectedValue }
onChange={ ( tokens ) => {
setSelectedValue( tokens );
onChange?.( tokens );
} }
__nextHasNoMarginBottom
/>
);
};
const expectTokensToBeInTheDocument = ( tokensText: string[] ) => {
tokensText.forEach( ( tokenText, tokenIndex, tokensArray ) => {
// Each token has 2 tags rendered in the DOM:
// - one with the format "takenName (X of Y)", which is visibly hidden,
// and is used for assistive technology;
// - one with the format "tokenName", which is visible but hidden to
// assistive technology.
const assistiveTechnologyToken = screen.getByText(
`${ tokenText } (${ tokenIndex + 1 } of ${ tokensArray.length })`,
{
normalizer: getDefaultNormalizer( {
collapseWhitespace: false,
trim: false,
} ),
}
);
// The "exact" flag is necessary in order no to match the element
// used for assistive technology.
const visibleToken = screen.getByText( tokenText, {
exact: true,
normalizer: getDefaultNormalizer( {
collapseWhitespace: false,
trim: false,
} ),
} );
expect( assistiveTechnologyToken ).toBeInTheDocument();
expect( visibleToken ).toBeVisible();
expect( visibleToken ).toHaveAttribute( 'aria-hidden', 'true' );
} );
};
const expectTokensNotToBeInTheDocument = ( tokensText: string[] ) => {
tokensText.forEach( ( tokenText ) =>
expect( screen.queryByText( tokenText ) ).not.toBeInTheDocument()
);
};
const expectEscapedProperly = ( tokenHtml: string ) => {
screen.getByText( ( _, node: Element | null ) => {
if ( node === null ) {
return false;
}
// This is hacky, but it's a way we can check exactly the output HTML
return node.innerHTML === tokenHtml;
} );
};
const expectVisibleSuggestionsToBe = (
listElement: HTMLElement,
suggestionsText: string[]
) => {
const allVisibleOptions = within( listElement ).queryAllByRole( 'option' );
expect( allVisibleOptions ).toHaveLength( suggestionsText.length );
allVisibleOptions.forEach( ( matchedOption, index ) => {
expect( matchedOption ).toHaveAccessibleName(
suggestionsText[ index ]
);
} );
};
function unescapeAndFormatSpaces( str: string ) {
const nbsp = String.fromCharCode( 160 );
const escaped = new DOMParser().parseFromString( str, 'text/html' );
return escaped.documentElement.textContent?.replace( / /g, nbsp ) ?? '';
}
describe( 'FormTokenField', () => {
describe( 'basic usage', () => {
it( "should add tokens with the input's value when pressing the enter key", async () => {
const user = userEvent.setup();
const onChangeSpy = jest.fn();
render( <FormTokenFieldWithState onChange={ onChangeSpy } /> );
const input = screen.getByRole( 'combobox' );
// Add 'apple' token by typing it and pressing enter to tokenize it.
await user.type( input, 'apple[Enter]' );
expect( onChangeSpy ).toHaveBeenCalledTimes( 1 );
expect( onChangeSpy ).toHaveBeenCalledWith( [ 'apple' ] );
expectTokensToBeInTheDocument( [ 'apple' ] );
// Add 'pear' token by typing it and pressing enter to tokenize it.
await user.type( input, 'pear[Enter]' );
expect( onChangeSpy ).toHaveBeenCalledTimes( 2 );
expect( onChangeSpy ).toHaveBeenLastCalledWith( [
'apple',
'pear',
] );
expectTokensToBeInTheDocument( [ 'apple', 'pear' ] );
} );
it( "should add a token with the input's value when pressing the comma key", async () => {
const user = userEvent.setup();
const onChangeSpy = jest.fn();
render( <FormTokenFieldWithState onChange={ onChangeSpy } /> );
const input = screen.getByRole( 'combobox' );
// Add 'orange' token by typing it and pressing enter to tokenize it.
await user.type( input, 'orange,' );
expect( onChangeSpy ).toHaveBeenCalledTimes( 1 );
expect( onChangeSpy ).toHaveBeenCalledWith( [ 'orange' ] );
expectTokensToBeInTheDocument( [ 'orange' ] );
} );
it( 'should add a token with the input value when pressing the space key and the `tokenizeOnSpace` prop is `true`', async () => {
const user = userEvent.setup();
const onChangeSpy = jest.fn();
const { rerender } = render(
<FormTokenFieldWithState onChange={ onChangeSpy } />
);
const input = screen.getByRole( 'combobox' );
// Add 'dragon fruit' token by typing it and pressing enter to tokenize it.
await user.type( input, 'dragon fruit[Enter]' );
expect( onChangeSpy ).toHaveBeenCalledTimes( 1 );
expect( onChangeSpy ).toHaveBeenCalledWith( [ 'dragon fruit' ] );
expectTokensToBeInTheDocument( [ 'dragon fruit' ] );
rerender(
<FormTokenFieldWithState
onChange={ onChangeSpy }
tokenizeOnSpace
/>
);
// Add 'dragon fruit' token by typing it and pressing enter to tokenize it,
// this time two separate tokens should be added
await user.type( input, 'dragon fruit[Enter]' );
expect( onChangeSpy ).toHaveBeenCalledTimes( 3 );
expect( onChangeSpy ).toHaveBeenNthCalledWith( 2, [
'dragon fruit',
'dragon',
] );
expect( onChangeSpy ).toHaveBeenNthCalledWith( 3, [
'dragon fruit',
'dragon',
'fruit',
] );
expectTokensToBeInTheDocument( [
'dragon fruit',
'dragon',
'fruit',
] );
} );
it( 'should add a token with the input value with onBlur when `tokenizeOnBlur` prop is `true`', async () => {
const user = userEvent.setup();
const onChangeSpy = jest.fn();
const { rerender } = render(
<FormTokenFieldWithState onChange={ onChangeSpy } />
);
const input = screen.getByRole( 'combobox' );
// Add 'grapefruit' token by typing it and check blur of field does not tokenize it.
await user.type( input, 'grapefruit' );
await user.click( document.body );
expect( onChangeSpy ).toHaveBeenCalledTimes( 0 );
expectTokensNotToBeInTheDocument( [ 'grapefruit' ] );
rerender(
<FormTokenFieldWithState
onChange={ onChangeSpy }
tokenizeOnBlur
/>
);
await user.clear( input );
// Add 'grapefruit' token by typing it and check blur of field tokenizes it.
await user.type( input, 'grapefruit' );
await user.click( document.body );
expect( onChangeSpy ).toHaveBeenNthCalledWith( 1, [
'grapefruit',
] );
expectTokensToBeInTheDocument( [ 'grapefruit' ] );
} );
it( "should not add a token with the input's value when tokenizeOnBlur is not set and pressing the tab key", async () => {
const user = userEvent.setup();
const onChangeSpy = jest.fn();
render( <FormTokenFieldWithState onChange={ onChangeSpy } /> );
const input = screen.getByRole( 'combobox' );
// Add 'orange' token by typing it and pressing enter to tokenize it.
await user.type( input, 'grapefruit' );
await user.tab();
expect( onChangeSpy ).toHaveBeenCalledTimes( 0 );
expectTokensNotToBeInTheDocument( [ 'grapefruit' ] );
} );
it( 'should remove the last token when pressing the backspace key', async () => {
const user = userEvent.setup();
const onChangeSpy = jest.fn();
render(
<FormTokenFieldWithState
onChange={ onChangeSpy }
initialValue={ [ 'banana', 'mango' ] }
/>
);
const input = screen.getByRole( 'combobox' );
// Press backspace to remove the last token ("mango")
await user.type( input, '[Backspace]' );
expect( onChangeSpy ).toHaveBeenCalledTimes( 1 );
expect( onChangeSpy ).toHaveBeenLastCalledWith( [ 'banana' ] );
expectTokensToBeInTheDocument( [ 'banana' ] );
expectTokensNotToBeInTheDocument( [ 'mango' ] );
// Press backspace to remove the last token ("banana")
await user.type( input, '[Backspace]' );
expect( onChangeSpy ).toHaveBeenCalledTimes( 2 );
expect( onChangeSpy ).toHaveBeenLastCalledWith( [] );
expectTokensNotToBeInTheDocument( [ 'banana', 'mango' ] );
} );
it( 'should remove a token when clicking the token\'s "remove" button', async () => {
const user = userEvent.setup();
const onChangeSpy = jest.fn();
render(
<FormTokenFieldWithState
initialValue={ [ 'lemon', 'bergamot' ] }
onChange={ onChangeSpy }
/>
);
expectTokensToBeInTheDocument( [ 'lemon', 'bergamot' ] );
// There should be 2 "remove item" buttons, one per token
expect(
screen.getAllByRole( 'button', { name: 'Remove item' } )
).toHaveLength( 2 );
// Click the "X" button for the "lemon" token (the first one)
await user.click(
screen.getAllByRole( 'button', { name: 'Remove item' } )[ 0 ]
);
expect( onChangeSpy ).toHaveBeenCalledTimes( 1 );
expect( onChangeSpy ).toHaveBeenLastCalledWith( [ 'bergamot' ] );
expectTokensToBeInTheDocument( [ 'bergamot' ] );
expectTokensNotToBeInTheDocument( [ 'lemon' ] );
// There should be 1 "remove item" button for the "bergamot" token
expect(
screen.getByRole( 'button', { name: 'Remove item' } )
).toBeInTheDocument();
// Click the "X" button for the "bergamot" token (the only one)
await user.click(
screen.getAllByRole( 'button', { name: 'Remove item' } )[ 0 ]
);
expect( onChangeSpy ).toHaveBeenCalledTimes( 2 );
expect( onChangeSpy ).toHaveBeenLastCalledWith( [] );
expectTokensNotToBeInTheDocument( [ 'lemon', 'bergamot' ] );
} );
it( 'should remove a token when by focusing on the token\'s "remove" button and pressing space bar', async () => {
const user = userEvent.setup();
const onChangeSpy = jest.fn();
render(
<FormTokenFieldWithState
onChange={ onChangeSpy }
initialValue={ [ 'persimmon', 'plum' ] }
/>
);
const input = screen.getByRole( 'combobox' );
await user.click( input );
// Currently the focus in on the input. Pressing shift+tab twice should
// move focus on the "remove item" button of the first token ("persimmon")
await user.tab( { shift: true } );
await user.tab( { shift: true } );
expect(
screen.getAllByRole( 'button', { name: 'Remove item' } )
).toHaveLength( 2 );
expect(
screen.getAllByRole( 'button', { name: 'Remove item' } )[ 0 ]
).toHaveFocus();
// Pressing the "space" key on the button should remove the "persimmon" item
await user.keyboard( '[Space]' );
expect( onChangeSpy ).toHaveBeenCalledTimes( 1 );
expect( onChangeSpy ).toHaveBeenLastCalledWith( [ 'plum' ] );
expectTokensToBeInTheDocument( [ 'plum' ] );
expectTokensNotToBeInTheDocument( [ 'persimmon' ] );
} );
it( 'should not add a new token if a token with the same value already exists', async () => {
const user = userEvent.setup();
const onChangeSpy = jest.fn();
render(
<FormTokenFieldWithState
initialValue={ [ 'papaya' ] }
onChange={ onChangeSpy }
/>
);
const input = screen.getByRole( 'combobox' );
// Add 'guava' token by typing it and pressing enter to tokenize it.
await user.type( input, 'guava[Enter]' );
expect( onChangeSpy ).toHaveBeenCalledTimes( 1 );
expect( onChangeSpy ).toHaveBeenCalledWith( [ 'papaya', 'guava' ] );
expectTokensToBeInTheDocument( [ 'papaya', 'guava' ] );
// Try to add a 'papaya' token by typing it and pressing enter to tokenize it,
// but the token won't be added because it already exists.
await user.type( input, 'papaya[Enter]' );
expect( onChangeSpy ).toHaveBeenCalledTimes( 1 );
expectTokensToBeInTheDocument( [ 'papaya', 'guava' ] );
} );
it( 'should not add a new token if the text input is blank', async () => {
const user = userEvent.setup();
const onChangeSpy = jest.fn();
render(
<FormTokenFieldWithState
initialValue={ [ 'melon' ] }
onChange={ onChangeSpy }
/>
);
const input = screen.getByRole( 'combobox' );
// Press enter on an empty input, no token gets added
await user.type( input, '[Enter]' );
expect( onChangeSpy ).not.toHaveBeenCalled();
expectTokensToBeInTheDocument( [ 'melon' ] );
} );
it( 'should allow moving the cursor through the tokens when pressing the arrow keys, and should remove the token in front of the cursor when pressing the delete key', async () => {
const user = userEvent.setup();
const onChangeSpy = jest.fn();
render(
<FormTokenFieldWithState
initialValue={ [ 'kiwi', 'peach', 'nectarine', 'coconut' ] }
onChange={ onChangeSpy }
/>
);
expectTokensToBeInTheDocument( [
'kiwi',
'peach',
'nectarine',
'coconut',
] );
const input = screen.getByRole( 'combobox' );
// Press "delete" to delete the token in front of the cursor, but since
// there's no token in front of the cursor, nothing happens
await user.type( input, '[Delete]' );
// Pressing the right arrow doesn't move the cursor because there are no
// tokens in front of it, and therefore pressing "delete" yields the same
// result as before — no tokens are deleted.
await user.type( input, '[ArrowRight][Delete]' );
// Proof that so far, all keyboard interactions didn't delete any tokens.
expect( onChangeSpy ).not.toHaveBeenCalled();
expectTokensToBeInTheDocument( [
'kiwi',
'peach',
'nectarine',
'coconut',
] );
// Press the left arrow 4 times, moving cursor between the "kiwi" and
// "peach" tokens. Pressing the "delete" key will delete the "peach"
// token, since it's in front of the cursor.
await user.type(
input,
'[ArrowLeft][ArrowLeft][ArrowLeft][ArrowLeft][Delete]'
);
expect( onChangeSpy ).toHaveBeenCalledTimes( 1 );
expect( onChangeSpy ).toHaveBeenCalledWith( [
'peach',
'nectarine',
'coconut',
] );
expectTokensToBeInTheDocument( [
'peach',
'nectarine',
'coconut',
] );
expectTokensNotToBeInTheDocument( [ 'kiwi' ] );
// Press backspace to delete the token before the cursor, but since
// there's no token before the cursor, nothing happens
await user.type( input, '[Backspace]' );
// Pressing the left arrow doesn't move the cursor because there are no
// tokens before it, and therefore pressing backspace yields the same
// result as before — no tokens are deleted.
await user.type( input, '[ArrowLeft][Backspace]' );
// Proof that pressing backspace hasn't caused any further token deletion.
expect( onChangeSpy ).toHaveBeenCalledTimes( 1 );
// Press the right arrow, moving cursor between the "kiwi" and
// "nectarine" tokens. Pressing the "delete" key will delete the "nectarine"
// token, since it's in front of the cursor.
await user.type( input, '[ArrowRight][Delete]' );
expect( onChangeSpy ).toHaveBeenCalledTimes( 2 );
expect( onChangeSpy ).toHaveBeenCalledWith( [
'peach',
'coconut',
] );
expectTokensToBeInTheDocument( [ 'peach', 'coconut' ] );
expectTokensNotToBeInTheDocument( [ 'kiwi', 'nectarine' ] );
// Add 'starfruit' token while the cursor is in between the "peach" and
// "coconut" tokens.
await user.type( input, 'starfruit[Enter]' );
expect( onChangeSpy ).toHaveBeenCalledTimes( 3 );
expect( onChangeSpy ).toHaveBeenCalledWith( [
'peach',
// Notice that starfruit is added in between "peach" and "coconut"
'starfruit',
'coconut',
] );
expectTokensToBeInTheDocument( [
'peach',
'starfruit',
'coconut',
] );
} );
it( "should add additional classnames passed via the `className` prop to the input element's 2nd level wrapper", () => {
render( <FormTokenFieldWithState className="test-classname" /> );
const input = screen.getByRole( 'combobox' );
// This is testing implementation details, but I'm not sure there's
// a better way.
// eslint-disable-next-line testing-library/no-node-access
expect( input.parentElement?.parentElement ).toHaveClass(
'test-classname'
);
} );
it( 'should label the input correctly via the `label` prop', () => {
const { rerender } = render( <FormTokenFieldWithState /> );
expect(
screen.getByRole( 'combobox', { name: 'Add item' } )
).toBeVisible();
rerender( <FormTokenFieldWithState label="Test label" /> );
expect(
screen.getByRole( 'combobox', { name: 'Test label' } )
).toBeVisible();
} );
it( 'should fire the `onFocus` callback when the input is focused', async () => {
const user = userEvent.setup();
const onFocusSpy = jest.fn();
render( <FormTokenFieldWithState onFocus={ onFocusSpy } /> );
const input = screen.getByRole( 'combobox' );
await user.click( input );
expect( onFocusSpy ).toHaveBeenCalledTimes( 1 );
expect( onFocusSpy ).toHaveBeenCalledWith(
expect.objectContaining( {
type: 'focus',
target: input,
} )
);
expect( input ).toHaveFocus();
} );
it( "should fire the `onInputChange` callback when the input's value changes", async () => {
const user = userEvent.setup();
const onInputChangeSpy = jest.fn();
render(
<FormTokenFieldWithState onInputChange={ onInputChangeSpy } />
);
const input = screen.getByRole( 'combobox' );
await user.type( input, 'strawberry[Enter]' );
expect( onInputChangeSpy ).toHaveBeenCalledTimes(
'strawberry'.length
);
expect( onInputChangeSpy ).toHaveBeenNthCalledWith(
5,
'strawberry'.slice( 0, 5 )
);
} );
it( 'should show extra instructions when the `__experimentalShowHowTo` prop is set to `true`', () => {
const instructionsTokenizeSpace =
'Separate with commas, spaces, or the Enter key.';
const instructionsDefault =
'Separate with commas or the Enter key.';
// The __experimentalShowHowTo prop is `true` by default
const { rerender } = render( <FormTokenFieldWithState /> );
expect( screen.getByText( instructionsDefault ) ).toBeVisible();
// The "show how to" text is used to aria-describedby the input
expect(
screen.getByRole( 'combobox' )
).toHaveAccessibleDescription( instructionsDefault );
rerender( <FormTokenFieldWithState tokenizeOnSpace /> );
expect(
screen.getByText( instructionsTokenizeSpace )
).toBeVisible();
// The "show how to" text is used to aria-describedby the input
expect(
screen.getByRole( 'combobox' )
).toHaveAccessibleDescription( instructionsTokenizeSpace );
rerender(
<FormTokenFieldWithState
tokenizeOnSpace
__experimentalShowHowTo={ false }
/>
);
expect(
screen.queryByText( instructionsDefault )
).not.toBeInTheDocument();
expect(
screen.queryByText( instructionsTokenizeSpace )
).not.toBeInTheDocument();
expect(
screen.getByRole( 'combobox' )
).not.toHaveAccessibleDescription();
} );
it( "should use the value of the `placeholder` prop as the input's placeholder only when there are no tokens", async () => {
const user = userEvent.setup();
const onChangeSpy = jest.fn();
render(
<FormTokenFieldWithState
onChange={ onChangeSpy }
placeholder="Test placeholder"
/>
);
expect(
screen.getByPlaceholderText( 'Test placeholder' )
).toBeVisible();
const input = screen.getByRole( 'combobox' );
// Add 'blueberry' token. The placeholder text should not be shown anymore
await user.type( input, 'blueberry[Enter]' );
expect( onChangeSpy ).toHaveBeenCalledTimes( 1 );
expect( onChangeSpy ).toHaveBeenCalledWith( [ 'blueberry' ] );
expectTokensToBeInTheDocument( [ 'blueberry' ] );
expect(
screen.queryByPlaceholderText( 'Test placeholder' )
).not.toBeInTheDocument();
} );
it( 'should handle accents and special characters in tokens and input value', async () => {
const user = userEvent.setup();
const onChangeSpy = jest.fn();
render(
<FormTokenFieldWithState
onChange={ onChangeSpy }
initialValue={ [ 'français', 'español', '日本', 'עברית' ] }
/>
);
const input = screen.getByRole( 'combobox' );
// Add 'عربى' token by typing it and pressing enter to tokenize it.
await user.type( input, 'عربى[Enter]' );
expect( onChangeSpy ).toHaveBeenCalledTimes( 1 );
expect( onChangeSpy ).toHaveBeenCalledWith( [
'français',
'español',
'日本',
'עברית',
'عربى',
] );
expectTokensToBeInTheDocument( [
'français',
'español',
'日本',
'עברית',
'عربى',
] );
} );
} );
describe( 'suggestions', () => {
it( 'should not render suggestions in its default state', () => {
render(
<FormTokenFieldWithState
suggestions={ [ 'Red', 'Magenta', 'Vermilion' ] }
/>
);
expect( screen.queryByRole( 'listbox' ) ).not.toBeInTheDocument();
} );
it( 'should render suggestions when receiving focus if the `__experimentalExpandOnFocus` prop is set to `true`', async () => {
const user = userEvent.setup();
const onFocusSpy = jest.fn();
const suggestions = [ 'Cobalt', 'Blue', 'Octane' ];
render(
<>
<FormTokenFieldWithState
onFocus={ onFocusSpy }
suggestions={ suggestions }
__experimentalExpandOnFocus
/>
</>
);
const input = screen.getByRole( 'combobox' );
expect( screen.queryByRole( 'listbox' ) ).not.toBeInTheDocument();
// Click the input, focusing it.
await user.click( input );
const suggestionList = screen.getByRole( 'listbox' );
expect( onFocusSpy ).toHaveBeenCalledTimes( 1 );
expect( suggestionList ).toBeVisible();
expectVisibleSuggestionsToBe(
screen.getByRole( 'listbox' ),
suggestions
);
// Minimum length limitations don't affect the search text when the
// `__experimentalExpandOnFocus` is `true`
await user.keyboard( 'c' );
expectVisibleSuggestionsToBe( screen.getByRole( 'listbox' ), [
'Cobalt',
'Octane',
] );
} );
it( 'should render suggestions after a selection is made when the `__experimentalExpandOnFocus` prop is set to `true`', async () => {
const user = userEvent.setup();
const onFocusSpy = jest.fn();
const suggestions = [ 'Green', 'Emerald', 'Seaweed' ];
render(
<>
<FormTokenFieldWithState
onFocus={ onFocusSpy }
suggestions={ suggestions }
__experimentalExpandOnFocus
/>
</>
);
const input = screen.getByRole( 'combobox' );
await user.type( input, 'ee' );
expectVisibleSuggestionsToBe( screen.getByRole( 'listbox' ), [
'Green',
'Seaweed',
] );
// Select the first suggestion ("Green")
await user.keyboard( '[ArrowDown][Enter]' );
expect( screen.getByRole( 'listbox' ) ).toBeVisible();
} );
it( 'should not render suggestions after a selection is made when the `__experimentalExpandOnFocus` prop is set to `false` or not defined', async () => {
const user = userEvent.setup();
const onFocusSpy = jest.fn();
const suggestions = [ 'Green', 'Emerald', 'Seaweed' ];
render(
<>
<FormTokenFieldWithState
onFocus={ onFocusSpy }
suggestions={ suggestions }
/>
</>
);
const input = screen.getByRole( 'combobox' );
await user.type( input, 'ee' );
expectVisibleSuggestionsToBe( screen.getByRole( 'listbox' ), [
'Green',
'Seaweed',
] );
// Select the first suggestion ("Green")
await user.keyboard( '[ArrowDown][Enter]' );
expect( screen.queryByRole( 'listbox' ) ).not.toBeInTheDocument();
} );
it( 'should not render suggestions after the input is blurred', async () => {
const user = userEvent.setup();
const onFocusSpy = jest.fn();
const suggestions = [ 'Green', 'Emerald', 'Seaweed' ];
render(
<>
<FormTokenFieldWithState
onFocus={ onFocusSpy }
suggestions={ suggestions }
/>
</>
);
const input = screen.getByRole( 'combobox' );
await user.type( input, 'ee' );
expectVisibleSuggestionsToBe( screen.getByRole( 'listbox' ), [
'Green',
'Seaweed',
] );
// Select the first suggestion ("Green")
await user.keyboard( '[ArrowDown][Enter]' );
// Click the body, blurring the input.
await user.click( document.body );
expect( screen.queryByRole( 'listbox' ) ).not.toBeInTheDocument();
} );
it( 'should not render suggestions if the text input is not matching any of the suggestions', async () => {
const user = userEvent.setup();
const suggestions = [ 'White', 'Pearl', 'Alabaster' ];
render( <FormTokenFieldWithState suggestions={ suggestions } /> );
const input = screen.getByRole( 'combobox' );
// Type 'Snow' which doesn't match any of the suggestions
await user.type( input, 'Snow' );
expect( screen.queryByRole( 'listbox' ) ).not.toBeInTheDocument();
} );
it( 'should render the matching suggestions only if the text input has the minimum length', async () => {
const user = userEvent.setup();
const suggestions = [ 'Yellow', 'Canary', 'Gold', 'Blonde' ];
render( <FormTokenFieldWithState suggestions={ suggestions } /> );
const input = screen.getByRole( 'combobox' );
// Despite 'l' matches some suggestions, the search text needs to be
// at least 2 characters
await user.type( input, ' l ' );
expect( screen.queryByRole( 'listbox' ) ).not.toBeInTheDocument();
// The trimmed search text is now 2 characters long (`lo`), which is
// enough to show matching suggestions ('Yellow' and 'Blonde')
await user.type( input, '[ArrowLeft][ArrowLeft][ArrowLeft]o' );
expectVisibleSuggestionsToBe( screen.getByRole( 'listbox' ), [
'Yellow',
'Blonde',
] );
} );
it( 'should not render a matching suggestion if a token with the same value has already been added', async () => {
const user = userEvent.setup();
const suggestions = [ 'Green', 'Emerald', 'Seaweed' ];
render(
<FormTokenFieldWithState
suggestions={ suggestions }
initialValue={ [ 'Green' ] }
/>
);
const input = screen.getByRole( 'combobox' );
// Despite 'ee' matches both the "Green" and "Seaweed", "Green" won't be
// displayed because there's already a token with the same value
await user.type( input, 'ee' );
expectVisibleSuggestionsToBe( screen.getByRole( 'listbox' ), [
'Seaweed',
] );
} );
it( 'should allow the user to use the keyboard to navigate and select suggestions (which are marked with the `aria-selected` attribute)', async () => {
const user = userEvent.setup();
const onChangeSpy = jest.fn();
const suggestions = [
'Pink',
'Salmon',
'Flamingo',
'Carnation',
'Neon',
];
render(
<FormTokenFieldWithState
onChange={ onChangeSpy }
suggestions={ suggestions }
/>
);
const input = screen.getByRole( 'combobox' );
// Typing "on" will show the "Salmon", "Carnation" and "Neon" suggestions
await user.type( input, 'on' );
const suggestionList = screen.getByRole( 'listbox' );
expectVisibleSuggestionsToBe( suggestionList, [
'Salmon',
'Carnation',
'Neon',
] );
// Currently, none of the suggestions are selected
expect(
within( suggestionList ).queryByRole( 'option', {
selected: true,
} )
).not.toBeInTheDocument();
// Pressing the down arrow will select "Salmon"
await user.keyboard( '[ArrowDown]' );
expect(
within( suggestionList ).getByRole( 'option', {
selected: true,
} )
).toHaveAccessibleName( 'Salmon' );
// Pressing the up arrow will select "Neon" (the selection wraps around
// the list)
await user.keyboard( '[ArrowUp]' );
expect(
within( suggestionList ).getByRole( 'option', {
selected: true,
} )
).toHaveAccessibleName( 'Neon' );
// Pressing the down arrow twice will select "Carnation" (the selection
// wraps around the list)
await user.keyboard( '[ArrowDown][ArrowDown]' );
expect(
within( suggestionList ).getByRole( 'option', {
selected: true,
} )
).toHaveAccessibleName( 'Carnation' );
// Pressing enter will add "Carnation" as a token and close the suggestion list
await user.keyboard( '[Enter]' );
expect( onChangeSpy ).toHaveBeenCalledTimes( 1 );
expect( onChangeSpy ).toHaveBeenCalledWith( [ 'Carnation' ] );
expectTokensToBeInTheDocument( [ 'Carnation' ] );
expect( screen.queryByRole( 'listbox' ) ).not.toBeInTheDocument();
} );
it( 'should allow the user to use the mouse to navigate and select suggestions (which are marked with the `aria-selected` attribute)', async () => {
const user = userEvent.setup();
const onChangeSpy = jest.fn();
const suggestions = [ 'Tiger', 'Tangerine', 'Orange' ];
render(
<FormTokenFieldWithState
onChange={ onChangeSpy }
suggestions={ suggestions }
/>
);
const input = screen.getByRole( 'combobox' );
// Typing "er" will show the "Tiger" and "Tangerine" suggestions
await user.type( input, 'er' );