diff --git a/.changeset/check-through-label.md b/.changeset/check-through-label.md new file mode 100644 index 0000000000..13b098e244 --- /dev/null +++ b/.changeset/check-through-label.md @@ -0,0 +1,5 @@ +--- +"@e2e-dev/web": patch +--- + +`check`, `uncheck`, and `tap` click a checkbox or radio hidden under its own label (as in Element Plus) through that label. `uncheck` still refuses a native radio without clicking it. Anything else on top of the point the click lands on still fails `ACTION_FAILED`. diff --git a/docs/reference/screen.mdx b/docs/reference/screen.mdx index eace89d5b5..b9a2046e38 100644 --- a/docs/reference/screen.mdx +++ b/docs/reference/screen.mdx @@ -760,6 +760,10 @@ check(options?: ActionOptions): Promise; await screen.getByRole('checkbox', 'Remember me').check(); ``` +On the web engine, a checkbox or radio hidden under its own label (as in +Element Plus) is clicked through that label. Anything else on top of the +point the click lands on still fails `ACTION_FAILED`. + #### `uncheck` ```ts diff --git a/packages/web/src/actions.ts b/packages/web/src/actions.ts index 6a2f22410f..1985317ef4 100644 --- a/packages/web/src/actions.ts +++ b/packages/web/src/actions.ts @@ -62,7 +62,7 @@ async function setChecked(target: ActionTarget, checked: boolean, operation: Con retryable: false, }); } - await element.click({ timeout: remaining() }); + await clickControl({ kind: 'element', element }, verb, { timeout: remaining(), signal: operation.signal }); const hint = radio === 'aria' ? '; a radio usually clears only when another radio in its group is selected' : ''; const unchanged = (detail = ''): EngineError => new EngineError('NOT_ACTIONABLE', `${verb} clicked the control but its checked state did not change${detail}${hint}`, { @@ -91,6 +91,127 @@ async function setChecked(target: ActionTarget, checked: boolean, operation: Con } } +/** + * What the page throws while a checkbox or radio and every one of its labels + * are unrendered, so a click could reach none of them yet. + */ +const UNRENDERED = 'the control and its labels are not visible'; + +/** + * Runs in the page. A component library (Element Plus) hides a native + * checkbox or radio under its label's styled spans with `z-index: -1`, or + * gives it no box at all, so Playwright refuses the input itself (` + * intercepts pointer events`, `element is not visible`) though a user's click + * there reaches it through the label. Returns that label, or null to click the + * control itself. The choice reads the control and its labels only, past + * anything else on top (a loading mask, a modal): Playwright's checks on the + * label wait that out, or fail on it. Throws `UNRENDERED` while none of them + * is rendered (a dialog not open yet), since nothing tells the two apart then. + */ +function pickStandIn(node: Element, unrendered: string): HTMLLabelElement | null { + if (!(node instanceof HTMLInputElement) || (node.type !== 'checkbox' && node.type !== 'radio') || node.matches(':disabled')) { + return null; + } + const labels = [...(node.labels ?? [])]; + const root = node.getRootNode(); + if (labels.length === 0 || (!(root instanceof Document) && !(root instanceof ShadowRoot))) return null; + const INTERACTIVE = 'a,button,input,select,textarea,summary,[contenteditable],[role="button"],[role="link"]'; + const hasBox = ({ width, height }: DOMRect): boolean => width > 0 && height > 0; + const centre = ({ left, top, width, height }: DOMRect): [number, number] => [left + width / 2, top + height / 2]; + const topmost = (x: number, y: number): Element | undefined => + root.elementsFromPoint(x, y).find((hit) => hit === node || labels.some((label) => label.contains(hit))); + const pressesInteractive = (label: HTMLLabelElement, hit: Element | undefined): boolean => + label.contains(hit?.closest(INTERACTIVE) ?? null); + node.scrollIntoView({ block: 'nearest', inline: 'nearest' }); + const box = node.getBoundingClientRect(); + if (!hasBox(box)) { + const shown = labels.filter((label) => hasBox(label.getBoundingClientRect()) && label.checkVisibility({ visibilityProperty: true })); + if (shown.length === 0) throw new Error(unrendered); + return ( + shown.find((label) => { + label.scrollIntoView({ block: 'nearest', inline: 'nearest' }); + return !pressesInteractive(label, topmost(...centre(label.getBoundingClientRect()))); + }) ?? null + ); + } + const [x, y] = centre(box); + const hit = topmost(x, y); + if (hit === undefined) throw new Error(unrendered); + const label = labels.find((own) => own.contains(hit)); + if (label === undefined || pressesInteractive(label, hit)) return null; + const outer = label.getBoundingClientRect(); + return x >= outer.left && x <= outer.right && y >= outer.top && y <= outer.bottom ? label : null; +} + +/** + * Runs in the page: where a click on the label lands, the centre of its + * control relative to the label, or none for a control with no box, which + * takes the label's centre. + */ +function controlPoint(label: HTMLLabelElement): { x: number; y: number } | null { + const box = label.control?.getBoundingClientRect(); + if (box === undefined || box.width === 0 || box.height === 0) return null; + const outer = label.getBoundingClientRect(); + return { x: box.left + box.width / 2 - outer.left, y: box.top + box.height / 2 - outer.top }; +} + +/** + * Clicks a control with Playwright's actionability checks, through its own + * label when `pickStandIn` names one. The checks then run on the label, so + * anything else on top, such as a modal, still fails NOT_ACTIONABLE. The + * choice is read again until the control or a label renders, within the + * deadline. + */ +async function clickControl( + target: ActionTarget, + verb: 'tap' | 'check' | 'uncheck', + options: { timeout: number; signal: AbortSignal; modifiers?: KeyModifier[] }, +): Promise { + const { signal, ...click } = options; + const deadline = new Deadline(options.timeout); + const remaining = (): number => Math.max(1, deadline.remaining()); + let label: ElementHandle | undefined; + let firstRead = true; + await pollCondition({ + deadline, + signal, + negated: false, + evaluate: async () => { + const first = firstRead; + firstRead = false; + try { + const handle = + target.kind === 'locator' + ? await target.locator.evaluateHandle(pickStandIn, UNRENDERED, { timeout: remaining() }) + : await target.element.evaluateHandle(pickStandIn, UNRENDERED); + label = handle.asElement() ?? undefined; + if (label === undefined) void handle.dispose().catch(() => undefined); + return true; + } catch (cause) { + if (message(cause).includes(UNRENDERED)) return undefined; + // A read after one that found nothing rendered times out only at the deadline, which ends the poll. + if (!first && isPwTimeout(cause)) return undefined; + throw cause; + } + }, + onTimeout: () => + new EngineError('NOT_ACTIONABLE', `${verb} did not become actionable in time: ${UNRENDERED}`, { retryable: false }), + }); + // The operation abandons this call when cancelled; a read still in flight then must not lead to a click. + if (label === undefined) { + signal.throwIfAborted(); + await asActionable(target).click({ ...click, timeout: remaining() }); + return; + } + try { + const position = await label.evaluate(controlPoint); + signal.throwIfAborted(); + await label.click({ ...click, timeout: remaining(), ...(position === null ? {} : { position }) }); + } finally { + void label.dispose().catch(() => undefined); + } +} + /** * Which kind of radio a checkable element is, if any. A native radio can be * selected but never cleared by a click. An ARIA radio is clicked like any @@ -165,7 +286,7 @@ export async function dispatchLocatorAction( const locator = asActionable(target); switch (action.kind) { case 'tap': - await locator.click({ timeout, ...heldKeys(action) }); + await clickControl(target, 'tap', { timeout, signal: operation.signal, ...heldKeys(action) }); return; case 'doubleTap': await locator.dblclick({ timeout, ...heldKeys(action) }); diff --git a/packages/web/tests/integration/check-actions.test.ts b/packages/web/tests/integration/check-actions.test.ts index 5cc98146cc..28b8bf6d7a 100644 --- a/packages/web/tests/integration/check-actions.test.ts +++ b/packages/web/tests/integration/check-actions.test.ts @@ -13,6 +13,7 @@ import { chromium, type Browser, type Page } from 'playwright-core'; import { afterAll, beforeAll, beforeEach, describe, expect, it } from 'vitest'; import type { LocatorAction } from 'e2e/engine'; import { classifyActionError, dispatchLocatorAction } from '../../src/actions.ts'; +import { ElementList } from '../../src/element-list.ts'; import type { ActionTarget } from '../../src/support.ts'; let browser: Browser; @@ -46,19 +47,24 @@ beforeEach(async () => { const KINDS = ['locator', 'element'] as const; -/** The control as the engine would hold it: a locator, or an element handle pinned by an observation. */ +/** + * The control as the engine would hold it: a locator, or the element handle + * an observed ref resolves to, made on first use from the walk's in-page array. + */ async function targetOf(kind: (typeof KINDS)[number], selector: string): Promise { const locator = page.locator(selector); if (kind === 'locator') return { kind, locator }; - const element = await locator.elementHandle(); - if (element === null) throw new Error(`no element for ${selector}`); - return { kind, element }; + const walk = new ElementList(await locator.evaluateHandle((node) => [node])); + return { kind, element: await walk.at(0) }; } +/** A refusal waits out the whole deadline, so the cases that expect one take a short one. */ +const REFUSAL_TIMEOUT_MS = 500; + /** Performs one action and returns the contract error it failed with, classified as the engine reports it. */ -async function perform(target: ActionTarget, action: LocatorAction): Promise { +async function perform(target: ActionTarget, action: LocatorAction, timeoutMs = 2000): Promise { try { - await dispatchLocatorAction(target, action, { timeoutMs: 2000, signal: new AbortController().signal }, () => { + await dispatchLocatorAction(target, action, { timeoutMs, signal: new AbortController().signal }, () => { throw new Error('no second target'); }); return undefined; @@ -187,3 +193,256 @@ describe('a control gone before the click', () => { expect(await perform(target, { kind: 'check' })).toMatchObject({ code: 'NODE_STALE', retryable: true }); }); }); + +describe('a locator that matches another control after the state read', () => { + it('clicks the control it read, not the one the locator matches now', async () => { + await page.setContent(` + + `); + const locator = page.locator('[data-pick]'); + const moved = new Proxy(locator, { + get(real, property) { + if (property === 'elementHandle') { + return async (options?: { timeout?: number }) => { + const element = await real.elementHandle(options); + await page.evaluate(() => { + document.getElementById('first')!.removeAttribute('data-pick'); + document.getElementById('second')!.setAttribute('data-pick', ''); + }); + return element; + }; + } + const value: unknown = Reflect.get(real, property); + return typeof value === 'function' ? value.bind(real) : value; + }, + }); + expect(await perform({ kind: 'locator', locator: moved }, { kind: 'check' })).toBeUndefined(); + expect(await page.isChecked('#first')).toBe(true); + expect(await page.isChecked('#second')).toBe(false); + }); +}); + +const ELEMENT_PLUS_CSS = ` +.el-radio-button{outline:none;display:inline-block;position:relative} +.el-radio-button__original-radio{opacity:0;z-index:-1;outline:none;position:absolute} +.el-radio-button__inner{white-space:nowrap;vertical-align:middle;background:#fff;border:1px solid #dcdfe6;line-height:1;cursor:pointer;display:inline-block;position:relative;padding:8px 15px} +.el-checkbox{cursor:pointer;display:inline-flex;align-items:center;position:relative} +.el-checkbox__input{white-space:nowrap;cursor:pointer;outline:none;display:inline-flex;position:relative} +.el-checkbox__original{opacity:0;z-index:-1;outline:none;width:0;height:0;margin:0;position:absolute} +.el-checkbox__inner{display:inline-block;position:relative;border:1px solid #dcdfe6;width:14px;height:14px;background:#fff;z-index:1} +.el-radio{cursor:pointer;display:inline-flex;align-items:center;position:relative} +.el-radio__input{white-space:nowrap;cursor:pointer;outline:none;display:inline-flex;position:relative} +.el-radio__original{opacity:0;z-index:-1;outline:none;margin:0;position:absolute;top:0;bottom:0;left:0;right:0} +.el-radio__inner{border:1px solid #dcdfe6;border-radius:100%;width:14px;height:14px;background:#fff;position:relative;display:inline-block} +.modal{position:fixed;inset:0;background:rgba(0,0,0,.4);z-index:10} +`; + +const ELEMENT_PLUS_CONTROLS = ` + + + + +`; + +const ELEMENT_PLUS_PAGE = `${ELEMENT_PLUS_CONTROLS}`; + +const ELEMENT_PLUS_CASES = [ + ['radio-button', '#install'], + ['checkbox', '#agree'], + ['radio', '#large'], +] as const; + +describe.each(KINDS)('a control its own label covers, through the %s target', (kind) => { + it.each(ELEMENT_PLUS_CASES)('checks an Element Plus %s', async (_, selector) => { + await page.setContent(ELEMENT_PLUS_PAGE); + expect(await perform(await targetOf(kind, selector), { kind: 'check' })).toBeUndefined(); + expect(await page.isChecked(selector)).toBe(true); + }); + + it.each(ELEMENT_PLUS_CASES)('taps an Element Plus %s', async (_, selector) => { + await page.setContent(ELEMENT_PLUS_PAGE); + expect(await perform(await targetOf(kind, selector), { kind: 'tap' })).toBeUndefined(); + expect(await page.isChecked(selector)).toBe(true); + }); + + it('unchecks an Element Plus checkbox, and refuses an Element Plus radio without clicking it', async () => { + await page.setContent(`${COUNT_CLICKS}${ELEMENT_PLUS_PAGE}`); + await page.evaluate(() => { + for (const id of ['agree', 'large']) (document.getElementById(id) as HTMLInputElement).checked = true; + }); + expect(await perform(await targetOf(kind, '#agree'), { kind: 'uncheck' })).toBeUndefined(); + expect(await page.isChecked('#agree')).toBe(false); + const before = await clicks(); + expect(await perform(await targetOf(kind, '#large'), { kind: 'uncheck' })).toMatchObject({ code: 'NOT_ACTIONABLE' }); + expect(await page.isChecked('#large')).toBe(true); + expect(await clicks()).toBe(before); + }); + + it.each(ELEMENT_PLUS_CASES)('still refuses an Element Plus %s under a modal', async (_, selector) => { + await page.setContent(`${ELEMENT_PLUS_PAGE}`); + for (const action of [{ kind: 'check' }, { kind: 'tap' }] as const) { + expect(await perform(await targetOf(kind, selector), action, REFUSAL_TIMEOUT_MS)).toMatchObject({ code: 'NOT_ACTIONABLE' }); + expect(await page.isChecked(selector)).toBe(false); + } + }); + + it.each(ELEMENT_PLUS_CASES)('waits out a loading mask over an Element Plus %s', async (_, selector) => { + for (const action of [{ kind: 'check' }, { kind: 'tap' }] as const) { + await page.setContent(`${ELEMENT_PLUS_PAGE} + `); + expect(await perform(await targetOf(kind, selector), action)).toBeUndefined(); + expect(await page.isChecked(selector)).toBe(true); + } + }); + + it.each(ELEMENT_PLUS_CASES)('waits for an Element Plus %s in a dialog that opens later', async (_, selector) => { + for (const display of ['display:none', 'visibility:hidden']) { + for (const action of [{ kind: 'check' }, { kind: 'tap' }] as const) { + await page.setContent(`
${ELEMENT_PLUS_CONTROLS}
+ `); + expect(await perform(await targetOf(kind, selector), action)).toBeUndefined(); + expect(await page.isChecked(selector)).toBe(true); + } + } + }); + + it('still refuses a radio whose label covers it from outside the label box', async () => { + await page.setContent(` + `); + for (const action of [{ kind: 'check' }, { kind: 'tap' }] as const) { + expect(await perform(await targetOf(kind, '#r'), action, REFUSAL_TIMEOUT_MS)).toMatchObject({ + code: 'NOT_ACTIONABLE', + message: expect.stringContaining('intercepts pointer events'), + }); + expect(await page.isChecked('#r')).toBe(false); + } + }); + + it('checks a boxless checkbox through its first visible label, past a hidden one', async () => { + await page.setContent(` + + + `); + expect(await perform(await targetOf(kind, '#c'), { kind: 'check' })).toBeUndefined(); + expect(await page.isChecked('#c')).toBe(true); + }); + + it('checks a boxless checkbox past a label hidden by visibility, which keeps its box', async () => { + await page.setContent(` + + + `); + expect(await perform(await targetOf(kind, '#c'), { kind: 'check' })).toBeUndefined(); + expect(await page.isChecked('#c')).toBe(true); + }); + + it('still refuses a radio under a link in its own label, and follows no link', async () => { + await page.setContent(` + `); + for (const action of [{ kind: 'check' }, { kind: 'tap' }] as const) { + expect(await perform(await targetOf(kind, '#install'), action, REFUSAL_TIMEOUT_MS)).toMatchObject({ + code: 'NOT_ACTIONABLE', + message: expect.stringContaining('intercepts pointer events'), + }); + expect(await page.isChecked('#install')).toBe(false); + expect(page.url()).not.toContain('#went'); + } + }); + + it('still refuses a boxless checkbox whose visible label has a link at its centre', async () => { + await page.setContent(` + + `); + for (const action of [{ kind: 'check' }, { kind: 'tap' }] as const) { + expect(await perform(await targetOf(kind, '#c'), action, REFUSAL_TIMEOUT_MS)).toMatchObject({ + code: 'NOT_ACTIONABLE', + message: expect.stringContaining('not visible'), + }); + expect(await page.isChecked('#c')).toBe(false); + expect(page.url()).not.toContain('#went'); + } + }); + + it('still refuses an Element Plus radio-button a disabled fieldset holds', async () => { + await page.setContent(`
${ELEMENT_PLUS_CONTROLS}
`); + for (const action of [{ kind: 'check' }, { kind: 'tap' }] as const) { + expect(await perform(await targetOf(kind, '#install'), action, REFUSAL_TIMEOUT_MS)).toMatchObject({ + code: 'NOT_ACTIONABLE', + message: expect.stringContaining('not enabled'), + }); + expect(await page.isChecked('#install')).toBe(false); + } + }); + + it('still refuses a boxless checkbox whose every label is hidden', async () => { + await page.setContent(` + + `); + for (const action of [{ kind: 'check' }, { kind: 'tap' }] as const) { + expect(await perform(await targetOf(kind, '#c'), action, REFUSAL_TIMEOUT_MS)).toMatchObject({ + code: 'NOT_ACTIONABLE', + message: `${action.kind} did not become actionable in time: the control and its labels are not visible`, + }); + expect(await page.isChecked('#c')).toBe(false); + } + }); + + it('still refuses a disabled Element Plus radio-button', async () => { + await page.setContent(ELEMENT_PLUS_PAGE.replace('id="install"', 'id="install" disabled')); + for (const action of [{ kind: 'check' }, { kind: 'tap' }] as const) { + expect(await perform(await targetOf(kind, '#install'), action, REFUSAL_TIMEOUT_MS)).toMatchObject({ code: 'NOT_ACTIONABLE' }); + expect(await page.isChecked('#install')).toBe(false); + } + }); + + it('checks an Element Plus radio-button inside a shadow root', async () => { + await page.setContent(`
`); + expect(await perform(await targetOf(kind, '#install'), { kind: 'check' })).toBeUndefined(); + expect(await page.isChecked('#install')).toBe(true); + }); +}); + +describe('a tap on a locator that never appears', () => { + it('fails NOT_ACTIONABLE within one deadline, as a plain click does', async () => { + await page.setContent('

Nothing to tap

'); + const started = Date.now(); + const error = await perform({ kind: 'locator', locator: page.locator('#missing') }, { kind: 'tap' }); + expect(Date.now() - started).toBeLessThan(3500); + expect(error).toMatchObject({ code: 'NOT_ACTIONABLE', retryable: false }); + expect(error?.message).toMatch(/^tap did not become actionable in time: .*Timeout 2000ms exceeded/); + expect(error?.message).toContain("waiting for locator('#missing')"); + }); +}); + +describe('a control its own label covers, inside a frame', () => { + it('checks an Element Plus radio-button', async () => { + await page.setContent(`

Outer

`); + const locator = page.frameLocator('iframe').locator('#install'); + expect(await perform({ kind: 'locator', locator }, { kind: 'check' })).toBeUndefined(); + expect(await locator.isChecked()).toBe(true); + }); +}); + +describe('an action cancelled while its stand-in read is in flight', () => { + it.each(KINDS)('clicks nothing through the %s target', async (kind) => { + for (const [selector, action] of [['#install', { kind: 'tap' }], ['#install', { kind: 'check' }], ['#plain', { kind: 'tap' }]] as const) { + await page.setContent(`${ELEMENT_PLUS_PAGE}`); + const target = await targetOf(kind, selector); + // Holds the page's main thread, so the read waits behind it until after the abort. + await page.evaluate(() => setTimeout(() => { const until = Date.now() + 400; while (Date.now() < until); }, 0)); + const controller = new AbortController(); + setTimeout(() => controller.abort(new Error('cancelled')), 100); + await expect( + dispatchLocatorAction(target, action, { timeoutMs: 2000, signal: controller.signal }, () => { + throw new Error('no second target'); + }), + ).rejects.toThrow('cancelled'); + expect(await page.isChecked(selector)).toBe(false); + } + }); +});