Precise Playwright Selectors: Directional Control

by Luna Greco 50 views

Hey guys! Let's dive into a cool feature request that could seriously level up our Playwright game. We're talking about making those directional selectors way more precise and intuitive. You know how sometimes :right-of, :left-of, :above, and :below can be a bit… off? Yeah, we're fixing that.

The Problem with Current Directional Selectors

Currently, the directional selectors in Playwright sometimes miss the mark. Imagine you're trying to select an element directly to the right of another, but Playwright grabs something that's also a bit above or below. It's like trying to point at something and accidentally hitting the thing next to it. This imprecision can lead to flaky tests and a whole lot of frustration. When using :right-of, the expectation is often to find an element that is strictly to the right, not one that is also vertically displaced. The current behavior often selects elements that are 250 pixels above and 50 pixels to the right, instead of the desired element 300 pixels to the right. This discrepancy highlights the need for more refined directional selectors.

For instance, consider a scenario where you have multiple input fields near a label, and you specifically want the input field that is directly to the right of the label "Op-cost". Using the current :right-of selector might inadvertently select an input field that is slightly above or below the label, leading to incorrect test outcomes. The goal is to select the third input element whose Y coordinates overlap with the Y coordinates of the "Op-cost" label. It shouldn't matter if there are other input elements above or below, only those directly to the right should be considered. If no matching elements are found directly to the right, the selector should fail, ensuring that tests don't pass erroneously.

This issue forces developers to resort to less elegant and more brittle selectors, such as "3rd button within element X," which are highly susceptible to breaking with minor UI changes. The core problem is that the existing selectors are too broad, often including irrelevant elements that are not directly aligned in the intended direction. This lack of precision undermines the reliability and maintainability of tests, making it crucial to address this limitation in Playwright's selector capabilities.

Proposed Solutions: More Precise Selectors

To tackle this, we've got a couple of awesome solutions on the table. The main idea? Introduce new selectors that are laser-focused on direction. No more guessing games!

1. New Set of Directional Selectors

Why not add a fresh set of selectors that do exactly what we need? Think of it like this:

  • :east-of, :west-of, :north-of, :south-of – These are your compass directions. Simple and to the point.
  • :leftOf, :rightOf, :onTopOf, :underneath – More explicit names for clarity.

With these, `page.locator('input:rightOf(:text(