Skip to content

fix: list selector highlighting #544

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: develop
Choose a base branch
from
Open

fix: list selector highlighting #544

wants to merge 1 commit into from

Conversation

RohitR311
Copy link
Collaborator

@RohitR311 RohitR311 commented Apr 17, 2025

What this PR does?

Improved list selector highlighting based on element dimensions and children elements.

Fixes: #543

Summary by CodeRabbit

  • Refactor

    • Improved the method for selecting container elements on the page, enhancing accuracy when identifying relevant elements under the cursor.
  • New Features

    • Added logging of browser console messages to the server console for better visibility during interactions.

@RohitR311 RohitR311 added Type: Bug Something isn't working Status: Work In Progess This issue/PR is actively being worked on labels Apr 17, 2025
Copy link

coderabbitai bot commented Apr 17, 2025

Walkthrough

The changes update the logic for selecting elements at a specific point on a web page within the selector.ts module. The previous method, which chose the deepest DOM element, is replaced with a new heuristic that prioritizes container elements with a minimum size and visible containment of other elements. This adjustment is applied across three functions: getElementInformation, getRect, and getNonUniqueSelectors. Additionally, a console message logging listener is added to the page object in the getElementInformation function. No exported function signatures or public API declarations are altered.

Changes

File(s) Change Summary
server/src/workflow-management/selector.ts Replaced deepest element selection logic with a container-based heuristic in three functions; added browser console message logging in getElementInformation.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant Page
    participant SelectorModule

    User->>Page: Hover/click at (x, y)
    Page->>SelectorModule: Call getElementInformation/getRect/getNonUniqueSelectors(x, y)
    SelectorModule->>Page: document.elementsFromPoint(x, y)
    Page-->>SelectorModule: List of elements at point
    SelectorModule->>SelectorModule: Select first container element (≥30x30px, contains others)
    SelectorModule-->>Page: Return selected element info/rect/selector
Loading

Assessment against linked issues

Objective Addressed Explanation
Correct element highlighting for list selector (Issue #543)

Possibly related PRs

  • fix: improve list container detection and highlighting #493: Both PRs modify the logic in getElementInformation, getRect, and getNonUniqueSelectors within selector.ts to improve how a container or deepest element is selected from elements at a point, replacing the previous deepest element approach with a container-focused heuristic.
  • fix: include visual containment for capture list selection #241: Both PRs modify the element containment logic within the same functions (getElementInformation, getRect, and getNonUniqueSelectors) in selector.ts, focusing on improving how container elements are identified and used for selection.
  • feat: apply conditional visual containment #238: Both PRs modify the internal logic in selector.ts related to identifying container elements in the DOM, focusing on refining how container elements are determined based on visual containment and element hierarchy.

Suggested labels

Scope: Ext

Suggested reviewers

  • amhsirak

Poem

In the warren of code, a change hops through,
Selecting containers, not just the deep and few.
With bounding boxes wide, and children inside,
The right element now, no longer will hide.
Console logs chatter, as rabbits delight,
The selector’s new logic is perfectly right! 🐇✨

Tip

⚡💬 Agentic Chat (Pro Plan, General Availability)
  • We're introducing multi-step agentic chat in review comments and issue comments, within and outside of PR's. This feature enhances review and issue discussions with the CodeRabbit agentic chat by enabling advanced interactions, including the ability to create pull requests directly from comments and add commits to existing pull requests.
✨ Finishing Touches
  • 📝 Generate Docstrings

🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 2

🧹 Nitpick comments (1)
server/src/workflow-management/selector.ts (1)

318-330: Potential O(n²) traversal inside the heuristic

Inside findContainerElement, the inner elements.some is executed for each
element, yielding O(n²) contains checks. On pages with many overlapped DOM
nodes (e.g. complex SVGs), this can noticeably slow highlight calculation.

A micro‑optimisation is to pre‑compute an Set of ancestors for each element or
short‑circuit once a suitable container is found. A very small refactor:

-  for (let i = 0; i < elements.length; i++) {
-    const element = elements[i];
-
-    const hasChildrenInList = elements.some((other, j) => i !== j && element.contains(other));
-    if (hasChildrenInList) return element;
-  }
+  for (const element of elements) {
+    const rect = element.getBoundingClientRect();
+    if (rect.width < 30 || rect.height < 30) continue;
+    for (const child of elements) {
+      if (child !== element && element.contains(child)) {
+        return element;            // early‑exit
+      }
+    }
+  }

Also applies to: 828-840, 2003-2015

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 0f472ca and 3bf659b.

📒 Files selected for processing (1)
  • server/src/workflow-management/selector.ts (3 hunks)
🔇 Additional comments (1)
server/src/workflow-management/selector.ts (1)

322-330: Hard‑coded 30 × 30 threshold – verify it fits all list items

The new rule ignores any candidate whose bounding‑box is smaller than
30 px × 30 px. Small interactive targets (icons, checkboxes, compact list
rows, etc.) will now be skipped and may revert to the first element in the
stack, changing previous behaviour.

Please confirm (or make the threshold configurable) before release to avoid
regressions.

Also applies to: 832-840, 2007-2013

Comment on lines +314 to 337
const findContainerElement = (elements: HTMLElement[]): HTMLElement | null => {
if (!elements.length) return null;
if (elements.length === 1) return elements[0];

let deepestElement = elements[0];
let maxDepth = 0;

for (const element of elements) {
let depth = 0;
let current = element;
for (let i = 0; i < elements.length; i++) {
const element = elements[i];
const rect = element.getBoundingClientRect();

while (current) {
depth++;
if (current.parentElement) {
current = current.parentElement;
} else {
break;
}
}

if (depth > maxDepth) {
maxDepth = depth;
deepestElement = element;
if (rect.width >= 30 && rect.height >= 30) {
const hasChildrenInList = elements.some((otherElement, j) =>
i !== j && element.contains(otherElement)
);

if (hasChildrenInList) {
return element;
}
}
}

return deepestElement;
return elements[0];
};

// Logic to get list container element
let targetElement = null;

for (const element of elements) {
const deepestEl = findDeepestElement(elements);

if (deepestEl && element !== deepestEl) {
if (element.contains(deepestEl) &&
element !== deepestEl.parentElement &&
element.tagName !== 'HTML' &&
element.tagName !== 'BODY') {
targetElement = element;
break;
}
}
}

let deepestElement = targetElement || findDeepestElement(elements);
let deepestElement = findContainerElement(elements);
if (!deepestElement) return null;
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Duplicate “container element” heuristic – consider extracting to a helper

The identical findContainerElement implementation now appears three times
(getElementInformation, getRect, getNonUniqueSelectors). Besides the
maintenance burden, any future tweak (e.g. size threshold, containment rule)
must be triplicated and risks drifting out of sync.

Suggestion:

  1. Define the helper once in TypeScript:

    function findContainerElement(elements: HTMLElement[]): HTMLElement {
      // …body…
    }
  2. Pass it into each page.evaluate via
    page.addInitScript(findContainerElement.toString()) or by serialising the
    function in the evaluate call (evaluate(findContainerElement, …)).

This keeps the heuristic single‑sourced and testable.

Also applies to: 824-847, 1999-2022

Comment on lines +305 to +307
page.on('console', msg => {
console.log(`Browser console: ${msg.text()}`);
});
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Avoid adding a new page.on('console') listener on every call

page.on('console', …) is executed every time getElementInformation enters this
branch. After just a few invocations the page will have dozens of identical
listeners, causing:

  • memory‑leak‐like growth,
  • duplicated logs,
  • slower teardown.
-      page.on('console', msg => {
-        console.log(`Browser console: ${msg.text()}`);
-      });
+      if (page.listenerCount('console') === 0) {
+        page.on('console', msg => console.log(`Browser console: ${msg.text()}`));
+      }

(You could also register the listener once at module‑initialisation time instead.)

📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
page.on('console', msg => {
console.log(`Browser console: ${msg.text()}`);
});
if (page.listenerCount('console') === 0) {
page.on('console', msg => console.log(`Browser console: ${msg.text()}`));
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Status: Work In Progess This issue/PR is actively being worked on Type: Bug Something isn't working
Projects
None yet
Development

Successfully merging this pull request may close these issues.

Bug: List selector highlighting
1 participant