Repository navigation
[feat]: add locator.filter() - #3567
Conversation
🦋 Changeset detectedLatest commit: cb756a7 The changes in this PR will be included in the next version bump. This PR includes changesets to release 19 packages
Not sure what this means? Click here to learn what changesets are. Click here if you're a maintainer who wants to add another changeset to this PR |
There was a problem hiding this comment.
All reported issues were addressed across 28 files
Architecture diagram
sequenceDiagram
participant SDK as SDK (TS/Python)
participant Protocol as Protocol Schemas/Validation
participant API as Browser API (Locator engine)
participant Chain as Chain Resolver (Understudy)
participant DOM as DOM Extension (Frame Chain)
participant Browser as Browser/CDP
Note over SDK,Protocol: Locator.filter() API construction
SDK->>SDK: filter({hasText, hasNotText}) or filter(has_text, has_not_text)
SDK->>Protocol: Build LocatorFilterStep
Protocol->>Protocol: Validate options (string-only, no regex/has/exact)
alt Invalid options (regex, null in Python, has/hasNot, exact)
Protocol-->>SDK: Throw validation error before dispatch
else Valid options
SDK->>API: appendSteps([{type:"filter", ...options}])
API->>API: Store as new lazy locator (doesn't mutate original)
end
Note over API,Chain: Chain resolution with filter step (lazy, on action/count)
API->>Chain: resolve(chain, {mode: "count"/"selected"/"all"})
Chain->>Chain: Walk steps in order (query, frame, nth, filter)
alt Maintenance chain includes filter step
Chain->>DOM: this.filter(options, selectedIds)
DOM->>DOM: filterTextMatches(candidates, options)
DOM->>DOM: Create text matcher with normalization (case-insensitive, whitespace, zero-width removal)
DOM->>DOM: Include/exclude based on hasText/hasNotText (both must pass)
DOM-->>Chain: Return retained element IDs (original order/dedup)
end
alt Frame chain includes filter step (iframes/cross-origin)
Chain->>Chain: groupByWorld(matches)
Chain->>Browser: Runtime.callFunctionOn per world (filter options, IDs)
Browser->>Browser: Execute this.filter(options, ids) per document
Browser-->>Chain: Return filtered IDs per world
Chain->>Chain: Merge results preserving original order
end
Note over Chain,Browser: Filter semantics
opt Filtering iframe element
DOM->>DOM: Test iframe's own DOM text only (NOT child document)
end
opt Shadow DOM (open/closed)
DOM->>DOM: Extract text from shadow roots (closed needs http/https)
end
Chain-->>API: Resolved elements (IDs kept, no handles exported for count)
API-->>SDK: Return count/selected/all result
Note over API,SDK: Text updates cause re-evaluation on next action
SDK->>API: count()/click()/locator() after filter
API->>Chain: Re-resolve chain (fresh filter evaluation)
DOM->>DOM: Re-run filterTextMatches on current DOM text
DOM-->>Chain: Updated filtered set
Chain-->>API: New results (e.g., count now 0 if text changed)
Reply with feedback, questions, or to request a fix.
View guided diff | Turn on auto-fix | Re-trigger cubic
|
|
||
| Filtering an iframe tests the iframe element's own DOM text and does not enter its child document. Use `page.locator("iframe").locator(".card").filter({ hasText: "Billing" })` to filter cards inside it. Closed shadow-root traversal requires an `http:` or `https:` page. | ||
|
|
||
| `filter()` and `filter({})` retain all current matches. An empty `hasText` retains all matches; an empty `hasNotText` retains none. Regular expressions, `has`, `hasNot`, and exact matching are unsupported. Invalid options fail during construction, before a browser request. |
There was a problem hiding this comment.
nit: the docs say an empty hasNotText retains none, but whitespace-only values behave the same after normalization: in Chrome " ", "\n" and a lone zero-width space each dropped every match. Could this say "empty or whitespace-only" (same line at 1208 for Python)? Playwright ignores an empty hasNotText, so a note on that difference would help people porting code.
[claude-opus-5-5, /auto-review, severity 3/10]
| const secondCardIfBilling = cards.nth(1).filter({ hasText: "Billing" }); | ||
| ``` | ||
|
|
||
| Matching uses case-insensitive substrings. It removes zero-width spaces (`U+200B`) and soft hyphens (`U+00AD`), then trims and collapses whitespace in both the filter and element text. Text extraction follows `getByText()`, including descendant text, button input values, and open/closed shadow roots. Hidden text is included. The filter retains each original element, rather than selecting its smallest matching descendant. |
There was a problem hiding this comment.
nit: filter reads text the way getByText() does, so anything in <head> or a <template> reads as empty. In Chrome locator("title").filter({ hasText: "Save" }) matched nothing on a page titled "Save title", and hasNotText kept it. Worth one line next to "Hidden text is included".
[claude-opus-5-5, /auto-review, severity 2/10]
| ); | ||
| }, | ||
| filter(options: LocatorFilterStep, selected: number[]): number[] { | ||
| return filterTextMatches(this.elements(selected), options).map((node) => ids.get(node)!); |
There was a problem hiding this comment.
question: filter() goes through this.elements(selected), which throws "Chain iframe detached before entry" for a detached iframe but lets a detached div through to be filtered on its stale text. Nothing retries that error. Is the difference intended, or should filter skip the entry guard?
[claude-opus-5-5, /auto-review, severity 3/10]
| if (step.type === "nth") { | ||
| const selected = matches[step.index]; | ||
| matches = selected ? [selected] : []; | ||
| } else if (step.type === "filter") { |
There was a problem hiding this comment.
question: this branch, and the filter-ordering tests in elementChainResolution.test.ts, run through resolveElementChain, which only FrameElementChainResolver calls, and nothing outside tests constructs that class. Is the element resolver still a supported path? If not, the assertions could move onto FrameChainResolver and this branch could go.
[claude-opus-5-5, /auto-review, severity 3/10]
Merge origin/main into cursor/fix-remote-session-status-propagation-38a5 Conflicts resolved: - packages/cli/src/lib/driver/remote.ts: Keep PR's extractHttpStatus/extractUpstreamMessage helpers for cause chain extraction and 402/429 handling, incorporate main's removal of redundant JSDoc comments - packages/cli/src/lib/driver/remote.disabled.ts: Keep PR's extractHttpStatus function for consistent httpStatus extraction in disabled stub Changes from main: - locator.filter() feature (#3567) - page-level error classification (#3515) - bare hostname URL fix (#3512) - comment removal cleanup (#3538) - other SDK and CLI improvements Co-authored-by: Shrey Pandya <[email protected]>
why
this pr adds
Locator.filter(), which allows for filtering matches by textwhat changed
.nth(1).filter(...)tests the second original match;.filter(...).nth(1)selects the second surviving match.hasTextretains all, & emptyhasNotTextretains none. unsupported options & non-string matchers are rejected before dispatch; python usesNoneto omit a condition.test plan
added & extended tests covering:
Summary by cubic
Adds
Locator.filter()for narrowing element matches by text without changing the original locator.filter({ hasText, hasNotText })option takes case-insensitive, whitespace-normalized substring conditions; both conditions must pass when supplied together.nth()and query steps.getByText()including descendants and open/closed shadow roots; filtering an iframe does not enter its child document.has,hasNot, andexactfail during construction, before any browser request.Migration
locator.filter({ ... })andlocator.filter(has_text=..., has_not_text=...)accept string-only matchers; useNone(Python) or omit the option (TypeScript) to skip a condition.Written for commit cb756a7. Summary will update on new commits.