Debian Codegraph @

debian/tests/test_modules/vitest/browser.js

raw
1 const modifierState = {
2 Alt: false,
3 AltGraph: false,
4 Control: false,
5 Meta: false,
6 Shift: false,
7 }
8
9 const modifierToInit = {
10 Alt: "altKey",
11 AltGraph: "modifierAltGraph",
12 Control: "ctrlKey",
13 Meta: "metaKey",
14 Shift: "shiftKey",
15 }
16
17 function eventInit(overrides = {}) {
18 let init = { bubbles: true, ...overrides }
19 for (let [modifier, field] of Object.entries(modifierToInit)) {
20 if (modifierState[modifier]) {
21 init[field] = true
22 }
23 }
24 return init
25 }
26
27 function keyInfo(input) {
28 if (/^Key[A-Z]$/.test(input)) {
29 return { key: input.slice(3).toLowerCase(), code: input }
30 }
31 if (/^F\d+$/.test(input)) {
32 return { key: input, code: input }
33 }
34 if (modifierToInit[input]) {
35 return { key: input, code: `${input}Left` }
36 }
37 if (input.length === 1) {
38 return { key: input, code: `Key${input.toUpperCase()}` }
39 }
40 return { key: input, code: input }
41 }
42
43 function dispatch(target, type, input) {
44 let info = keyInfo(input)
45 target.dispatchEvent(new KeyboardEvent(type, eventInit(info)))
46 }
47
48 async function keyboard(input, target = window) {
49 let tokens = input.match(/\{[^}]+\}|./g) || []
50
51 for (let token of tokens) {
52 if (token.startsWith("{/")) {
53 let modifier = token.slice(2, -1)
54 dispatch(target, "keyup", modifier)
55 modifierState[modifier] = false
56 } else if (token.startsWith("{") && token.endsWith(">}" )) {
57 let modifier = token.slice(1, -2)
58 modifierState[modifier] = true
59 dispatch(target, "keydown", modifier)
60 } else {
61 let key = token.startsWith("{") ? token.slice(1, -1) : token
62 dispatch(target, "keydown", key)
63 dispatch(target, "keyup", key)
64 }
65 }
66 }
67
68 export const userEvent = {
69 keyboard(input) {
70 return keyboard(input, window)
71 },
72 type(element, input) {
73 return keyboard(input, element)
74 },
75 }