Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions docs/src/api/params.md
Original file line number Diff line number Diff line change
Expand Up @@ -1765,6 +1765,8 @@ await page.GetByAltText("Playwright logo").ClickAsync();

Allows locating input elements by the text of the associated `<label>` or `aria-labelledby` element, or by the `aria-label` attribute.

Associated `<label>` elements are also supported for form-associated custom elements.

**Usage**

For example, this method will find inputs by label "Username" and "Password" in the following DOM:
Expand Down
35 changes: 35 additions & 0 deletions packages/injected/src/domUtils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,38 @@ export function enclosingShadowRootOrDocument(element: Element): Document | Shad
return node as Document | ShadowRoot;
}

export function getAssociatedLabels(element: Element): HTMLLabelElement[] {
// https://html.spec.whatwg.org/multipage/forms.html#category-label
const isNonHiddenInput = element.nodeName === 'INPUT' && (element as HTMLInputElement).type !== 'hidden';
if (['BUTTON', 'METER', 'OUTPUT', 'PROGRESS', 'SELECT', 'TEXTAREA'].includes(element.nodeName) || isNonHiddenInput)
return [...(element as HTMLInputElement).labels || []];
if (!element.localName.includes('-'))
return [];

// Custom elements expose labels only through ElementInternals. Read the association from the labels instead.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Very very very unfortunate!

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

const root = element.getRootNode() as Document | DocumentFragment | Element;
let labelsByControl = cacheLabelsByControl?.get(root);
if (!labelsByControl) {
labelsByControl = new Map();
const allLabels = [...root.querySelectorAll('label')];
if (root instanceof HTMLLabelElement)
allLabels.unshift(root);
for (const label of allLabels) {
const control = label.control;
if (!control)
continue;
let labels = labelsByControl.get(control);
if (!labels) {
labels = [];
labelsByControl.set(control, labels);
}
labels.push(label);
}
cacheLabelsByControl?.set(root, labelsByControl);
}
return labelsByControl.get(element) || [];
}

function enclosingShadowHost(element: Element): Element | undefined {
while (element.parentElement)
element = element.parentElement;
Expand Down Expand Up @@ -199,6 +231,7 @@ let cacheStyle: Map<Element, CSSStyleDeclaration | undefined> | undefined;
let cacheStyleBefore: Map<Element, CSSStyleDeclaration | undefined> | undefined;
let cacheStyleAfter: Map<Element, CSSStyleDeclaration | undefined> | undefined;
let cacheStyleVisibility: Map<Element, boolean> | undefined;
let cacheLabelsByControl: Map<Node, Map<Element, HTMLLabelElement[]>> | undefined;
let cachesCounter = 0;

export function beginDOMCaches() {
Expand All @@ -207,6 +240,7 @@ export function beginDOMCaches() {
cacheStyleBefore ??= new Map();
cacheStyleAfter ??= new Map();
cacheStyleVisibility ??= new Map();
cacheLabelsByControl ??= new Map();
}

export function endDOMCaches() {
Expand All @@ -215,5 +249,6 @@ export function endDOMCaches() {
cacheStyleBefore = undefined;
cacheStyleAfter = undefined;
cacheStyleVisibility = undefined;
cacheLabelsByControl = undefined;
}
}
11 changes: 8 additions & 3 deletions packages/injected/src/injectedScript.ts
Original file line number Diff line number Diff line change
Expand Up @@ -517,9 +517,14 @@ export class InjectedScript {
queryAll: (root: SelectorRoot, selector: string): Element[] => {
const { matcher } = createTextMatcher(selector, true);
const allElements = this._evaluator._queryCSS({ scope: root as Document | Element, pierceShadow: true }, '*');
return allElements.filter(element => {
return getElementLabels(this._evaluator._cacheText, element).some(label => matcher(label));
});
beginDOMCaches();
try {
return allElements.filter(element => {
return getElementLabels(this._evaluator._cacheText, element).some(label => matcher(label));
});
} finally {
endDOMCaches();
}
}
};
}
Expand Down
10 changes: 9 additions & 1 deletion packages/injected/src/roleUtils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@

import * as css from '@isomorphic/cssTokenizer';

import { beginDOMCaches, closestCrossShadow, elementSafeTagName, enclosingShadowRootOrDocument, endDOMCaches, getElementComputedStyle, isElementStyleVisibilityVisible, isListBoxSelect, isVisibleTextNode, parentElementOrShadowHost } from './domUtils';
import { beginDOMCaches, closestCrossShadow, elementSafeTagName, enclosingShadowRootOrDocument, endDOMCaches, getAssociatedLabels, getElementComputedStyle, isElementStyleVisibilityVisible, isListBoxSelect, isVisibleTextNode, parentElementOrShadowHost } from './domUtils';

import type { AriaRole } from '@isomorphic/ariaSnapshot';

Expand Down Expand Up @@ -808,6 +808,14 @@ function getTextAlternativeInternal(element: Element, options: AccessibleNameOpt

// step 2e.
if (!['presentation', 'none'].includes(role)) {
if (!labelledBy && tagName.includes('-')) {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should we check that we are not inside an svg context?

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't know!

const labels = getAssociatedLabels(element);
if (labels.length) {
options.visitedElements.add(element);
return getAccessibleNameFromAssociatedLabels(labels, options);
}
}

// https://w3c.github.io/html-aam/#input-type-button-input-type-submit-and-input-type-reset-accessible-name-computation
//
// SPEC DIFFERENCE.
Expand Down
10 changes: 2 additions & 8 deletions packages/injected/src/selectorUtils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@

import { normalizeWhiteSpace } from '@isomorphic/stringUtils';

import { getAssociatedLabels } from './domUtils';
import { getAriaLabelledByElements } from './roleUtils';

import type { AttributeSelectorPart } from '@isomorphic/selectorParser';
Expand Down Expand Up @@ -125,12 +126,5 @@ export function getElementLabels(textCache: Map<Element | ShadowRoot, ElementTex
if (ariaLabel !== null && !!ariaLabel.trim())
return [{ full: ariaLabel, normalized: normalizeWhiteSpace(ariaLabel), immediate: [ariaLabel] }];

// https://html.spec.whatwg.org/multipage/forms.html#category-label
const isNonHiddenInput = element.nodeName === 'INPUT' && (element as HTMLInputElement).type !== 'hidden';
if (['BUTTON', 'METER', 'OUTPUT', 'PROGRESS', 'SELECT', 'TEXTAREA'].includes(element.nodeName) || isNonHiddenInput) {
const labels = (element as HTMLInputElement).labels;
if (labels)
return [...labels].map(label => elementText(textCache, label));
}
return [];
return getAssociatedLabels(element).map(label => elementText(textCache, label));
}
8 changes: 8 additions & 0 deletions packages/playwright-client/types/types.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3100,6 +3100,8 @@ export interface Page {
* Allows locating input elements by the text of the associated `<label>` or `aria-labelledby` element, or by the
* `aria-label` attribute.
*
* Associated `<label>` elements are also supported for form-associated custom elements.
*
* **Usage**
*
* For example, this method will find inputs by label "Username" and "Password" in the following DOM:
Expand Down Expand Up @@ -7483,6 +7485,8 @@ export interface Frame {
* Allows locating input elements by the text of the associated `<label>` or `aria-labelledby` element, or by the
* `aria-label` attribute.
*
* Associated `<label>` elements are also supported for form-associated custom elements.
*
* **Usage**
*
* For example, this method will find inputs by label "Username" and "Password" in the following DOM:
Expand Down Expand Up @@ -15753,6 +15757,8 @@ export interface Locator {
* Allows locating input elements by the text of the associated `<label>` or `aria-labelledby` element, or by the
* `aria-label` attribute.
*
* Associated `<label>` elements are also supported for form-associated custom elements.
*
* **Usage**
*
* For example, this method will find inputs by label "Username" and "Password" in the following DOM:
Expand Down Expand Up @@ -21821,6 +21827,8 @@ export interface FrameLocator {
* Allows locating input elements by the text of the associated `<label>` or `aria-labelledby` element, or by the
* `aria-label` attribute.
*
* Associated `<label>` elements are also supported for form-associated custom elements.
*
* **Usage**
*
* For example, this method will find inputs by label "Username" and "Password" in the following DOM:
Expand Down
8 changes: 8 additions & 0 deletions packages/playwright-core/types/types.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3100,6 +3100,8 @@ export interface Page {
* Allows locating input elements by the text of the associated `<label>` or `aria-labelledby` element, or by the
* `aria-label` attribute.
*
* Associated `<label>` elements are also supported for form-associated custom elements.
*
* **Usage**
*
* For example, this method will find inputs by label "Username" and "Password" in the following DOM:
Expand Down Expand Up @@ -7483,6 +7485,8 @@ export interface Frame {
* Allows locating input elements by the text of the associated `<label>` or `aria-labelledby` element, or by the
* `aria-label` attribute.
*
* Associated `<label>` elements are also supported for form-associated custom elements.
*
* **Usage**
*
* For example, this method will find inputs by label "Username" and "Password" in the following DOM:
Expand Down Expand Up @@ -15753,6 +15757,8 @@ export interface Locator {
* Allows locating input elements by the text of the associated `<label>` or `aria-labelledby` element, or by the
* `aria-label` attribute.
*
* Associated `<label>` elements are also supported for form-associated custom elements.
*
* **Usage**
*
* For example, this method will find inputs by label "Username" and "Password" in the following DOM:
Expand Down Expand Up @@ -21821,6 +21827,8 @@ export interface FrameLocator {
* Allows locating input elements by the text of the associated `<label>` or `aria-labelledby` element, or by the
* `aria-label` attribute.
*
* Associated `<label>` elements are also supported for form-associated custom elements.
*
* **Usage**
*
* For example, this method will find inputs by label "Username" and "Password" in the following DOM:
Expand Down
21 changes: 20 additions & 1 deletion tests/page/selectors-get-by.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -71,12 +71,31 @@ it('SE-076 getByText should work', async ({ page }) => {
expect(await page.getByText('Hello', { exact: true }).evaluate(e => e.outerHTML)).toContain('>Hello</div>');
});

it('SE-077 getByLabel should work', async ({ page }) => {
it('SE-077 getByLabel should work', { annotation: { type: 'issue', description: 'https://github.com/microsoft/playwright/issues/43898' } }, async ({ page }) => {
await page.setContent(`<div><label for=target>Name</label><input id=target type=text></div>`);
expect(await page.getByText('Name').evaluate(e => e.nodeName)).toBe('LABEL');
expect(await page.getByLabel('Name').evaluate(e => e.nodeName)).toBe('INPUT');
expect(await page.mainFrame().getByLabel('Name').evaluate(e => e.nodeName)).toBe('INPUT');
expect(await page.locator('div').getByLabel('Name').evaluate(e => e.nodeName)).toBe('INPUT');

await page.setContent(`
<label for="city">City</label><my-field id="city" role="combobox">Pick one</my-field>
<label>Street <my-field id="street" role="combobox">Pick one</my-field></label>
`);
await page.evaluate(() => {
customElements.define('my-field', class extends HTMLElement {
static formAssociated = true;
constructor() {
super();
this.attachInternals();
}
});
});
expect(await page.evaluate(() => [...document.querySelectorAll('label')].map(label => label.control?.id))).toEqual(['city', 'street']);
expect.soft(await page.getByLabel('City').evaluateAll(elements => elements.map(e => e.id))).toEqual(['city']);
expect.soft(await page.getByLabel('Street').evaluateAll(elements => elements.map(e => e.id))).toEqual(['street']);
expect.soft(await page.getByRole('combobox', { name: 'City', exact: true }).evaluateAll(elements => elements.map(e => e.id))).toEqual(['city']);
expect.soft(await page.getByRole('combobox', { name: 'Street', exact: true }).evaluateAll(elements => elements.map(e => e.id))).toEqual(['street']);
});

it('SE-078 getByLabel should work with nested elements', async ({ page }) => {
Expand Down
Loading