Skip to content
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

feat: better selection #396

Merged
merged 3 commits into from
Feb 3, 2025
Merged

feat: better selection #396

merged 3 commits into from
Feb 3, 2025

Conversation

RohitR311
Copy link
Contributor

@RohitR311 RohitR311 commented Jan 26, 2025

Better Selector generation for child selectors to handle identical classes

Summary by CodeRabbit

  • Bug Fixes
    • Improved selector generation for elements with identical siblings.
    • Enhanced accuracy of element selection when multiple elements share similar attributes.
    • Cleaned selector strings by removing unnecessary nth-child pseudo-classes to ensure consistency.
    • Refined handling of selectors in the BrowserWindow component for better formatting.

@RohitR311 RohitR311 requested a review from amhsirak January 26, 2025 13:23
Copy link

coderabbitai bot commented Jan 26, 2025

Walkthrough

The pull request introduces improvements to selector generation in the server/src/workflow-management/selector.ts file. The primary enhancement focuses on handling identical sibling elements during selector creation. The modifications update the getNonUniqueSelector and getChildSelectors functions to incorporate a more precise selector generation mechanism. When multiple elements share similar attributes, the new logic appends a :nth-child(n) pseudo-class to distinguish between them based on their position among siblings. Additionally, the BrowserWindow component's handleClick function is updated to clean selector strings by removing unnecessary pseudo-classes.

Changes

File Change Summary
server/src/workflow-management/selector.ts - Enhanced getNonUniqueSelector function to handle identical sibling elements
- Updated getChildSelectors function to apply :nth-child(n) logic
src/components/browser/BrowserWindow.tsx - Modified handleClick function to clean selector strings by removing nth-child pseudo-classes

Possibly related PRs

Suggested reviewers

  • amhsirak

Poem

🐰 Selectors dancing, siblings in line,
With nth-child magic, they now align!
No more confusion, each element clear,
A rabbit's precision brings selector cheer!
Code weaves its web, with surgical might! 🕸️


📜 Recent review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 4a7b111 and 2d78cbf.

📒 Files selected for processing (1)
  • src/components/browser/BrowserWindow.tsx (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/components/browser/BrowserWindow.tsx

🪧 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. (Beta)
  • @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: 1

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

1657-1681: Consider caching selector results for performance optimization.

The new sibling comparison logic requires additional DOM traversal and string operations for each element. For large DOMs with many identical siblings, this could impact performance.

Consider implementing a simple cache to store computed selectors:

+ const selectorCache = new WeakMap<HTMLElement, string>();

  function getNonUniqueSelector(element: HTMLElement): string {
+   const cachedSelector = selectorCache.get(element);
+   if (cachedSelector) return cachedSelector;

    let selector = element.tagName.toLowerCase();
    // ... existing logic ...
    
+   selectorCache.set(element, selector);
    return selector;
  }

1663-1665: Improve robustness of className type checking.

The current implementation handles non-string className values, but the type checking could be more explicit and comprehensive.

Consider enhancing the type checking:

- const siblingClassName = typeof sibling.className === 'string' ? sibling.className : '';
+ const siblingClassName = (sibling.className?.toString() || '').trim();

This change:

  • Handles undefined className values safely
  • Trims whitespace to avoid empty class names
  • Uses toString() to handle SVGAnimatedString class names

Also applies to: 1928-1930, 2084-2086

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 5cadc49 and 1ad4b5d.

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

Comment on lines +1657 to +1681
if (element.parentElement) {
// Look for identical siblings
const siblings = Array.from(element.parentElement.children);
const identicalSiblings = siblings.filter(sibling => {
if (sibling === element) return false;

let siblingSelector = sibling.tagName.toLowerCase();
const siblingClassName = typeof sibling.className === 'string' ? sibling.className : '';
if (siblingClassName) {
const siblingClasses = siblingClassName.split(/\s+/).filter(Boolean);
const validSiblingClasses = siblingClasses.filter(cls => !cls.startsWith('!') && !cls.includes(':'));
if (validSiblingClasses.length > 0) {
siblingSelector += '.' + validSiblingClasses.map(cls => CSS.escape(cls)).join('.');
}
}

return siblingSelector === selector;
});

if (identicalSiblings.length > 0) {
const position = siblings.indexOf(element) + 1;
selector += `:nth-child(${position})`;
}
}

Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Refactor duplicated selector generation logic into a shared function.

The identical sibling handling logic is duplicated in three locations. This violates the DRY principle and makes maintenance more difficult.

Consider extracting the common logic into a shared utility function:

+ function appendNthChildSelectorIfNeeded(element: HTMLElement, selector: string): string {
+   if (element.parentElement) {
+     const siblings = Array.from(element.parentElement.children);
+     const identicalSiblings = siblings.filter(sibling => {
+       if (sibling === element) return false;
+       
+       let siblingSelector = sibling.tagName.toLowerCase();
+       const siblingClassName = typeof sibling.className === 'string' ? sibling.className : '';
+       if (siblingClassName) {
+         const siblingClasses = siblingClassName.split(/\s+/).filter(Boolean);
+         const validSiblingClasses = siblingClasses.filter(cls => !cls.startsWith('!') && !cls.includes(':'));
+         if (validSiblingClasses.length > 0) {
+           siblingSelector += '.' + validSiblingClasses.map(cls => CSS.escape(cls)).join('.');
+         }
+       }
+       
+       return siblingSelector === selector;
+     });
+ 
+     if (identicalSiblings.length > 0) {
+       const position = siblings.indexOf(element) + 1;
+       selector += `:nth-child(${position})`;
+     }
+   }
+   return selector;
+ }

  function getNonUniqueSelector(element: HTMLElement): string {
    let selector = element.tagName.toLowerCase();
    // ... existing class handling logic ...
-   if (element.parentElement) {
-     // ... duplicate sibling handling logic ...
-   }
+   selector = appendNthChildSelectorIfNeeded(element, selector);
    return selector;
  }

Also applies to: 1922-1946, 2078-2102

@amhsirak amhsirak changed the title feat: nth-child selector generation for child selectors feat: better selection Jan 26, 2025
@amhsirak amhsirak added Type: Enhancement Improvements to existing features Status: On Hold Work on this has been temporarily paused Status: 🚫🚫 DO NOT MERGE 🚫🚫 Don't merge this PR. It is not perfect. labels Jan 26, 2025
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)
src/components/browser/BrowserWindow.tsx (1)

Line range hint 266-294: Consider extracting selector cleaning logic into a utility function.

The selector cleaning logic is duplicated and could be reused in other components. Consider extracting it into a utility function for better maintainability and reusability.

Create a new utility function:

// utils/selectorUtils.ts
export const cleanNthChildSelector = (selector: string): string => {
  return selector.replace(/:nth-child\(\d+\)/g, '');
};

Then use it in the component:

-    let cleanedSelector = highlighterData.selector;
-    if (cleanedSelector.includes('nth-child')) {
-        cleanedSelector = cleanedSelector.replace(/:nth-child\(\d+\)/g, '');
-    }
+    const cleanedSelector = cleanNthChildSelector(highlighterData.selector);
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 1ad4b5d and 4a7b111.

📒 Files selected for processing (1)
  • src/components/browser/BrowserWindow.tsx (2 hunks)
🔇 Additional comments (2)
src/components/browser/BrowserWindow.tsx (2)

301-301: LGTM!

The use of the cleaned currentSelector in the TextStep object is correct and aligns with the PR's objective to improve selector generation.


Line range hint 266-294: Add unit tests for selector cleaning logic.

The new selector cleaning functionality lacks unit tests. This is critical for ensuring the reliability of the selector generation improvements.

Would you like me to help create unit tests for the selector cleaning logic? The tests should cover:

  1. Basic selector cleaning
  2. Complex selectors with multiple nth-child
  3. Child selector handling
  4. Edge cases (empty selectors, no nth-child, etc.)

Comment on lines +266 to +270
let cleanedSelector = highlighterData.selector;
if (cleanedSelector.includes('nth-child')) {
cleanedSelector = cleanedSelector.replace(/:nth-child\(\d+\)/g, '');
}

Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Fix unused cleaned selector.

The cleaned selector is computed but never used. The original selector with nth-child is still being set as the listSelector, which defeats the purpose of cleaning the selector.

Apply this diff to fix the issue:

     let cleanedSelector = highlighterData.selector;
     if (cleanedSelector.includes('nth-child')) {
         cleanedSelector = cleanedSelector.replace(/:nth-child\(\d+\)/g, '');
     }
-
-    setListSelector(highlighterData.selector);
+    setListSelector(cleanedSelector);

Committable suggestion skipped: line range outside the PR's diff.

Comment on lines +283 to +294
let currentSelector = highlighterData.selector;

if (currentSelector.includes('>')) {
const [firstPart, ...restParts] = currentSelector.split('>').map(p => p.trim());
const listSelectorRightPart = listSelector.split('>').pop()?.trim().replace(/:nth-child\(\d+\)/g, '');

if (firstPart.includes('nth-child') &&
firstPart.replace(/:nth-child\(\d+\)/g, '') === listSelectorRightPart) {
currentSelector = `${firstPart.replace(/:nth-child\(\d+\)/g, '')} > ${restParts.join(' > ')}`;
}
}

Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Improve robustness and readability of child selector handling.

The current implementation has potential issues:

  1. Missing null checks for split operations
  2. Assumes listSelector always contains '>'
  3. Complex logic could benefit from better readability

Apply this diff to improve the code:

     let currentSelector = highlighterData.selector;
 
     if (currentSelector.includes('>')) {
         const [firstPart, ...restParts] = currentSelector.split('>').map(p => p.trim());
-        const listSelectorRightPart = listSelector.split('>').pop()?.trim().replace(/:nth-child\(\d+\)/g, '');
+        // Extract the rightmost part of the list selector (if it contains '>')
+        const listSelectorParts = listSelector.split('>');
+        const listSelectorRightPart = listSelectorParts.length > 1 
+            ? listSelectorParts.pop()?.trim().replace(/:nth-child\(\d+\)/g, '')
+            : listSelector.replace(/:nth-child\(\d+\)/g, '');
 
+        // Only clean nth-child if the base selectors match
         if (firstPart.includes('nth-child') && 
-            firstPart.replace(/:nth-child\(\d+\)/g, '') === listSelectorRightPart) {
+            listSelectorRightPart && 
+            firstPart.replace(/:nth-child\(\d+\)/g, '') === listSelectorRightPart) {
             currentSelector = `${firstPart.replace(/:nth-child\(\d+\)/g, '')} > ${restParts.join(' > ')}`;
         }
     }
📝 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
let currentSelector = highlighterData.selector;
if (currentSelector.includes('>')) {
const [firstPart, ...restParts] = currentSelector.split('>').map(p => p.trim());
const listSelectorRightPart = listSelector.split('>').pop()?.trim().replace(/:nth-child\(\d+\)/g, '');
if (firstPart.includes('nth-child') &&
firstPart.replace(/:nth-child\(\d+\)/g, '') === listSelectorRightPart) {
currentSelector = `${firstPart.replace(/:nth-child\(\d+\)/g, '')} > ${restParts.join(' > ')}`;
}
}
let currentSelector = highlighterData.selector;
if (currentSelector.includes('>')) {
const [firstPart, ...restParts] = currentSelector.split('>').map(p => p.trim());
// Extract the rightmost part of the list selector (if it contains '>')
const listSelectorParts = listSelector.split('>');
const listSelectorRightPart = listSelectorParts.length > 1
? listSelectorParts.pop()?.trim().replace(/:nth-child\(\d+\)/g, '')
: listSelector.replace(/:nth-child\(\d+\)/g, '');
// Only clean nth-child if the base selectors match
if (firstPart.includes('nth-child') &&
listSelectorRightPart &&
firstPart.replace(/:nth-child\(\d+\)/g, '') === listSelectorRightPart) {
currentSelector = `${firstPart.replace(/:nth-child\(\d+\)/g, '')} > ${restParts.join(' > ')}`;
}
}

@RohitR311 RohitR311 removed the Status: 🚫🚫 DO NOT MERGE 🚫🚫 Don't merge this PR. It is not perfect. label Feb 3, 2025
@amhsirak amhsirak merged commit 34b557f into develop Feb 3, 2025
1 check passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Status: On Hold Work on this has been temporarily paused Type: Enhancement Improvements to existing features
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants