diff --git a/docs/src/guides/webviews.md b/docs/src/guides/webviews.md index 1e0f1ca..116b87f 100644 --- a/docs/src/guides/webviews.md +++ b/docs/src/guides/webviews.md @@ -94,7 +94,25 @@ const count = await page.getByRole('listitem').count(); const value = await page.locator('#email').inputValue(); ``` -`fill` and `type` put the typed text in the step title, which reports show. Pass `{ mask: true }` to keep a password or other secret out of it. +`fill`, `type` and `pressSequentially` put the typed text in the step title, which reports show. Pass `{ mask: true }` to keep a password or other secret out of it. + +### Real touch and typing + +`click()` dispatches a synthetic click in the page. `tap()` is a **real touch**: it scrolls the element into view and taps its on-screen center through the device, so the page receives trusted touch, pointer and click events, exactly as from a finger: + +```typescript +await page.getByRole('button', { name: 'Continue' }).tap(); +``` + +`fill()` works like Playwright's: it sets the value in the page, with no tap and no keyboard. For **real typing**, use `pressSequentially()`. It taps the field, waits for keyboard focus and sends the keys one by one through the device keyboard, so the page sees genuine key and input events. This matters for frameworks and input components that ignore synthetic `input` events. Like Playwright, it appends to the current text, so call `clear()` first to replace it: + +```typescript +const email = page.getByLabel('Email'); +await email.clear(); +await email.pressSequentially('user@example.com'); +``` + +Real touch and typing need the web view to appear in the native view hierarchy, which gives its on-screen position. `tap()` and `pressSequentially()` throw on a page that has no device behind it. ## Frames @@ -200,7 +218,7 @@ The engine is re-injected automatically after navigations (a fresh document drop ## Supported API and limitations -The web-first surface for driving content is supported: navigation, the `getBy*` locators, actions (`click`, `fill`, `type`, `press`, `hover`, `focus`, `scrollIntoViewIfNeeded`), value/state queries, and the web-first `expect` matchers (`toBeVisible`, `toHaveText`, `toHaveValue`, `toHaveCount`, `toHaveAttribute`, `toHaveClass`, `toHaveCSS`, `toHaveId`, `toHaveJSProperty`, `toBeChecked`, `toBeEnabled`, `toBeEditable`, `toHaveURL`, `toHaveTitle`, …). +The web-first surface for driving content is supported: navigation, the `getBy*` locators, actions (`click`, `tap`, `fill`, `clear`, `pressSequentially`, `type`, `press`, `hover`, `focus`, `scrollIntoViewIfNeeded`), value/state queries, and the web-first `expect` matchers (`toBeVisible`, `toHaveText`, `toHaveValue`, `toHaveCount`, `toHaveAttribute`, `toHaveClass`, `toHaveCSS`, `toHaveId`, `toHaveJSProperty`, `toBeChecked`, `toBeEnabled`, `toBeEditable`, `toHaveURL`, `toHaveTitle`, …). Some Playwright capabilities have no equivalent inside an embedded web view and will throw if called: diff --git a/e2e/playwright.config.ts b/e2e/playwright.config.ts index 720b0aa..8d1dbff 100644 --- a/e2e/playwright.config.ts +++ b/e2e/playwright.config.ts @@ -11,7 +11,8 @@ export default defineConfig({ projects: [ { name: 'chromium', - use: { ...devices['Desktop Chrome'] }, + // hasTouch: locator.tap() needs touch, as on a device. + use: { ...devices['Desktop Chrome'], hasTouch: true }, }, ], }); diff --git a/e2e/src/conformance/specs/actions.spec.ts b/e2e/src/conformance/specs/actions.spec.ts index de03807..cf84b9c 100644 --- a/e2e/src/conformance/specs/actions.spec.ts +++ b/e2e/src/conformance/specs/actions.spec.ts @@ -6,6 +6,8 @@ export const actionsSpec = async (page: Page, expect: Expect): Promise => + +
idle
@@ -22,6 +24,18 @@ export const actionsSpec = async (page: Page, expect: Expect): Promise => await page.locator('#fill').fill('hello@example.com'); await expect(page.locator('#fill')).toHaveValue('hello@example.com'); + // tap: a real touch, so the page receives a trusted click + await page.locator('#tap').tap(); + await expect(page.locator('#tap')).toHaveText('tapped:true'); + + // clear, then pressSequentially types through the keyboard (appends) + await page.locator('#keys').clear(); + await expect(page.locator('#keys')).toHaveValue(''); + await page.locator('#keys').pressSequentially('hello'); + await expect(page.locator('#keys')).toHaveValue('hello'); + await page.locator('#keys').pressSequentially('42'); + await expect(page.locator('#keys')).toHaveValue('hello42'); + // type (appends) await page.locator('#type').type('abc'); await expect(page.locator('#type')).toHaveValue('abc'); diff --git a/packages/mobilewright-core/src/index.ts b/packages/mobilewright-core/src/index.ts index 381be1d..c0d39ef 100644 --- a/packages/mobilewright-core/src/index.ts +++ b/packages/mobilewright-core/src/index.ts @@ -6,7 +6,7 @@ export { Dialog, type DialogType, type DialogHandler } from './dialog.js'; export { Device, type DeviceOptions } from './device.js'; export { App } from './app.js'; export { MobileWebViewPage, MobileWebViewPage as Page } from './page.js'; -export { MobileWebViewLocator, MobileWebViewLocator as WebLocator, MobileWebViewFrameLocator } from './web-locator.js'; +export { MobileWebViewLocator, MobileWebViewLocator as WebLocator, MobileWebViewFrameLocator, type WebViewNativeInput } from './web-locator.js'; export { expect, ExpectError, setSoftFailureHandler, setDefaultStepFn, type ExpectOptions, type ExpectTextOptions, type SoftFailureHandler } from './expect.js'; export { queryAll, ROLE_TYPE_MAP, bareTypeName, type LocatorStrategy, type Role } from './query-engine.js'; export { sleep } from './sleep.js'; diff --git a/packages/mobilewright-core/src/page.ts b/packages/mobilewright-core/src/page.ts index 0130ed3..d45849b 100644 --- a/packages/mobilewright-core/src/page.ts +++ b/packages/mobilewright-core/src/page.ts @@ -3,7 +3,7 @@ import type { WebViewSession } from '@mobilewright/protocol'; import type { StepFn } from './locator.js'; import { sleep } from './sleep.js'; import { runStep } from './stackTrace.js'; -import { MobileWebViewLocator } from './web-locator.js'; +import { MobileWebViewLocator, type WebViewNativeInput } from './web-locator.js'; import { type ExpectedTextValue } from './web-expect-matcher.js'; import { bootstrapScript, @@ -128,6 +128,8 @@ export class MobileWebViewPage { // it they refuse the page with "can be only used with Page object". _apiName = 'Page'; _stepFn: StepFn | null = null; + // Device input for real taps and typing; set by screen.getByWebView().page(). + _nativeInput: WebViewNativeInput | null = null; private _url = 'about:blank'; private readonly _frame: MobileWebViewMainFrame; @@ -163,6 +165,7 @@ export class MobileWebViewPage { private locatorFor(selector: string): MobileWebViewLocator { const loc = new MobileWebViewLocator(this.session, selector); loc._stepFn = this._stepFn; + loc._nativeInput = this._nativeInput; return loc; } diff --git a/packages/mobilewright-core/src/web-locator-native-input.test.ts b/packages/mobilewright-core/src/web-locator-native-input.test.ts new file mode 100644 index 0000000..365f671 --- /dev/null +++ b/packages/mobilewright-core/src/web-locator-native-input.test.ts @@ -0,0 +1,227 @@ +import { test, expect as playwrightExpect } from '@playwright/test'; +import type { MobilewrightDriver, ViewNode, WebViewSession } from '@mobilewright/protocol'; +import { Page } from './page.js'; +import { WebLocator, SCREEN_POINT_BODY } from './web-locator.js'; +import { WebViewLocator } from './webview-locator.js'; +import { fakeWebViewSession } from './fake-webview-session.js'; + +interface FakeField { + page: Page; + events: string[]; + evaluateCalls: string[]; +} + +// A page with device input over a fake text field that takes keyboard focus +// after `focusAfterTaps` native taps. +interface FakeFieldOptions { + focusAfterTaps?: number; + viewportWidth?: number; +} + +function fakeField(opts: FakeFieldOptions = {}): FakeField { + const events: string[] = []; + let taps = 0; + const { session, evaluateCalls } = fakeWebViewSession(); + session.evaluate = async (expr: string): Promise => { + evaluateCalls.push(expr); + if (expr.includes('getBoundingClientRect')) { + return { x: 10, y: 20, viewportWidth: opts.viewportWidth ?? 400 } as T; + } + if (expr.includes('ownerDocument.activeElement')) { + return (taps >= (opts.focusAfterTaps ?? 1)) as T; + } + return true as T; + }; + const page = new Page(session); + page._nativeInput = { + bounds: async () => ({ x: 0, y: 100, width: 800, height: 1600 }), + tap: async (x, y) => { taps++; events.push(`tap ${x},${y}`); }, + typeText: async (text) => { events.push(`type ${text}`); }, + }; + return { page, events, evaluateCalls }; +} + +const taps = (events: string[]): number => events.filter((e) => e.startsWith('tap ')).length; +const typedKeys = (events: string[]): string[] => events.filter((e) => e.startsWith('type ')).map((e) => e.slice('type '.length)); + +// ─── tap() ──────────────────────────────────────────────────── + +test.describe('MobileWebViewLocator.tap()', () => { + test('taps natively at the element center, mapped onto the webview bounds', async () => { + const { page, events } = fakeField(); + await page.locator('button').tap(); + // scale = 800 native / 400 CSS px wide = 2 → (10 * 2, 100 + 20 * 2) + playwrightExpect(events).toEqual(['tap 20,140']); + }); + + test('fails clearly instead of tapping a bogus point when the webview has no width', async () => { + const { page, events } = fakeField({ viewportWidth: 0 }); + await playwrightExpect(page.locator('button').tap()).rejects.toThrow(/no valid on-screen size/); + playwrightExpect(events).toEqual([]); + }); + + test('waits until the element is visible, enabled and stable', async () => { + const { page, evaluateCalls } = fakeField(); + await page.locator('button').tap(); + playwrightExpect(evaluateCalls[0]).toContain('checkElementStates(el, ["visible","enabled","stable"])'); + }); + + test('without device input it fails clearly instead of faking a click', async () => { + const { session } = fakeWebViewSession({ evaluateAlways: true }); + await playwrightExpect(new WebLocator(session, 'button').tap()).rejects.toThrow( + /locator\.tap\(\): needs the page from screen\.getByWebView\(\)\.page\(\)/, + ); + }); + + test('device input carries over into iframe locators', async () => { + const { page, events } = fakeField(); + await page.frameLocator('#app').getByRole('button').tap(); + playwrightExpect(taps(events)).toBe(1); + }); + + test('device input carries over to chained and derived locators', async () => { + const { page, events } = fakeField(); + await page.locator('form').getByRole('button').first().tap(); + playwrightExpect(taps(events)).toBe(1); + }); +}); + +// ─── The in-page screen point ───────────────────────────────── + +interface Rect { left: number; top: number; width: number; height: number } +interface FakeWin { innerWidth?: number; frameElement?: unknown; parent?: FakeWin } + +// Run the screen-point script for `el` with `top` as the top window. +function screenPoint(el: unknown, top: FakeWin): { x: number; y: number; viewportWidth: number } { + return new Function('window', 'el', SCREEN_POINT_BODY)(top, el); +} + +function element(rect: Rect, win: FakeWin): { scrolled: boolean } { + const el = { + scrolled: false, + scrollIntoView: () => { el.scrolled = true; }, + getBoundingClientRect: () => rect, + ownerDocument: { defaultView: win }, + }; + return el; +} + +// An