@probolabs/playwright 0.4.5 → 0.4.7
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.js +38 -14
- package/dist/index.js.map +1 -1
- package/dist/types/actions.d.ts.map +1 -1
- package/package.json +2 -2
- package/dist/actions.d.ts +0 -24
- package/dist/actions.d.ts.map +0 -1
- package/dist/actions.js +0 -241
- package/dist/api-client.d.ts +0 -32
- package/dist/api-client.d.ts.map +0 -1
- package/dist/api-client.js +0 -125
- package/dist/highlight.d.ts +0 -28
- package/dist/highlight.d.ts.map +0 -1
- package/dist/highlight.js +0 -79
- package/dist/index.d.ts.map +0 -1
- package/dist/probo-playwright.esm.js +0 -63
- package/dist/probo-playwright.umd.js +0 -644
- package/dist/src/actions.d.ts +0 -18
- package/dist/src/api-client.d.ts +0 -13
- package/dist/src/highlight.d.ts +0 -28
- package/dist/src/index.d.ts +0 -20
- package/dist/src/utils.d.ts +0 -20
- package/dist/tsconfig.tsbuildinfo +0 -1
- package/dist/utils.d.ts +0 -21
- package/dist/utils.d.ts.map +0 -1
- package/dist/utils.js +0 -39
package/dist/index.js
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
|
-
const highlighterCode = "(function (global, factory) {\n typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :\n typeof define === 'function' && define.amd ? define(['exports'], factory) :\n (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.ProboLabs = {}));\n})(this, (function (exports) { 'use strict';\n\n const ElementTag = {\r\n CLICKABLE: \"CLICKABLE\", // button, link, toggle switch, checkbox, radio, dropdowns, clickable divs\r\n FILLABLE: \"FILLABLE\", // input, textarea content_editable, date picker??\r\n SELECTABLE: \"SELECTABLE\", // select\r\n NON_INTERACTIVE_ELEMENT: 'NON_INTERACTIVE_ELEMENT',\r\n };\r\n\r\n class ElementInfo {\r\n constructor(element, index, {tag, type, text, html, xpath, css_selector, bounding_box, iframe_selector}) {\r\n this.index = index.toString();\r\n this.tag = tag;\r\n this.type = type;\r\n this.text = text;\r\n this.html = html;\r\n this.xpath = xpath;\r\n this.css_selector = css_selector;\r\n this.bounding_box = bounding_box;\r\n this.iframe_selector = iframe_selector;\r\n this.element = element;\r\n this.depth = -1;\r\n }\r\n\r\n getSelector() {\r\n return this.xpath ? this.xpath : this.css_selector;\r\n }\r\n\r\n getDepth() {\r\n if (this.depth >= 0) {\r\n return this.depth;\r\n }\r\n \r\n this.depth = 0;\r\n let currentElement = this.element;\r\n \r\n while (currentElement.nodeType === Node.ELEMENT_NODE) { \r\n this.depth++;\r\n if (currentElement.assignedSlot) {\r\n currentElement = currentElement.assignedSlot;\r\n }\r\n else {\r\n currentElement = currentElement.parentNode;\r\n // Check if we're at a shadow root\r\n if (currentElement && currentElement.nodeType !== Node.ELEMENT_NODE && currentElement.getRootNode() instanceof ShadowRoot) {\r\n // Get the shadow root's host element\r\n currentElement = currentElement.getRootNode().host; \r\n }\r\n }\r\n }\r\n \r\n return this.depth;\r\n }\r\n }\n\n // import { realpath } from \"fs\";\r\n\r\n function getAllDocumentElementsIncludingShadow(selectors, root = document) {\r\n const elements = Array.from(root.querySelectorAll(selectors));\r\n\r\n root.querySelectorAll('*').forEach(el => {\r\n if (el.shadowRoot) {\r\n elements.push(...getAllDocumentElementsIncludingShadow(selectors, el.shadowRoot));\r\n }\r\n });\r\n return elements;\r\n }\r\n\r\n function getAllFrames(root = document) {\r\n const result = [root];\r\n const frames = getAllDocumentElementsIncludingShadow('frame, iframe', root); \r\n frames.forEach(frame => {\r\n try {\r\n const frameDocument = frame.contentDocument || frame.contentWindow.document;\r\n if (frameDocument) {\r\n result.push(frameDocument);\r\n }\r\n } catch (e) {\r\n // Skip cross-origin frames\r\n console.warn('Could not access frame content:', e.message);\r\n }\r\n });\r\n\r\n return result;\r\n }\r\n\r\n function getAllElementsIncludingShadow(selectors, root = document) {\r\n const elements = [];\r\n\r\n getAllFrames(root).forEach(doc => {\r\n elements.push(...getAllDocumentElementsIncludingShadow(selectors, doc));\r\n });\r\n\r\n return elements;\r\n }\r\n\r\n /**\r\n * Deeply searches through DOM trees including Shadow DOM and frames/iframes\r\n * @param {string} selector - CSS selector to search for\r\n * @param {Document|Element} [root=document] - Starting point for the search\r\n * @param {Object} [options] - Search options\r\n * @param {boolean} [options.searchShadow=true] - Whether to search Shadow DOM\r\n * @param {boolean} [options.searchFrames=true] - Whether to search frames/iframes\r\n * @returns {Element[]} Array of found elements\r\n \r\n function getAllElementsIncludingShadow(selector, root = document, options = {}) {\r\n const {\r\n searchShadow = true,\r\n searchFrames = true\r\n } = options;\r\n\r\n const results = new Set();\r\n \r\n // Helper to check if an element is valid and not yet found\r\n const addIfValid = (element) => {\r\n if (element && !results.has(element)) {\r\n results.add(element);\r\n }\r\n };\r\n\r\n // Helper to process a single document or element\r\n function processNode(node) {\r\n // Search regular DOM\r\n node.querySelectorAll(selector).forEach(addIfValid);\r\n\r\n if (searchShadow) {\r\n // Search all shadow roots\r\n const treeWalker = document.createTreeWalker(\r\n node,\r\n NodeFilter.SHOW_ELEMENT,\r\n {\r\n acceptNode: (element) => {\r\n return element.shadowRoot ? \r\n NodeFilter.FILTER_ACCEPT : \r\n NodeFilter.FILTER_SKIP;\r\n }\r\n }\r\n );\r\n\r\n while (treeWalker.nextNode()) {\r\n const element = treeWalker.currentNode;\r\n if (element.shadowRoot) {\r\n // Search within shadow root\r\n element.shadowRoot.querySelectorAll(selector).forEach(addIfValid);\r\n // Recursively process the shadow root for nested shadow DOMs\r\n processNode(element.shadowRoot);\r\n }\r\n }\r\n }\r\n\r\n if (searchFrames) {\r\n // Search frames and iframes\r\n const frames = node.querySelectorAll('frame, iframe');\r\n frames.forEach(frame => {\r\n try {\r\n const frameDocument = frame.contentDocument;\r\n if (frameDocument) {\r\n processNode(frameDocument);\r\n }\r\n } catch (e) {\r\n // Skip cross-origin frames\r\n console.warn('Could not access frame content:', e.message);\r\n }\r\n });\r\n }\r\n }\r\n\r\n // Start processing from the root\r\n processNode(root);\r\n\r\n return Array.from(results);\r\n }\r\n */\r\n // <div x=1 y=2 role='combobox'> </div>\r\n function findDropdowns() {\r\n const dropdowns = [];\r\n \r\n // Native select elements\r\n dropdowns.push(...getAllElementsIncludingShadow('select'));\r\n \r\n // Elements with dropdown roles that don't have <input>..</input>\r\n const roleElements = getAllElementsIncludingShadow('[role=\"combobox\"], [role=\"listbox\"], [role=\"dropdown\"], [role=\"option\"], [role=\"menu\"], [role=\"menuitem\"]').filter(el => {\r\n return el.tagName.toLowerCase() !== 'input' || ![\"button\", \"checkbox\", \"radio\"].includes(el.getAttribute(\"type\"));\r\n });\r\n dropdowns.push(...roleElements);\r\n \r\n // Common dropdown class patterns\r\n const dropdownPattern = /.*(dropdown|select|combobox|menu).*/i;\r\n const elements = getAllElementsIncludingShadow('*');\r\n const dropdownClasses = Array.from(elements).filter(el => {\r\n const hasDropdownClass = dropdownPattern.test(el.className);\r\n const validTag = ['li', 'ul', 'span', 'div', 'p', 'a', 'button'].includes(el.tagName.toLowerCase());\r\n const style = window.getComputedStyle(el); \r\n const result = hasDropdownClass && validTag && (style.cursor === 'pointer' || el.tagName.toLowerCase() === 'a' || el.tagName.toLowerCase() === 'button');\r\n return result;\r\n });\r\n \r\n dropdowns.push(...dropdownClasses);\r\n \r\n // Elements with aria-haspopup attribute\r\n dropdowns.push(...getAllElementsIncludingShadow('[aria-haspopup=\"true\"], [aria-haspopup=\"listbox\"], [aria-haspopup=\"menu\"]'));\r\n\r\n // Improve navigation element detection\r\n // Semantic nav elements with list items\r\n dropdowns.push(...getAllElementsIncludingShadow('nav ul li, nav ol li'));\r\n \r\n // Navigation elements in common design patterns\r\n dropdowns.push(...getAllElementsIncludingShadow('header a, .header a, .nav a, .navigation a, .menu a, .sidebar a, aside a'));\r\n \r\n // Elements in primary navigation areas with common attributes\r\n dropdowns.push(...getAllElementsIncludingShadow('[role=\"navigation\"] a, [aria-label*=\"navigation\"] a, [aria-label*=\"menu\"] a'));\r\n\r\n return dropdowns;\r\n }\r\n\r\n function findClickables() {\r\n const clickables = [];\r\n \r\n const checkboxPattern = /checkbox/i;\r\n // Collect all clickable elements first\r\n const nativeLinks = [...getAllElementsIncludingShadow('a[href]')];\r\n const nativeButtons = [...getAllElementsIncludingShadow('button')];\r\n const inputButtons = [...getAllElementsIncludingShadow('input[type=\"button\"], input[type=\"submit\"], input[type=\"reset\"]')];\r\n const roleButtons = [...getAllElementsIncludingShadow('[role=\"button\"]')];\r\n // const tabbable = [...getAllElementsIncludingShadow('[tabindex=\"0\"]')];\r\n const clickHandlers = [...getAllElementsIncludingShadow('[onclick]')];\r\n const dropdowns = findDropdowns();\r\n const nativeCheckboxes = [...getAllElementsIncludingShadow('input[type=\"checkbox\"]')]; \r\n const fauxCheckboxes = getAllElementsIncludingShadow('*').filter(el => {\r\n if (checkboxPattern.test(el.className)) {\r\n const realCheckboxes = getAllElementsIncludingShadow('input[type=\"checkbox\"]', el);\r\n if (realCheckboxes.length === 1) {\r\n const boundingRect = realCheckboxes[0].getBoundingClientRect();\r\n return boundingRect.width <= 1 && boundingRect.height <= 1 \r\n }\r\n }\r\n return false;\r\n });\r\n const nativeRadios = [...getAllElementsIncludingShadow('input[type=\"radio\"]')];\r\n const toggles = findToggles();\r\n const pointerElements = findElementsWithPointer();\r\n // Add all elements at once\r\n clickables.push(\r\n ...nativeLinks,\r\n ...nativeButtons,\r\n ...inputButtons,\r\n ...roleButtons,\r\n // ...tabbable,\r\n ...clickHandlers,\r\n ...dropdowns,\r\n ...nativeCheckboxes,\r\n ...fauxCheckboxes,\r\n ...nativeRadios,\r\n ...toggles,\r\n ...pointerElements\r\n );\r\n\r\n // Only uniquify once at the end\r\n return clickables; // Let findElements handle the uniquification\r\n }\r\n\r\n function findToggles() {\r\n const toggles = [];\r\n const checkboxes = getAllElementsIncludingShadow('input[type=\"checkbox\"]');\r\n const togglePattern = /switch|toggle|slider/i;\r\n\r\n checkboxes.forEach(checkbox => {\r\n let isToggle = false;\r\n\r\n // Check the checkbox itself\r\n if (togglePattern.test(checkbox.className) || togglePattern.test(checkbox.getAttribute('role') || '')) {\r\n isToggle = true;\r\n }\r\n\r\n // Check parent elements (up to 3 levels)\r\n if (!isToggle) {\r\n let element = checkbox;\r\n for (let i = 0; i < 3; i++) {\r\n const parent = element.parentElement;\r\n if (!parent) break;\r\n\r\n const className = parent.className || '';\r\n const role = parent.getAttribute('role') || '';\r\n\r\n if (togglePattern.test(className) || togglePattern.test(role)) {\r\n isToggle = true;\r\n break;\r\n }\r\n element = parent;\r\n }\r\n }\r\n\r\n // Check next sibling\r\n if (!isToggle) {\r\n const nextSibling = checkbox.nextElementSibling;\r\n if (nextSibling) {\r\n const className = nextSibling.className || '';\r\n const role = nextSibling.getAttribute('role') || '';\r\n if (togglePattern.test(className) || togglePattern.test(role)) {\r\n isToggle = true;\r\n }\r\n }\r\n }\r\n\r\n if (isToggle) {\r\n toggles.push(checkbox);\r\n }\r\n });\r\n\r\n return toggles;\r\n }\r\n\r\n function findNonInteractiveElements() {\r\n // Get all elements in the document\r\n const all = Array.from(getAllElementsIncludingShadow('*'));\r\n \r\n // Filter elements based on Python implementation rules\r\n return all.filter(element => {\r\n if (!element.firstElementChild) {\r\n const tag = element.tagName.toLowerCase(); \r\n if (!['select', 'button', 'a'].includes(tag)) {\r\n const validTags = ['p', 'span', 'div', 'input', 'textarea'].includes(tag) || /^h\\d$/.test(tag) || /text/.test(tag);\r\n const boundingRect = element.getBoundingClientRect();\r\n return validTags && boundingRect.height > 1 && boundingRect.width > 1;\r\n }\r\n }\r\n return false;\r\n });\r\n }\r\n\r\n\r\n\r\n // export function findNonInteractiveElements() {\r\n // const all = [];\r\n // try {\r\n // const elements = getAllElementsIncludingShadow('*');\r\n // all.push(...elements);\r\n // } catch (e) {\r\n // console.warn('Error getting elements:', e);\r\n // }\r\n \r\n // console.debug('Total elements found:', all.length);\r\n \r\n // return all.filter(element => {\r\n // try {\r\n // const tag = element.tagName.toLowerCase(); \r\n\r\n // // Special handling for input elements\r\n // if (tag === 'input' || tag === 'textarea') {\r\n // const boundingRect = element.getBoundingClientRect();\r\n // const value = element.value || '';\r\n // const placeholder = element.placeholder || '';\r\n // return boundingRect.height > 1 && \r\n // boundingRect.width > 1 && \r\n // (value.trim() !== '' || placeholder.trim() !== '');\r\n // }\r\n\r\n \r\n // // Check if it's a valid tag for text content\r\n // const validTags = ['p', 'span', 'div', 'label', 'th', 'td', 'li', 'button', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'a', 'select'].includes(tag) || \r\n // /^h\\d$/.test(tag) || \r\n // /text/.test(tag);\r\n\r\n // const boundingRect = element.getBoundingClientRect();\r\n\r\n // // Get direct text content, excluding child element text\r\n // let directText = '';\r\n // for (const node of element.childNodes) {\r\n // // Only include text nodes (nodeType 3)\r\n // if (node.nodeType === 3) {\r\n // directText += node.textContent || '';\r\n // }\r\n // }\r\n \r\n // // If no direct text and it's a table cell or heading, check label content\r\n // if (!directText.trim() && (tag === 'th' || tag === 'td' || tag === 'h1')) {\r\n // const labels = element.getElementsByTagName('label');\r\n // for (const label of labels) {\r\n // directText += label.textContent || '';\r\n // }\r\n // }\r\n\r\n // // If still no text and it's a heading, get all text content\r\n // if (!directText.trim() && tag === 'h1') {\r\n // directText = element.textContent || '';\r\n // }\r\n\r\n // directText = directText.trim();\r\n\r\n // // Debug logging\r\n // if (directText) {\r\n // console.debugg('Text element found:', {\r\n // tag,\r\n // text: directText,\r\n // dimensions: boundingRect,\r\n // element\r\n // });\r\n // }\r\n\r\n // return validTags && \r\n // boundingRect.height > 1 && \r\n // boundingRect.width > 1 && \r\n // directText !== '';\r\n \r\n // } catch (e) {\r\n // console.warn('Error processing element:', e);\r\n // return false;\r\n // }\r\n // });\r\n // }\r\n\r\n\r\n\r\n\r\n\r\n function findElementsWithPointer() {\r\n const elements = [];\r\n const allElements = getAllElementsIncludingShadow('*');\r\n \r\n console.log('Checking elements with pointer style...');\r\n \r\n allElements.forEach(element => {\r\n // Skip SVG elements for now\r\n if (element instanceof SVGElement || element.tagName.toLowerCase() === 'svg') {\r\n return;\r\n }\r\n \r\n const style = window.getComputedStyle(element);\r\n if (style.cursor === 'pointer') {\r\n elements.push(element);\r\n }\r\n });\r\n \r\n console.log(`Found ${elements.length} elements with pointer cursor`);\r\n return elements;\r\n }\r\n\r\n function findCheckables() {\r\n const elements = [];\r\n\r\n elements.push(...getAllElementsIncludingShadow('input[type=\"checkbox\"]'));\r\n elements.push(...getAllElementsIncludingShadow('input[type=\"radio\"]'));\r\n const all_elements = getAllElementsIncludingShadow('label');\r\n const radioClasses = Array.from(all_elements).filter(el => {\r\n return /.*radio.*/i.test(el.className); \r\n });\r\n elements.push(...radioClasses);\r\n return elements;\r\n }\r\n\r\n function findFillables() {\r\n const elements = [];\r\n\r\n const inputs = [...getAllElementsIncludingShadow('input:not([type=\"radio\"]):not([type=\"checkbox\"])')];\r\n console.log('Found inputs:', inputs.length, inputs);\r\n elements.push(...inputs);\r\n \r\n const textareas = [...getAllElementsIncludingShadow('textarea')];\r\n console.log('Found textareas:', textareas.length);\r\n elements.push(...textareas);\r\n \r\n const editables = [...getAllElementsIncludingShadow('[contenteditable=\"true\"]')];\r\n console.log('Found editables:', editables.length);\r\n elements.push(...editables);\r\n\r\n return elements;\r\n }\n\n // Helper function to check if element is a form control\r\n function isFormControl(elementInfo) {\r\n return /^(input|select|textarea|button|label)$/i.test(elementInfo.tag);\r\n }\r\n\r\n const isDropdownItem = (elementInfo) => {\r\n const dropdownPatterns = [\r\n /dropdown[-_]?item/i, // matches: dropdown-item, dropdownitem, dropdown_item\r\n /menu[-_]?item/i, // matches: menu-item, menuitem, menu_item\r\n /dropdown[-_]?link/i, // matches: dropdown-link, dropdownlink, dropdown_link\r\n /list[-_]?item/i, // matches: list-item, listitem, list_item\r\n /select[-_]?item/i, // matches: select-item, selectitem, select_item \r\n ];\r\n\r\n const rolePatterns = [\r\n /menu[-_]?item/i, // matches: menuitem, menu-item\r\n /option/i, // matches: option\r\n /list[-_]?item/i, // matches: listitem, list-item\r\n /tree[-_]?item/i // matches: treeitem, tree-item\r\n ];\r\n\r\n const hasMatchingClass = elementInfo.element.className && \r\n dropdownPatterns.some(pattern => \r\n pattern.test(elementInfo.element.className)\r\n );\r\n\r\n const hasMatchingRole = elementInfo.element.getAttribute('role') && \r\n rolePatterns.some(pattern => \r\n pattern.test(elementInfo.element.getAttribute('role'))\r\n );\r\n\r\n return hasMatchingClass || hasMatchingRole;\r\n };\r\n\r\n /**\r\n * Finds the first element matching a CSS selector, traversing Shadow DOM if necessary\r\n * @param {string} selector - CSS selector to search for\r\n * @param {Element} [root=document] - Root element to start searching from\r\n * @returns {Element|null} - The first matching element or null if not found\r\n */\r\n function querySelectorShadow(selector, root = document) {\r\n // First try to find in light DOM\r\n let element = root.querySelector(selector);\r\n if (element) return element;\r\n \r\n // Get all elements with shadow root\r\n const shadowElements = Array.from(root.querySelectorAll('*'))\r\n .filter(el => el.shadowRoot);\r\n \r\n // Search through each shadow root until we find a match\r\n for (const el of shadowElements) {\r\n element = querySelectorShadow(selector, el.shadowRoot);\r\n if (element) return element;\r\n }\r\n \r\n return null;\r\n }\r\n\r\n const getElementByXPathOrCssSelector = (element_info) => {\r\n let element;\r\n\r\n console.log('getElementByXPathOrCssSelector:', element_info);\r\n // if (element_info.xpath) { //try xpath if exists\r\n // element = document.evaluate(\r\n // element_info.xpath, \r\n // document, \r\n // null, \r\n // XPathResult.FIRST_ORDERED_NODE_TYPE, \r\n // null\r\n // ).singleNodeValue;\r\n \r\n // if (!element) {\r\n // console.warn('Failed to find element with xpath:', element_info.xpath);\r\n // }\r\n // }\r\n // else { //try CSS selector\r\n if (element_info.iframe_selector) {\r\n console.log('elementInfo with iframe: ', element_info);\r\n const frames = getAllDocumentElementsIncludingShadow('iframe');\r\n \r\n // Iterate over all frames and compare their CSS selectors\r\n for (const frame of frames) {\r\n const cssSelector = generateCssPath(frame);\r\n if (cssSelector === element_info.iframe_selector) {\r\n const frameDocument = frame.contentDocument || frame.contentWindow.document;\r\n element = querySelectorShadow(element_info.css_selector, frameDocument);\r\n console.log('found element ', element);\r\n break;\r\n } \r\n } }\r\n else\r\n element = querySelectorShadow(element_info.css_selector);\r\n // console.log('found element by CSS elector: ', element);\r\n if (!element) {\r\n console.warn('Failed to find element with CSS selector:', element_info.css_selector);\r\n }\r\n // }\r\n\r\n return element;\r\n };\r\n\r\n function generateXPath(element) {\r\n if (!element || element.getRootNode() instanceof ShadowRoot) return '';\r\n \r\n // If element has an id, use that (it's unique and shorter)\r\n if (element.id) {\r\n return `//*[@id=\"${element.id}\"]`;\r\n }\r\n \r\n const parts = [];\r\n let current = element;\r\n \r\n while (current && current.nodeType === Node.ELEMENT_NODE) {\r\n let index = 1;\r\n let sibling = current.previousSibling;\r\n \r\n while (sibling) {\r\n if (sibling.nodeType === Node.ELEMENT_NODE && sibling.tagName === current.tagName) {\r\n index++;\r\n }\r\n sibling = sibling.previousSibling;\r\n }\r\n \r\n const tagName = current.tagName.toLowerCase();\r\n parts.unshift(`${tagName}[${index}]`);\r\n current = current.parentNode;\r\n }\r\n \r\n return '/' + parts.join('/');\r\n }\r\n\r\n function isDecendent(parent, child) {\r\n let element = child;\r\n while (element.nodeType === Node.ELEMENT_NODE) { \r\n \r\n if (element.assignedSlot) {\r\n element = element.assignedSlot;\r\n }\r\n else {\r\n element = element.parentNode;\r\n // Check if we're at a shadow root\r\n if (element && element.nodeType !== Node.ELEMENT_NODE && element.getRootNode() instanceof ShadowRoot) {\r\n // Get the shadow root's host element\r\n element = element.getRootNode().host; \r\n }\r\n }\r\n if (element === parent)\r\n return true;\r\n }\r\n return false;\r\n }\r\n\r\n function generateCssPath(element) {\r\n if (!element) {\r\n console.error('ERROR: No element provided to generateCssPath returning empty string');\r\n return '';\r\n }\r\n const path = [];\r\n // console.group('Generating CSS path for:', element);\r\n while (element && element.nodeType === Node.ELEMENT_NODE) { \r\n let selector = element.nodeName.toLowerCase();\r\n // console.log('Element:', selector, element);\r\n \r\n // if (element.id) {\r\n // //escape special characters\r\n // const normalized_id = element.id.replace(/[:;.#()[\\]!@$%^&*]/g, '\\\\$&');\r\n // selector = `#${normalized_id}`;\r\n // path.unshift(selector);\r\n // break;\r\n // } \r\n \r\n let sibling = element;\r\n let nth = 1;\r\n while (sibling = sibling.previousElementSibling) {\r\n if (sibling.nodeName.toLowerCase() === selector) nth++;\r\n }\r\n sibling = element;\r\n while (sibling = sibling.nextElementSibling) {\r\n if (sibling.nodeName.toLowerCase() === selector) {\r\n break;\r\n }\r\n }\r\n selector += `:nth-of-type(${nth})`;\r\n \r\n \r\n path.unshift(selector);\r\n //console.log(` Current path: ${path.join(' > ')}`);\r\n\r\n if (element.assignedSlot) {\r\n element = element.assignedSlot;\r\n // console.log(' Moving to assigned slot');\r\n }\r\n else {\r\n element = element.parentNode;\r\n // console.log(' Moving to parent:', element);\r\n\r\n // Check if we're at a shadow root\r\n if (element && element.nodeType !== Node.ELEMENT_NODE && element.getRootNode() instanceof ShadowRoot) {\r\n console.log(' Found shadow root, moving to host');\r\n // Get the shadow root's host element\r\n element = element.getRootNode().host; \r\n }\r\n }\r\n }\r\n \r\n // console.log('Final selector:', path.join(' > '));\r\n // console.groupEnd();\r\n return path.join(' > ');\r\n }\r\n\r\n\r\n function cleanHTML(rawHTML) {\r\n const parser = new DOMParser();\r\n const doc = parser.parseFromString(rawHTML, \"text/html\");\r\n\r\n function cleanElement(element) {\r\n const allowedAttributes = new Set([\r\n \"role\",\r\n \"type\",\r\n \"class\",\r\n \"href\",\r\n \"alt\",\r\n \"title\",\r\n \"readonly\",\r\n \"checked\",\r\n \"enabled\",\r\n \"disabled\",\r\n ]);\r\n\r\n [...element.attributes].forEach(attr => {\r\n const name = attr.name.toLowerCase();\r\n const value = attr.value;\r\n\r\n const isTestAttribute = /^(testid|test-id|data-test-id)$/.test(name);\r\n const isDataAttribute = name.startsWith(\"data-\") && value;\r\n const isBooleanAttribute = [\"readonly\", \"checked\", \"enabled\", \"disabled\"].includes(name);\r\n\r\n if (!allowedAttributes.has(name) && !isDataAttribute && !isTestAttribute && !isBooleanAttribute) {\r\n element.removeAttribute(name);\r\n }\r\n });\r\n\r\n // Handle SVG content - more aggressive replacement\r\n if (element.tagName.toLowerCase() === \"svg\") {\r\n // Remove all attributes except class and role\r\n [...element.attributes].forEach(attr => {\r\n const name = attr.name.toLowerCase();\r\n if (name !== \"class\" && name !== \"role\") {\r\n element.removeAttribute(name);\r\n }\r\n });\r\n element.innerHTML = \"CONTENT REMOVED\";\r\n } else {\r\n // Recursively clean child elements\r\n Array.from(element.children).forEach(cleanElement);\r\n }\r\n\r\n // Only remove empty elements that aren't semantic or icon elements\r\n const keepEmptyElements = ['i', 'span', 'svg', 'button', 'input'];\r\n if (!keepEmptyElements.includes(element.tagName.toLowerCase()) && \r\n !element.children.length && \r\n !element.textContent.trim()) {\r\n element.remove();\r\n }\r\n }\r\n\r\n // Process all elements in the document body\r\n Array.from(doc.body.children).forEach(cleanElement);\r\n return doc.body.innerHTML;\r\n }\r\n\r\n function getContainingIframe(element) {\r\n // If not in an iframe, return null\r\n if (element.ownerDocument.defaultView === window.top) {\r\n return null;\r\n }\r\n \r\n // Try to find the iframe in the parent document that contains our element\r\n try {\r\n const parentDocument = element.ownerDocument.defaultView.parent.document;\r\n const iframes = parentDocument.querySelectorAll('iframe');\r\n \r\n for (const iframe of iframes) {\r\n if (iframe.contentWindow === element.ownerDocument.defaultView) {\r\n return iframe;\r\n }\r\n }\r\n } catch (e) {\r\n // Cross-origin restriction\r\n return \"Cross-origin iframe - cannot access details\";\r\n }\r\n \r\n return null;\r\n }\r\n\r\n function getElementInfo(element, index) {\r\n\r\n const xpath = generateXPath(element);\r\n const css_selector = generateCssPath(element);\r\n\r\n const iframe = getContainingIframe(element);\r\n const iframe_selector = iframe ? generateCssPath(iframe) : \"\";\r\n\r\n // Return element info with pre-calculated values\r\n return new ElementInfo(element, index, {\r\n tag: element.tagName.toLowerCase(),\r\n type: element.type || '',\r\n text: element.innerText, //getTextContent(element),\r\n html: cleanHTML(element.outerHTML),\r\n xpath: xpath,\r\n css_selector: css_selector,\r\n bounding_box: element.getBoundingClientRect(),\r\n iframe_selector: iframe_selector\r\n });\r\n }\r\n\r\n\r\n\r\n\r\n const filterZeroDimensions = (elementInfo) => {\r\n const rect = elementInfo.bounding_box;\r\n //single pixel elements are typically faux controls and should be filtered too\r\n const hasSize = rect.width > 1 && rect.height > 1;\r\n const style = window.getComputedStyle(elementInfo.element);\r\n const isVisible = style.display !== 'none' && style.visibility !== 'hidden';\r\n \r\n if (!hasSize || !isVisible) {\r\n // if (elementInfo.element.isConnected) {\r\n // console.log('Filtered out invisible/zero-size element:', {\r\n // tag: elementInfo.tag,\r\n // xpath: elementInfo.xpath,\r\n // element: elementInfo.element,\r\n // hasSize,\r\n // isVisible,\r\n // dimensions: rect\r\n // });\r\n // }\r\n return false;\r\n }\r\n return true;\r\n };\r\n\r\n\r\n\r\n function uniquifyElements(elements) {\r\n const seen = new Set();\r\n\r\n console.log(`Starting uniquification with ${elements.length} elements`);\r\n\r\n // Filter out testing infrastructure elements first\r\n const filteredInfrastructure = elements.filter(element_info => {\r\n // Skip the highlight-overlay element completely - it's part of the testing infrastructure\r\n if (element_info.element.id === 'highlight-overlay' || \r\n (element_info.css_selector && element_info.css_selector.includes('#highlight-overlay'))) {\r\n console.log('Filtered out testing infrastructure element:', element_info.css_selector);\r\n return false;\r\n }\r\n \r\n // Filter out UI framework container/manager elements\r\n const el = element_info.element;\r\n // UI framework container checks - generic detection for any framework\r\n if ((el.getAttribute('data-rendered-by') || \r\n el.getAttribute('data-reactroot') || \r\n el.getAttribute('ng-version') || \r\n el.getAttribute('data-component-id') ||\r\n el.getAttribute('data-root') ||\r\n el.getAttribute('data-framework')) && \r\n (el.className && \r\n typeof el.className === 'string' && \r\n (el.className.includes('Container') || \r\n el.className.includes('container') || \r\n el.className.includes('Manager') || \r\n el.className.includes('manager')))) {\r\n console.log('Filtered out UI framework container element:', element_info.css_selector);\r\n return false;\r\n }\r\n \r\n // Direct filter for framework container elements that shouldn't be interactive\r\n // Consolidating multiple container detection patterns into one efficient check\r\n const isFullViewport = element_info.bounding_box && \r\n element_info.bounding_box.x <= 5 && \r\n element_info.bounding_box.y <= 5 && \r\n element_info.bounding_box.width >= (window.innerWidth * 0.95) && \r\n element_info.bounding_box.height >= (window.innerHeight * 0.95);\r\n \r\n // Empty content check\r\n const isEmpty = !el.innerText || el.innerText.trim() === '';\r\n \r\n // Check if it's a framework container element\r\n if (element_info.element.tagName === 'DIV' && \r\n isFullViewport && \r\n isEmpty && \r\n (\r\n // Pattern matching for root containers\r\n (element_info.xpath && \r\n (element_info.xpath.match(/^\\/html\\[\\d+\\]\\/body\\[\\d+\\]\\/div\\[\\d+\\]\\/div\\[\\d+\\]$/) || \r\n element_info.xpath.match(/^\\/\\/\\*\\[@id='[^']+'\\]\\/div\\[\\d+\\]$/))) ||\r\n \r\n // Simple DOM structure\r\n (element_info.css_selector.split(' > ').length <= 4 && element_info.depth <= 5) ||\r\n \r\n // Empty or container-like classes\r\n (!el.className || el.className === '' || \r\n (typeof el.className === 'string' && \r\n (el.className.includes('overlay') || \r\n el.className.includes('container') || \r\n el.className.includes('wrapper'))))\r\n )) {\r\n console.log('Filtered out framework container element:', element_info.css_selector);\r\n return false;\r\n }\r\n \r\n return true;\r\n });\r\n\r\n // First filter out elements with zero dimensions\r\n const nonZeroElements = filteredInfrastructure.filter(filterZeroDimensions);\r\n // sort by CSS selector depth so parents are processed first\r\n nonZeroElements.sort((a, b) => a.getDepth() - b.getDepth());\r\n console.log(`After dimension filtering: ${nonZeroElements.length} elements remain (${elements.length - nonZeroElements.length} removed)`);\r\n \r\n const filteredByParent = nonZeroElements.filter(element_info => {\r\n\r\n const parent = findClosestParent(seen, element_info);\r\n const keep = parent == null || shouldKeepNestedElement(element_info, parent);\r\n // console.log(\"node \", element_info.index, \": keep=\", keep, \" parent=\", parent);\r\n // if (!keep && !element_info.xpath) {\r\n // console.log(\"Filtered out element \", element_info,\" because it's a nested element of \", parent);\r\n // }\r\n if (keep)\r\n seen.add(element_info.css_selector);\r\n\r\n return keep;\r\n });\r\n\r\n console.log(`After parent/child filtering: ${filteredByParent.length} elements remain (${nonZeroElements.length - filteredByParent.length} removed)`);\r\n\r\n // Final overlap filtering\r\n const filteredResults = filteredByParent.filter(element => {\r\n\r\n // Look for any element that came BEFORE this one in the array\r\n const hasEarlierOverlap = filteredByParent.some(other => {\r\n // Only check elements that came before (lower index)\r\n if (filteredByParent.indexOf(other) >= filteredByParent.indexOf(element)) {\r\n return false;\r\n }\r\n \r\n const isOverlapping = areElementsOverlapping(element, other); \r\n return isOverlapping;\r\n }); \r\n\r\n // Keep element if it has no earlier overlapping elements\r\n return !hasEarlierOverlap;\r\n });\r\n \r\n \r\n \r\n // Check for overlay removal\r\n console.log(`After filtering: ${filteredResults.length} (${filteredByParent.length - filteredResults.length} removed by overlap)`);\r\n \r\n const nonOverlaidElements = filteredResults.filter(element => {\r\n return !isOverlaid(element);\r\n });\r\n\r\n console.log(`Final elements after overlay removal: ${nonOverlaidElements.length} (${filteredResults.length - nonOverlaidElements.length} removed)`);\r\n \r\n return nonOverlaidElements;\r\n\r\n }\r\n\r\n\r\n\r\n const areElementsOverlapping = (element1, element2) => {\r\n if (element1.css_selector === element2.css_selector) {\r\n return true;\r\n }\r\n \r\n const box1 = element1.bounding_box;\r\n const box2 = element2.bounding_box;\r\n \r\n return box1.x === box2.x &&\r\n box1.y === box2.y &&\r\n box1.width === box2.width &&\r\n box1.height === box2.height;\r\n // element1.text === element2.text &&\r\n // element2.tag === 'a';\r\n };\r\n\r\n function findClosestParent(seen, element_info) { \r\n // //Use element child/parent queries\r\n // let parent = element_info.element.parentNode;\r\n // if (parent.getRootNode() instanceof ShadowRoot) {\r\n // // Get the shadow root's host element\r\n // parent = parent.getRootNode().host; \r\n // }\r\n\r\n // while (parent.nodeType === Node.ELEMENT_NODE) { \r\n // const css_selector = generateCssPath(parent);\r\n // if (seen.has(css_selector)) {\r\n // console.log(\"element \", element_info, \" closest parent is \", parent)\r\n // return parent; \r\n // }\r\n // parent = parent.parentNode;\r\n // if (parent.getRootNode() instanceof ShadowRoot) {\r\n // // Get the shadow root's host element\r\n // parent = parent.getRootNode().host; \r\n // }\r\n // }\r\n\r\n // Split the xpath into segments\r\n const segments = element_info.css_selector.split(' > ');\r\n \r\n // Try increasingly shorter paths until we find one in the seen set\r\n for (let i = segments.length - 1; i > 0; i--) {\r\n const parentPath = segments.slice(0, i).join(' > ');\r\n if (seen.has(parentPath)) {\r\n return parentPath;\r\n }\r\n }\r\n\r\n return null;\r\n }\r\n\r\n function shouldKeepNestedElement(elementInfo, parentPath) {\r\n let result = false;\r\n const parentSegments = parentPath.split(' > ');\r\n\r\n const isParentLink = /^a(:nth-of-type\\(\\d+\\))?$/.test(parentSegments[parentSegments.length - 1]);\r\n if (isParentLink) {\r\n return false; \r\n }\r\n // If this is a checkbox/radio input\r\n if (elementInfo.tag === 'input' && \r\n (elementInfo.type === 'checkbox' || elementInfo.type === 'radio')) {\r\n \r\n // Check if parent is a label by looking at the parent xpath's last segment\r\n \r\n const isParentLabel = /^label(:nth-of-type\\(\\d+\\))?$/.test(parentSegments[parentSegments.length - 1]);\r\n \r\n // If parent is a label, don't keep the input (we'll keep the label instead)\r\n if (isParentLabel) {\r\n return false;\r\n }\r\n }\r\n \r\n // Keep all other form controls and dropdown items\r\n if (isFormControl(elementInfo) || isDropdownItem(elementInfo)) {\r\n result = true;\r\n }\r\n \r\n // console.log(`shouldKeepNestedElement: ${elementInfo.tag} ${elementInfo.text} ${elementInfo.xpath} -> ${parentXPath} -> ${result}`);\r\n return result;\r\n }\r\n\r\n\r\n\r\n function isOverlaid(elementInfo) {\r\n const element = elementInfo.element;\r\n const boundingRect = element.getBoundingClientRect();\r\n \r\n\r\n \r\n \r\n // Create a diagnostic logging function that only logs when needed\r\n const diagnosticLog = (...args) => {\r\n };\r\n\r\n // Special handling for tooltips\r\n if (elementInfo.element.className && typeof elementInfo.element.className === 'string' && \r\n elementInfo.element.className.includes('tooltip')) {\r\n return false;\r\n }\r\n \r\n // Special handling for deep component hierarchies\r\n const cssSelector = elementInfo.css_selector;\r\n \r\n // Identify complex components with deep hierarchy (important for Shadow DOM components)\r\n const isComplexComponent = cssSelector.length > 500 || \r\n (cssSelector.includes('slot:nth-of-type') && \r\n cssSelector.split('>').length > 15);\r\n \r\n // Special handling for deep component buttons in any framework\r\n const isFrameworkButton = cssSelector.split('>').length > 10 && \r\n cssSelector.includes('button:nth-of-type');\r\n \r\n if (isComplexComponent || isFrameworkButton) {\r\n // Check if the element is visible on screen\r\n if (boundingRect.width > 0 && \r\n boundingRect.height > 0 && \r\n boundingRect.bottom > 0 && \r\n boundingRect.right > 0 &&\r\n boundingRect.top < window.innerHeight &&\r\n boundingRect.left < window.innerWidth) {\r\n \r\n // Get element at the center point to check if it's covered by a popup/modal\r\n const middleX = boundingRect.x + boundingRect.width/2;\r\n const middleY = boundingRect.y + boundingRect.height/2;\r\n const elementAtMiddle = element.ownerDocument.elementFromPoint(middleX, middleY);\r\n \r\n if (elementAtMiddle && \r\n elementAtMiddle !== element && \r\n !isDecendent(element, elementAtMiddle) && \r\n !isDecendent(elementAtMiddle, element)) {\r\n // Make sure it doesn't have CSS that would hide it\r\n const style = window.getComputedStyle(element);\r\n if (style.display !== 'none' && \r\n style.visibility !== 'hidden' && \r\n style.opacity !== '0') {\r\n diagnosticLog('Style properties:', { \r\n display: style.display, \r\n visibility: style.visibility, \r\n opacity: style.opacity \r\n });\r\n return false; // It's visible and not covered, so not overlaid\r\n }\r\n }\r\n \r\n // Check specifically if the element at middle is a popup/modal\r\n if (elementAtMiddle && isElementOrAncestorPopup(elementAtMiddle)) {\r\n return true; // It's under a popup, so it is overlaid\r\n }\r\n }\r\n }\r\n \r\n // Function to check if an element is likely a popup/modal/dialog\r\n function isLikelyPopupOrModal(el) {\r\n if (!el) return false;\r\n \r\n try {\r\n // First check if this is actually a navigation element - we don't want to\r\n // misidentify navigation elements as popups\r\n if (isLikelyNavElement(el)) {\r\n return false;\r\n }\r\n \r\n // Navigation elements can still be overlaid - remove the automatic exclusion\r\n \r\n const rect = el.getBoundingClientRect();\r\n const style = window.getComputedStyle(el);\r\n \r\n // Quick checks first to fail fast\r\n const position = style.position;\r\n if (position !== 'fixed' && position !== 'absolute') {\r\n return false;\r\n }\r\n \r\n // Check tag name and role - very fast checks\r\n const isDialogElement = el.tagName.toLowerCase() === 'dialog';\r\n const hasDialogRole = el.getAttribute('role') === 'dialog' || el.getAttribute('role') === 'alertdialog';\r\n \r\n if (isDialogElement || hasDialogRole) {\r\n return true;\r\n }\r\n \r\n // Class name checks are unreliable as they depend entirely on developer conventions\r\n // We rely on structural properties instead\r\n \r\n // Most expensive checks last\r\n const zIndex = parseInt(style.zIndex, 10);\r\n const hasHighZIndex = !isNaN(zIndex) && zIndex > 100;\r\n \r\n // Size check for modals - they typically cover a significant portion of the screen\r\n // Navigation elements at the top are usually not this large\r\n const isSizeOfModal = rect.width > (window.innerWidth * 0.5) && \r\n rect.height > (window.innerHeight * 0.3) &&\r\n // Additional check: modals are usually not at the very top of the page\r\n rect.top > 50;\r\n \r\n return (hasHighZIndex && position === 'fixed' && rect.top > 50) || \r\n (isSizeOfModal && position === 'fixed');\r\n } catch (e) {\r\n return false;\r\n }\r\n }\r\n \r\n // Renamed from isLikelyTopNavElement to isLikelyNavElement since it detects navigation anywhere\r\n function isLikelyNavElement(el) {\r\n if (!el) return false;\r\n \r\n try {\r\n // Don't restrict navigation detection based on top position\r\n \r\n // Check tag names associated with navigation\r\n const tagName = el.tagName.toLowerCase();\r\n if (tagName === 'nav' || tagName === 'header') {\r\n return true;\r\n }\r\n \r\n // Check for navigation roles\r\n const role = el.getAttribute('role');\r\n if (role === 'navigation') {\r\n return true;\r\n }\r\n \r\n // Check for navigation-related class names - strong indicator\r\n const className = typeof el.className === 'string' ? el.className.toLowerCase() : '';\r\n if (className.includes('navbar') ||\r\n className.includes('navigation') ||\r\n className.includes('header') ||\r\n className.includes('nav-') ||\r\n className.includes('-nav') ||\r\n className.includes('sidebar') ||\r\n className.includes('menu')) {\r\n return true;\r\n }\r\n \r\n // Check for tab items (common in navigation)\r\n if (el.tagName === 'SPAN' && \r\n (el.classList.contains('tab') || \r\n el.classList.contains('nav'))) {\r\n return true;\r\n }\r\n \r\n return false;\r\n } catch (e) {\r\n return false;\r\n }\r\n }\r\n \r\n // Function to check if an element or any of its ancestors are part of top navigation\r\n function isElementOrAncestorTopNav(el, maxDepth = 4) {\r\n if (!el) return false;\r\n \r\n // Check self first - most common case\r\n if (isLikelyNavElement(el)) {\r\n return true;\r\n }\r\n \r\n // Then check ancestors if needed\r\n let current = el.parentElement;\r\n let depth = 1; // Start at 1 since we already checked self\r\n \r\n while (current && depth < maxDepth) {\r\n if (isLikelyNavElement(current)) {\r\n return true;\r\n }\r\n current = current.parentElement;\r\n depth++;\r\n }\r\n \r\n return false;\r\n }\r\n \r\n // Function to check if an element or any of its ancestors are a popup/modal\r\n function isElementOrAncestorPopup(el, maxDepth = 4) {\r\n if (!el) return false;\r\n \r\n // Check self first - most common case\r\n if (isLikelyPopupOrModal(el)) {\r\n return true;\r\n }\r\n \r\n // Then check ancestors if needed\r\n let current = el.parentElement;\r\n let depth = 1; // Start at 1 since we already checked self\r\n \r\n while (current && depth < maxDepth) {\r\n if (isLikelyPopupOrModal(current)) {\r\n return true;\r\n }\r\n current = current.parentElement;\r\n depth++;\r\n }\r\n \r\n return false;\r\n }\r\n \r\n // Check if element is at the top of the viewport\r\n const isNearTopOfViewport = boundingRect.top >= 0 && boundingRect.top < 100;\r\n \r\n // For elements near the top of the viewport, we need a special case\r\n // that handles fixed position elements at the top of the viewport\r\n if (isNearTopOfViewport) {\r\n // Get element at middle point of the row\r\n const middleX = boundingRect.x + boundingRect.width/2;\r\n const middleY = boundingRect.y + boundingRect.height/2;\r\n const elementAtMiddle = element.ownerDocument.elementFromPoint(middleX, middleY);\r\n \r\n // If we found an element and it's not the row itself or a descendant/ancestor\r\n if (elementAtMiddle && \r\n elementAtMiddle !== element && \r\n !isDecendent(element, elementAtMiddle) && \r\n !isDecendent(elementAtMiddle, element)) {\r\n \r\n // First check if the overlaying element is part of a popup/modal\r\n // If so, the element IS overlaid (regardless of whether it's also under nav)\r\n if (isElementOrAncestorPopup(elementAtMiddle)) {\r\n /* Debug code - commented out\r\n if (isRowToDebug) {\r\n console.log('Element is under a popup/modal');\r\n console.log('Final overlay decision: OVERLAID');\r\n console.log('-------------------------------------------');\r\n }\r\n */\r\n return true;\r\n }\r\n \r\n // Additional check specifically for the problematic span elements in debug logs\r\n if (elementAtMiddle.tagName === 'SPAN' && \r\n elementAtMiddle.className && \r\n typeof elementAtMiddle.className === 'string' && \r\n (elementAtMiddle.className.includes('tab') || \r\n elementAtMiddle.className.includes('nav'))) {\r\n /* Debug code - commented out\r\n if (isRowToDebug) {\r\n console.log('Element is under a navigation tab element');\r\n console.log('Final overlay decision: NOT OVERLAID');\r\n console.log('-------------------------------------------');\r\n }\r\n */\r\n return false;\r\n }\r\n \r\n // Check if the overlaying element is part of top navigation\r\n if (isElementOrAncestorTopNav(elementAtMiddle)) {\r\n /* Debug code - commented out\r\n if (isRowToDebug) {\r\n console.log('Element is under a top navigation element');\r\n console.log('Final overlay decision: NOT OVERLAID');\r\n console.log('-------------------------------------------');\r\n }\r\n */\r\n return false;\r\n }\r\n }\r\n }\r\n \r\n // Check if element is mostly or completely outside the viewport\r\n const viewportHeight = window.innerHeight;\r\n const viewportWidth = window.innerWidth;\r\n const elementHeight = boundingRect.height;\r\n const elementWidth = boundingRect.width;\r\n \r\n // Calculate how much of the element is visible in the viewport\r\n const visibleTop = Math.max(0, boundingRect.top);\r\n const visibleBottom = Math.min(viewportHeight, boundingRect.bottom);\r\n const visibleLeft = Math.max(0, boundingRect.left);\r\n const visibleRight = Math.min(viewportWidth, boundingRect.right);\r\n \r\n // Calculate visible area\r\n const visibleHeight = Math.max(0, visibleBottom - visibleTop);\r\n const visibleWidth = Math.max(0, visibleRight - visibleLeft);\r\n const visibleArea = visibleHeight * visibleWidth;\r\n const totalArea = elementHeight * elementWidth;\r\n \r\n // Check if less than half of the element is visible in the viewport\r\n const isPartiallyOffScreen = visibleArea < (totalArea / 2);\r\n \r\n // If the element is mostly offscreen, don't consider it overlaid - this avoids\r\n // false positives from elements near viewport boundaries\r\n if (isPartiallyOffScreen) {\r\n return false;\r\n }\r\n \r\n // Track if we find any popup elements covering our element\r\n let isUnderPopup = false;\r\n \r\n // Check multiple points to improve cross-browser consistency\r\n const points = [\r\n { x: boundingRect.x + boundingRect.width/2, y: boundingRect.y + boundingRect.height/2 }, // Center\r\n { x: boundingRect.x + 5, y: boundingRect.y + 5 }, // Top-left\r\n { x: boundingRect.x + boundingRect.width - 5, y: boundingRect.y + 5 }, // Top-right\r\n { x: boundingRect.x + 5, y: boundingRect.y + boundingRect.height - 5 }, // Bottom-left\r\n { x: boundingRect.x + boundingRect.width - 5, y: boundingRect.y + boundingRect.height - 5 } // Bottom-right\r\n ];\r\n \r\n // We'll only consider points that are inside the viewport\r\n let validPoints = 0;\r\n let overlaidPoints = 0;\r\n \r\n for (const point of points) {\r\n // Skip points outside viewport\r\n if (point.x < 0 || point.x >= viewportWidth || point.y < 0 || point.y >= viewportHeight) {\r\n continue;\r\n }\r\n \r\n validPoints++;\r\n const elementAtPoint = element.ownerDocument.elementFromPoint(point.x, point.y);\r\n \r\n if (isComplexComponent || isFrameworkButton) {\r\n diagnosticLog('Element at point:', elementAtPoint ? {\r\n tagName: elementAtPoint.tagName,\r\n className: elementAtPoint.className,\r\n id: elementAtPoint.id\r\n } : 'None found');\r\n }\r\n \r\n // Define helper functions for scroll detection outside the point loop\r\n function calculateVisibleAreaRatio(elementRect, containerRect) {\r\n // Calculate intersection\r\n const intersectionRect = {\r\n top: Math.max(elementRect.top, containerRect.top),\r\n left: Math.max(elementRect.left, containerRect.left),\r\n bottom: Math.min(elementRect.bottom, containerRect.bottom),\r\n right: Math.min(elementRect.right, containerRect.right)\r\n };\r\n \r\n // Check if there is any intersection at all\r\n if (intersectionRect.top >= intersectionRect.bottom || \r\n intersectionRect.left >= intersectionRect.right) {\r\n return 0; // No intersection, element is completely outside\r\n }\r\n \r\n // Calculate areas\r\n const intersectionArea = (intersectionRect.right - intersectionRect.left) * \r\n (intersectionRect.bottom - intersectionRect.top);\r\n const elementArea = (elementRect.right - elementRect.left) * \r\n (elementRect.bottom - elementRect.top);\r\n \r\n // Return ratio of visible area\r\n return elementArea > 0 ? intersectionArea / elementArea : 0;\r\n }\r\n \r\n function isInScrollableContainerButNotFullyVisible(el) {\r\n if (!el) return false;\r\n \r\n const rect = el.getBoundingClientRect();\r\n \r\n // First check if the element itself is sufficiently visible in the viewport\r\n const viewportVisibilityRatio = calculateVisibleAreaRatio(rect, {\r\n top: 0,\r\n left: 0,\r\n bottom: window.innerHeight,\r\n right: window.innerWidth\r\n });\r\n \r\n // If element is less than 80% visible in viewport, consider it overlaid\r\n if (viewportVisibilityRatio < 0.8) {\r\n if (isComplexComponent || isFrameworkButton) {\r\n diagnosticLog('Element is not sufficiently visible in viewport:', {\r\n visibilityRatio: viewportVisibilityRatio,\r\n elementRect: {\r\n top: rect.top,\r\n right: rect.right,\r\n bottom: rect.bottom,\r\n left: rect.left\r\n }\r\n });\r\n }\r\n return true;\r\n }\r\n \r\n // Then check all ancestor containers\r\n let parent = el.parentElement;\r\n while (parent) {\r\n const parentStyle = window.getComputedStyle(parent);\r\n \r\n // Reliable way to detect if an element has scrollbars or is scrollable\r\n const hasScrollHeight = parent.scrollHeight > parent.clientHeight;\r\n const hasScrollWidth = parent.scrollWidth > parent.clientWidth;\r\n \r\n // Check actual style properties\r\n const hasOverflowY = parentStyle.overflowY === 'auto' || \r\n parentStyle.overflowY === 'scroll' || \r\n parentStyle.overflowY === 'overlay';\r\n const hasOverflowX = parentStyle.overflowX === 'auto' || \r\n parentStyle.overflowX === 'scroll' || \r\n parentStyle.overflowX === 'overlay';\r\n \r\n // Check common class names and attributes for scrollable containers across frameworks\r\n const hasScrollClasses = parent.classList.contains('scroll') || \r\n parent.classList.contains('scrollable') ||\r\n parent.classList.contains('overflow') ||\r\n parent.classList.contains('overflow-auto') ||\r\n parent.classList.contains('overflow-scroll') ||\r\n parent.getAttribute('data-scrollable') === 'true';\r\n \r\n // Check for height/max-height constraints that often indicate scrolling content\r\n const hasHeightConstraint = parentStyle.maxHeight && \r\n parentStyle.maxHeight !== 'none' && \r\n parentStyle.maxHeight !== 'auto';\r\n \r\n // An element is scrollable if it has:\r\n // 1. Actual scrollbars in use (most reliable check) OR\r\n // 2. Overflow styles allowing scrolling AND content that would require scrolling\r\n const isScrollable = (hasScrollHeight && hasOverflowY) || \r\n (hasScrollWidth && hasOverflowX) ||\r\n (hasScrollClasses && (hasScrollHeight || hasScrollWidth)) ||\r\n (hasHeightConstraint && hasScrollHeight);\r\n \r\n if (isScrollable) {\r\n const parentRect = parent.getBoundingClientRect();\r\n \r\n // Calculate how much of the element is visible within the container\r\n const visibilityRatio = calculateVisibleAreaRatio(rect, parentRect);\r\n \r\n // Only consider elements as overlaid if they're completely invisible (0% visible)\r\n // This ensures elements partially visible at the bottom of scrollable containers are still detected\r\n if (visibilityRatio === 0) {\r\n diagnosticLog('Element is in scrollable container but completely invisible:', {\r\n visibilityRatio: visibilityRatio,\r\n elementRect: {\r\n top: rect.top,\r\n right: rect.right,\r\n bottom: rect.bottom,\r\n left: rect.left\r\n },\r\n containerRect: {\r\n top: parentRect.top,\r\n right: parentRect.right,\r\n bottom: parentRect.bottom,\r\n left: parentRect.left\r\n },\r\n containerClass: parent.className,\r\n hasScrollHeight,\r\n hasScrollWidth,\r\n hasOverflowY,\r\n hasOverflowX\r\n });\r\n return true;\r\n }\r\n }\r\n \r\n parent = parent.parentElement;\r\n }\r\n \r\n return false;\r\n }\r\n \r\n // Check if element is in a scrollable container but not fully visible\r\n let isInScrollableContainerOnly = false;\r\n \r\n // For all elements, check if in scrollable container but not fully visible\r\n isInScrollableContainerOnly = isInScrollableContainerButNotFullyVisible(element);\r\n \r\n // Special handling for elements in scrollable containers\r\n if (isInScrollableContainerOnly) {\r\n // Special handling for very deep nested selectors (which are often in scrollable containers)\r\n // These are typically elements in tables, lists, and grids with scroll\r\n if (elementInfo.css_selector && \r\n (elementInfo.css_selector.split('>').length > 10 || \r\n (elementInfo.element.className && \r\n typeof elementInfo.element.className === 'string' && \r\n (elementInfo.element.className.includes('widget') || \r\n elementInfo.element.className.includes('list-item') ||\r\n elementInfo.element.className.includes('item') ||\r\n elementInfo.element.className.includes('card') ||\r\n elementInfo.element.className.includes('result'))))) {\r\n \r\n diagnosticLog('Allowing deeply nested element in scrollable container:', \r\n elementInfo.css_selector.substring(0, 100) + '...');\r\n // Don't consider it overlaid, this is likely a valid item in a scrollable list/table/widget\r\n return false;\r\n }\r\n return true; // Element needs scrolling to be fully visible\r\n }\r\n \r\n // If no element found at this point, or if element is self/ancestor/descendant, \r\n // this point is not overlaid\r\n if (!elementAtPoint ||\r\n elementAtPoint === element || \r\n isDecendent(element, elementAtPoint) || \r\n isDecendent(elementAtPoint, element)) {\r\n continue;\r\n }\r\n \r\n // Check if this point is covered by a popup/modal - this takes precedence\r\n if (isElementOrAncestorPopup(elementAtPoint)) {\r\n isUnderPopup = true;\r\n overlaidPoints++;\r\n continue;\r\n }\r\n \r\n // Special handling for complex components like those with Shadow DOM\r\n if ((isComplexComponent || isFrameworkButton) && !isUnderPopup) {\r\n // Only count as overlaid if it's clearly not part of the component's internal structure\r\n // For complex components, elementFromPoint often returns internal implementation details\r\n // that shouldn't count as \"overlaying\" the component itself\r\n \r\n // Skip points that might be part of the same component system\r\n if (elementAtPoint.tagName && elementAtPoint.tagName.toLowerCase().includes('-')) {\r\n // Custom elements (containing dash in the name) are likely part of the component framework\r\n continue;\r\n }\r\n \r\n // Only count clear UI overlays like dialogs or tooltips as actual overlays\r\n const elementTag = elementAtPoint.tagName.toLowerCase();\r\n const isOverlayingElement = elementTag === 'dialog' || \r\n elementAtPoint.getAttribute('role') === 'dialog' ||\r\n elementAtPoint.getAttribute('role') === 'tooltip' ||\r\n (elementAtPoint.className && \r\n typeof elementAtPoint.className === 'string' && \r\n (elementAtPoint.className.includes('overlay') || \r\n elementAtPoint.className.includes('modal') ||\r\n elementAtPoint.className.includes('popup')));\r\n \r\n if (!isOverlayingElement) {\r\n continue; // Don't count this point as overlaid for complex components\r\n }\r\n }\r\n \r\n // Special check for debug rows and elements from topbar\r\n /* Debug code - commented out\r\n if (isRowToDebug && elementAtPoint.tagName === 'SPAN' && \r\n elementAtPoint.className && \r\n typeof elementAtPoint.className === 'string' && \r\n (elementAtPoint.className.includes('tab') || \r\n elementAtPoint.className.includes('nav') ||\r\n elementAtPoint.className.includes('topbar'))) {\r\n continue;\r\n }\r\n */\r\n \r\n // If this point is covered by a top navigation element, don't count it as overlaid\r\n if (isNearTopOfViewport && isElementOrAncestorTopNav(elementAtPoint)) {\r\n continue;\r\n }\r\n \r\n // This point is overlaid by something else\r\n overlaidPoints++;\r\n if (isComplexComponent || isFrameworkButton) {\r\n diagnosticLog('Point is overlaid by element:', elementAtPoint.tagName);\r\n }\r\n }\r\n \r\n // If we don't have any valid points (all outside viewport), element isn't overlaid\r\n if (validPoints === 0) {\r\n /* Debug code - commented out\r\n if (isRowToDebug) {\r\n console.log('No valid points inside viewport');\r\n console.log('Final overlay decision: NOT OVERLAID');\r\n console.log('-------------------------------------------');\r\n }\r\n */\r\n return false;\r\n }\r\n \r\n // If we detected the element is under a popup with significant coverage, it's overlaid\r\n if (isUnderPopup && overlaidPoints > (validPoints / 2)) {\r\n /* Debug code - commented out\r\n if (isRowToDebug) {\r\n console.log('Element is under a popup/modal with significant coverage');\r\n console.log('Final overlay decision: OVERLAID');\r\n console.log('-------------------------------------------');\r\n }\r\n */\r\n return true;\r\n }\r\n \r\n // Calculate percentage of points that are overlaid\r\n const overlaidPercentage = overlaidPoints / validPoints;\r\n \r\n // For complex components, we want to be especially certain they're truly overlaid\r\n // rather than just having framework-specific DOM complexities\r\n let overlayThreshold = 0.5; // Default threshold - 50% of points must be overlaid\r\n \r\n // Complex components require stronger evidence of overlay\r\n if ((isComplexComponent || isFrameworkButton) && !isUnderPopup) {\r\n // For complex components like those with Shadow DOM, \r\n // we need stronger evidence they're actually overlaid\r\n overlayThreshold = 0.7; // 70% of points must be overlaid for complex components\r\n }\r\n \r\n // More robust threshold - require sufficient points to be overlaid based on component type\r\n const isElementOverlaid = overlaidPercentage > overlayThreshold;\r\n \r\n return isElementOverlaid;\r\n }\n\n const highlight = {\r\n execute: async function(elementTypes, handleScroll=false) {\r\n const elements = await findElements(elementTypes);\r\n highlightElements(elements);\r\n return elements;\r\n },\r\n\r\n unexecute: function(handleScroll=false) {\r\n unhighlightElements(handleScroll);\r\n },\r\n\r\n generateJSON: async function() {\r\n const json = {};\r\n await Promise.all(Object.values(ElementTag).map(async elementType => {\r\n const elements = await findElements(elementType);\r\n json[elementType] = elements;\r\n }));\r\n\r\n // Serialize the JSON object\r\n const jsonString = JSON.stringify(json, null, 4); // Pretty print with 4 spaces\r\n\r\n console.log(`JSON: ${jsonString}`);\r\n return jsonString;\r\n },\r\n\r\n getElementInfo\r\n };\r\n\r\n\r\n function unhighlightElements(handleScroll=false) {\r\n const documents = getAllFrames();\r\n documents.forEach(doc => {\r\n const overlay = doc.getElementById('highlight-overlay');\r\n if (overlay) {\r\n if (handleScroll) {\r\n // Remove event listeners\r\n doc.removeEventListener('scroll', overlay.scrollHandler, true);\r\n doc.removeEventListener('resize', overlay.resizeHandler);\r\n }\r\n overlay.remove();\r\n }\r\n });\r\n }\r\n\r\n\r\n\r\n\r\n async function findElements(elementTypes, verbose=true) {\r\n const typesArray = Array.isArray(elementTypes) ? elementTypes : [elementTypes];\r\n console.log('Starting element search for types:', typesArray);\r\n\r\n const elements = [];\r\n typesArray.forEach(elementType => {\r\n if (elementType === ElementTag.FILLABLE) {\r\n elements.push(...findFillables());\r\n }\r\n if (elementType === ElementTag.SELECTABLE) {\r\n elements.push(...findDropdowns());\r\n }\r\n if (elementType === ElementTag.CLICKABLE) {\r\n elements.push(...findClickables());\r\n elements.push(...findToggles());\r\n elements.push(...findCheckables());\r\n }\r\n if (elementType === ElementTag.NON_INTERACTIVE_ELEMENT) {\r\n elements.push(...findNonInteractiveElements());\r\n }\r\n });\r\n\r\n // console.log('Before uniquify:', elements.length);\r\n const elementsWithInfo = elements.map((element, index) => \r\n getElementInfo(element, index)\r\n );\r\n \r\n const uniqueElements = uniquifyElements(elementsWithInfo);\r\n console.log(`Found ${uniqueElements.length} elements:`);\r\n \r\n // More comprehensive visibility check\r\n const visibleElements = uniqueElements.filter(elementInfo => {\r\n const el = elementInfo.element;\r\n const style = getComputedStyle(el);\r\n \r\n // Check various style properties that affect visibility\r\n if (style.display === 'none' || \r\n style.visibility === 'hidden' || \r\n parseFloat(style.opacity) === 0) {\r\n return false;\r\n }\r\n \r\n // Check if element has non-zero dimensions\r\n const rect = el.getBoundingClientRect();\r\n if (rect.width === 0 || rect.height === 0) {\r\n return false;\r\n }\r\n \r\n // Check if element is within viewport\r\n if (rect.bottom < 0 || \r\n rect.top > window.innerHeight || \r\n rect.right < 0 || \r\n rect.left > window.innerWidth) {\r\n // Element is outside viewport, but still might be valid \r\n // if user scrolls to it, so we'll include it\r\n return true;\r\n }\r\n \r\n return true;\r\n });\r\n \r\n console.log(`Out of which ${visibleElements.length} elements are visible:`);\r\n if (verbose) {\r\n visibleElements.forEach(info => {\r\n console.log(`Element ${info.index}:`, info);\r\n });\r\n }\r\n \r\n return visibleElements;\r\n }\r\n\r\n // elements is an array of objects with index, xpath\r\n function highlightElements(elements) {\r\n // console.log('Starting highlight for elements:', elements);\r\n \r\n // Create overlay if it doesn't exist and store it in a dictionary\r\n const documents = getAllFrames(); \r\n let overlays = {};\r\n documents.forEach(doc => {\r\n let overlay = doc.getElementById('highlight-overlay');\r\n if (!overlay) {\r\n overlay = doc.createElement('div');\r\n overlay.id = 'highlight-overlay';\r\n overlay.style.cssText = `\r\n position: fixed;\r\n top: 0;\r\n left: 0;\r\n width: 100%;\r\n height: 100%;\r\n pointer-events: none;\r\n z-index: 10000;\r\n `;\r\n doc.body.appendChild(overlay);\r\n }\r\n overlays[doc.documentURI] = overlay;\r\n });\r\n \r\n\r\n const updateHighlights = (doc = null) => {\r\n if (doc) {\r\n overlays[doc.documentURI].innerHTML = '';\r\n } else {\r\n Object.values(overlays).forEach(overlay => { overlay.innerHTML = ''; });\r\n } \r\n elements.forEach(elementInfo => {\r\n // console.log('updateHighlights-Processing elementInfo:', elementInfo);\r\n let element = elementInfo.element; //getElementByXPathOrCssSelector(elementInfo);\r\n if (!element) {\r\n element = getElementByXPathOrCssSelector(elementInfo);\r\n if (!element)\r\n return;\r\n }\r\n \r\n //if highlights requested for a specific doc, skip unrelated elements\r\n if (doc && element.ownerDocument !== doc) {\r\n console.log(\"skipped element \", element, \" since it doesn't belong to document \", doc);\r\n return;\r\n }\r\n\r\n const rect = element.getBoundingClientRect();\r\n // console.log('Element rect:', elementInfo.tag, rect);\r\n \r\n if (rect.width === 0 || rect.height === 0) {\r\n console.warn('Element has zero dimensions:', elementInfo);\r\n return;\r\n }\r\n \r\n // Create border highlight (red rectangle)\r\n // use ownerDocument to support iframes/frames\r\n const highlight = element.ownerDocument.createElement('div');\r\n highlight.style.cssText = `\r\n position: fixed;\r\n left: ${rect.x}px;\r\n top: ${rect.y}px;\r\n width: ${rect.width}px;\r\n height: ${rect.height}px;\r\n border: 1px solid rgb(255, 0, 0);\r\n transition: all 0.2s ease-in-out;\r\n `;\r\n\r\n // Create index label container - now positioned to the right and slightly up\r\n const labelContainer = element.ownerDocument.createElement('div');\r\n labelContainer.style.cssText = `\r\n position: absolute;\r\n right: -10px; /* Offset to the right */\r\n top: -10px; /* Offset upwards */\r\n padding: 4px;\r\n background-color: rgba(255, 255, 0, 0.6);\r\n display: flex;\r\n align-items: center;\r\n justify-content: center;\r\n `;\r\n\r\n const text = element.ownerDocument.createElement('span');\r\n text.style.cssText = `\r\n color: rgb(0, 0, 0, 0.8);\r\n font-family: 'Courier New', Courier, monospace;\r\n font-size: 12px;\r\n font-weight: bold;\r\n line-height: 1;\r\n `;\r\n text.textContent = elementInfo.index;\r\n \r\n labelContainer.appendChild(text);\r\n highlight.appendChild(labelContainer); \r\n overlays[element.ownerDocument.documentURI].appendChild(highlight);\r\n });\r\n };\r\n\r\n // Initial highlight\r\n updateHighlights();\r\n\r\n documents.forEach(doc => {\r\n // Update highlights on scroll and resize\r\n console.log('registering scroll and resize handlers for document: ', doc);\r\n const scrollHandler = () => {\r\n requestAnimationFrame(() => updateHighlights(doc));\r\n };\r\n const resizeHandler = () => {\r\n updateHighlights(doc);\r\n };\r\n doc.addEventListener('scroll', scrollHandler, true);\r\n doc.addEventListener('resize', resizeHandler);\r\n // Store event handlers for cleanup\r\n overlays[doc.documentURI].scrollHandler = scrollHandler;\r\n overlays[doc.documentURI].resizeHandler = resizeHandler;\r\n }); \r\n }\r\n\r\n // function unexecute() {\r\n // unhighlightElements();\r\n // }\r\n\r\n // Make it available globally for both Extension and Playwright\r\n if (typeof window !== 'undefined') {\r\n window.ProboLabs = {\r\n ElementTag,\r\n highlight,\r\n unhighlightElements,\r\n findElements,\r\n highlightElements,\r\n getElementInfo\r\n };\r\n }\n\n exports.findElements = findElements;\n exports.getElementInfo = getElementInfo;\n exports.highlight = highlight;\n exports.highlightElements = highlightElements;\n exports.unhighlightElements = unhighlightElements;\n\n Object.defineProperty(exports, '__esModule', { value: true });\n\n}));\n//# sourceMappingURL=probolabs.umd.js.map\n";
|
|
2
|
-
const ElementTag = {
|
|
3
|
-
CLICKABLE: "CLICKABLE", // button, link, toggle switch, checkbox, radio, dropdowns, clickable divs
|
|
4
|
-
FILLABLE: "FILLABLE", // input, textarea content_editable, date picker??
|
|
5
|
-
SELECTABLE: "SELECTABLE", // select
|
|
6
|
-
NON_INTERACTIVE_ELEMENT: 'NON_INTERACTIVE_ELEMENT',
|
|
1
|
+
const highlighterCode = "(function (global, factory) {\n typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :\n typeof define === 'function' && define.amd ? define(['exports'], factory) :\n (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.ProboLabs = {}));\n})(this, (function (exports) { 'use strict';\n\n const ElementTag = {\n CLICKABLE: \"CLICKABLE\", // button, link, toggle switch, checkbox, radio, dropdowns, clickable divs\n FILLABLE: \"FILLABLE\", // input, textarea content_editable, date picker??\n SELECTABLE: \"SELECTABLE\", // select\n NON_INTERACTIVE_ELEMENT: 'NON_INTERACTIVE_ELEMENT',\n };\n\n class ElementInfo {\n constructor(element, index, {tag, type, text, html, xpath, css_selector, bounding_box, iframe_selector}) {\n this.index = index.toString();\n this.tag = tag;\n this.type = type;\n this.text = text;\n this.html = html;\n this.xpath = xpath;\n this.css_selector = css_selector;\n this.bounding_box = bounding_box;\n this.iframe_selector = iframe_selector;\n this.element = element;\n this.depth = -1;\n }\n\n getSelector() {\n return this.xpath ? this.xpath : this.css_selector;\n }\n\n getDepth() {\n if (this.depth >= 0) {\n return this.depth;\n }\n \n this.depth = 0;\n let currentElement = this.element;\n \n while (currentElement.nodeType === Node.ELEMENT_NODE) { \n this.depth++;\n if (currentElement.assignedSlot) {\n currentElement = currentElement.assignedSlot;\n }\n else {\n currentElement = currentElement.parentNode;\n // Check if we're at a shadow root\n if (currentElement && currentElement.nodeType !== Node.ELEMENT_NODE && currentElement.getRootNode() instanceof ShadowRoot) {\n // Get the shadow root's host element\n currentElement = currentElement.getRootNode().host; \n }\n }\n }\n \n return this.depth;\n }\n }\n\n // import { realpath } from \"fs\";\n\n function getAllDocumentElementsIncludingShadow(selectors, root = document) {\n const elements = Array.from(root.querySelectorAll(selectors));\n\n root.querySelectorAll('*').forEach(el => {\n if (el.shadowRoot) {\n elements.push(...getAllDocumentElementsIncludingShadow(selectors, el.shadowRoot));\n }\n });\n return elements;\n }\n\n function getAllFrames(root = document) {\n const result = [root];\n const frames = getAllDocumentElementsIncludingShadow('frame, iframe', root); \n frames.forEach(frame => {\n try {\n const frameDocument = frame.contentDocument || frame.contentWindow.document;\n if (frameDocument) {\n result.push(frameDocument);\n }\n } catch (e) {\n // Skip cross-origin frames\n console.warn('Could not access frame content:', e.message);\n }\n });\n\n return result;\n }\n\n function getAllElementsIncludingShadow(selectors, root = document) {\n const elements = [];\n\n getAllFrames(root).forEach(doc => {\n elements.push(...getAllDocumentElementsIncludingShadow(selectors, doc));\n });\n\n return elements;\n }\n\n /**\n * Deeply searches through DOM trees including Shadow DOM and frames/iframes\n * @param {string} selector - CSS selector to search for\n * @param {Document|Element} [root=document] - Starting point for the search\n * @param {Object} [options] - Search options\n * @param {boolean} [options.searchShadow=true] - Whether to search Shadow DOM\n * @param {boolean} [options.searchFrames=true] - Whether to search frames/iframes\n * @returns {Element[]} Array of found elements\n \n function getAllElementsIncludingShadow(selector, root = document, options = {}) {\n const {\n searchShadow = true,\n searchFrames = true\n } = options;\n\n const results = new Set();\n \n // Helper to check if an element is valid and not yet found\n const addIfValid = (element) => {\n if (element && !results.has(element)) {\n results.add(element);\n }\n };\n\n // Helper to process a single document or element\n function processNode(node) {\n // Search regular DOM\n node.querySelectorAll(selector).forEach(addIfValid);\n\n if (searchShadow) {\n // Search all shadow roots\n const treeWalker = document.createTreeWalker(\n node,\n NodeFilter.SHOW_ELEMENT,\n {\n acceptNode: (element) => {\n return element.shadowRoot ? \n NodeFilter.FILTER_ACCEPT : \n NodeFilter.FILTER_SKIP;\n }\n }\n );\n\n while (treeWalker.nextNode()) {\n const element = treeWalker.currentNode;\n if (element.shadowRoot) {\n // Search within shadow root\n element.shadowRoot.querySelectorAll(selector).forEach(addIfValid);\n // Recursively process the shadow root for nested shadow DOMs\n processNode(element.shadowRoot);\n }\n }\n }\n\n if (searchFrames) {\n // Search frames and iframes\n const frames = node.querySelectorAll('frame, iframe');\n frames.forEach(frame => {\n try {\n const frameDocument = frame.contentDocument;\n if (frameDocument) {\n processNode(frameDocument);\n }\n } catch (e) {\n // Skip cross-origin frames\n console.warn('Could not access frame content:', e.message);\n }\n });\n }\n }\n\n // Start processing from the root\n processNode(root);\n\n return Array.from(results);\n }\n */\n // <div x=1 y=2 role='combobox'> </div>\n function findDropdowns() {\n const dropdowns = [];\n \n // Native select elements\n dropdowns.push(...getAllElementsIncludingShadow('select'));\n \n // Elements with dropdown roles that don't have <input>..</input>\n const roleElements = getAllElementsIncludingShadow('[role=\"combobox\"], [role=\"listbox\"], [role=\"dropdown\"], [role=\"option\"], [role=\"menu\"], [role=\"menuitem\"]').filter(el => {\n return el.tagName.toLowerCase() !== 'input' || ![\"button\", \"checkbox\", \"radio\"].includes(el.getAttribute(\"type\"));\n });\n dropdowns.push(...roleElements);\n \n // Common dropdown class patterns\n const dropdownPattern = /.*(dropdown|select|combobox|menu).*/i;\n const elements = getAllElementsIncludingShadow('*');\n const dropdownClasses = Array.from(elements).filter(el => {\n const hasDropdownClass = dropdownPattern.test(el.className);\n const validTag = ['li', 'ul', 'span', 'div', 'p', 'a', 'button'].includes(el.tagName.toLowerCase());\n const style = window.getComputedStyle(el); \n const result = hasDropdownClass && validTag && (style.cursor === 'pointer' || el.tagName.toLowerCase() === 'a' || el.tagName.toLowerCase() === 'button');\n return result;\n });\n \n dropdowns.push(...dropdownClasses);\n \n // Elements with aria-haspopup attribute\n dropdowns.push(...getAllElementsIncludingShadow('[aria-haspopup=\"true\"], [aria-haspopup=\"listbox\"], [aria-haspopup=\"menu\"]'));\n\n // Improve navigation element detection\n // Semantic nav elements with list items\n dropdowns.push(...getAllElementsIncludingShadow('nav ul li, nav ol li'));\n \n // Navigation elements in common design patterns\n dropdowns.push(...getAllElementsIncludingShadow('header a, .header a, .nav a, .navigation a, .menu a, .sidebar a, aside a'));\n \n // Elements in primary navigation areas with common attributes\n dropdowns.push(...getAllElementsIncludingShadow('[role=\"navigation\"] a, [aria-label*=\"navigation\"] a, [aria-label*=\"menu\"] a'));\n\n return dropdowns;\n }\n\n function findClickables() {\n const clickables = [];\n \n const checkboxPattern = /checkbox/i;\n // Collect all clickable elements first\n const nativeLinks = [...getAllElementsIncludingShadow('a[href]')];\n const nativeButtons = [...getAllElementsIncludingShadow('button')];\n const inputButtons = [...getAllElementsIncludingShadow('input[type=\"button\"], input[type=\"submit\"], input[type=\"reset\"]')];\n const roleButtons = [...getAllElementsIncludingShadow('[role=\"button\"]')];\n // const tabbable = [...getAllElementsIncludingShadow('[tabindex=\"0\"]')];\n const clickHandlers = [...getAllElementsIncludingShadow('[onclick]')];\n const dropdowns = findDropdowns();\n const nativeCheckboxes = [...getAllElementsIncludingShadow('input[type=\"checkbox\"]')]; \n const fauxCheckboxes = getAllElementsIncludingShadow('*').filter(el => {\n if (checkboxPattern.test(el.className)) {\n const realCheckboxes = getAllElementsIncludingShadow('input[type=\"checkbox\"]', el);\n if (realCheckboxes.length === 1) {\n const boundingRect = realCheckboxes[0].getBoundingClientRect();\n return boundingRect.width <= 1 && boundingRect.height <= 1 \n }\n }\n return false;\n });\n const nativeRadios = [...getAllElementsIncludingShadow('input[type=\"radio\"]')];\n const toggles = findToggles();\n const pointerElements = findElementsWithPointer();\n // Add all elements at once\n clickables.push(\n ...nativeLinks,\n ...nativeButtons,\n ...inputButtons,\n ...roleButtons,\n // ...tabbable,\n ...clickHandlers,\n ...dropdowns,\n ...nativeCheckboxes,\n ...fauxCheckboxes,\n ...nativeRadios,\n ...toggles,\n ...pointerElements\n );\n\n // Only uniquify once at the end\n return clickables; // Let findElements handle the uniquification\n }\n\n function findToggles() {\n const toggles = [];\n const checkboxes = getAllElementsIncludingShadow('input[type=\"checkbox\"]');\n const togglePattern = /switch|toggle|slider/i;\n\n checkboxes.forEach(checkbox => {\n let isToggle = false;\n\n // Check the checkbox itself\n if (togglePattern.test(checkbox.className) || togglePattern.test(checkbox.getAttribute('role') || '')) {\n isToggle = true;\n }\n\n // Check parent elements (up to 3 levels)\n if (!isToggle) {\n let element = checkbox;\n for (let i = 0; i < 3; i++) {\n const parent = element.parentElement;\n if (!parent) break;\n\n const className = parent.className || '';\n const role = parent.getAttribute('role') || '';\n\n if (togglePattern.test(className) || togglePattern.test(role)) {\n isToggle = true;\n break;\n }\n element = parent;\n }\n }\n\n // Check next sibling\n if (!isToggle) {\n const nextSibling = checkbox.nextElementSibling;\n if (nextSibling) {\n const className = nextSibling.className || '';\n const role = nextSibling.getAttribute('role') || '';\n if (togglePattern.test(className) || togglePattern.test(role)) {\n isToggle = true;\n }\n }\n }\n\n if (isToggle) {\n toggles.push(checkbox);\n }\n });\n\n return toggles;\n }\n\n function findNonInteractiveElements() {\n // Get all elements in the document\n const all = Array.from(getAllElementsIncludingShadow('*'));\n \n // Filter elements based on Python implementation rules\n return all.filter(element => {\n if (!element.firstElementChild) {\n const tag = element.tagName.toLowerCase(); \n if (!['select', 'button', 'a'].includes(tag)) {\n const validTags = ['p', 'span', 'div', 'input', 'textarea'].includes(tag) || /^h\\d$/.test(tag) || /text/.test(tag);\n const boundingRect = element.getBoundingClientRect();\n return validTags && boundingRect.height > 1 && boundingRect.width > 1;\n }\n }\n return false;\n });\n }\n\n\n\n // export function findNonInteractiveElements() {\n // const all = [];\n // try {\n // const elements = getAllElementsIncludingShadow('*');\n // all.push(...elements);\n // } catch (e) {\n // console.warn('Error getting elements:', e);\n // }\n \n // console.debug('Total elements found:', all.length);\n \n // return all.filter(element => {\n // try {\n // const tag = element.tagName.toLowerCase(); \n\n // // Special handling for input elements\n // if (tag === 'input' || tag === 'textarea') {\n // const boundingRect = element.getBoundingClientRect();\n // const value = element.value || '';\n // const placeholder = element.placeholder || '';\n // return boundingRect.height > 1 && \n // boundingRect.width > 1 && \n // (value.trim() !== '' || placeholder.trim() !== '');\n // }\n\n \n // // Check if it's a valid tag for text content\n // const validTags = ['p', 'span', 'div', 'label', 'th', 'td', 'li', 'button', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'a', 'select'].includes(tag) || \n // /^h\\d$/.test(tag) || \n // /text/.test(tag);\n\n // const boundingRect = element.getBoundingClientRect();\n\n // // Get direct text content, excluding child element text\n // let directText = '';\n // for (const node of element.childNodes) {\n // // Only include text nodes (nodeType 3)\n // if (node.nodeType === 3) {\n // directText += node.textContent || '';\n // }\n // }\n \n // // If no direct text and it's a table cell or heading, check label content\n // if (!directText.trim() && (tag === 'th' || tag === 'td' || tag === 'h1')) {\n // const labels = element.getElementsByTagName('label');\n // for (const label of labels) {\n // directText += label.textContent || '';\n // }\n // }\n\n // // If still no text and it's a heading, get all text content\n // if (!directText.trim() && tag === 'h1') {\n // directText = element.textContent || '';\n // }\n\n // directText = directText.trim();\n\n // // Debug logging\n // if (directText) {\n // console.debugg('Text element found:', {\n // tag,\n // text: directText,\n // dimensions: boundingRect,\n // element\n // });\n // }\n\n // return validTags && \n // boundingRect.height > 1 && \n // boundingRect.width > 1 && \n // directText !== '';\n \n // } catch (e) {\n // console.warn('Error processing element:', e);\n // return false;\n // }\n // });\n // }\n\n\n\n\n\n function findElementsWithPointer() {\n const elements = [];\n const allElements = getAllElementsIncludingShadow('*');\n \n console.log('Checking elements with pointer style...');\n \n allElements.forEach(element => {\n // Skip SVG elements for now\n if (element instanceof SVGElement || element.tagName.toLowerCase() === 'svg') {\n return;\n }\n \n const style = window.getComputedStyle(element);\n if (style.cursor === 'pointer') {\n elements.push(element);\n }\n });\n \n console.log(`Found ${elements.length} elements with pointer cursor`);\n return elements;\n }\n\n function findCheckables() {\n const elements = [];\n\n elements.push(...getAllElementsIncludingShadow('input[type=\"checkbox\"]'));\n elements.push(...getAllElementsIncludingShadow('input[type=\"radio\"]'));\n const all_elements = getAllElementsIncludingShadow('label');\n const radioClasses = Array.from(all_elements).filter(el => {\n return /.*radio.*/i.test(el.className); \n });\n elements.push(...radioClasses);\n return elements;\n }\n\n function findFillables() {\n const elements = [];\n\n const inputs = [...getAllElementsIncludingShadow('input:not([type=\"radio\"]):not([type=\"checkbox\"])')];\n console.log('Found inputs:', inputs.length, inputs);\n elements.push(...inputs);\n \n const textareas = [...getAllElementsIncludingShadow('textarea')];\n console.log('Found textareas:', textareas.length);\n elements.push(...textareas);\n \n const editables = [...getAllElementsIncludingShadow('[contenteditable=\"true\"]')];\n console.log('Found editables:', editables.length);\n elements.push(...editables);\n\n return elements;\n }\n\n // Helper function to check if element is a form control\n function isFormControl(elementInfo) {\n return /^(input|select|textarea|button|label)$/i.test(elementInfo.tag);\n }\n\n const isDropdownItem = (elementInfo) => {\n const dropdownPatterns = [\n /dropdown[-_]?item/i, // matches: dropdown-item, dropdownitem, dropdown_item\n /menu[-_]?item/i, // matches: menu-item, menuitem, menu_item\n /dropdown[-_]?link/i, // matches: dropdown-link, dropdownlink, dropdown_link\n /list[-_]?item/i, // matches: list-item, listitem, list_item\n /select[-_]?item/i, // matches: select-item, selectitem, select_item \n ];\n\n const rolePatterns = [\n /menu[-_]?item/i, // matches: menuitem, menu-item\n /option/i, // matches: option\n /list[-_]?item/i, // matches: listitem, list-item\n /tree[-_]?item/i // matches: treeitem, tree-item\n ];\n\n const hasMatchingClass = elementInfo.element.className && \n dropdownPatterns.some(pattern => \n pattern.test(elementInfo.element.className)\n );\n\n const hasMatchingRole = elementInfo.element.getAttribute('role') && \n rolePatterns.some(pattern => \n pattern.test(elementInfo.element.getAttribute('role'))\n );\n\n return hasMatchingClass || hasMatchingRole;\n };\n\n /**\n * Finds the first element matching a CSS selector, traversing Shadow DOM if necessary\n * @param {string} selector - CSS selector to search for\n * @param {Element} [root=document] - Root element to start searching from\n * @returns {Element|null} - The first matching element or null if not found\n */\n function querySelectorShadow(selector, root = document) {\n // First try to find in light DOM\n let element = root.querySelector(selector);\n if (element) return element;\n \n // Get all elements with shadow root\n const shadowElements = Array.from(root.querySelectorAll('*'))\n .filter(el => el.shadowRoot);\n \n // Search through each shadow root until we find a match\n for (const el of shadowElements) {\n element = querySelectorShadow(selector, el.shadowRoot);\n if (element) return element;\n }\n \n return null;\n }\n\n const getElementByXPathOrCssSelector = (element_info) => {\n let element;\n\n if (element_info.xpath) { //try xpath if exists\n element = document.evaluate(\n element_info.xpath, \n document, \n null, \n XPathResult.FIRST_ORDERED_NODE_TYPE, \n null\n ).singleNodeValue;\n \n if (!element) {\n console.warn('Failed to find element with xpath:', element_info.xpath);\n }\n }\n else { //try CSS selector\n if (element_info.iframe_selector) {\n const frames = getAllDocumentElementsIncludingShadow('iframe');\n \n // Iterate over all frames and compare their CSS selectors\n frames.forEach(frame => { \n const cssSelector = generateCssPath(frame);\n if (cssSelector === element_info.iframe_selector) {\n const frameDocument = frame.contentDocument || frame.contentWindow.document;\n element = querySelectorShadow(element_info.css_selector, frameDocument);\n } \n }); \n }\n else\n element = querySelectorShadow(element_info.css_selector);\n // console.log('found element by CSS elector: ', element);\n if (!element) {\n console.warn('Failed to find element with CSS selector:', element_info.css_selector);\n }\n }\n\n return element;\n };\n\n function generateXPath(element) {\n if (!element || element.getRootNode() instanceof ShadowRoot) return '';\n \n // If element has an id, use that (it's unique and shorter)\n if (element.id) {\n return `//*[@id=\"${element.id}\"]`;\n }\n \n const parts = [];\n let current = element;\n \n while (current && current.nodeType === Node.ELEMENT_NODE) {\n let index = 1;\n let sibling = current.previousSibling;\n \n while (sibling) {\n if (sibling.nodeType === Node.ELEMENT_NODE && sibling.tagName === current.tagName) {\n index++;\n }\n sibling = sibling.previousSibling;\n }\n \n const tagName = current.tagName.toLowerCase();\n parts.unshift(`${tagName}[${index}]`);\n current = current.parentNode;\n }\n \n return '/' + parts.join('/');\n }\n\n function isDecendent(parent, child) {\n let element = child;\n while (element.nodeType === Node.ELEMENT_NODE) { \n \n if (element.assignedSlot) {\n element = element.assignedSlot;\n }\n else {\n element = element.parentNode;\n // Check if we're at a shadow root\n if (element && element.nodeType !== Node.ELEMENT_NODE && element.getRootNode() instanceof ShadowRoot) {\n // Get the shadow root's host element\n element = element.getRootNode().host; \n }\n }\n if (element === parent)\n return true;\n }\n return false;\n }\n\n function generateCssPath(element) {\n if (!element) {\n console.error('ERROR: No element provided to generateCssPath returning empty string');\n return '';\n }\n const path = [];\n // console.group('Generating CSS path for:', element);\n while (element && element.nodeType === Node.ELEMENT_NODE) { \n let selector = element.nodeName.toLowerCase();\n // console.log('Element:', selector, element);\n \n // if (element.id) {\n // //escape special characters\n // const normalized_id = element.id.replace(/[:;.#()[\\]!@$%^&*]/g, '\\\\$&');\n // selector = `#${normalized_id}`;\n // path.unshift(selector);\n // break;\n // } \n \n let sibling = element;\n let nth = 1;\n while (sibling = sibling.previousElementSibling) {\n if (sibling.nodeName.toLowerCase() === selector) nth++;\n }\n sibling = element;\n while (sibling = sibling.nextElementSibling) {\n if (sibling.nodeName.toLowerCase() === selector) {\n break;\n }\n }\n selector += `:nth-of-type(${nth})`;\n \n \n path.unshift(selector);\n //console.log(` Current path: ${path.join(' > ')}`);\n\n if (element.assignedSlot) {\n element = element.assignedSlot;\n // console.log(' Moving to assigned slot');\n }\n else {\n element = element.parentNode;\n // console.log(' Moving to parent:', element);\n\n // Check if we're at a shadow root\n if (element && element.nodeType !== Node.ELEMENT_NODE && element.getRootNode() instanceof ShadowRoot) {\n console.log(' Found shadow root, moving to host');\n // Get the shadow root's host element\n element = element.getRootNode().host; \n }\n }\n }\n \n // console.log('Final selector:', path.join(' > '));\n // console.groupEnd();\n return path.join(' > ');\n }\n\n\n function cleanHTML(rawHTML) {\n const parser = new DOMParser();\n const doc = parser.parseFromString(rawHTML, \"text/html\");\n\n function cleanElement(element) {\n const allowedAttributes = new Set([\n \"role\",\n \"type\",\n \"class\",\n \"href\",\n \"alt\",\n \"title\",\n \"readonly\",\n \"checked\",\n \"enabled\",\n \"disabled\",\n ]);\n\n [...element.attributes].forEach(attr => {\n const name = attr.name.toLowerCase();\n const value = attr.value;\n\n const isTestAttribute = /^(testid|test-id|data-test-id)$/.test(name);\n const isDataAttribute = name.startsWith(\"data-\") && value;\n const isBooleanAttribute = [\"readonly\", \"checked\", \"enabled\", \"disabled\"].includes(name);\n\n if (!allowedAttributes.has(name) && !isDataAttribute && !isTestAttribute && !isBooleanAttribute) {\n element.removeAttribute(name);\n }\n });\n\n // Handle SVG content - more aggressive replacement\n if (element.tagName.toLowerCase() === \"svg\") {\n // Remove all attributes except class and role\n [...element.attributes].forEach(attr => {\n const name = attr.name.toLowerCase();\n if (name !== \"class\" && name !== \"role\") {\n element.removeAttribute(name);\n }\n });\n element.innerHTML = \"CONTENT REMOVED\";\n } else {\n // Recursively clean child elements\n Array.from(element.children).forEach(cleanElement);\n }\n\n // Only remove empty elements that aren't semantic or icon elements\n const keepEmptyElements = ['i', 'span', 'svg', 'button', 'input'];\n if (!keepEmptyElements.includes(element.tagName.toLowerCase()) && \n !element.children.length && \n !element.textContent.trim()) {\n element.remove();\n }\n }\n\n // Process all elements in the document body\n Array.from(doc.body.children).forEach(cleanElement);\n return doc.body.innerHTML;\n }\n\n function getContainingIframe(element) {\n // If not in an iframe, return null\n if (element.ownerDocument.defaultView === window.top) {\n return null;\n }\n \n // Try to find the iframe in the parent document that contains our element\n try {\n const parentDocument = element.ownerDocument.defaultView.parent.document;\n const iframes = parentDocument.querySelectorAll('iframe');\n \n for (const iframe of iframes) {\n if (iframe.contentWindow === element.ownerDocument.defaultView) {\n return iframe;\n }\n }\n } catch (e) {\n // Cross-origin restriction\n return \"Cross-origin iframe - cannot access details\";\n }\n \n return null;\n }\n\n function getElementInfo(element, index) {\n\n const xpath = generateXPath(element);\n const css_selector = generateCssPath(element);\n\n const iframe = getContainingIframe(element);\n const iframe_selector = iframe ? generateCssPath(iframe) : \"\";\n\n // Return element info with pre-calculated values\n return new ElementInfo(element, index, {\n tag: element.tagName.toLowerCase(),\n type: element.type || '',\n text: element.innerText, //getTextContent(element),\n html: cleanHTML(element.outerHTML),\n xpath: xpath,\n css_selector: css_selector,\n bounding_box: element.getBoundingClientRect(),\n iframe_selector: iframe_selector\n });\n }\n\n\n\n\n const filterZeroDimensions = (elementInfo) => {\n const rect = elementInfo.bounding_box;\n //single pixel elements are typically faux controls and should be filtered too\n const hasSize = rect.width > 1 && rect.height > 1;\n const style = window.getComputedStyle(elementInfo.element);\n const isVisible = style.display !== 'none' && style.visibility !== 'hidden';\n \n if (!hasSize || !isVisible) {\n // if (elementInfo.element.isConnected) {\n // console.log('Filtered out invisible/zero-size element:', {\n // tag: elementInfo.tag,\n // xpath: elementInfo.xpath,\n // element: elementInfo.element,\n // hasSize,\n // isVisible,\n // dimensions: rect\n // });\n // }\n return false;\n }\n return true;\n };\n\n\n\n function uniquifyElements(elements) {\n const seen = new Set();\n\n console.log(`Starting uniquification with ${elements.length} elements`);\n\n // Filter out testing infrastructure elements first\n const filteredInfrastructure = elements.filter(element_info => {\n // Skip the highlight-overlay element completely - it's part of the testing infrastructure\n if (element_info.element.id === 'highlight-overlay' || \n (element_info.css_selector && element_info.css_selector.includes('#highlight-overlay'))) {\n console.log('Filtered out testing infrastructure element:', element_info.css_selector);\n return false;\n }\n \n // Filter out UI framework container/manager elements\n const el = element_info.element;\n // UI framework container checks - generic detection for any framework\n if ((el.getAttribute('data-rendered-by') || \n el.getAttribute('data-reactroot') || \n el.getAttribute('ng-version') || \n el.getAttribute('data-component-id') ||\n el.getAttribute('data-root') ||\n el.getAttribute('data-framework')) && \n (el.className && \n typeof el.className === 'string' && \n (el.className.includes('Container') || \n el.className.includes('container') || \n el.className.includes('Manager') || \n el.className.includes('manager')))) {\n console.log('Filtered out UI framework container element:', element_info.css_selector);\n return false;\n }\n \n // Direct filter for framework container elements that shouldn't be interactive\n // Consolidating multiple container detection patterns into one efficient check\n const isFullViewport = element_info.bounding_box && \n element_info.bounding_box.x <= 5 && \n element_info.bounding_box.y <= 5 && \n element_info.bounding_box.width >= (window.innerWidth * 0.95) && \n element_info.bounding_box.height >= (window.innerHeight * 0.95);\n \n // Empty content check\n const isEmpty = !el.innerText || el.innerText.trim() === '';\n \n // Check if it's a framework container element\n if (element_info.element.tagName === 'DIV' && \n isFullViewport && \n isEmpty && \n (\n // Pattern matching for root containers\n (element_info.xpath && \n (element_info.xpath.match(/^\\/html\\[\\d+\\]\\/body\\[\\d+\\]\\/div\\[\\d+\\]\\/div\\[\\d+\\]$/) || \n element_info.xpath.match(/^\\/\\/\\*\\[@id='[^']+'\\]\\/div\\[\\d+\\]$/))) ||\n \n // Simple DOM structure\n (element_info.css_selector.split(' > ').length <= 4 && element_info.depth <= 5) ||\n \n // Empty or container-like classes\n (!el.className || el.className === '' || \n (typeof el.className === 'string' && \n (el.className.includes('overlay') || \n el.className.includes('container') || \n el.className.includes('wrapper'))))\n )) {\n console.log('Filtered out framework container element:', element_info.css_selector);\n return false;\n }\n \n return true;\n });\n\n // First filter out elements with zero dimensions\n const nonZeroElements = filteredInfrastructure.filter(filterZeroDimensions);\n // sort by CSS selector depth so parents are processed first\n nonZeroElements.sort((a, b) => a.getDepth() - b.getDepth());\n console.log(`After dimension filtering: ${nonZeroElements.length} elements remain (${elements.length - nonZeroElements.length} removed)`);\n \n const filteredByParent = nonZeroElements.filter(element_info => {\n\n const parent = findClosestParent(seen, element_info);\n const keep = parent == null || shouldKeepNestedElement(element_info, parent);\n // console.log(\"node \", element_info.index, \": keep=\", keep, \" parent=\", parent);\n // if (!keep && !element_info.xpath) {\n // console.log(\"Filtered out element \", element_info,\" because it's a nested element of \", parent);\n // }\n if (keep)\n seen.add(element_info.css_selector);\n\n return keep;\n });\n\n console.log(`After parent/child filtering: ${filteredByParent.length} elements remain (${nonZeroElements.length - filteredByParent.length} removed)`);\n\n // Final overlap filtering\n const filteredResults = filteredByParent.filter(element => {\n\n // Look for any element that came BEFORE this one in the array\n const hasEarlierOverlap = filteredByParent.some(other => {\n // Only check elements that came before (lower index)\n if (filteredByParent.indexOf(other) >= filteredByParent.indexOf(element)) {\n return false;\n }\n \n const isOverlapping = areElementsOverlapping(element, other); \n return isOverlapping;\n }); \n\n // Keep element if it has no earlier overlapping elements\n return !hasEarlierOverlap;\n });\n \n \n \n // Check for overlay removal\n console.log(`After filtering: ${filteredResults.length} (${filteredByParent.length - filteredResults.length} removed by overlap)`);\n \n const nonOverlaidElements = filteredResults.filter(element => {\n return !isOverlaid(element);\n });\n\n console.log(`Final elements after overlay removal: ${nonOverlaidElements.length} (${filteredResults.length - nonOverlaidElements.length} removed)`);\n \n return nonOverlaidElements;\n\n }\n\n\n\n const areElementsOverlapping = (element1, element2) => {\n if (element1.css_selector === element2.css_selector) {\n return true;\n }\n \n const box1 = element1.bounding_box;\n const box2 = element2.bounding_box;\n \n return box1.x === box2.x &&\n box1.y === box2.y &&\n box1.width === box2.width &&\n box1.height === box2.height;\n // element1.text === element2.text &&\n // element2.tag === 'a';\n };\n\n function findClosestParent(seen, element_info) { \n // //Use element child/parent queries\n // let parent = element_info.element.parentNode;\n // if (parent.getRootNode() instanceof ShadowRoot) {\n // // Get the shadow root's host element\n // parent = parent.getRootNode().host; \n // }\n\n // while (parent.nodeType === Node.ELEMENT_NODE) { \n // const css_selector = generateCssPath(parent);\n // if (seen.has(css_selector)) {\n // console.log(\"element \", element_info, \" closest parent is \", parent)\n // return parent; \n // }\n // parent = parent.parentNode;\n // if (parent.getRootNode() instanceof ShadowRoot) {\n // // Get the shadow root's host element\n // parent = parent.getRootNode().host; \n // }\n // }\n\n // Split the xpath into segments\n const segments = element_info.css_selector.split(' > ');\n \n // Try increasingly shorter paths until we find one in the seen set\n for (let i = segments.length - 1; i > 0; i--) {\n const parentPath = segments.slice(0, i).join(' > ');\n if (seen.has(parentPath)) {\n return parentPath;\n }\n }\n\n return null;\n }\n\n function shouldKeepNestedElement(elementInfo, parentPath) {\n let result = false;\n const parentSegments = parentPath.split(' > ');\n\n const isParentLink = /^a(:nth-of-type\\(\\d+\\))?$/.test(parentSegments[parentSegments.length - 1]);\n if (isParentLink) {\n return false; \n }\n // If this is a checkbox/radio input\n if (elementInfo.tag === 'input' && \n (elementInfo.type === 'checkbox' || elementInfo.type === 'radio')) {\n \n // Check if parent is a label by looking at the parent xpath's last segment\n \n const isParentLabel = /^label(:nth-of-type\\(\\d+\\))?$/.test(parentSegments[parentSegments.length - 1]);\n \n // If parent is a label, don't keep the input (we'll keep the label instead)\n if (isParentLabel) {\n return false;\n }\n }\n \n // Keep all other form controls and dropdown items\n if (isFormControl(elementInfo) || isDropdownItem(elementInfo)) {\n result = true;\n }\n \n // console.log(`shouldKeepNestedElement: ${elementInfo.tag} ${elementInfo.text} ${elementInfo.xpath} -> ${parentXPath} -> ${result}`);\n return result;\n }\n\n\n\n function isOverlaid(elementInfo) {\n const element = elementInfo.element;\n const boundingRect = element.getBoundingClientRect();\n \n\n \n \n // Create a diagnostic logging function that only logs when needed\n const diagnosticLog = (...args) => {\n };\n\n // Special handling for tooltips\n if (elementInfo.element.className && typeof elementInfo.element.className === 'string' && \n elementInfo.element.className.includes('tooltip')) {\n return false;\n }\n \n // Special handling for deep component hierarchies\n const cssSelector = elementInfo.css_selector;\n \n // Identify complex components with deep hierarchy (important for Shadow DOM components)\n const isComplexComponent = cssSelector.length > 500 || \n (cssSelector.includes('slot:nth-of-type') && \n cssSelector.split('>').length > 15);\n \n // Special handling for deep component buttons in any framework\n const isFrameworkButton = cssSelector.split('>').length > 10 && \n cssSelector.includes('button:nth-of-type');\n \n if (isComplexComponent || isFrameworkButton) {\n // Check if the element is visible on screen\n if (boundingRect.width > 0 && \n boundingRect.height > 0 && \n boundingRect.bottom > 0 && \n boundingRect.right > 0 &&\n boundingRect.top < window.innerHeight &&\n boundingRect.left < window.innerWidth) {\n \n // Get element at the center point to check if it's covered by a popup/modal\n const middleX = boundingRect.x + boundingRect.width/2;\n const middleY = boundingRect.y + boundingRect.height/2;\n const elementAtMiddle = element.ownerDocument.elementFromPoint(middleX, middleY);\n \n if (elementAtMiddle && \n elementAtMiddle !== element && \n !isDecendent(element, elementAtMiddle) && \n !isDecendent(elementAtMiddle, element)) {\n // Make sure it doesn't have CSS that would hide it\n const style = window.getComputedStyle(element);\n if (style.display !== 'none' && \n style.visibility !== 'hidden' && \n style.opacity !== '0') {\n diagnosticLog('Style properties:', { \n display: style.display, \n visibility: style.visibility, \n opacity: style.opacity \n });\n return false; // It's visible and not covered, so not overlaid\n }\n }\n \n // Check specifically if the element at middle is a popup/modal\n if (elementAtMiddle && isElementOrAncestorPopup(elementAtMiddle)) {\n return true; // It's under a popup, so it is overlaid\n }\n }\n }\n \n // Function to check if an element is likely a popup/modal/dialog\n function isLikelyPopupOrModal(el) {\n if (!el) return false;\n \n try {\n // First check if this is actually a navigation element - we don't want to\n // misidentify navigation elements as popups\n if (isLikelyNavElement(el)) {\n return false;\n }\n \n // Navigation elements can still be overlaid - remove the automatic exclusion\n \n const rect = el.getBoundingClientRect();\n const style = window.getComputedStyle(el);\n \n // Quick checks first to fail fast\n const position = style.position;\n if (position !== 'fixed' && position !== 'absolute') {\n return false;\n }\n \n // Check tag name and role - very fast checks\n const isDialogElement = el.tagName.toLowerCase() === 'dialog';\n const hasDialogRole = el.getAttribute('role') === 'dialog' || el.getAttribute('role') === 'alertdialog';\n \n if (isDialogElement || hasDialogRole) {\n return true;\n }\n \n // Class name checks are unreliable as they depend entirely on developer conventions\n // We rely on structural properties instead\n \n // Most expensive checks last\n const zIndex = parseInt(style.zIndex, 10);\n const hasHighZIndex = !isNaN(zIndex) && zIndex > 100;\n \n // Size check for modals - they typically cover a significant portion of the screen\n // Navigation elements at the top are usually not this large\n const isSizeOfModal = rect.width > (window.innerWidth * 0.5) && \n rect.height > (window.innerHeight * 0.3) &&\n // Additional check: modals are usually not at the very top of the page\n rect.top > 50;\n \n return (hasHighZIndex && position === 'fixed' && rect.top > 50) || \n (isSizeOfModal && position === 'fixed');\n } catch (e) {\n return false;\n }\n }\n \n // Renamed from isLikelyTopNavElement to isLikelyNavElement since it detects navigation anywhere\n function isLikelyNavElement(el) {\n if (!el) return false;\n \n try {\n // Don't restrict navigation detection based on top position\n \n // Check tag names associated with navigation\n const tagName = el.tagName.toLowerCase();\n if (tagName === 'nav' || tagName === 'header') {\n return true;\n }\n \n // Check for navigation roles\n const role = el.getAttribute('role');\n if (role === 'navigation') {\n return true;\n }\n \n // Check for navigation-related class names - strong indicator\n const className = typeof el.className === 'string' ? el.className.toLowerCase() : '';\n if (className.includes('navbar') ||\n className.includes('navigation') ||\n className.includes('header') ||\n className.includes('nav-') ||\n className.includes('-nav') ||\n className.includes('sidebar') ||\n className.includes('menu')) {\n return true;\n }\n \n // Check for tab items (common in navigation)\n if (el.tagName === 'SPAN' && \n (el.classList.contains('tab') || \n el.classList.contains('nav'))) {\n return true;\n }\n \n return false;\n } catch (e) {\n return false;\n }\n }\n \n // Function to check if an element or any of its ancestors are part of top navigation\n function isElementOrAncestorTopNav(el, maxDepth = 4) {\n if (!el) return false;\n \n // Check self first - most common case\n if (isLikelyNavElement(el)) {\n return true;\n }\n \n // Then check ancestors if needed\n let current = el.parentElement;\n let depth = 1; // Start at 1 since we already checked self\n \n while (current && depth < maxDepth) {\n if (isLikelyNavElement(current)) {\n return true;\n }\n current = current.parentElement;\n depth++;\n }\n \n return false;\n }\n \n // Function to check if an element or any of its ancestors are a popup/modal\n function isElementOrAncestorPopup(el, maxDepth = 4) {\n if (!el) return false;\n \n // Check self first - most common case\n if (isLikelyPopupOrModal(el)) {\n return true;\n }\n \n // Then check ancestors if needed\n let current = el.parentElement;\n let depth = 1; // Start at 1 since we already checked self\n \n while (current && depth < maxDepth) {\n if (isLikelyPopupOrModal(current)) {\n return true;\n }\n current = current.parentElement;\n depth++;\n }\n \n return false;\n }\n \n // Check if element is at the top of the viewport\n const isNearTopOfViewport = boundingRect.top >= 0 && boundingRect.top < 100;\n \n // For elements near the top of the viewport, we need a special case\n // that handles fixed position elements at the top of the viewport\n if (isNearTopOfViewport) {\n // Get element at middle point of the row\n const middleX = boundingRect.x + boundingRect.width/2;\n const middleY = boundingRect.y + boundingRect.height/2;\n const elementAtMiddle = element.ownerDocument.elementFromPoint(middleX, middleY);\n \n // If we found an element and it's not the row itself or a descendant/ancestor\n if (elementAtMiddle && \n elementAtMiddle !== element && \n !isDecendent(element, elementAtMiddle) && \n !isDecendent(elementAtMiddle, element)) {\n \n // First check if the overlaying element is part of a popup/modal\n // If so, the element IS overlaid (regardless of whether it's also under nav)\n if (isElementOrAncestorPopup(elementAtMiddle)) {\n /* Debug code - commented out\n if (isRowToDebug) {\n console.log('Element is under a popup/modal');\n console.log('Final overlay decision: OVERLAID');\n console.log('-------------------------------------------');\n }\n */\n return true;\n }\n \n // Additional check specifically for the problematic span elements in debug logs\n if (elementAtMiddle.tagName === 'SPAN' && \n elementAtMiddle.className && \n typeof elementAtMiddle.className === 'string' && \n (elementAtMiddle.className.includes('tab') || \n elementAtMiddle.className.includes('nav'))) {\n /* Debug code - commented out\n if (isRowToDebug) {\n console.log('Element is under a navigation tab element');\n console.log('Final overlay decision: NOT OVERLAID');\n console.log('-------------------------------------------');\n }\n */\n return false;\n }\n \n // Check if the overlaying element is part of top navigation\n if (isElementOrAncestorTopNav(elementAtMiddle)) {\n /* Debug code - commented out\n if (isRowToDebug) {\n console.log('Element is under a top navigation element');\n console.log('Final overlay decision: NOT OVERLAID');\n console.log('-------------------------------------------');\n }\n */\n return false;\n }\n }\n }\n \n // Check if element is mostly or completely outside the viewport\n const viewportHeight = window.innerHeight;\n const viewportWidth = window.innerWidth;\n const elementHeight = boundingRect.height;\n const elementWidth = boundingRect.width;\n \n // Calculate how much of the element is visible in the viewport\n const visibleTop = Math.max(0, boundingRect.top);\n const visibleBottom = Math.min(viewportHeight, boundingRect.bottom);\n const visibleLeft = Math.max(0, boundingRect.left);\n const visibleRight = Math.min(viewportWidth, boundingRect.right);\n \n // Calculate visible area\n const visibleHeight = Math.max(0, visibleBottom - visibleTop);\n const visibleWidth = Math.max(0, visibleRight - visibleLeft);\n const visibleArea = visibleHeight * visibleWidth;\n const totalArea = elementHeight * elementWidth;\n \n // Check if less than half of the element is visible in the viewport\n const isPartiallyOffScreen = visibleArea < (totalArea / 2);\n \n // If the element is mostly offscreen, don't consider it overlaid - this avoids\n // false positives from elements near viewport boundaries\n if (isPartiallyOffScreen) {\n return false;\n }\n \n // Track if we find any popup elements covering our element\n let isUnderPopup = false;\n \n // Check multiple points to improve cross-browser consistency\n const points = [\n { x: boundingRect.x + boundingRect.width/2, y: boundingRect.y + boundingRect.height/2 }, // Center\n { x: boundingRect.x + 5, y: boundingRect.y + 5 }, // Top-left\n { x: boundingRect.x + boundingRect.width - 5, y: boundingRect.y + 5 }, // Top-right\n { x: boundingRect.x + 5, y: boundingRect.y + boundingRect.height - 5 }, // Bottom-left\n { x: boundingRect.x + boundingRect.width - 5, y: boundingRect.y + boundingRect.height - 5 } // Bottom-right\n ];\n \n // We'll only consider points that are inside the viewport\n let validPoints = 0;\n let overlaidPoints = 0;\n \n for (const point of points) {\n // Skip points outside viewport\n if (point.x < 0 || point.x >= viewportWidth || point.y < 0 || point.y >= viewportHeight) {\n continue;\n }\n \n validPoints++;\n const elementAtPoint = element.ownerDocument.elementFromPoint(point.x, point.y);\n \n if (isComplexComponent || isFrameworkButton) {\n diagnosticLog('Element at point:', elementAtPoint ? {\n tagName: elementAtPoint.tagName,\n className: elementAtPoint.className,\n id: elementAtPoint.id\n } : 'None found');\n }\n \n // Define helper functions for scroll detection outside the point loop\n function calculateVisibleAreaRatio(elementRect, containerRect) {\n // Calculate intersection\n const intersectionRect = {\n top: Math.max(elementRect.top, containerRect.top),\n left: Math.max(elementRect.left, containerRect.left),\n bottom: Math.min(elementRect.bottom, containerRect.bottom),\n right: Math.min(elementRect.right, containerRect.right)\n };\n \n // Check if there is any intersection at all\n if (intersectionRect.top >= intersectionRect.bottom || \n intersectionRect.left >= intersectionRect.right) {\n return 0; // No intersection, element is completely outside\n }\n \n // Calculate areas\n const intersectionArea = (intersectionRect.right - intersectionRect.left) * \n (intersectionRect.bottom - intersectionRect.top);\n const elementArea = (elementRect.right - elementRect.left) * \n (elementRect.bottom - elementRect.top);\n \n // Return ratio of visible area\n return elementArea > 0 ? intersectionArea / elementArea : 0;\n }\n \n function isInScrollableContainerButNotFullyVisible(el) {\n if (!el) return false;\n \n const rect = el.getBoundingClientRect();\n \n // First check if the element itself is sufficiently visible in the viewport\n const viewportVisibilityRatio = calculateVisibleAreaRatio(rect, {\n top: 0,\n left: 0,\n bottom: window.innerHeight,\n right: window.innerWidth\n });\n \n // If element is less than 80% visible in viewport, consider it overlaid\n if (viewportVisibilityRatio < 0.8) {\n if (isComplexComponent || isFrameworkButton) {\n diagnosticLog('Element is not sufficiently visible in viewport:', {\n visibilityRatio: viewportVisibilityRatio,\n elementRect: {\n top: rect.top,\n right: rect.right,\n bottom: rect.bottom,\n left: rect.left\n }\n });\n }\n return true;\n }\n \n // Then check all ancestor containers\n let parent = el.parentElement;\n while (parent) {\n const parentStyle = window.getComputedStyle(parent);\n \n // Reliable way to detect if an element has scrollbars or is scrollable\n const hasScrollHeight = parent.scrollHeight > parent.clientHeight;\n const hasScrollWidth = parent.scrollWidth > parent.clientWidth;\n \n // Check actual style properties\n const hasOverflowY = parentStyle.overflowY === 'auto' || \n parentStyle.overflowY === 'scroll' || \n parentStyle.overflowY === 'overlay';\n const hasOverflowX = parentStyle.overflowX === 'auto' || \n parentStyle.overflowX === 'scroll' || \n parentStyle.overflowX === 'overlay';\n \n // Check common class names and attributes for scrollable containers across frameworks\n const hasScrollClasses = parent.classList.contains('scroll') || \n parent.classList.contains('scrollable') ||\n parent.classList.contains('overflow') ||\n parent.classList.contains('overflow-auto') ||\n parent.classList.contains('overflow-scroll') ||\n parent.getAttribute('data-scrollable') === 'true';\n \n // Check for height/max-height constraints that often indicate scrolling content\n const hasHeightConstraint = parentStyle.maxHeight && \n parentStyle.maxHeight !== 'none' && \n parentStyle.maxHeight !== 'auto';\n \n // An element is scrollable if it has:\n // 1. Actual scrollbars in use (most reliable check) OR\n // 2. Overflow styles allowing scrolling AND content that would require scrolling\n const isScrollable = (hasScrollHeight && hasOverflowY) || \n (hasScrollWidth && hasOverflowX) ||\n (hasScrollClasses && (hasScrollHeight || hasScrollWidth)) ||\n (hasHeightConstraint && hasScrollHeight);\n \n if (isScrollable) {\n const parentRect = parent.getBoundingClientRect();\n \n // Calculate how much of the element is visible within the container\n const visibilityRatio = calculateVisibleAreaRatio(rect, parentRect);\n \n // Only consider elements as overlaid if they're completely invisible (0% visible)\n // This ensures elements partially visible at the bottom of scrollable containers are still detected\n if (visibilityRatio === 0) {\n diagnosticLog('Element is in scrollable container but completely invisible:', {\n visibilityRatio: visibilityRatio,\n elementRect: {\n top: rect.top,\n right: rect.right,\n bottom: rect.bottom,\n left: rect.left\n },\n containerRect: {\n top: parentRect.top,\n right: parentRect.right,\n bottom: parentRect.bottom,\n left: parentRect.left\n },\n containerClass: parent.className,\n hasScrollHeight,\n hasScrollWidth,\n hasOverflowY,\n hasOverflowX\n });\n return true;\n }\n }\n \n parent = parent.parentElement;\n }\n \n return false;\n }\n \n // Check if element is in a scrollable container but not fully visible\n let isInScrollableContainerOnly = false;\n \n // For all elements, check if in scrollable container but not fully visible\n isInScrollableContainerOnly = isInScrollableContainerButNotFullyVisible(element);\n \n // Special handling for elements in scrollable containers\n if (isInScrollableContainerOnly) {\n // Special handling for very deep nested selectors (which are often in scrollable containers)\n // These are typically elements in tables, lists, and grids with scroll\n if (elementInfo.css_selector && \n (elementInfo.css_selector.split('>').length > 10 || \n (elementInfo.element.className && \n typeof elementInfo.element.className === 'string' && \n (elementInfo.element.className.includes('widget') || \n elementInfo.element.className.includes('list-item') ||\n elementInfo.element.className.includes('item') ||\n elementInfo.element.className.includes('card') ||\n elementInfo.element.className.includes('result'))))) {\n \n diagnosticLog('Allowing deeply nested element in scrollable container:', \n elementInfo.css_selector.substring(0, 100) + '...');\n // Don't consider it overlaid, this is likely a valid item in a scrollable list/table/widget\n return false;\n }\n return true; // Element needs scrolling to be fully visible\n }\n \n // If no element found at this point, or if element is self/ancestor/descendant, \n // this point is not overlaid\n if (!elementAtPoint ||\n elementAtPoint === element || \n isDecendent(element, elementAtPoint) || \n isDecendent(elementAtPoint, element)) {\n continue;\n }\n \n // Check if this point is covered by a popup/modal - this takes precedence\n if (isElementOrAncestorPopup(elementAtPoint)) {\n isUnderPopup = true;\n overlaidPoints++;\n continue;\n }\n \n // Special handling for complex components like those with Shadow DOM\n if ((isComplexComponent || isFrameworkButton) && !isUnderPopup) {\n // Only count as overlaid if it's clearly not part of the component's internal structure\n // For complex components, elementFromPoint often returns internal implementation details\n // that shouldn't count as \"overlaying\" the component itself\n \n // Skip points that might be part of the same component system\n if (elementAtPoint.tagName && elementAtPoint.tagName.toLowerCase().includes('-')) {\n // Custom elements (containing dash in the name) are likely part of the component framework\n continue;\n }\n \n // Only count clear UI overlays like dialogs or tooltips as actual overlays\n const elementTag = elementAtPoint.tagName.toLowerCase();\n const isOverlayingElement = elementTag === 'dialog' || \n elementAtPoint.getAttribute('role') === 'dialog' ||\n elementAtPoint.getAttribute('role') === 'tooltip' ||\n (elementAtPoint.className && \n typeof elementAtPoint.className === 'string' && \n (elementAtPoint.className.includes('overlay') || \n elementAtPoint.className.includes('modal') ||\n elementAtPoint.className.includes('popup')));\n \n if (!isOverlayingElement) {\n continue; // Don't count this point as overlaid for complex components\n }\n }\n \n // Special check for debug rows and elements from topbar\n /* Debug code - commented out\n if (isRowToDebug && elementAtPoint.tagName === 'SPAN' && \n elementAtPoint.className && \n typeof elementAtPoint.className === 'string' && \n (elementAtPoint.className.includes('tab') || \n elementAtPoint.className.includes('nav') ||\n elementAtPoint.className.includes('topbar'))) {\n continue;\n }\n */\n \n // If this point is covered by a top navigation element, don't count it as overlaid\n if (isNearTopOfViewport && isElementOrAncestorTopNav(elementAtPoint)) {\n continue;\n }\n \n // This point is overlaid by something else\n overlaidPoints++;\n if (isComplexComponent || isFrameworkButton) {\n diagnosticLog('Point is overlaid by element:', elementAtPoint.tagName);\n }\n }\n \n // If we don't have any valid points (all outside viewport), element isn't overlaid\n if (validPoints === 0) {\n /* Debug code - commented out\n if (isRowToDebug) {\n console.log('No valid points inside viewport');\n console.log('Final overlay decision: NOT OVERLAID');\n console.log('-------------------------------------------');\n }\n */\n return false;\n }\n \n // If we detected the element is under a popup with significant coverage, it's overlaid\n if (isUnderPopup && overlaidPoints > (validPoints / 2)) {\n /* Debug code - commented out\n if (isRowToDebug) {\n console.log('Element is under a popup/modal with significant coverage');\n console.log('Final overlay decision: OVERLAID');\n console.log('-------------------------------------------');\n }\n */\n return true;\n }\n \n // Calculate percentage of points that are overlaid\n const overlaidPercentage = overlaidPoints / validPoints;\n \n // For complex components, we want to be especially certain they're truly overlaid\n // rather than just having framework-specific DOM complexities\n let overlayThreshold = 0.5; // Default threshold - 50% of points must be overlaid\n \n // Complex components require stronger evidence of overlay\n if ((isComplexComponent || isFrameworkButton) && !isUnderPopup) {\n // For complex components like those with Shadow DOM, \n // we need stronger evidence they're actually overlaid\n overlayThreshold = 0.7; // 70% of points must be overlaid for complex components\n }\n \n // More robust threshold - require sufficient points to be overlaid based on component type\n const isElementOverlaid = overlaidPercentage > overlayThreshold;\n \n return isElementOverlaid;\n }\n\n const highlight = {\n execute: async function(elementTypes, handleScroll=false) {\n const elements = await findElements(elementTypes);\n highlightElements(elements);\n return elements;\n },\n\n unexecute: function(handleScroll=false) {\n unhighlightElements(handleScroll);\n },\n\n generateJSON: async function() {\n const json = {};\n await Promise.all(Object.values(ElementTag).map(async elementType => {\n const elements = await findElements(elementType);\n json[elementType] = elements;\n }));\n\n // Serialize the JSON object\n const jsonString = JSON.stringify(json, null, 4); // Pretty print with 4 spaces\n\n console.log(`JSON: ${jsonString}`);\n return jsonString;\n },\n\n getElementInfo\n };\n\n\n function unhighlightElements(handleScroll=false) {\n const documents = getAllFrames();\n documents.forEach(doc => {\n const overlay = doc.getElementById('highlight-overlay');\n if (overlay) {\n if (handleScroll) {\n // Remove event listeners\n doc.removeEventListener('scroll', overlay.scrollHandler, true);\n doc.removeEventListener('resize', overlay.resizeHandler);\n }\n overlay.remove();\n }\n });\n }\n\n\n\n\n async function findElements(elementTypes, verbose=true) {\n const typesArray = Array.isArray(elementTypes) ? elementTypes : [elementTypes];\n console.log('Starting element search for types:', typesArray);\n\n const elements = [];\n typesArray.forEach(elementType => {\n if (elementType === ElementTag.FILLABLE) {\n elements.push(...findFillables());\n }\n if (elementType === ElementTag.SELECTABLE) {\n elements.push(...findDropdowns());\n }\n if (elementType === ElementTag.CLICKABLE) {\n elements.push(...findClickables());\n elements.push(...findToggles());\n elements.push(...findCheckables());\n }\n if (elementType === ElementTag.NON_INTERACTIVE_ELEMENT) {\n elements.push(...findNonInteractiveElements());\n }\n });\n\n // console.log('Before uniquify:', elements.length);\n const elementsWithInfo = elements.map((element, index) => \n getElementInfo(element, index)\n );\n \n const uniqueElements = uniquifyElements(elementsWithInfo);\n console.log(`Found ${uniqueElements.length} elements:`);\n \n // More comprehensive visibility check\n const visibleElements = uniqueElements.filter(elementInfo => {\n const el = elementInfo.element;\n const style = getComputedStyle(el);\n \n // Check various style properties that affect visibility\n if (style.display === 'none' || \n style.visibility === 'hidden' || \n parseFloat(style.opacity) === 0) {\n return false;\n }\n \n // Check if element has non-zero dimensions\n const rect = el.getBoundingClientRect();\n if (rect.width === 0 || rect.height === 0) {\n return false;\n }\n \n // Check if element is within viewport\n if (rect.bottom < 0 || \n rect.top > window.innerHeight || \n rect.right < 0 || \n rect.left > window.innerWidth) {\n // Element is outside viewport, but still might be valid \n // if user scrolls to it, so we'll include it\n return true;\n }\n \n return true;\n });\n \n console.log(`Out of which ${visibleElements.length} elements are visible:`);\n if (verbose) {\n visibleElements.forEach(info => {\n console.log(`Element ${info.index}:`, info);\n });\n }\n \n return visibleElements;\n }\n\n // elements is an array of objects with index, xpath\n function highlightElements(elements) {\n // console.log('Starting highlight for elements:', elements);\n \n // Create overlay if it doesn't exist and store it in a dictionary\n const documents = getAllFrames(); \n let overlays = {};\n documents.forEach(doc => {\n let overlay = doc.getElementById('highlight-overlay');\n if (!overlay) {\n overlay = doc.createElement('div');\n overlay.id = 'highlight-overlay';\n overlay.style.cssText = `\n position: fixed;\n top: 0;\n left: 0;\n width: 100%;\n height: 100%;\n pointer-events: none;\n z-index: 10000;\n `;\n doc.body.appendChild(overlay);\n }\n overlays[doc.documentURI] = overlay;\n });\n \n\n const updateHighlights = (doc = null) => {\n if (doc) {\n overlays[doc.documentURI].innerHTML = '';\n } else {\n Object.values(overlays).forEach(overlay => { overlay.innerHTML = ''; });\n } \n elements.forEach(elementInfo => {\n // console.log('updateHighlights-Processing elementInfo:', elementInfo);\n let element = elementInfo.element; //getElementByXPathOrCssSelector(elementInfo);\n if (!element) {\n element = getElementByXPathOrCssSelector(elementInfo);\n if (!element)\n return;\n }\n \n //if highlights requested for a specific doc, skip unrelated elements\n if (doc && element.ownerDocument !== doc) {\n console.log(\"skipped element \", element, \" since it doesn't belong to document \", doc);\n return;\n }\n\n const rect = element.getBoundingClientRect();\n // console.log('Element rect:', elementInfo.tag, rect);\n \n if (rect.width === 0 || rect.height === 0) {\n console.warn('Element has zero dimensions:', elementInfo);\n return;\n }\n \n // Create border highlight (red rectangle)\n // use ownerDocument to support iframes/frames\n const highlight = element.ownerDocument.createElement('div');\n highlight.style.cssText = `\n position: fixed;\n left: ${rect.x}px;\n top: ${rect.y}px;\n width: ${rect.width}px;\n height: ${rect.height}px;\n border: 1px solid rgb(255, 0, 0);\n transition: all 0.2s ease-in-out;\n `;\n\n // Create index label container - now positioned to the right and slightly up\n const labelContainer = element.ownerDocument.createElement('div');\n labelContainer.style.cssText = `\n position: absolute;\n right: -10px; /* Offset to the right */\n top: -10px; /* Offset upwards */\n padding: 4px;\n background-color: rgba(255, 255, 0, 0.6);\n display: flex;\n align-items: center;\n justify-content: center;\n `;\n\n const text = element.ownerDocument.createElement('span');\n text.style.cssText = `\n color: rgb(0, 0, 0, 0.8);\n font-family: 'Courier New', Courier, monospace;\n font-size: 12px;\n font-weight: bold;\n line-height: 1;\n `;\n text.textContent = elementInfo.index;\n \n labelContainer.appendChild(text);\n highlight.appendChild(labelContainer); \n overlays[element.ownerDocument.documentURI].appendChild(highlight);\n });\n };\n\n // Initial highlight\n updateHighlights();\n\n documents.forEach(doc => {\n // Update highlights on scroll and resize\n console.log('registering scroll and resize handlers for document: ', doc);\n const scrollHandler = () => {\n requestAnimationFrame(() => updateHighlights(doc));\n };\n const resizeHandler = () => {\n updateHighlights(doc);\n };\n doc.addEventListener('scroll', scrollHandler, true);\n doc.addEventListener('resize', resizeHandler);\n // Store event handlers for cleanup\n overlays[doc.documentURI].scrollHandler = scrollHandler;\n overlays[doc.documentURI].resizeHandler = resizeHandler;\n }); \n }\n\n // function unexecute() {\n // unhighlightElements();\n // }\n\n // Make it available globally for both Extension and Playwright\n if (typeof window !== 'undefined') {\n window.ProboLabs = {\n ElementTag,\n highlight,\n unhighlightElements,\n findElements,\n highlightElements,\n getElementInfo\n };\n }\n\n exports.findElements = findElements;\n exports.getElementInfo = getElementInfo;\n exports.highlight = highlight;\n exports.highlightElements = highlightElements;\n exports.unhighlightElements = unhighlightElements;\n\n Object.defineProperty(exports, '__esModule', { value: true });\n\n}));\n//# sourceMappingURL=probolabs.umd.js.map\n";
|
|
2
|
+
const ElementTag = {
|
|
3
|
+
CLICKABLE: "CLICKABLE", // button, link, toggle switch, checkbox, radio, dropdowns, clickable divs
|
|
4
|
+
FILLABLE: "FILLABLE", // input, textarea content_editable, date picker??
|
|
5
|
+
SELECTABLE: "SELECTABLE", // select
|
|
6
|
+
NON_INTERACTIVE_ELEMENT: 'NON_INTERACTIVE_ELEMENT',
|
|
7
7
|
};
|
|
8
8
|
|
|
9
9
|
var ProboLogLevel;
|
|
@@ -127,7 +127,7 @@ const PlaywrightAction = {
|
|
|
127
127
|
/**
|
|
128
128
|
* Handle potential navigation exactly like Python's handle_potential_navigation
|
|
129
129
|
*/
|
|
130
|
-
async function handlePotentialNavigation(page, locator = null, options = {}) {
|
|
130
|
+
async function handlePotentialNavigation(page, locator = null, value = null, options = {}) {
|
|
131
131
|
const { initialTimeout = 5000, navigationTimeout = 7000, globalTimeout = 15000, } = options;
|
|
132
132
|
const startTime = Date.now();
|
|
133
133
|
let navigationCount = 0;
|
|
@@ -143,8 +143,8 @@ async function handlePotentialNavigation(page, locator = null, options = {}) {
|
|
|
143
143
|
page.on("framenavigated", onFrameNav);
|
|
144
144
|
try {
|
|
145
145
|
if (locator) {
|
|
146
|
-
proboLogger.debug(`DEBUG_NAV: Executing click()`);
|
|
147
|
-
await
|
|
146
|
+
proboLogger.debug(`DEBUG_NAV: Executing click(${value})`);
|
|
147
|
+
await clickAtPosition(page, locator, value);
|
|
148
148
|
}
|
|
149
149
|
// wait for any initial nav to fire
|
|
150
150
|
await page.waitForTimeout(initialTimeout);
|
|
@@ -361,7 +361,7 @@ async function executePlaywrightAction(page, action, value, iframe_selector, ele
|
|
|
361
361
|
locator = page.locator(element_css_selector);
|
|
362
362
|
switch (action) {
|
|
363
363
|
case PlaywrightAction.CLICK:
|
|
364
|
-
await handlePotentialNavigation(page, locator);
|
|
364
|
+
await handlePotentialNavigation(page, locator, value);
|
|
365
365
|
break;
|
|
366
366
|
case PlaywrightAction.FILL_IN:
|
|
367
367
|
await locator.click();
|
|
@@ -449,7 +449,7 @@ async function executeCachedPlaywrightAction(page, action, value, iframe_selecto
|
|
|
449
449
|
await page.goto(value, { waitUntil: 'networkidle' });
|
|
450
450
|
break;
|
|
451
451
|
case PlaywrightAction.CLICK:
|
|
452
|
-
await locator
|
|
452
|
+
await clickAtPosition(page, locator, value);
|
|
453
453
|
await handlePotentialNavigation(page);
|
|
454
454
|
break;
|
|
455
455
|
case PlaywrightAction.FILL_IN:
|
|
@@ -520,6 +520,30 @@ async function executeCachedPlaywrightAction(page, action, value, iframe_selecto
|
|
|
520
520
|
throw e;
|
|
521
521
|
}
|
|
522
522
|
}
|
|
523
|
+
var ClickPosition;
|
|
524
|
+
(function (ClickPosition) {
|
|
525
|
+
ClickPosition["LEFT"] = "LEFT";
|
|
526
|
+
ClickPosition["RIGHT"] = "RIGHT";
|
|
527
|
+
ClickPosition["CENTER"] = "CENTER";
|
|
528
|
+
})(ClickPosition || (ClickPosition = {}));
|
|
529
|
+
/**
|
|
530
|
+
* Click on an element at a specific position
|
|
531
|
+
*/
|
|
532
|
+
async function clickAtPosition(page, locator, clickPosition) {
|
|
533
|
+
if (!clickPosition || clickPosition === ClickPosition.CENTER) {
|
|
534
|
+
await locator.click({ noWaitAfter: false });
|
|
535
|
+
return;
|
|
536
|
+
}
|
|
537
|
+
const boundingBox = await locator.boundingBox();
|
|
538
|
+
if (boundingBox) {
|
|
539
|
+
if (clickPosition === ClickPosition.LEFT) {
|
|
540
|
+
await page.mouse.click(boundingBox.x + 10, boundingBox.y + boundingBox.height / 2);
|
|
541
|
+
}
|
|
542
|
+
else if (clickPosition === ClickPosition.RIGHT) {
|
|
543
|
+
await page.mouse.click(boundingBox.x + boundingBox.width - 10, boundingBox.y + boundingBox.height / 2);
|
|
544
|
+
}
|
|
545
|
+
}
|
|
546
|
+
}
|
|
523
547
|
|
|
524
548
|
class Highlighter {
|
|
525
549
|
constructor(enableConsoleLogs = true) {
|
|
@@ -533,9 +557,9 @@ class Highlighter {
|
|
|
533
557
|
proboLogger.debug('Injecting highlighter script...');
|
|
534
558
|
await page.evaluate(highlighterCode);
|
|
535
559
|
// Verify the script was injected correctly
|
|
536
|
-
const verified = await page.evaluate(`
|
|
537
|
-
//console.log('ProboLabs global:', window.ProboLabs);
|
|
538
|
-
typeof window.ProboLabs?.highlight?.execute === 'function'
|
|
560
|
+
const verified = await page.evaluate(`
|
|
561
|
+
//console.log('ProboLabs global:', window.ProboLabs);
|
|
562
|
+
typeof window.ProboLabs?.highlight?.execute === 'function'
|
|
539
563
|
`);
|
|
540
564
|
proboLogger.debug('Script injection verified:', verified);
|
|
541
565
|
}
|