feat: exclude utlitly classes + esc spc. chars

This commit is contained in:
karishmas6
2024-08-12 18:24:27 +05:30
parent 6cafc9ef2d
commit 7c2ff6c2c9

View File

@@ -730,35 +730,39 @@ export const getSelectors = async (page: Page, coordinates: Coordinates) => {
* @returns {Promise<Selectors|null|undefined>} * @returns {Promise<Selectors|null|undefined>}
*/ */
export const getNonUniqueSelectors = async (page: Page, coordinates: Coordinates) => { export const getNonUniqueSelectors = async (page: Page, coordinates: Coordinates) => {
try { try {
const selectors = await page.evaluate(({ x, y }) => { const selectors = await page.evaluate(({ x, y }: { x: number, y: number }) => {
function getSelector(element: any) {
function getNonUniqueSelector(element: HTMLElement): string {
let selector = element.tagName.toLowerCase(); let selector = element.tagName.toLowerCase();
// Capture a single, relevant class if present // Avoid using IDs to maintain non-uniqueness
if (element.className) { if (element.className) {
const classes = element.className.split(/\s+/).filter(Boolean); const classes = element.className.split(/\s+/).filter((cls: string) => Boolean(cls));
if (classes.length > 0) { if (classes.length > 0) {
// Use only the first class to avoid over-specificity // Exclude utility classes and escape special characters
selector += '.' + classes[0]; const validClasses = classes.filter((cls: string) => !cls.startsWith('!') && !cls.includes(':'));
if (validClasses.length > 0) {
selector += '.' + validClasses.map(cls => CSS.escape(cls)).join('.');
}
} }
} }
return selector; return selector;
} }
function getSelectorPath(element: any) { function getSelectorPath(element: HTMLElement | null): string {
const path = []; const path: string[] = [];
while (element && element !== document.body) { while (element && element !== document.body) {
const selector = getSelector(element); const selector = getNonUniqueSelector(element);
path.unshift(selector); path.unshift(selector);
element = element.parentElement; element = element.parentElement;
} }
return path.join(' > '); return path.join(' > ');
} }
const element = document.elementFromPoint(x, y); const element = document.elementFromPoint(x, y) as HTMLElement | null;
if (!element) return null; if (!element) return null;
const generalSelector = getSelectorPath(element); const generalSelector = getSelectorPath(element);
@@ -775,6 +779,8 @@ export const getNonUniqueSelectors = async (page: Page, coordinates: Coordinate
}; };
/** /**
* Returns the first pair from the given workflow that contains the given selector * Returns the first pair from the given workflow that contains the given selector
* inside the where condition, and it is the only selector there. * inside the where condition, and it is the only selector there.