Skip to content

fix(actions): apply offset_x/offset_y to element-resolved presses - #411

Open
kun-codes wants to merge 8 commits into
mozarkai:mainfrom
kun-codes:fix/press-element-offset-on-webelement
Open

kun-codes wants to merge 8 commits into
mozarkai:mainfrom
kun-codes:fix/press-element-offset-on-webelement

Conversation

@kun-codes

Copy link
Copy Markdown
Member

Summary

press_element's offset_x / offset_y were silently ignored whenever the element resolved to a WebElement (accessibility / XPath match). The offset only ever took effect for coordinate-resolved matches (OCR / image), so an offset press against an accessibility- or XPath-located element just clicked the element centre.

Root cause

if isinstance(located, tuple):
    x, y = located
    self.driver.press_coordinates(x + int(offset_x), y + int(offset_y), event_name)  # offset applied
else:
    self.driver.press_element(located, int(repeat), event_name)                      # WebElement → offset dropped

located is a (x, y) tuple only for coordinate strategies; for accessibility/XPath it is a WebElement, and that branch never consulted offset_x / offset_y. So the offset reached the tap only for OCR/image matches and was discarded for every element-resolved match.

- `press_element` only applied `offset_x`/`offset_y` when the element resolved
  to coordinates (OCR/image). For a WebElement match (accessibility/XPath) the
  `else` branch clicked the element directly and silently dropped the offset, so
  any requested offset was ignored.
- When an offset is requested and the match is a WebElement, derive the element
  centre from its location/size and press by coordinates with the offset applied
  (honoring `repeat`); fall back to a direct element click with a warning if the
  centre can't be read.
- No behavior change when no offset is requested (offset 0/0 still clicks the
  element directly).
- Add `_element_centre` helper (works for both Appium and Selenium WebElements).
Copilot AI review requested due to automatic review settings July 28, 2026 12:45

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Copilot was unable to review this pull request because the user who requested the review has reached their quota limit.

@chinmayajha chinmayajha left a comment •

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.

Good catch and fix

Holding on two things (mentioned below

Comment thread optics_framework/api/action_keyword.py Resolved
- An offset press goes through `press_coordinates`, which skips the
  scroll-into-view `element.click()` does implicitly — so an offset on a partly
  off-screen element could tap the wrong spot.
- Derive the centre from `location_once_scrolled_into_view` (a Selenium property
  Appium's WebElement inherits), which scrolls it on-screen first; fall back to
  `location` when unavailable.
- Add WebElement offset cases to `TestPressElementWithIndex`: centre+offset
  reaches `press_coordinates`, a partly off-screen element uses the
  scrolled-into-view coords, `repeat` re-taps, and missing geometry falls back
  to `press_element`.
Copilot AI review requested due to automatic review settings July 29, 2026 08:04

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Copilot was unable to review this pull request because the user who requested the review has reached their quota limit.

@chinmayajha chinmayajha left a comment •

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.

thanks for the tests coverage

The scroll-into-view fix regresses native mobile: location_once_scrolled_into_view is JS-backed and raises under Appium native, and that exception isn't caught, so an offset press now fails as X0201 instead of tapping the centre. Details inline.

Also update the press_element example in docs/architecture/strategies.md (~line 750) — it still shows the old two-branch body.

Comment thread optics_framework/api/action_keyword.py Outdated
Comment on lines +467 to +482
@staticmethod
def _element_centre(element: Any) -> Optional[Tuple[int, int]]:
"""Centre (x, y) of a located WebElement, or None if geometry is unavailable.

Uses ``location_once_scrolled_into_view`` (scrolls it on-screen first, so an
offset lands even on a partly off-screen element); falls back to ``location``.
"""
try:
loc = getattr(element, "location_once_scrolled_into_view", None) or element.location
size = element.size
return (
int(loc["x"] + size["width"] / 2),
int(loc["y"] + size["height"] / 2),
)
except (AttributeError, KeyError, TypeError):
return None

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.

This makes offset presses fail outright on native mobile. location_once_scrolled_into_view is JS-backed (selenium executes arguments[0].scrollIntoView(true); return arguments[0].getBoundingClientRect()), so under Appium native it raises WebDriverException — not in the caught tuple, so it escapes _element_centre, escapes press_element, and _try_results_until_success turns it into X0201: All strategies failed for '//zone' in 'press_element'. Repro'd locally: on main the offset was ignored and the tap landed on the centre; now the step fails.

The MagicMock tests can't catch this — every attribute on a MagicMock succeeds.

Catch broadly and fall through to element_source.get_bbox_for_element (elementsource_interface.py:83), which already handles Appium bounds/rect and Playwright bounding_box(). That also makes offsets work on Playwright, where a Locator has no .location/.size so the offset is still dropped today. It also drops the .location fallback, which on Selenium web returns document coords while press_coordinates uses elementFromPoint (viewport) — wrong tap on a scrolled page.

Suggested change
@staticmethod
def _element_centre(element: Any) -> Optional[Tuple[int, int]]:
"""Centre (x, y) of a located WebElement, or None if geometry is unavailable.
Uses ``location_once_scrolled_into_view`` (scrolls it on-screen first, so an
offset lands even on a partly off-screen element); falls back to ``location``.
"""
try:
loc = getattr(element, "location_once_scrolled_into_view", None) or element.location
size = element.size
return (
int(loc["x"] + size["width"] / 2),
int(loc["y"] + size["height"] / 2),
)
except (AttributeError, KeyError, TypeError):
return None
def _element_centre(self, element: Any) -> Optional[Tuple[int, int]]:
"""Centre (x, y) of a located element, or None if geometry is unavailable.
Prefers ``location_once_scrolled_into_view``: on web it scrolls the element
on-screen and returns viewport coords, which is what ``press_coordinates``
expects. It is JS-backed, so it raises in a native Appium context - fall back
to the source-agnostic bbox accessor there.
"""
try:
loc = element.location_once_scrolled_into_view
size = element.size
return (
int(loc["x"] + size["width"] / 2),
int(loc["y"] + size["height"] / 2),
)
except Exception as exc: # noqa: BLE001 - JS-backed, unsupported on native
internal_logger.debug(f"Scrolled-into-view geometry unavailable: {exc}")
bbox = self.element_source.get_bbox_for_element(element)
if bbox is None:
return None
(x1, y1), (x2, y2) = bbox
return ((x1 + x2) // 2, (y1 + y2) // 2)

@kun-codes kun-codes Aug 7, 2026 •

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

fixed in f85abe7

Comment thread optics_framework/api/action_keyword.py Outdated
internal_logger.info(
f"Pressing at coordinates ({x + int(offset_x)}, {y + int(offset_y)}) with offset ({offset_x}, {offset_y})")
f"Pressing at coordinates ({x + offset_x_i}, {y + offset_y_i}) with offset ({offset_x_i}, {offset_y_i})")
self.driver.press_coordinates(

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.

Coordinate-located presses still ignore repeat (one press_coordinates call regardless), while the new branch loops. Pre-existing, but now the same keyword honours repeat in two of three branches — fold it in here or file a follow-up.

@kun-codes kun-codes Aug 7, 2026 •

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

fixed in 4a5f352

… unsupported

- `element.location_once_scrolled_into_view` is JS-backed and raises under Appium native, since UiAutomator2 doesn't implement it
- That exception wasn't in `_element_centre`'s caught tuple, so an offset press on a WebElement failed outright instead of falling back to a plain click
- Catch broadly and fall through to `element_source.get_bbox_for_element`, which already handles Appium `bounds`/`rect` and Playwright `bounding_box()`
- Add a test asserting `_element_centre` falls back to `element_source.get_bbox_for_element` when `location_once_scrolled_into_view` raises
- Update `test_offset_on_webelement_without_geometry_falls_back_to_press_element` to set `get_bbox_for_element.return_value = None` explicitly, needed to keep exercising the "no geometry at all" path after f85abe7
- The coordinate-tuple branch of `press_element` called `press_coordinates` once regardless of `repeat`
- The WebElement-offset branch already looped, so the same keyword only honored `repeat` in two of three branches
- Fold the loop into this branch too
- Add `test_coordinate_result_with_repeat_repeats_press`
- Asserts a coordinate-located press (OCR/image match) calls `press_coordinates` `repeat` times, matching 4a5f352
…h body

- The `press_element` example in `docs/architecture/strategies.md` still showed the old two-branch body, coordinate vs. plain click
- Update it to the current three-branch logic: coordinate with offset and repeat, WebElement with offset via `_element_centre`, and plain WebElement click
@kun-codes

kun-codes commented Aug 7, 2026 •

Copy link
Copy Markdown
Member Author

thanks for the tests coverage

The scroll-into-view fix regresses native mobile: location_once_scrolled_into_view is JS-backed and raises under Appium native, and that exception isn't caught, so an offset press now fails as X0201 instead of tapping the centre. Details inline.

Also update the press_element example in docs/architecture/strategies.md (~line 750) — it still shows the old two-branch body.

fixed in f85abe7 and docs is updated in 8376cfd

@sonarqubecloud

sonarqubecloud Bot commented Aug 7, 2026

Copy link
Copy Markdown

thakur-patel
thakur-patel previously approved these changes Nov 25, 2026

@thakur-patel thakur-patel left a comment

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.

Product review: approved. I've reviewed the intent and use case of this change, and it makes sense from a user and product point of view. This covers product intent and use case only. I haven't reviewed the implementation, so please rely on the code reviewers for that.

@thakur-patel
thakur-patel dismissed their stale review November 25, 2026 10:18

Approval withdrawn: posted by mistake. This PR is outside the product review scope.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants