summaryrefslogtreecommitdiffstats
path: root/remote/test/puppeteer/test/src/keyboard.spec.ts
blob: 1ae6db22ddc8fda5aadd52ee10650a031c56747e (plain)
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
/**
 * Copyright 2018 Google Inc. All rights reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import os from 'os';

import expect from 'expect';
import {KeyInput} from 'puppeteer-core/internal/common/USKeyboardLayout.js';

import {
  getTestState,
  setupTestBrowserHooks,
  setupTestPageAndContextHooks,
} from './mocha-utils.js';
import {attachFrame} from './utils.js';

describe('Keyboard', function () {
  setupTestBrowserHooks();
  setupTestPageAndContextHooks();

  it('should type into a textarea', async () => {
    const {page} = getTestState();

    await page.evaluate(() => {
      const textarea = document.createElement('textarea');
      document.body.appendChild(textarea);
      textarea.focus();
    });
    const text = 'Hello world. I am the text that was typed!';
    await page.keyboard.type(text);
    expect(
      await page.evaluate(() => {
        return document.querySelector('textarea')!.value;
      })
    ).toBe(text);
  });
  it('should press the metaKey', async () => {
    const {page, isFirefox} = getTestState();

    await page.evaluate(() => {
      (window as any).keyPromise = new Promise(resolve => {
        return document.addEventListener('keydown', event => {
          return resolve(event.key);
        });
      });
    });
    await page.keyboard.press('Meta');
    expect(await page.evaluate('keyPromise')).toBe(
      isFirefox && os.platform() !== 'darwin' ? 'OS' : 'Meta'
    );
  });
  it('should move with the arrow keys', async () => {
    const {page, server} = getTestState();

    await page.goto(server.PREFIX + '/input/textarea.html');
    await page.type('textarea', 'Hello World!');
    expect(
      await page.evaluate(() => {
        return document.querySelector('textarea')!.value;
      })
    ).toBe('Hello World!');
    for (let i = 0; i < 'World!'.length; i++) {
      page.keyboard.press('ArrowLeft');
    }
    await page.keyboard.type('inserted ');
    expect(
      await page.evaluate(() => {
        return document.querySelector('textarea')!.value;
      })
    ).toBe('Hello inserted World!');
    page.keyboard.down('Shift');
    for (let i = 0; i < 'inserted '.length; i++) {
      page.keyboard.press('ArrowLeft');
    }
    page.keyboard.up('Shift');
    await page.keyboard.press('Backspace');
    expect(
      await page.evaluate(() => {
        return document.querySelector('textarea')!.value;
      })
    ).toBe('Hello World!');
  });
  // @see https://github.com/puppeteer/puppeteer/issues/1313
  it('should trigger commands of keyboard shortcuts', async () => {
    const {page, server} = getTestState();
    const cmdKey = os.platform() !== 'darwin' ? 'Meta' : 'Control';

    await page.goto(server.PREFIX + '/input/textarea.html');
    await page.type('textarea', 'hello');

    await page.keyboard.down(cmdKey);
    await page.keyboard.press('a', {commands: ['SelectAll']});
    await page.keyboard.up(cmdKey);

    await page.keyboard.down(cmdKey);
    await page.keyboard.down('c', {commands: ['Copy']});
    await page.keyboard.up('c');
    await page.keyboard.up(cmdKey);

    await page.keyboard.down(cmdKey);
    await page.keyboard.press('v', {commands: ['Paste']});
    await page.keyboard.up(cmdKey);
    await page.keyboard.down(cmdKey);
    await page.keyboard.press('v', {commands: ['Paste']});
    await page.keyboard.up(cmdKey);

    expect(
      await page.evaluate(() => {
        return document.querySelector('textarea')!.value;
      })
    ).toBe('hellohello');
  });
  it('should send a character with ElementHandle.press', async () => {
    const {page, server} = getTestState();

    await page.goto(server.PREFIX + '/input/textarea.html');
    const textarea = (await page.$('textarea'))!;
    await textarea.press('a');
    expect(
      await page.evaluate(() => {
        return document.querySelector('textarea')!.value;
      })
    ).toBe('a');

    await page.evaluate(() => {
      return window.addEventListener(
        'keydown',
        e => {
          return e.preventDefault();
        },
        true
      );
    });

    await textarea.press('b');
    expect(
      await page.evaluate(() => {
        return document.querySelector('textarea')!.value;
      })
    ).toBe('a');
  });
  it('ElementHandle.press should support |text| option', async () => {
    const {page, server} = getTestState();

    await page.goto(server.PREFIX + '/input/textarea.html');
    const textarea = (await page.$('textarea'))!;
    await textarea.press('a', {text: 'ё'});
    expect(
      await page.evaluate(() => {
        return document.querySelector('textarea')!.value;
      })
    ).toBe('ё');
  });
  it('should send a character with sendCharacter', async () => {
    const {page, server} = getTestState();

    await page.goto(server.PREFIX + '/input/textarea.html');
    await page.focus('textarea');
    await page.keyboard.sendCharacter('嗨');
    expect(
      await page.evaluate(() => {
        return document.querySelector('textarea')!.value;
      })
    ).toBe('嗨');
    await page.evaluate(() => {
      return window.addEventListener(
        'keydown',
        e => {
          return e.preventDefault();
        },
        true
      );
    });
    await page.keyboard.sendCharacter('a');
    expect(
      await page.evaluate(() => {
        return document.querySelector('textarea')!.value;
      })
    ).toBe('嗨a');
  });
  it('should report shiftKey', async () => {
    const {page, server} = getTestState();

    await page.goto(server.PREFIX + '/input/keyboard.html');
    const keyboard = page.keyboard;
    const codeForKey = new Map<KeyInput, number>([
      ['Shift', 16],
      ['Alt', 18],
      ['Control', 17],
    ]);
    for (const [modifierKey, modifierCode] of codeForKey) {
      await keyboard.down(modifierKey);
      expect(
        await page.evaluate(() => {
          return (globalThis as any).getResult();
        })
      ).toBe(
        'Keydown: ' +
          modifierKey +
          ' ' +
          modifierKey +
          'Left ' +
          modifierCode +
          ' [' +
          modifierKey +
          ']'
      );
      await keyboard.down('!');
      // Shift+! will generate a keypress
      if (modifierKey === 'Shift') {
        expect(
          await page.evaluate(() => {
            return (globalThis as any).getResult();
          })
        ).toBe(
          'Keydown: ! Digit1 49 [' +
            modifierKey +
            ']\nKeypress: ! Digit1 33 33 [' +
            modifierKey +
            ']'
        );
      } else {
        expect(
          await page.evaluate(() => {
            return (globalThis as any).getResult();
          })
        ).toBe('Keydown: ! Digit1 49 [' + modifierKey + ']');
      }

      await keyboard.up('!');
      expect(
        await page.evaluate(() => {
          return (globalThis as any).getResult();
        })
      ).toBe('Keyup: ! Digit1 49 [' + modifierKey + ']');
      await keyboard.up(modifierKey);
      expect(
        await page.evaluate(() => {
          return (globalThis as any).getResult();
        })
      ).toBe(
        'Keyup: ' +
          modifierKey +
          ' ' +
          modifierKey +
          'Left ' +
          modifierCode +
          ' []'
      );
    }
  });
  it('should report multiple modifiers', async () => {
    const {page, server} = getTestState();

    await page.goto(server.PREFIX + '/input/keyboard.html');
    const keyboard = page.keyboard;
    await keyboard.down('Control');
    expect(
      await page.evaluate(() => {
        return (globalThis as any).getResult();
      })
    ).toBe('Keydown: Control ControlLeft 17 [Control]');
    await keyboard.down('Alt');
    expect(
      await page.evaluate(() => {
        return (globalThis as any).getResult();
      })
    ).toBe('Keydown: Alt AltLeft 18 [Alt Control]');
    await keyboard.down(';');
    expect(
      await page.evaluate(() => {
        return (globalThis as any).getResult();
      })
    ).toBe('Keydown: ; Semicolon 186 [Alt Control]');
    await keyboard.up(';');
    expect(
      await page.evaluate(() => {
        return (globalThis as any).getResult();
      })
    ).toBe('Keyup: ; Semicolon 186 [Alt Control]');
    await keyboard.up('Control');
    expect(
      await page.evaluate(() => {
        return (globalThis as any).getResult();
      })
    ).toBe('Keyup: Control ControlLeft 17 [Alt]');
    await keyboard.up('Alt');
    expect(
      await page.evaluate(() => {
        return (globalThis as any).getResult();
      })
    ).toBe('Keyup: Alt AltLeft 18 []');
  });
  it('should send proper codes while typing', async () => {
    const {page, server} = getTestState();

    await page.goto(server.PREFIX + '/input/keyboard.html');
    await page.keyboard.type('!');
    expect(
      await page.evaluate(() => {
        return (globalThis as any).getResult();
      })
    ).toBe(
      [
        'Keydown: ! Digit1 49 []',
        'Keypress: ! Digit1 33 33 []',
        'Keyup: ! Digit1 49 []',
      ].join('\n')
    );
    await page.keyboard.type('^');
    expect(
      await page.evaluate(() => {
        return (globalThis as any).getResult();
      })
    ).toBe(
      [
        'Keydown: ^ Digit6 54 []',
        'Keypress: ^ Digit6 94 94 []',
        'Keyup: ^ Digit6 54 []',
      ].join('\n')
    );
  });
  it('should send proper codes while typing with shift', async () => {
    const {page, server} = getTestState();

    await page.goto(server.PREFIX + '/input/keyboard.html');
    const keyboard = page.keyboard;
    await keyboard.down('Shift');
    await page.keyboard.type('~');
    expect(
      await page.evaluate(() => {
        return (globalThis as any).getResult();
      })
    ).toBe(
      [
        'Keydown: Shift ShiftLeft 16 [Shift]',
        'Keydown: ~ Backquote 192 [Shift]', // 192 is ` keyCode
        'Keypress: ~ Backquote 126 126 [Shift]', // 126 is ~ charCode
        'Keyup: ~ Backquote 192 [Shift]',
      ].join('\n')
    );
    await keyboard.up('Shift');
  });
  it('should not type canceled events', async () => {
    const {page, server} = getTestState();

    await page.goto(server.PREFIX + '/input/textarea.html');
    await page.focus('textarea');
    await page.evaluate(() => {
      window.addEventListener(
        'keydown',
        event => {
          event.stopPropagation();
          event.stopImmediatePropagation();
          if (event.key === 'l') {
            event.preventDefault();
          }
          if (event.key === 'o') {
            event.preventDefault();
          }
        },
        false
      );
    });
    await page.keyboard.type('Hello World!');
    expect(
      await page.evaluate(() => {
        return (globalThis as any).textarea.value;
      })
    ).toBe('He Wrd!');
  });
  it('should specify repeat property', async () => {
    const {page, server} = getTestState();

    await page.goto(server.PREFIX + '/input/textarea.html');
    await page.focus('textarea');
    await page.evaluate(() => {
      return document.querySelector('textarea')!.addEventListener(
        'keydown',
        e => {
          return ((globalThis as any).lastEvent = e);
        },
        true
      );
    });
    await page.keyboard.down('a');
    expect(
      await page.evaluate(() => {
        return (globalThis as any).lastEvent.repeat;
      })
    ).toBe(false);
    await page.keyboard.press('a');
    expect(
      await page.evaluate(() => {
        return (globalThis as any).lastEvent.repeat;
      })
    ).toBe(true);

    await page.keyboard.down('b');
    expect(
      await page.evaluate(() => {
        return (globalThis as any).lastEvent.repeat;
      })
    ).toBe(false);
    await page.keyboard.down('b');
    expect(
      await page.evaluate(() => {
        return (globalThis as any).lastEvent.repeat;
      })
    ).toBe(true);

    await page.keyboard.up('a');
    await page.keyboard.down('a');
    expect(
      await page.evaluate(() => {
        return (globalThis as any).lastEvent.repeat;
      })
    ).toBe(false);
  });
  it('should type all kinds of characters', async () => {
    const {page, server} = getTestState();

    await page.goto(server.PREFIX + '/input/textarea.html');
    await page.focus('textarea');
    const text = 'This text goes onto two lines.\nThis character is 嗨.';
    await page.keyboard.type(text);
    expect(await page.evaluate('result')).toBe(text);
  });
  it('should specify location', async () => {
    const {page, server} = getTestState();

    await page.goto(server.PREFIX + '/input/textarea.html');
    await page.evaluate(() => {
      window.addEventListener(
        'keydown',
        event => {
          return ((globalThis as any).keyLocation = event.location);
        },
        true
      );
    });
    const textarea = (await page.$('textarea'))!;

    await textarea.press('Digit5');
    expect(await page.evaluate('keyLocation')).toBe(0);

    await textarea.press('ControlLeft');
    expect(await page.evaluate('keyLocation')).toBe(1);

    await textarea.press('ControlRight');
    expect(await page.evaluate('keyLocation')).toBe(2);

    await textarea.press('NumpadSubtract');
    expect(await page.evaluate('keyLocation')).toBe(3);
  });
  it('should throw on unknown keys', async () => {
    const {page} = getTestState();

    let error = await page.keyboard
      // @ts-expect-error bad input
      .press('NotARealKey')
      .catch(error_ => {
        return error_;
      });
    expect(error.message).toBe('Unknown key: "NotARealKey"');

    // @ts-expect-error bad input
    error = await page.keyboard.press('ё').catch(error_ => {
      return error_;
    });
    expect(error && error.message).toBe('Unknown key: "ё"');

    // @ts-expect-error bad input
    error = await page.keyboard.press('😊').catch(error_ => {
      return error_;
    });
    expect(error && error.message).toBe('Unknown key: "😊"');
  });
  it('should type emoji', async () => {
    const {page, server} = getTestState();

    await page.goto(server.PREFIX + '/input/textarea.html');
    await page.type('textarea', '👹 Tokyo street Japan 🇯🇵');
    expect(
      await page.$eval('textarea', textarea => {
        return textarea.value;
      })
    ).toBe('👹 Tokyo street Japan 🇯🇵');
  });
  it('should type emoji into an iframe', async () => {
    const {page, server} = getTestState();

    await page.goto(server.EMPTY_PAGE);
    await attachFrame(
      page,
      'emoji-test',
      server.PREFIX + '/input/textarea.html'
    );
    const frame = page.frames()[1]!;
    const textarea = (await frame.$('textarea'))!;
    await textarea.type('👹 Tokyo street Japan 🇯🇵');
    expect(
      await frame.$eval('textarea', textarea => {
        return textarea.value;
      })
    ).toBe('👹 Tokyo street Japan 🇯🇵');
  });
  it('should press the meta key', async () => {
    const {page, isFirefox} = getTestState();

    await page.evaluate(() => {
      (globalThis as any).result = null;
      document.addEventListener('keydown', event => {
        (globalThis as any).result = [event.key, event.code, event.metaKey];
      });
    });
    await page.keyboard.press('Meta');
    // Have to do this because we lose a lot of type info when evaluating a
    // string not a function. This is why functions are recommended rather than
    // using strings (although we'll leave this test so we have coverage of both
    // approaches.)
    const [key, code, metaKey] = (await page.evaluate('result')) as [
      string,
      string,
      boolean
    ];
    if (isFirefox && os.platform() !== 'darwin') {
      expect(key).toBe('OS');
    } else {
      expect(key).toBe('Meta');
    }

    if (isFirefox) {
      expect(code).toBe('OSLeft');
    } else {
      expect(code).toBe('MetaLeft');
    }

    if (isFirefox && os.platform() !== 'darwin') {
      expect(metaKey).toBe(false);
    } else {
      expect(metaKey).toBe(true);
    }
  });
});