Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
75 changes: 75 additions & 0 deletions server/src/workflow-management/selector.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1654,6 +1654,31 @@ export const getNonUniqueSelectors = async (page: Page, coordinates: Coordinates
}
}

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})`;
}
}

Comment on lines +1657 to +1681
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

return selector;
}

Expand Down Expand Up @@ -1894,6 +1919,31 @@ export const getNonUniqueSelectors = async (page: Page, coordinates: Coordinates
}
}

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})`;
}
}

return selector;
}

Expand Down Expand Up @@ -2025,6 +2075,31 @@ export const getChildSelectors = async (page: Page, parentSelector: string): Pro
}
}

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})`;
}
}

return selector;
}

Expand Down
21 changes: 19 additions & 2 deletions src/components/browser/BrowserWindow.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -263,7 +263,12 @@ export const BrowserWindow = () => {
}

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

Comment on lines +266 to +270
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.

setListSelector(cleanedSelector);
notify(`info`, t('browser_window.attribute_modal.notifications.list_select_success'));
setCurrentListId(Date.now());
setFields({});
Expand All @@ -275,13 +280,25 @@ export const BrowserWindow = () => {
// Add fields to the list
if (options.length === 1) {
const attribute = options[0].value;
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(' > ')}`;
}
}

Comment on lines +283 to +294
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(' > ')}`;
}
}

const newField: TextStep = {
id: Date.now(),
type: 'text',
label: `Label ${Object.keys(fields).length + 1}`,
data: data,
selectorObj: {
selector: highlighterData.selector,
selector: currentSelector,
tag: highlighterData.elementInfo?.tagName,
shadow: highlighterData.elementInfo?.isShadowRoot,
attribute
Expand Down