diff --git a/src/actions/pressKey.ts b/src/actions/pressKey.ts index ef4ea94e..4e9c694c 100644 --- a/src/actions/pressKey.ts +++ b/src/actions/pressKey.ts @@ -1,20 +1,73 @@ import {LogEventType} from '../constants/internal'; import {getPlaywrightPage} from '../useContext'; +import {E2edError} from '../utils/error'; import {log} from '../utils/log'; +import {getDescriptionFromSelector} from '../utils/selectors'; -import type {Keyboard} from '@playwright/test'; +import type {KeyboardPressKey, Selector} from '../types/internal'; -import type {KeyboardPressKey} from '../types/internal'; +type Options = Readonly<{delay?: number; timeout?: number}>; -type Options = Parameters[1]; +type PressKey = (( + this: void, + selector: Selector, + key: KeyboardPressKey, + options?: Options, +) => Promise) & + ((this: void, key: KeyboardPressKey, options?: Options) => Promise); /** * Presses the specified keyboard keys. */ -export const pressKey = async (key: KeyboardPressKey, options: Options = {}): Promise => { - log(`Press keyboard key: "${key}"`, options, LogEventType.InternalAction); +export const pressKey: PressKey = async ( + keyOrSelector: KeyboardPressKey | Selector, + keyOrOptions?: KeyboardPressKey | Options, + maybeOptions?: Options, +): Promise => { + let key: KeyboardPressKey; + let selector: Selector | undefined; + let options: Options; + + if (typeof keyOrSelector === 'string') { + key = keyOrSelector; + + if (typeof keyOrOptions === 'string') { + throw new E2edError('keyOrOptions is string', { + keyOrOptions, + keyOrSelector, + maybeOptions, + }); + } + + options = keyOrOptions ?? {}; + } else { + selector = keyOrSelector; + + if (typeof keyOrOptions !== 'string') { + throw new E2edError('keyOrOptions is not string', { + keyOrOptions, + keyOrSelector, + maybeOptions, + }); + } + + key = keyOrOptions; + + options = maybeOptions ?? {}; + } + + const withDescription = + selector !== undefined + ? ` on element with description ${getDescriptionFromSelector(selector)}` + : ''; + + log(`Press keyboard key${withDescription}: "${key}"`, options, LogEventType.InternalAction); const page = getPlaywrightPage(); - await page.keyboard.press(key, options); + if (selector !== undefined) { + await selector.getPlaywrightLocator().press(key, options); + } else { + await page.keyboard.press(key, options); + } }; diff --git a/tsconfig.json b/tsconfig.json index 9a484543..35d28100 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -14,6 +14,7 @@ "noImplicitReturns": true, "noPropertyAccessFromIndexSignature": true, "noUncheckedIndexedAccess": true, + "noUncheckedSideEffectImports": true, "noUnusedLocals": true, "outDir": "build", "paths": {