Skip to content
Closed
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
5 changes: 5 additions & 0 deletions .changeset/web-name-invisible-characters.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@e2e-dev/web': patch
---

A name or label in the web tree drops zero-width spaces and soft hyphens, as Playwright's `getByRole` does. `<a href="https://example.com/privacy">Datenschutz&shy;erklärung</a>` reads as `link "Datenschutzerklärung"`, so `toHaveAccessibleName('Datenschutzerklärung')` holds for the link `getByRole('link', { name: 'Datenschutzerklärung' })` finds; it used to fail on the hidden character. `getByRole` and an exact `getByLabel` drop them from the name a test passes too, so a name copied from the page, hidden soft hyphen and all, still finds the control. `toHaveAccessibleName` compares the text it is passed as written, so that text should omit them.
10 changes: 10 additions & 0 deletions docs/reference/web.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -1755,6 +1755,16 @@ characters from every name:
- A `RegExp` name matches the browser's name, glyph included, so don't
anchor it: `/Login/`.

A zero-width space never shows, and a soft hyphen (`&shy;`) shows only where
a line breaks at it. A name drops both, as `getByRole` does:
`<a href="https://example.com/privacy">Datenschutz&shy;erklärung</a>` is
`link "Datenschutzerklärung"`, and
`toHaveAccessibleName('Datenschutzerklärung')` holds for it. Labels drop
them too, and `getByRole` and an exact `getByLabel` drop them from a string
name you pass, so a name copied from the page still finds the control.
`toHaveAccessibleName` compares the text you pass as written, so write the name
without them.

## Semantic capture recovery

When the semantic reader times out, agent observations can recover with a
Expand Down
26 changes: 19 additions & 7 deletions packages/web/src/in-page/read-semantics.ts
Original file line number Diff line number Diff line change
Expand Up @@ -500,10 +500,22 @@ export const readSemanticsFunction = <Mode extends SemanticMode>(
* ends, finds it by that.
*/
const ICON_GLYPHS = /\p{Co}/gu;
/** `ICON_GLYPHS` without the global flag, for `test`. */
const HAS_ICON_GLYPH = /\p{Co}/u;

/** A computed name or label as the tree reports it: each icon glyph a space, whitespace collapsed. */
/**
* A zero-width space never shows and a soft hyphen shows only where a line
* breaks at it, and Playwright's `getByRole` drops both, so a name does too:
* `Datenschutz&shy;erklärung` is the link "Datenschutzerklärung".
*/
const INVISIBLE_BREAKS = /[\u200b\u00ad]/g;

/** A title as a name falls back to it: as the page set it, less its invisible breaks. */
const titleName = (title: string): string => title.replace(INVISIBLE_BREAKS, '').trim();

/** A computed name or label as the tree reports it: each icon glyph a space, invisible breaks dropped, whitespace collapsed. */
const withoutGlyphs = (name: string): string => {
const spaced = name.replace(ICON_GLYPHS, ' ');
const spaced = name.replace(ICON_GLYPHS, ' ').replace(INVISIBLE_BREAKS, '');
Comment thread
gagarinyury marked this conversation as resolved.
Resolved
Comment thread
gagarinyury marked this conversation as resolved.
Resolved
return spaced === name ? name : spaced.replace(/\s+/g, ' ').trim();
};

Expand All @@ -516,8 +528,8 @@ export const readSemanticsFunction = <Mode extends SemanticMode>(
const reportedName = (el: Element, name: string | null): string | null => {
if (name === null) return null;
const shown = withoutGlyphs(name);
if (shown !== '' || shown === name) return shown;
const title = (el.getAttribute('title') ?? '').trim();
if (shown !== '' || !HAS_ICON_GLYPH.test(name)) return shown;
const title = titleName(el.getAttribute('title') ?? '');
return title === '' ? null : title;
};

Expand Down Expand Up @@ -1847,7 +1859,7 @@ export const readSemanticsFunction = <Mode extends SemanticMode>(
// A secure field withholds its value, never its labels: a password field is still found by its label.
const labels = labelsOf(el);
const isDocumentRoot = projection.documentRoot && tag === 'html';
if (isDocumentRoot) name = el.ownerDocument.title;
if (isDocumentRoot) name = titleName(el.ownerDocument.title);

// No layout box at all (`display: none`, an empty `display: contents`) is
// no rect, as Playwright's `boundingBox()` answers null; a box with no
Expand Down Expand Up @@ -1969,8 +1981,8 @@ export const readSemanticsFunction = <Mode extends SemanticMode>(
const node = nodes[index]!;
node.frameSelector = frameSelectorOf(el);
if (node.name === null) {
const title = el.getAttribute('title');
if (title !== null && title.trim() !== '') node.name = title.trim();
const title = titleName(el.getAttribute('title') ?? '');
if (title !== '') node.name = title;
}
return;
}
Expand Down
8 changes: 5 additions & 3 deletions packages/web/src/label-selector.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,15 +44,17 @@ export function exactLabelSelector(body: ExactLabelSelectorBody): string {
* The engine behind `e2e-label=<json>`: the labelable controls under the query
* root, across the closed shadow roots recorded under it, whose labels as the
* reader names them (`RawNodeData.labels`) include the body's value once both
* are whitespace-normalized, the comparison the surface makes with
* `matchesText` on an exact string pattern. Reading a node's semantics for
* are whitespace-normalized and rid of zero-width spaces and soft hyphens, the
* comparison the surface makes with `matchesText` on an exact string pattern.
* The body's value is the label as the test wrote it, so the engine drops them
* itself. Reading a node's semantics for
* each candidate is what the standalone query pays too. The reader is embedded
* as source because a selector engine, like the reader, is one self-contained
* page function.
*/
export const EXACT_LABEL_SELECTOR_ENGINE_SOURCE = `() => {${CLOSED_SHADOW_HELPERS_SOURCE}
const read = (${readSemanticsFunction.toString()});
const normalize = (text) => text.replace(/\\s+/gu, ' ').trim();
const normalize = (text) => text.replace(/[\\u200b\\u00ad]/gu, '').replace(/\\s+/gu, ' ').trim();
const queryAll = (root, selector) => {
const body = JSON.parse(selector);
const expected = normalize(body.value);
Expand Down
9 changes: 8 additions & 1 deletion packages/web/src/locators.ts
Original file line number Diff line number Diff line change
Expand Up @@ -102,7 +102,10 @@ const GLYPH_OR_SPACE = '[\\s\\p{Co}]';
* string name.
*/
function glyphTolerantName(name: string, exact: boolean): RegExp {
// Playwright drops zero-width spaces and soft hyphens from the name it computes, so a name
// copied from the page with one in it is matched without it.
const body = name
.replace(/[\u200b\u00ad]/gu, '')
.trim()
.split(/\s+/)
.map((word) => word.replace(/[.*+?^${}()|[\]\\/]/g, '\\$&'))
Expand Down Expand Up @@ -310,7 +313,11 @@ function project(scope: PwScope, expression: LocatorExpression, options: Project
? scope
: requireComposable(project(scope, expression.scope, options));
const { query } = expression;
const exactLabel = query.kind === 'label' && query.value.kind === 'string' && query.value.exact ? query.value : null;
// The tree drops zero-width spaces and soft hyphens from a label, so the label asked for drops them too.
const exactLabel =
query.kind === 'label' && query.value.kind === 'string' && query.value.exact
? { ...query.value, value: query.value.value.replace(/[\u200b\u00ad]/gu, '') }
: null;
const locator = visibleQueryToPw(inner, query, options);
return {
locator,
Expand Down
6 changes: 6 additions & 0 deletions packages/web/tests/crosscheck/expected.txt
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,12 @@ fixture: disabled states | chrome selected | option "Poland" | ours true | their
fixture: generated content | chrome name | link "Sign out" | ours Sign out | theirs | Chrome names a link whose only content is an icon-font glyph by the glyph, which is nothing once dropped; the tree falls back to its title so the model reads the word a person hovering it sees
fixture: generated content | playwright getByRole | link "Sign out" | ours match | theirs no match | Known limit: the browser names a glyph-only link by the glyph, so a role query by the title the tree shows finds nothing; web.locator('[title="..."]') reaches it. Composing a title alternative with or() drops matches inside closed shadow roots
fixture: hidden content | chrome name | button "Save draft" | ours Save draft | theirs Save | Chrome drops inert text from a name, Playwright's getByRole keeps it; the tree names as getByRole matches, so a name read off the tree finds the control
fixture: invisible characters | chrome name | button "" | ours | theirs ​ | Chrome keeps a zero-width space that is all of an aria-label, Playwright's getByRole drops it and reads the name as empty; the tree does as getByRole does and, since no icon glyph emptied the name, does not fall back to the title
fixture: invisible characters | chrome name | button "Go" | ours Go | theirs ​Go​ | Chrome keeps an invisible break (a zero-width space or a soft hyphen) in a name, Playwright's getByRole drops it; the tree names as getByRole matches, so a name read off the tree, which shows the word a person reads, finds the control
fixture: invisible characters | chrome name | link "Datenschutzerklärung" | ours Datenschutzerklärung | theirs Datenschutz­erklärung | Chrome keeps an invisible break (a zero-width space or a soft hyphen) in a name, Playwright's getByRole drops it; the tree names as getByRole matches, so a name read off the tree, which shows the word a person reads, finds the control
fixture: invisible characters | chrome name | link "Signin" | ours Signin | theirs Sign​in | Chrome keeps an invisible break (a zero-width space or a soft hyphen) in a name, Playwright's getByRole drops it; the tree names as getByRole matches, so a name read off the tree, which shows the word a person reads, finds the control
fixture: invisible characters | chrome name | link "Signout" | ours Signout | theirs | Chrome names a link whose only content is an icon-font glyph by the glyph, which is nothing once dropped; the tree falls back to its title so the model reads the word a person hovering it sees
fixture: invisible characters | playwright getByRole | link "Signout" | ours match | theirs no match | Known limit: the browser names a glyph-only link by the glyph, so a role query by the title the tree shows finds nothing; web.locator('[title="..."]') reaches it. Composing a title alternative with or() drops matches inside closed shadow roots
fixture: modal dialog the show order never saw | chrome unknown | button "Next step" | ours button | theirs no AX node | Focus left both open modal dialogs and the show order never saw the one a show-modal command opened, so nothing tells which is on top; the tree lists the page as it would with no modal rather than guess and drop the dialog that takes input
fixture: modal dialog the show order never saw | chrome unknown | button "Page button" | ours button | theirs no AX node | Focus left both open modal dialogs and the show order never saw the one a show-modal command opened, so nothing tells which is on top; the tree lists the page as it would with no modal rather than guess and drop the dialog that takes input
fixture: modal dialog the show order never saw | chrome unknown | dialog "Shown by script" | ours dialog | theirs no AX node | Focus left both open modal dialogs and the show order never saw the one a show-modal command opened, so nothing tells which is on top; the tree lists the page as it would with no modal rather than guess and drop the dialog that takes input
Expand Down
11 changes: 11 additions & 0 deletions packages/web/tests/crosscheck/fixtures.ts
Original file line number Diff line number Diff line change
Expand Up @@ -277,6 +277,17 @@ export const FIXTURE_PAGES: readonly FixturePage[] = [
<a href="/leave" title="Sign out"><i class="glyph"></i></a>
`,
},
{
name: 'invisible characters',
html: `
<style>.glyph::before { content: "\\f090"; }</style>
<a href="/privacy">Datenschutz&shy;erklärung</a>
<a href="/signin">Sign&#8203;in</a>
<button>&#8203;Go&#8203;</button>
<button aria-label="&#8203;" title="Save"></button>
<a href="/out" title="Sign&#8203;out"><i class="glyph"></i></a>
`,
},
{
name: 'hidden content',
html: `
Expand Down
34 changes: 34 additions & 0 deletions packages/web/tests/integration/icon-glyph-names.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,8 +28,14 @@ const PAGE = `
<a href="/leave" title="Sign out"><i class="glyph"></i></a>
<a href="/bare"><i class="glyph"></i></a>
<button>Log<i class="glyph"></i>out</button>
<a href="/privacy">Datenschutz&shy;erklärung</a>
<a href="/exit" title="Ex&#8203;it"><i class="glyph"></i></a>
<button aria-label="&#8203;" title="Save"></button>
<button>Sign&#8203;up</button>
<form id="address"><label>Post&#8203;code <input></label></form>
<label class="next">Email <input></label>
<label><i class="glyph"></i> Phone <input></label>
<label>Daten&shy;schutz <input></label>
<h2 data-testid="don't">Don't "quote" a &gt;&gt; b</h2>
`;

Expand Down Expand Up @@ -96,6 +102,10 @@ describe('names with CSS generated content', () => {
['link', 'Sign out'],
['link', undefined],
['button', 'Log out'],
['link', 'Datenschutzerklärung'],
['link', 'Exit'],
['button', ''],
['button', 'Signup'],
]);
});

Expand All @@ -106,6 +116,13 @@ describe('names with CSS generated content', () => {
expect(await names(byRole('button', 'Log out'))).toEqual(['Log out']);
});

it('finds a control by a name copied from the page, its soft hyphen included, as Playwright does', async () => {
expect(await names(byRole('link', 'Datenschutzerklärung'))).toEqual(['Datenschutzerklärung']);
expect(await names(byRole('link', 'Datenschutz\u00aderklärung'))).toEqual(['Datenschutzerklärung']);
expect(await names(byRole('link', 'schutz\u00aderkl', false))).toEqual(['Datenschutzerklärung']);
expect(await names(byRole('button', 'Sign\u200bup'))).toEqual(['Signup']);
});

it('matches a substring across a glyph and stays exact where asked', async () => {
expect(await names(byRole('button', 'sign IN', false))).toEqual(['Sign in']);
expect(await names(byRole('button', 'Sign'))).toEqual([]);
Expand All @@ -128,9 +145,26 @@ describe('names with CSS generated content', () => {
expect(await names(first(unicode('testId', "^don't$")))).toEqual([quoted]);
});

it('drops a soft hyphen and a zero-width space from the document name, as from any other', async () => {
const page = surfaceOf(engine)!.page();
await page.evaluate(() => { document.title = 'Daten\u00adschutz\u200b'; });
try {
const snapshot = await engine.observe!(op);
expect(flatten(snapshot.root).find((node) => node.role === 'document')?.name).toBe('Datenschutz');
} finally {
await page.evaluate(() => { document.title = ''; });
}
});

it('keeps generated content out of label text, as getByLabel reads it, and drops a glyph from it', async () => {
const label = (value: string): LocatorExpression => ({ kind: 'query', query: { kind: 'label', value: { kind: 'string', value, exact: true } } });
expect(await names(label('Email'))).toEqual(['→Email']);
expect(await names(label('Phone'))).toEqual(['Phone']);
expect(await names(label('Datenschutz'))).toEqual(['Datenschutz']);
expect(await names(label('Daten\u00adschutz'))).toEqual(['Datenschutz']);
expect(await names(label('Postcode'))).toEqual(['Postcode']);
expect(await names(label('Post\u200bcode'))).toEqual(['Postcode']);
const form: LocatorExpression = { kind: 'selector', selector: '#address' };
expect(await engine.locate!({ kind: 'filter', source: form, has: label('Post\u200bcode') }, op)).toHaveLength(1);
});
});
Loading