@base44/vite-plugin 0.2.24 → 0.2.26

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.
Files changed (38) hide show
  1. package/dist/injections/layer-dropdown/consts.d.ts +19 -0
  2. package/dist/injections/layer-dropdown/consts.d.ts.map +1 -0
  3. package/dist/injections/layer-dropdown/consts.js +40 -0
  4. package/dist/injections/layer-dropdown/consts.js.map +1 -0
  5. package/dist/injections/layer-dropdown/controller.d.ts +4 -0
  6. package/dist/injections/layer-dropdown/controller.d.ts.map +1 -0
  7. package/dist/injections/layer-dropdown/controller.js +88 -0
  8. package/dist/injections/layer-dropdown/controller.js.map +1 -0
  9. package/dist/injections/layer-dropdown/dropdown-ui.d.ts +13 -0
  10. package/dist/injections/layer-dropdown/dropdown-ui.d.ts.map +1 -0
  11. package/dist/injections/layer-dropdown/dropdown-ui.js +176 -0
  12. package/dist/injections/layer-dropdown/dropdown-ui.js.map +1 -0
  13. package/dist/injections/layer-dropdown/types.d.ts +26 -0
  14. package/dist/injections/layer-dropdown/types.d.ts.map +1 -0
  15. package/dist/injections/layer-dropdown/types.js +3 -0
  16. package/dist/injections/layer-dropdown/types.js.map +1 -0
  17. package/dist/injections/layer-dropdown/utils.d.ts +25 -0
  18. package/dist/injections/layer-dropdown/utils.d.ts.map +1 -0
  19. package/dist/injections/layer-dropdown/utils.js +143 -0
  20. package/dist/injections/layer-dropdown/utils.js.map +1 -0
  21. package/dist/injections/utils.d.ts +9 -0
  22. package/dist/injections/utils.d.ts.map +1 -1
  23. package/dist/injections/utils.js +33 -0
  24. package/dist/injections/utils.js.map +1 -1
  25. package/dist/injections/visual-edit-agent.d.ts.map +1 -1
  26. package/dist/injections/visual-edit-agent.js +115 -69
  27. package/dist/injections/visual-edit-agent.js.map +1 -1
  28. package/dist/statics/index.mjs +1 -1
  29. package/dist/statics/index.mjs.map +1 -1
  30. package/package.json +1 -1
  31. package/src/injections/layer-dropdown/LAYERS.md +258 -0
  32. package/src/injections/layer-dropdown/consts.ts +49 -0
  33. package/src/injections/layer-dropdown/controller.ts +109 -0
  34. package/src/injections/layer-dropdown/dropdown-ui.ts +230 -0
  35. package/src/injections/layer-dropdown/types.ts +30 -0
  36. package/src/injections/layer-dropdown/utils.ts +175 -0
  37. package/src/injections/utils.ts +44 -1
  38. package/src/injections/visual-edit-agent.ts +141 -80
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/injections/utils.ts","../../src/injections/visual-edit-agent.ts"],"sourcesContent":["/** Find elements by ID - first try data-source-location, fallback to data-visual-selector-id */\nexport function findElementsById(id: string | null): Element[] {\n if (!id) return [];\n const sourceElements = Array.from(\n document.querySelectorAll(`[data-source-location=\"${id}\"]`)\n );\n if (sourceElements.length > 0) {\n return sourceElements;\n }\n return Array.from(\n document.querySelectorAll(`[data-visual-selector-id=\"${id}\"]`)\n );\n}\n\n/**\n * Update element classes by visual selector ID.\n * Uses setAttribute instead of className to support both HTML and SVG elements.\n */\nexport function updateElementClasses(elements: Element[], classes: string): void {\n elements.forEach((element) => {\n element.setAttribute(\"class\", classes);\n }); \n}\n","import { findElementsById, updateElementClasses } from \"./utils.js\";\n\nexport function setupVisualEditAgent() {\n // State variables (replacing React useState/useRef)\n let isVisualEditMode = false;\n let isPopoverDragging = false;\n let isDropdownOpen = false;\n let hoverOverlays: HTMLDivElement[] = [];\n let selectedOverlays: HTMLDivElement[] = [];\n let currentHighlightedElements: Element[] = [];\n let selectedElementId: string | null = null;\n\n // Create overlay element\n const createOverlay = (isSelected = false): HTMLDivElement => {\n const overlay = document.createElement(\"div\");\n overlay.style.position = \"absolute\";\n overlay.style.pointerEvents = \"none\";\n overlay.style.transition = \"all 0.1s ease-in-out\";\n overlay.style.zIndex = \"9999\";\n\n if (isSelected) {\n overlay.style.border = \"2px solid #2563EB\";\n } else {\n overlay.style.border = \"2px solid #95a5fc\";\n overlay.style.backgroundColor = \"rgba(99, 102, 241, 0.05)\";\n }\n\n return overlay;\n };\n\n // Position overlay relative to element\n const positionOverlay = (\n overlay: HTMLDivElement,\n element: Element,\n isSelected = false\n ) => {\n if (!element || !isVisualEditMode) return;\n\n const htmlElement = element as HTMLElement;\n // Force layout recalculation\n void htmlElement.offsetWidth;\n\n const rect = element.getBoundingClientRect();\n overlay.style.top = `${rect.top + window.scrollY}px`;\n overlay.style.left = `${rect.left + window.scrollX}px`;\n overlay.style.width = `${rect.width}px`;\n overlay.style.height = `${rect.height}px`;\n\n // Check if label already exists in overlay\n let label = overlay.querySelector(\"div\") as HTMLDivElement | null;\n\n if (!label) {\n label = document.createElement(\"div\");\n label.textContent = element.tagName.toLowerCase();\n label.style.position = \"absolute\";\n label.style.top = \"-27px\";\n label.style.left = \"-2px\";\n label.style.padding = \"2px 8px\";\n label.style.fontSize = \"11px\";\n label.style.fontWeight = isSelected ? \"500\" : \"400\";\n label.style.color = isSelected ? \"#ffffff\" : \"#526cff\";\n label.style.backgroundColor = isSelected ? \"#526cff\" : \"#DBEAFE\";\n label.style.borderRadius = \"3px\";\n label.style.minWidth = \"24px\";\n label.style.textAlign = \"center\";\n overlay.appendChild(label);\n }\n };\n\n // Clear hover overlays\n const clearHoverOverlays = () => {\n hoverOverlays.forEach((overlay) => {\n if (overlay && overlay.parentNode) {\n overlay.remove();\n }\n });\n hoverOverlays = [];\n currentHighlightedElements = [];\n };\n\n // Handle mouse over event\n const handleMouseOver = (e: MouseEvent) => {\n if (!isVisualEditMode || isPopoverDragging) return;\n\n const target = e.target as Element;\n\n // Prevent hover effects when a dropdown is open\n if (isDropdownOpen) {\n clearHoverOverlays();\n return;\n }\n\n // Prevent hover effects on SVG path elements\n if (target.tagName.toLowerCase() === \"path\") {\n clearHoverOverlays();\n return;\n }\n\n // Support both data-source-location and data-visual-selector-id\n const element = target.closest(\n \"[data-source-location], [data-visual-selector-id]\"\n );\n if (!element) {\n clearHoverOverlays();\n return;\n }\n\n // Prefer data-source-location, fallback to data-visual-selector-id\n const htmlElement = element as HTMLElement;\n const selectorId =\n htmlElement.dataset.sourceLocation ||\n htmlElement.dataset.visualSelectorId;\n\n // Skip if this element is already selected\n if (selectedElementId === selectorId) {\n clearHoverOverlays();\n return;\n }\n\n // Find all elements with the same ID\n const elements = findElementsById(selectorId || null);\n\n // Clear previous hover overlays\n clearHoverOverlays();\n\n // Create overlays for all matching elements\n elements.forEach((el) => {\n const overlay = createOverlay(false);\n document.body.appendChild(overlay);\n hoverOverlays.push(overlay);\n positionOverlay(overlay, el);\n });\n\n currentHighlightedElements = elements;\n };\n\n // Handle mouse out event\n const handleMouseOut = () => {\n if (isPopoverDragging) return;\n clearHoverOverlays();\n };\n\n // Handle element click\n const handleElementClick = (e: MouseEvent) => {\n if (!isVisualEditMode) return;\n\n const target = e.target as Element;\n\n // Close dropdowns when clicking anywhere in iframe if a dropdown is open\n if (isDropdownOpen) {\n e.preventDefault();\n e.stopPropagation();\n e.stopImmediatePropagation();\n\n window.parent.postMessage({ type: \"close-dropdowns\" }, \"*\");\n return;\n }\n\n // Prevent clicking on SVG path elements\n if (target.tagName.toLowerCase() === \"path\") {\n return;\n }\n\n // Prevent default behavior immediately when in visual edit mode\n e.preventDefault();\n e.stopPropagation();\n e.stopImmediatePropagation();\n\n // Support both data-source-location and data-visual-selector-id\n const element = target.closest(\n \"[data-source-location], [data-visual-selector-id]\"\n );\n if (!element) {\n return;\n }\n\n const htmlElement = element as HTMLElement;\n const visualSelectorId =\n htmlElement.dataset.sourceLocation ||\n htmlElement.dataset.visualSelectorId;\n\n // Clear any existing selected overlays\n selectedOverlays.forEach((overlay) => {\n if (overlay && overlay.parentNode) {\n overlay.remove();\n }\n });\n selectedOverlays = [];\n\n // Find all elements with the same ID\n const elements = findElementsById(visualSelectorId || null);\n\n // Create selected overlays for all matching elements\n elements.forEach((el) => {\n const overlay = createOverlay(true);\n document.body.appendChild(overlay);\n selectedOverlays.push(overlay);\n positionOverlay(overlay, el, true);\n });\n\n selectedElementId = visualSelectorId || null;\n\n // Clear hover overlays\n clearHoverOverlays();\n\n // Calculate element position for popover positioning\n const rect = element.getBoundingClientRect();\n const elementPosition = {\n top: rect.top,\n left: rect.left,\n right: rect.right,\n bottom: rect.bottom,\n width: rect.width,\n height: rect.height,\n centerX: rect.left + rect.width / 2,\n centerY: rect.top + rect.height / 2,\n };\n\n const isTextElement = ['p', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'span', 'a', 'label'].includes(element.tagName?.toLowerCase())\n\n // Send message to parent window with element info including position\n const svgElement = element as SVGElement;\n const elementData = {\n type: \"element-selected\",\n tagName: element.tagName,\n classes:\n (svgElement.className as unknown as SVGAnimatedString)?.baseVal ||\n element.className ||\n \"\",\n visualSelectorId: visualSelectorId,\n content: isTextElement ? (element as HTMLElement).innerText : undefined,\n dataSourceLocation: htmlElement.dataset.sourceLocation,\n isDynamicContent: htmlElement.dataset.dynamicContent === \"true\",\n linenumber: htmlElement.dataset.linenumber,\n filename: htmlElement.dataset.filename,\n position: elementPosition,\n isTextElement: isTextElement,\n };\n window.parent.postMessage(elementData, \"*\");\n };\n\n // Unselect the current element\n const unselectElement = () => {\n selectedOverlays.forEach((overlay) => {\n if (overlay && overlay.parentNode) {\n overlay.remove();\n }\n });\n selectedOverlays = [];\n selectedElementId = null;\n };\n\n const updateElementClassesAndReposition = (visualSelectorId: string, classes: string) => {\n const elements = findElementsById(visualSelectorId);\n if (elements.length === 0) return;\n\n updateElementClasses(elements, classes);\n\n // Use a small delay to allow the browser to recalculate layout before repositioning\n setTimeout(() => {\n // Reposition selected overlays\n if (selectedElementId === visualSelectorId) {\n selectedOverlays.forEach((overlay, index) => {\n if (index < elements.length) {\n positionOverlay(overlay, elements[index]!);\n }\n });\n }\n\n // Reposition hover overlays if needed\n if (currentHighlightedElements.length > 0) {\n const hoveredElement = currentHighlightedElements[0] as HTMLElement;\n const hoveredId = hoveredElement?.dataset?.visualSelectorId;\n if (hoveredId === visualSelectorId) {\n hoverOverlays.forEach((overlay, index) => {\n if (index < currentHighlightedElements.length) {\n positionOverlay(overlay, currentHighlightedElements[index]!);\n }\n });\n }\n }\n }, 50);\n };\n\n // Update element content by visual selector ID\n const updateElementContent = (visualSelectorId: string, content: string) => {\n const elements = findElementsById(visualSelectorId);\n\n if (elements.length === 0) {\n return;\n }\n\n elements.forEach((element) => {\n (element as HTMLElement).innerText = content;\n });\n\n setTimeout(() => {\n if (selectedElementId === visualSelectorId) {\n selectedOverlays.forEach((overlay, index) => {\n if (index < elements.length) {\n positionOverlay(overlay, elements[index]!);\n }\n });\n }\n }, 50);\n };\n\n // Toggle visual edit mode\n const toggleVisualEditMode = (isEnabled: boolean) => {\n isVisualEditMode = isEnabled;\n\n if (!isEnabled) {\n clearHoverOverlays();\n\n selectedOverlays.forEach((overlay) => {\n if (overlay && overlay.parentNode) {\n overlay.remove();\n }\n });\n selectedOverlays = [];\n\n currentHighlightedElements = [];\n selectedElementId = null;\n document.body.style.cursor = \"default\";\n\n document.removeEventListener(\"mouseover\", handleMouseOver);\n document.removeEventListener(\"mouseout\", handleMouseOut);\n document.removeEventListener(\"click\", handleElementClick, true);\n } else {\n document.body.style.cursor = \"crosshair\";\n document.addEventListener(\"mouseover\", handleMouseOver);\n document.addEventListener(\"mouseout\", handleMouseOut);\n document.addEventListener(\"click\", handleElementClick, true);\n }\n };\n\n // Handle scroll events to update popover position\n const handleScroll = () => {\n if (selectedElementId) {\n const elements = findElementsById(selectedElementId);\n if (elements.length > 0) {\n const element = elements[0];\n const rect = element!.getBoundingClientRect();\n\n const viewportHeight = window.innerHeight;\n const viewportWidth = window.innerWidth;\n const isInViewport =\n rect.top < viewportHeight &&\n rect.bottom > 0 &&\n rect.left < viewportWidth &&\n rect.right > 0;\n\n const elementPosition = {\n top: rect.top,\n left: rect.left,\n right: rect.right,\n bottom: rect.bottom,\n width: rect.width,\n height: rect.height,\n centerX: rect.left + rect.width / 2,\n centerY: rect.top + rect.height / 2,\n };\n\n window.parent.postMessage(\n {\n type: \"element-position-update\",\n position: elementPosition,\n isInViewport: isInViewport,\n visualSelectorId: selectedElementId,\n },\n \"*\"\n );\n }\n }\n };\n\n // Handle messages from parent window\n const handleMessage = (event: MessageEvent) => {\n const message = event.data;\n\n switch (message.type) {\n case \"toggle-visual-edit-mode\":\n toggleVisualEditMode(message.data.enabled);\n break;\n\n case \"update-classes\":\n if (message.data && message.data.classes !== undefined) {\n updateElementClassesAndReposition(\n message.data.visualSelectorId,\n message.data.classes\n );\n } else {\n console.warn(\n \"[VisualEditAgent] Invalid update-classes message:\",\n message\n );\n }\n break;\n\n case \"unselect-element\":\n unselectElement();\n break;\n\n case \"refresh-page\":\n window.location.reload();\n break;\n\n case \"update-content\":\n if (message.data && message.data.content !== undefined) {\n updateElementContent(\n message.data.visualSelectorId,\n message.data.content\n );\n } else {\n console.warn(\n \"[VisualEditAgent] Invalid update-content message:\",\n message\n );\n }\n break;\n\n case \"request-element-position\":\n if (selectedElementId) {\n const elements = findElementsById(selectedElementId);\n if (elements.length > 0) {\n const element = elements[0];\n const rect = element!.getBoundingClientRect();\n\n const viewportHeight = window.innerHeight;\n const viewportWidth = window.innerWidth;\n const isInViewport =\n rect.top < viewportHeight &&\n rect.bottom > 0 &&\n rect.left < viewportWidth &&\n rect.right > 0;\n\n const elementPosition = {\n top: rect.top,\n left: rect.left,\n right: rect.right,\n bottom: rect.bottom,\n width: rect.width,\n height: rect.height,\n centerX: rect.left + rect.width / 2,\n centerY: rect.top + rect.height / 2,\n };\n\n window.parent.postMessage(\n {\n type: \"element-position-update\",\n position: elementPosition,\n isInViewport: isInViewport,\n visualSelectorId: selectedElementId,\n },\n \"*\"\n );\n }\n }\n break;\n\n case \"popover-drag-state\":\n if (message.data && message.data.isDragging !== undefined) {\n isPopoverDragging = message.data.isDragging;\n if (message.data.isDragging) {\n clearHoverOverlays();\n }\n }\n break;\n\n case \"dropdown-state\":\n if (message.data && message.data.isOpen !== undefined) {\n isDropdownOpen = message.data.isOpen;\n if (message.data.isOpen) {\n clearHoverOverlays();\n }\n }\n break;\n\n default:\n break;\n }\n };\n\n // Handle window resize to reposition overlays\n const handleResize = () => {\n if (selectedElementId) {\n const elements = findElementsById(selectedElementId);\n selectedOverlays.forEach((overlay, index) => {\n if (index < elements.length) {\n positionOverlay(overlay, elements[index]!);\n }\n });\n }\n\n if (currentHighlightedElements.length > 0) {\n hoverOverlays.forEach((overlay, index) => {\n if (index < currentHighlightedElements.length) {\n positionOverlay(overlay, currentHighlightedElements[index]!);\n }\n });\n }\n };\n\n // Initialize: Add IDs to elements that don't have them but have linenumbers\n const elementsWithLineNumber = document.querySelectorAll(\n \"[data-linenumber]:not([data-visual-selector-id])\"\n );\n elementsWithLineNumber.forEach((el, index) => {\n const htmlEl = el as HTMLElement;\n const id = `visual-id-${htmlEl.dataset.filename}-${htmlEl.dataset.linenumber}-${index}`;\n htmlEl.dataset.visualSelectorId = id;\n });\n\n // Create mutation observer to detect layout changes\n const mutationObserver = new MutationObserver((mutations) => {\n const needsUpdate = mutations.some((mutation) => {\n const hasVisualId = (node: Node): boolean => {\n if (node.nodeType === Node.ELEMENT_NODE) {\n const el = node as HTMLElement;\n if (el.dataset && el.dataset.visualSelectorId) {\n return true;\n }\n for (let i = 0; i < el.children.length; i++) {\n if (hasVisualId(el.children[i]!)) {\n return true;\n }\n }\n }\n return false;\n };\n\n const isLayoutChange =\n mutation.type === \"attributes\" &&\n (mutation.attributeName === \"style\" ||\n mutation.attributeName === \"class\" ||\n mutation.attributeName === \"width\" ||\n mutation.attributeName === \"height\");\n\n return isLayoutChange && hasVisualId(mutation.target);\n });\n\n if (needsUpdate) {\n setTimeout(handleResize, 50);\n }\n });\n\n // Set up event listeners\n window.addEventListener(\"message\", handleMessage);\n window.addEventListener(\"scroll\", handleScroll, true);\n document.addEventListener(\"scroll\", handleScroll, true);\n window.addEventListener(\"resize\", handleResize);\n window.addEventListener(\"scroll\", handleResize);\n\n // Start observing DOM mutations\n mutationObserver.observe(document.body, {\n attributes: true,\n childList: true,\n subtree: true,\n attributeFilter: [\"style\", \"class\", \"width\", \"height\"],\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AiB,SAAUJ,EAAc,EAAI,EACpD,SAAS,iBAAiB,SAAUA,EAAc,EAAI,EACtD,OAAO,iBAAiB,SAAUO,CAAY,EAC9C,OAAO,iBAAiB,SAAUA,CAAY,EAG9CG,EAAiB,QAAQ,SAAS,KAAM,CACtC,WAAY,GACZ,UAAW,GACX,QAAS,GACT,gBAAiB,CAAC,QAAS,QAAS,QAAS,QAAQ,CACvD,CAAC,EAGD,OAAO,OAAO,YAAY,CAAE,KAAM,yBAA0B,EAAG,GAAG,CACpE","names":["findElementsById","id","sourceElements","updateElementClasses","elements","classes","element","setupVisualEditAgent","isVisualEditMode","isPopoverDragging","isDropdownOpen","hoverOverlays","selectedOverlays","currentHighlightedElements","selectedElementId","createOverlay","isSelected","overlay","positionOverlay","element","rect","label","clearHoverOverlays","handleMouseOver","e","target","htmlElement","selectorId","elements","findElementsById","el","handleMouseOut","handleElementClick","visualSelectorId","elementPosition","isTextElement","svgElement","elementData","unselectElement","updateElementClassesAndReposition","classes","updateElementClasses","index","updateElementContent","content","toggleVisualEditMode","isEnabled","handleScroll","viewportHeight","viewportWidth","isInViewport","handleMessage","event","message","handleResize","htmlEl","id","mutationObserver","mutations","mutation","hasVisualId","node","i"]}
1
+ {"version":3,"sources":["../../src/injections/utils.ts","../../src/injections/layer-dropdown/consts.ts","../../src/injections/layer-dropdown/utils.ts","../../src/injections/layer-dropdown/dropdown-ui.ts","../../src/injections/layer-dropdown/controller.ts","../../src/injections/visual-edit-agent.ts"],"sourcesContent":["/** Check if an element has instrumentation attributes */\nexport function isInstrumentedElement(element: Element): boolean {\n const htmlEl = element as HTMLElement;\n return !!(\n htmlEl.dataset?.sourceLocation || htmlEl.dataset?.visualSelectorId\n );\n}\n\n/** Get the selector ID from an element's data attributes (prefers source-location) */\nexport function getElementSelectorId(element: Element): string | null {\n const htmlEl = element as HTMLElement;\n return (\n htmlEl.dataset?.sourceLocation ||\n htmlEl.dataset?.visualSelectorId ||\n null\n );\n}\n\nexport const ALLOWED_ATTRIBUTES: string[] = [\"src\"];\n\n/** Find elements by ID - first try data-source-location, fallback to data-visual-selector-id */\nexport function findElementsById(id: string | null): Element[] {\n if (!id) return [];\n const sourceElements = Array.from(\n document.querySelectorAll(`[data-source-location=\"${id}\"]`)\n );\n if (sourceElements.length > 0) {\n return sourceElements;\n }\n return Array.from(\n document.querySelectorAll(`[data-visual-selector-id=\"${id}\"]`)\n );\n}\n\n/**\n * Update element classes by visual selector ID.\n * Uses setAttribute instead of className to support both HTML and SVG elements.\n */\nexport function updateElementClasses(elements: Element[], classes: string): void {\n elements.forEach((element) => {\n element.setAttribute(\"class\", classes);\n });\n}\n\n/** Set a single attribute on all provided elements. */\nexport function updateElementAttribute(elements: Element[], attribute: string, value: string): void {\n if (!ALLOWED_ATTRIBUTES.includes(attribute)) {\n return;\n }\n\n elements.forEach((element) => {\n element.setAttribute(attribute, value);\n });\n}\n\n/** Collect attribute values from an element for a given allowlist. */\nexport function collectAllowedAttributes(element: Element, allowedAttributes: string[]): Record<string, string> {\n const attributes: Record<string, string> = {};\n for (const attr of allowedAttributes) {\n const val = element.getAttribute(attr);\n if (val !== null) {\n attributes[attr] = val;\n }\n }\n return attributes;\n}\n","/** Style constants for the layer dropdown UI */\n\nexport const DROPDOWN_CONTAINER_STYLES: Record<string, string> = {\n position: \"absolute\",\n backgroundColor: \"#ffffff\",\n border: \"1px solid #e2e8f0\",\n borderRadius: \"6px\",\n boxShadow: \"0 4px 12px rgba(0, 0, 0, 0.15)\",\n fontSize: \"12px\",\n minWidth: \"120px\",\n maxHeight: \"200px\",\n overflowY: \"auto\",\n zIndex: \"10001\",\n padding: \"4px 0\",\n pointerEvents: \"auto\",\n};\n\nexport const DROPDOWN_ITEM_BASE_STYLES: Record<string, string> = {\n padding: \"4px 12px\",\n cursor: \"pointer\",\n color: \"#334155\",\n backgroundColor: \"transparent\",\n whiteSpace: \"nowrap\",\n lineHeight: \"1.5\",\n fontWeight: \"400\",\n};\n\nexport const DROPDOWN_ITEM_ACTIVE_COLOR = \"#526cff\";\nexport const DROPDOWN_ITEM_ACTIVE_BG = \"#DBEAFE\";\nexport const DROPDOWN_ITEM_ACTIVE_FONT_WEIGHT = \"600\";\n\nexport const DROPDOWN_ITEM_HOVER_BG = \"#f1f5f9\";\n\nexport const DEPTH_INDENT_PX = 10;\n\n/** Chevron shown when dropdown is collapsed (click to expand) */\nexport const CHEVRON_COLLAPSED = \" \\u25BE\";\n/** Chevron shown when dropdown is expanded (click to collapse) */\nexport const CHEVRON_EXPANDED = \" \\u25B4\";\n\nexport const BASE_PADDING_PX = 12;\n\nexport const LAYER_DROPDOWN_ATTR = \"data-layer-dropdown\";\n\n/** Max instrumented ancestors to show above the selected element */\nexport const MAX_PARENT_DEPTH = 2;\n\n/** Max instrumented depth levels to show below the selected element */\nexport const MAX_CHILD_DEPTH = 2;\n","/** DOM utilities for the layer-dropdown module */\n\nimport { isInstrumentedElement, getElementSelectorId } from \"../utils.js\";\nimport { MAX_PARENT_DEPTH, MAX_CHILD_DEPTH } from \"./consts.js\";\n\nimport type { LayerInfo } from \"./types.js\";\n\n/** Apply a style map to an element */\nexport function applyStyles(element: HTMLElement, styles: Record<string, string>): void {\n for (const key of Object.keys(styles)) {\n element.style.setProperty(\n key.replace(/[A-Z]/g, (m) => `-${m.toLowerCase()}`),\n styles[key]!\n );\n }\n}\n\n/** Display name for a layer — just the real tag name */\nexport function getLayerDisplayName(layer: LayerInfo): string {\n return layer.tagName;\n}\n\nfunction toLayerInfo(element: Element, depth?: number): LayerInfo {\n const info: LayerInfo = {\n element,\n tagName: element.tagName.toLowerCase(),\n selectorId: getElementSelectorId(element),\n };\n if (depth !== undefined) info.depth = depth;\n return info;\n}\n\n/**\n * Collect instrumented descendants up to `maxDepth` instrumented nesting levels.\n * Non-instrumented wrappers are walked through without counting toward depth.\n * Results are in DOM order.\n * When `startDepth` is provided, assigns `depth` to each item during collection.\n */\nexport function getInstrumentedDescendants(\n parent: Element,\n maxDepth: number,\n startDepth?: number\n): LayerInfo[] {\n const result: LayerInfo[] = [];\n\n function walk(el: Element, instrDepth: number): void {\n if (instrDepth > maxDepth) return;\n for (let i = 0; i < el.children.length; i++) {\n const child = el.children[i]!;\n if (isInstrumentedElement(child)) {\n const info: LayerInfo = {\n element: child,\n tagName: child.tagName.toLowerCase(),\n selectorId: getElementSelectorId(child),\n };\n if (startDepth !== undefined) {\n info.depth = startDepth + instrDepth - 1;\n }\n result.push(info);\n walk(child, instrDepth + 1);\n } else {\n walk(child, instrDepth);\n }\n }\n }\n\n walk(parent, 1);\n return result;\n}\n\n/** Collect instrumented ancestors from selected element up to MAX_PARENT_DEPTH (outermost first). */\nfunction collectInstrumentedParents(selectedElement: Element): LayerInfo[] {\n const parents: LayerInfo[] = [];\n let current = selectedElement.parentElement;\n while (\n current &&\n current !== document.documentElement &&\n current !== document.body &&\n parents.length < MAX_PARENT_DEPTH\n ) {\n if (isInstrumentedElement(current)) {\n parents.push(toLayerInfo(current));\n }\n current = current.parentElement;\n }\n parents.reverse();\n return parents;\n}\n\n/** Add parents to chain with depth 0, 1, …; returns depth of selected (parents.length). */\nfunction addParentsToChain(chain: LayerInfo[], parents: LayerInfo[]): number {\n parents.forEach((p, i) => {\n chain.push({ ...p, depth: i });\n });\n return parents.length;\n}\n\n/** Add selected element and its descendants at the given depth. */\nfunction addSelfAndDescendantsToChain(\n chain: LayerInfo[],\n selectedElement: Element,\n selfDepth: number\n): void {\n chain.push(toLayerInfo(selectedElement, selfDepth));\n const descendants = getInstrumentedDescendants(\n selectedElement,\n MAX_CHILD_DEPTH,\n selfDepth + 1\n );\n chain.push(...descendants);\n}\n\n/** Get the innermost instrumented parent's DOM element, or null if none. */\nfunction getImmediateInstrParent(parents: LayerInfo[]): Element | null {\n return parents.at(-1)?.element ?? null;\n}\n\n/** Collect instrumented siblings of the selected element from its parent (DOM order). */\nfunction collectSiblings(parent: Element, selectedElement: Element): LayerInfo[] {\n const siblings = getInstrumentedDescendants(parent, 1);\n if (!siblings.some((s) => s.element === selectedElement)) {\n siblings.push(toLayerInfo(selectedElement));\n }\n return siblings;\n}\n\n/** Add siblings at selfDepth, expanding children only for the selected element. */\nfunction appendSiblingsWithSelected(\n chain: LayerInfo[],\n siblings: LayerInfo[],\n selectedElement: Element,\n selfDepth: number\n): void {\n const selectedSelectorId = getElementSelectorId(selectedElement);\n const seen = new Set<string>();\n for (const sibling of siblings) {\n if (sibling.element === selectedElement) {\n addSelfAndDescendantsToChain(chain, selectedElement, selfDepth);\n if (selectedSelectorId) seen.add(selectedSelectorId);\n } else {\n const id = sibling.selectorId;\n if (id != null) {\n if (id === selectedSelectorId || seen.has(id)) continue;\n seen.add(id);\n }\n chain.push({ ...sibling, depth: selfDepth });\n }\n }\n}\n\n/**\n * Build the layer chain for the dropdown:\n *\n * Parents – up to MAX_PARENT_DEPTH instrumented ancestors, outer → inner.\n * Siblings – instrumented children of the immediate parent, at the same depth.\n * Current – the selected element (highlighted), with children expanded.\n * Children – instrumented descendants within MAX_CHILD_DEPTH levels, DOM order.\n *\n * Each item carries a `depth` for visual indentation.\n */\nexport function buildLayerChain(selectedElement: Element): LayerInfo[] {\n const parents = collectInstrumentedParents(selectedElement);\n const chain: LayerInfo[] = [];\n const selfDepth = addParentsToChain(chain, parents);\n\n const instrParent = getImmediateInstrParent(parents);\n if (instrParent) {\n const siblings = collectSiblings(instrParent, selectedElement);\n appendSiblingsWithSelected(chain, siblings, selectedElement, selfDepth);\n } else {\n addSelfAndDescendantsToChain(chain, selectedElement, selfDepth);\n }\n\n return chain;\n}\n","/** Dropdown UI component for layer navigation */\n\nimport {\n DROPDOWN_CONTAINER_STYLES,\n DROPDOWN_ITEM_BASE_STYLES,\n DROPDOWN_ITEM_ACTIVE_COLOR,\n DROPDOWN_ITEM_ACTIVE_BG,\n DROPDOWN_ITEM_ACTIVE_FONT_WEIGHT,\n DROPDOWN_ITEM_HOVER_BG,\n DEPTH_INDENT_PX,\n BASE_PADDING_PX,\n CHEVRON_COLLAPSED,\n CHEVRON_EXPANDED,\n LAYER_DROPDOWN_ATTR,\n} from \"./consts.js\";\nimport { applyStyles, getLayerDisplayName } from \"./utils.js\";\nimport type { LayerInfo, DropdownCallbacks } from \"./types.js\";\n\nlet activeDropdown: HTMLDivElement | null = null;\nlet activeLabel: HTMLDivElement | null = null;\nlet outsideMousedownHandler: ((e: MouseEvent) => void) | null = null;\nlet activeOnHoverEnd: (() => void) | null = null;\nlet activeKeydownHandler: ((e: KeyboardEvent) => void) | null = null;\n\nfunction createDropdownItem(\n layer: LayerInfo,\n isActive: boolean,\n { onSelect, onHover, onHoverEnd }: DropdownCallbacks\n): HTMLDivElement {\n const item = document.createElement(\"div\");\n item.textContent = getLayerDisplayName(layer);\n applyStyles(item, DROPDOWN_ITEM_BASE_STYLES);\n\n const depth = layer.depth ?? 0;\n if (depth > 0) {\n item.style.paddingLeft = `${BASE_PADDING_PX + depth * DEPTH_INDENT_PX}px`;\n }\n\n if (isActive) {\n item.style.color = DROPDOWN_ITEM_ACTIVE_COLOR;\n item.style.backgroundColor = DROPDOWN_ITEM_ACTIVE_BG;\n item.style.fontWeight = DROPDOWN_ITEM_ACTIVE_FONT_WEIGHT;\n }\n\n item.addEventListener(\"mouseenter\", () => {\n if (!isActive) item.style.backgroundColor = DROPDOWN_ITEM_HOVER_BG;\n if (onHover) onHover(layer);\n });\n\n item.addEventListener(\"mouseleave\", () => {\n if (!isActive) item.style.backgroundColor = \"transparent\";\n if (onHoverEnd) onHoverEnd();\n });\n\n item.addEventListener(\"click\", (e: MouseEvent) => {\n e.stopPropagation();\n e.preventDefault();\n onSelect(layer);\n });\n\n return item;\n}\n\n/** Create the dropdown DOM element with layer items */\nexport function createDropdownElement(\n layers: LayerInfo[],\n currentElement: Element | null,\n callbacks: DropdownCallbacks\n): HTMLDivElement {\n const container = document.createElement(\"div\");\n container.setAttribute(LAYER_DROPDOWN_ATTR, \"true\");\n applyStyles(container, DROPDOWN_CONTAINER_STYLES);\n\n layers.forEach((layer) => {\n const isActive = layer.element === currentElement;\n container.appendChild(createDropdownItem(layer, isActive, callbacks));\n });\n\n return container;\n}\n\n/** Add chevron indicator and pointer-events to the label */\nexport function enhanceLabelWithChevron(label: HTMLDivElement): void {\n const t = label.textContent ?? \"\";\n if (t.endsWith(CHEVRON_COLLAPSED) || t.endsWith(CHEVRON_EXPANDED)) return;\n\n label.textContent = t + CHEVRON_COLLAPSED;\n label.style.cursor = \"pointer\";\n label.style.userSelect = \"none\";\n label.style.whiteSpace = \"nowrap\";\n label.style.pointerEvents = \"auto\";\n label.setAttribute(LAYER_DROPDOWN_ATTR, \"true\");\n}\n\nfunction setupKeyboardNavigation(\n dropdown: HTMLDivElement,\n layers: LayerInfo[],\n currentElement: Element | null,\n { onSelect, onHover, onHoverEnd }: DropdownCallbacks\n): void {\n const items = Array.from(dropdown.children) as HTMLDivElement[];\n let focusedIndex = layers.findIndex((l) => l.element === currentElement);\n\n const setFocusedItem = (index: number) => {\n if (focusedIndex >= 0 && focusedIndex < items.length) {\n const prev = items[focusedIndex]!;\n if (prev.style.color !== DROPDOWN_ITEM_ACTIVE_COLOR) {\n prev.style.backgroundColor = \"transparent\";\n }\n }\n focusedIndex = index;\n if (focusedIndex >= 0 && focusedIndex < items.length) {\n const cur = items[focusedIndex]!;\n if (cur.style.color !== DROPDOWN_ITEM_ACTIVE_COLOR) {\n cur.style.backgroundColor = DROPDOWN_ITEM_HOVER_BG;\n }\n cur.scrollIntoView({ block: \"nearest\" });\n if (onHover && focusedIndex >= 0 && focusedIndex < layers.length) {\n onHover(layers[focusedIndex]!);\n }\n }\n };\n\n activeKeydownHandler = (e: KeyboardEvent) => {\n if (e.key === \"ArrowDown\") {\n e.preventDefault();\n e.stopPropagation();\n setFocusedItem(focusedIndex < items.length - 1 ? focusedIndex + 1 : 0);\n } else if (e.key === \"ArrowUp\") {\n e.preventDefault();\n e.stopPropagation();\n setFocusedItem(focusedIndex > 0 ? focusedIndex - 1 : items.length - 1);\n } else if (e.key === \"Enter\" && focusedIndex >= 0 && focusedIndex < layers.length) {\n e.preventDefault();\n e.stopPropagation();\n if (onHoverEnd) onHoverEnd();\n onSelect(layers[focusedIndex]!);\n closeDropdown();\n }\n };\n document.addEventListener(\"keydown\", activeKeydownHandler, true);\n}\n\nfunction setupOutsideClickHandler(\n dropdown: HTMLDivElement,\n label: HTMLDivElement\n): void {\n let skipFirst = true;\n outsideMousedownHandler = (e: MouseEvent) => {\n if (skipFirst) { skipFirst = false; return; }\n const target = e.target as Node;\n if (!dropdown.contains(target) && target !== label) {\n closeDropdown();\n }\n };\n document.addEventListener(\"mousedown\", outsideMousedownHandler, true);\n}\n\n/** Show the dropdown below the label element */\nexport function showDropdown(\n label: HTMLDivElement,\n layers: LayerInfo[],\n currentElement: Element | null,\n callbacks: DropdownCallbacks\n): void {\n closeDropdown();\n\n const dropdown = createDropdownElement(\n layers,\n currentElement,\n {\n ...callbacks,\n onSelect: (layer) => {\n if (callbacks.onHoverEnd) callbacks.onHoverEnd();\n callbacks.onSelect(layer);\n closeDropdown();\n },\n }\n );\n\n const overlay = label.parentElement;\n if (!overlay) return;\n\n dropdown.style.top = `${label.offsetTop + label.offsetHeight + 2}px`;\n dropdown.style.left = `${label.offsetLeft}px`;\n\n overlay.appendChild(dropdown);\n activeDropdown = dropdown;\n activeLabel = label;\n if (label.textContent?.endsWith(CHEVRON_COLLAPSED.trim())) {\n label.textContent = label.textContent.slice(0, -CHEVRON_COLLAPSED.length) + CHEVRON_EXPANDED;\n }\n activeOnHoverEnd = callbacks.onHoverEnd ?? null;\n\n setupKeyboardNavigation(dropdown, layers, currentElement, callbacks);\n setupOutsideClickHandler(dropdown, label);\n}\n\n/** Close the active dropdown and clean up listeners */\nexport function closeDropdown(): void {\n if (activeLabel?.textContent?.includes(CHEVRON_EXPANDED)) {\n activeLabel.textContent = activeLabel.textContent.replace(CHEVRON_EXPANDED, CHEVRON_COLLAPSED);\n }\n activeLabel = null;\n\n if (activeOnHoverEnd) {\n activeOnHoverEnd();\n activeOnHoverEnd = null;\n }\n\n if (activeDropdown && activeDropdown.parentNode) {\n activeDropdown.remove();\n }\n activeDropdown = null;\n\n if (outsideMousedownHandler) {\n document.removeEventListener(\"mousedown\", outsideMousedownHandler, true);\n outsideMousedownHandler = null;\n }\n\n if (activeKeydownHandler) {\n document.removeEventListener(\"keydown\", activeKeydownHandler, true);\n activeKeydownHandler = null;\n }\n}\n\n/** Check if a dropdown is currently visible */\nexport function isDropdownOpen(): boolean {\n return activeDropdown !== null;\n}\n","/** Controller that encapsulates layer-dropdown integration logic */\n\nimport { getElementSelectorId } from \"../utils.js\";\nimport { buildLayerChain } from \"./utils.js\";\nimport {\n enhanceLabelWithChevron,\n showDropdown,\n closeDropdown,\n isDropdownOpen,\n} from \"./dropdown-ui.js\";\nimport type { LayerInfo, LayerControllerConfig, LayerController } from \"./types.js\";\n\nexport function createLayerController(config: LayerControllerConfig): LayerController {\n let layerPreviewOverlay: HTMLDivElement | null = null;\n let escapeHandler: ((e: KeyboardEvent) => void) | null = null;\n let dropdownSourceLayer: LayerInfo | null = null;\n\n const clearLayerPreview = () => {\n if (layerPreviewOverlay && layerPreviewOverlay.parentNode) {\n layerPreviewOverlay.remove();\n }\n layerPreviewOverlay = null;\n };\n\n const showLayerPreview = (layer: LayerInfo) => {\n clearLayerPreview();\n if (getElementSelectorId(layer.element) === config.getSelectedElementId()) return;\n\n layerPreviewOverlay = config.createPreviewOverlay(layer.element);\n };\n\n const selectLayer = (layer: LayerInfo) => {\n clearLayerPreview();\n closeDropdown();\n if (escapeHandler) {\n document.removeEventListener(\"keydown\", escapeHandler, true);\n escapeHandler = null;\n }\n dropdownSourceLayer = null;\n\n const firstOverlay = config.selectElement(layer.element);\n attachToOverlay(firstOverlay, layer.element);\n };\n\n const restoreSelection = () => {\n if (escapeHandler) {\n document.removeEventListener(\"keydown\", escapeHandler, true);\n escapeHandler = null;\n }\n if (dropdownSourceLayer) {\n selectLayer(dropdownSourceLayer);\n dropdownSourceLayer = null;\n }\n };\n\n const handleLabelClick = (e: MouseEvent, label: HTMLDivElement, element: Element, layers: LayerInfo[], currentId: string | null) => {\n e.stopPropagation();\n e.preventDefault();\n if (isDropdownOpen()) {\n closeDropdown();\n restoreSelection();\n } else {\n dropdownSourceLayer = {\n element,\n tagName: element.tagName.toLowerCase(),\n selectorId: currentId,\n };\n config.onDeselect();\n\n escapeHandler = (ev: KeyboardEvent) => {\n if (ev.key === \"Escape\") {\n ev.stopPropagation();\n closeDropdown();\n restoreSelection();\n }\n };\n document.addEventListener(\"keydown\", escapeHandler, true);\n\n showDropdown(label, layers, element, { onSelect: selectLayer, onHover: showLayerPreview, onHoverEnd: clearLayerPreview });\n }\n };\n\n const attachToOverlay = (\n overlay: HTMLDivElement | undefined,\n element: Element\n ) => {\n if (!overlay) return;\n\n const label = overlay.querySelector(\"div\") as HTMLDivElement | null;\n if (!label) return;\n\n const layers = buildLayerChain(element);\n if (layers.length <= 1) return;\n\n const currentId = getElementSelectorId(element);\n enhanceLabelWithChevron(label);\n\n label.addEventListener(\"click\", (e: MouseEvent) => {\n handleLabelClick(e, label, element, layers, currentId);\n });\n };\n\n const cleanup = () => {\n clearLayerPreview();\n closeDropdown();\n };\n\n return { attachToOverlay, cleanup };\n}\n","import { findElementsById, updateElementClasses, updateElementAttribute, collectAllowedAttributes, ALLOWED_ATTRIBUTES, getElementSelectorId } from \"./utils.js\";\nimport { createLayerController } from \"./layer-dropdown/controller.js\";\nimport { LAYER_DROPDOWN_ATTR } from \"./layer-dropdown/consts.js\";\n\nexport function setupVisualEditAgent() {\n // State variables (replacing React useState/useRef)\n let isVisualEditMode = false;\n let isPopoverDragging = false;\n let isDropdownOpen = false;\n let hoverOverlays: HTMLDivElement[] = [];\n let selectedOverlays: HTMLDivElement[] = [];\n let currentHighlightedElements: Element[] = [];\n let selectedElementId: string | null = null;\n\n // Create overlay element\n const createOverlay = (isSelected = false): HTMLDivElement => {\n const overlay = document.createElement(\"div\");\n overlay.style.position = \"absolute\";\n overlay.style.pointerEvents = \"none\";\n overlay.style.transition = \"all 0.1s ease-in-out\";\n overlay.style.zIndex = \"9999\";\n\n if (isSelected) {\n overlay.style.border = \"2px solid #2563EB\";\n } else {\n overlay.style.border = \"2px solid #95a5fc\";\n overlay.style.backgroundColor = \"rgba(99, 102, 241, 0.05)\";\n }\n\n return overlay;\n };\n\n // Position overlay relative to element\n const positionOverlay = (\n overlay: HTMLDivElement,\n element: Element,\n isSelected = false\n ) => {\n if (!element || !isVisualEditMode) return;\n\n const htmlElement = element as HTMLElement;\n // Force layout recalculation\n void htmlElement.offsetWidth;\n\n const rect = element.getBoundingClientRect();\n overlay.style.top = `${rect.top + window.scrollY}px`;\n overlay.style.left = `${rect.left + window.scrollX}px`;\n overlay.style.width = `${rect.width}px`;\n overlay.style.height = `${rect.height}px`;\n\n // Check if label already exists in overlay\n let label = overlay.querySelector(\"div\") as HTMLDivElement | null;\n\n if (!label) {\n label = document.createElement(\"div\");\n label.textContent = element.tagName.toLowerCase();\n label.style.position = \"absolute\";\n label.style.top = \"-27px\";\n label.style.left = \"-2px\";\n label.style.padding = \"2px 8px\";\n label.style.fontSize = \"11px\";\n label.style.fontWeight = isSelected ? \"500\" : \"400\";\n label.style.color = isSelected ? \"#ffffff\" : \"#526cff\";\n label.style.backgroundColor = isSelected ? \"#526cff\" : \"#DBEAFE\";\n label.style.borderRadius = \"3px\";\n label.style.minWidth = \"24px\";\n label.style.textAlign = \"center\";\n overlay.appendChild(label);\n }\n };\n\n // Clear hover overlays\n const clearHoverOverlays = () => {\n hoverOverlays.forEach((overlay) => {\n if (overlay && overlay.parentNode) {\n overlay.remove();\n }\n });\n hoverOverlays = [];\n currentHighlightedElements = [];\n };\n\n const clearSelectedOverlays = () => {\n selectedOverlays.forEach((overlay) => {\n if (overlay && overlay.parentNode) {\n overlay.remove();\n }\n });\n selectedOverlays = [];\n };\n\n const TEXT_TAGS = ['p', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'span', 'a', 'label'];\n\n const notifyElementSelected = (element: Element) => {\n const htmlElement = element as HTMLElement;\n const rect = element.getBoundingClientRect();\n const svgElement = element as SVGElement;\n const isTextElement = TEXT_TAGS.includes(element.tagName?.toLowerCase());\n window.parent.postMessage({\n type: \"element-selected\",\n tagName: element.tagName,\n classes:\n (svgElement.className as unknown as SVGAnimatedString)?.baseVal ||\n element.className ||\n \"\",\n visualSelectorId: getElementSelectorId(element),\n content: isTextElement ? htmlElement.innerText : undefined,\n dataSourceLocation: htmlElement.dataset.sourceLocation,\n isDynamicContent: htmlElement.dataset.dynamicContent === \"true\",\n linenumber: htmlElement.dataset.linenumber,\n filename: htmlElement.dataset.filename,\n position: {\n top: rect.top,\n left: rect.left,\n right: rect.right,\n bottom: rect.bottom,\n width: rect.width,\n height: rect.height,\n centerX: rect.left + rect.width / 2,\n centerY: rect.top + rect.height / 2,\n },\n attributes: collectAllowedAttributes(element, ALLOWED_ATTRIBUTES),\n isTextElement,\n }, \"*\");\n };\n\n // Select an element: create overlays, update state, notify parent\n const selectElement = (element: Element): HTMLDivElement | undefined => {\n const visualSelectorId = getElementSelectorId(element);\n\n clearSelectedOverlays();\n\n const elements = findElementsById(visualSelectorId || null);\n elements.forEach((el) => {\n const overlay = createOverlay(true);\n document.body.appendChild(overlay);\n selectedOverlays.push(overlay);\n positionOverlay(overlay, el, true);\n });\n\n selectedElementId = visualSelectorId || null;\n clearHoverOverlays();\n notifyElementSelected(element);\n\n return selectedOverlays[0];\n };\n\n const notifyDeselection = (): void => {\n selectedElementId = null;\n window.parent.postMessage({ type: \"unselect-element\" }, \"*\");\n };\n\n // Handle mouse over event\n const handleMouseOver = (e: MouseEvent) => {\n if (!isVisualEditMode || isPopoverDragging) return;\n\n const target = e.target as Element;\n\n // Prevent hover effects when a dropdown is open\n if (isDropdownOpen) {\n clearHoverOverlays();\n return;\n }\n\n // Prevent hover effects on SVG path elements\n if (target.tagName.toLowerCase() === \"path\") {\n clearHoverOverlays();\n return;\n }\n\n // Support both data-source-location and data-visual-selector-id\n const element = target.closest(\n \"[data-source-location], [data-visual-selector-id]\"\n );\n if (!element) {\n clearHoverOverlays();\n return;\n }\n\n // Prefer data-source-location, fallback to data-visual-selector-id\n const htmlElement = element as HTMLElement;\n const selectorId =\n htmlElement.dataset.sourceLocation ||\n htmlElement.dataset.visualSelectorId;\n\n // Skip if this element is already selected\n if (selectedElementId === selectorId) {\n clearHoverOverlays();\n return;\n }\n\n // Find all elements with the same ID\n const elements = findElementsById(selectorId || null);\n\n // Clear previous hover overlays\n clearHoverOverlays();\n\n // Create overlays for all matching elements\n elements.forEach((el) => {\n const overlay = createOverlay(false);\n document.body.appendChild(overlay);\n hoverOverlays.push(overlay);\n positionOverlay(overlay, el);\n });\n\n currentHighlightedElements = elements;\n };\n\n // Handle mouse out event\n const handleMouseOut = () => {\n if (isPopoverDragging) return;\n clearHoverOverlays();\n };\n\n // Handle element click\n const handleElementClick = (e: MouseEvent) => {\n if (!isVisualEditMode) return;\n\n const target = e.target as Element;\n\n // Let layer dropdown clicks pass through without interference\n if (target.closest(`[${LAYER_DROPDOWN_ATTR}]`)) return;\n\n // Close dropdowns when clicking anywhere in iframe if a dropdown is open\n if (isDropdownOpen) {\n e.preventDefault();\n e.stopPropagation();\n e.stopImmediatePropagation();\n\n window.parent.postMessage({ type: \"close-dropdowns\" }, \"*\");\n return;\n }\n\n // Prevent clicking on SVG path elements\n if (target.tagName.toLowerCase() === \"path\") {\n return;\n }\n\n // Prevent default behavior immediately when in visual edit mode\n e.preventDefault();\n e.stopPropagation();\n e.stopImmediatePropagation();\n\n // Support both data-source-location and data-visual-selector-id\n const element = target.closest(\n \"[data-source-location], [data-visual-selector-id]\"\n );\n if (!element) {\n return;\n }\n\n const selectedOverlay = selectElement(element);\n layerController.attachToOverlay(selectedOverlay, element);\n };\n\n // Clear the current selection\n const clearSelection = () => {\n clearSelectedOverlays();\n selectedElementId = null;\n };\n\n const updateElementClassesAndReposition = (visualSelectorId: string, classes: string) => {\n const elements = findElementsById(visualSelectorId);\n if (elements.length === 0) return;\n\n updateElementClasses(elements, classes);\n\n // Use a small delay to allow the browser to recalculate layout before repositioning\n setTimeout(() => {\n // Reposition selected overlays\n if (selectedElementId === visualSelectorId) {\n selectedOverlays.forEach((overlay, index) => {\n if (index < elements.length) {\n positionOverlay(overlay, elements[index]!);\n }\n });\n }\n\n // Reposition hover overlays if needed\n if (currentHighlightedElements.length > 0) {\n const hoveredElement = currentHighlightedElements[0] as HTMLElement;\n const hoveredId = hoveredElement?.dataset?.visualSelectorId;\n if (hoveredId === visualSelectorId) {\n hoverOverlays.forEach((overlay, index) => {\n if (index < currentHighlightedElements.length) {\n positionOverlay(overlay, currentHighlightedElements[index]!);\n }\n });\n }\n }\n }, 50);\n };\n\n // Update element attribute by visual selector ID\n const updateElementAttributeAndReposition = (\n visualSelectorId: string,\n attribute: string,\n value: string\n ) => {\n const elements = findElementsById(visualSelectorId);\n if (elements.length === 0) return;\n\n updateElementAttribute(elements, attribute, value);\n\n // Reposition overlays after attribute change (e.g. image src swap can affect layout)\n setTimeout(() => {\n if (selectedElementId === visualSelectorId) {\n selectedOverlays.forEach((overlay, index) => {\n if (index < elements.length) {\n positionOverlay(overlay, elements[index]!);\n }\n });\n }\n }, 50);\n };\n\n // Update element content by visual selector ID\n const updateElementContent = (visualSelectorId: string, content: string) => {\n const elements = findElementsById(visualSelectorId);\n\n if (elements.length === 0) {\n return;\n }\n\n elements.forEach((element) => {\n (element as HTMLElement).innerText = content;\n });\n\n setTimeout(() => {\n if (selectedElementId === visualSelectorId) {\n selectedOverlays.forEach((overlay, index) => {\n if (index < elements.length) {\n positionOverlay(overlay, elements[index]!);\n }\n });\n }\n }, 50);\n };\n\n // --- Layer dropdown controller ---\n const layerController = createLayerController({\n createPreviewOverlay: (element: Element) => {\n const overlay = createOverlay(false);\n overlay.style.zIndex = \"9998\";\n document.body.appendChild(overlay);\n positionOverlay(overlay, element);\n return overlay;\n },\n getSelectedElementId: () => selectedElementId,\n selectElement,\n onDeselect: notifyDeselection,\n });\n\n // Toggle visual edit mode\n const toggleVisualEditMode = (isEnabled: boolean) => {\n isVisualEditMode = isEnabled;\n\n if (!isEnabled) {\n layerController.cleanup();\n clearHoverOverlays();\n clearSelectedOverlays();\n\n currentHighlightedElements = [];\n selectedElementId = null;\n document.body.style.cursor = \"default\";\n\n document.removeEventListener(\"mouseover\", handleMouseOver);\n document.removeEventListener(\"mouseout\", handleMouseOut);\n document.removeEventListener(\"click\", handleElementClick, true);\n } else {\n document.body.style.cursor = \"crosshair\";\n document.addEventListener(\"mouseover\", handleMouseOver);\n document.addEventListener(\"mouseout\", handleMouseOut);\n document.addEventListener(\"click\", handleElementClick, true);\n }\n };\n\n // Handle scroll events to update popover position\n const handleScroll = () => {\n if (selectedElementId) {\n const elements = findElementsById(selectedElementId);\n if (elements.length > 0) {\n const element = elements[0];\n const rect = element!.getBoundingClientRect();\n\n const viewportHeight = window.innerHeight;\n const viewportWidth = window.innerWidth;\n const isInViewport =\n rect.top < viewportHeight &&\n rect.bottom > 0 &&\n rect.left < viewportWidth &&\n rect.right > 0;\n\n const elementPosition = {\n top: rect.top,\n left: rect.left,\n right: rect.right,\n bottom: rect.bottom,\n width: rect.width,\n height: rect.height,\n centerX: rect.left + rect.width / 2,\n centerY: rect.top + rect.height / 2,\n };\n\n window.parent.postMessage(\n {\n type: \"element-position-update\",\n position: elementPosition,\n isInViewport: isInViewport,\n visualSelectorId: selectedElementId,\n },\n \"*\"\n );\n }\n }\n };\n\n // Handle messages from parent window\n const handleMessage = (event: MessageEvent) => {\n const message = event.data;\n\n switch (message.type) {\n case \"toggle-visual-edit-mode\":\n toggleVisualEditMode(message.data.enabled);\n break;\n\n case \"update-classes\":\n if (message.data && message.data.classes !== undefined) {\n updateElementClassesAndReposition(\n message.data.visualSelectorId,\n message.data.classes\n );\n } else {\n console.warn(\n \"[VisualEditAgent] Invalid update-classes message:\",\n message\n );\n }\n break;\n\n case \"update-attribute\":\n if (\n message.data &&\n message.data.visualSelectorId &&\n message.data.attribute !== undefined &&\n message.data.value !== undefined\n ) {\n updateElementAttributeAndReposition(\n message.data.visualSelectorId,\n message.data.attribute,\n message.data.value\n );\n } else {\n console.warn(\n \"[VisualEditAgent] Invalid update-attribute message:\",\n message\n );\n }\n break;\n\n case \"unselect-element\":\n clearSelection();\n break;\n\n case \"refresh-page\":\n window.location.reload();\n break;\n\n case \"update-content\":\n if (message.data && message.data.content !== undefined) {\n updateElementContent(\n message.data.visualSelectorId,\n message.data.content\n );\n } else {\n console.warn(\n \"[VisualEditAgent] Invalid update-content message:\",\n message\n );\n }\n break;\n\n case \"request-element-position\":\n if (selectedElementId) {\n const elements = findElementsById(selectedElementId);\n if (elements.length > 0) {\n const element = elements[0];\n const rect = element!.getBoundingClientRect();\n\n const viewportHeight = window.innerHeight;\n const viewportWidth = window.innerWidth;\n const isInViewport =\n rect.top < viewportHeight &&\n rect.bottom > 0 &&\n rect.left < viewportWidth &&\n rect.right > 0;\n\n const elementPosition = {\n top: rect.top,\n left: rect.left,\n right: rect.right,\n bottom: rect.bottom,\n width: rect.width,\n height: rect.height,\n centerX: rect.left + rect.width / 2,\n centerY: rect.top + rect.height / 2,\n };\n\n window.parent.postMessage(\n {\n type: \"element-position-update\",\n position: elementPosition,\n isInViewport: isInViewport,\n visualSelectorId: selectedElementId,\n },\n \"*\"\n );\n }\n }\n break;\n\n case \"popover-drag-state\":\n if (message.data && message.data.isDragging !== undefined) {\n isPopoverDragging = message.data.isDragging;\n if (message.data.isDragging) {\n clearHoverOverlays();\n }\n }\n break;\n\n case \"dropdown-state\":\n if (message.data && message.data.isOpen !== undefined) {\n isDropdownOpen = message.data.isOpen;\n if (message.data.isOpen) {\n clearHoverOverlays();\n }\n }\n break;\n\n default:\n break;\n }\n };\n\n // Handle window resize to reposition overlays\n const handleResize = () => {\n if (selectedElementId) {\n const elements = findElementsById(selectedElementId);\n selectedOverlays.forEach((overlay, index) => {\n if (index < elements.length) {\n positionOverlay(overlay, elements[index]!);\n }\n });\n }\n\n if (currentHighlightedElements.length > 0) {\n hoverOverlays.forEach((overlay, index) => {\n if (index < currentHighlightedElements.length) {\n positionOverlay(overlay, currentHighlightedElements[index]!);\n }\n });\n }\n };\n\n // Initialize: Add IDs to elements that don't have them but have linenumbers\n const elementsWithLineNumber = document.querySelectorAll(\n \"[data-linenumber]:not([data-visual-selector-id])\"\n );\n elementsWithLineNumber.forEach((el, index) => {\n const htmlEl = el as HTMLElement;\n const id = `visual-id-${htmlEl.dataset.filename}-${htmlEl.dataset.linenumber}-${index}`;\n htmlEl.dataset.visualSelectorId = id;\n });\n\n // Create mutation observer to detect layout changes\n const mutationObserver = new MutationObserver((mutations) => {\n const needsUpdate = mutations.some((mutation) => {\n const hasVisualId = (node: Node): boolean => {\n if (node.nodeType === Node.ELEMENT_NODE) {\n const el = node as HTMLElement;\n if (el.dataset && el.dataset.visualSelectorId) {\n return true;\n }\n for (let i = 0; i < el.children.length; i++) {\n if (hasVisualId(el.children[i]!)) {\n return true;\n }\n }\n }\n return false;\n };\n\n const isLayoutChange =\n mutation.type === \"attributes\" &&\n (mutation.attributeName === \"style\" ||\n mutation.attributeName === \"class\" ||\n mutation.attributeName === \"width\" ||\n mutation.attributeName === \"height\");\n\n return isLayoutChange && hasVisualId(mutation.target);\n });\n\n if (needsUpdate) {\n setTimeout(handleResize, 50);\n }\n });\n\n // Set up event listeners\n window.addEventListener(\"message\", handleMessage);\n window.addEventListener(\"scroll\", handleScroll, true);\n document.addEventListener(\"scroll\", handleScroll, true);\n window.addEventListener(\"resize\", handleResize);\n window.addEventListener(\"scroll\", handleResize);\n\n // Start observing DOM mutations\n mutationObserver.observe(document.body, {\n attributes: true,\n childList: true,\n subtree: true,\n attributeFilter: [\"style\", \"class\", \"width\", \"height\"],\n });\n\n // Send ready message to parent\n window.parent.postMessage({ type: \"visual-edit-agent-ready\" }, \"*\");\n}"],"mappings":"AACO,SAASA,EAAsBC,EAA2B,CAC/D,IAAMC,EAASD,EACf,MAAO,CAAC,EACNC,EAAO,SAAS,gBAAkBA,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,EAAS,MAAM,CACtD,CAAC,GAGC,WAAWL,EAAc,EAAE,CAE/B,CAAC,EAGD,OAAO,iBAAiB,UAAWH,EAAa,EAChD,OAAO,iBAAiB,SAAUL,EAAc,EAAI,EACpD,SAAS,iBAAiB,SAAUA,EAAc,EAAI,EACtD,OAAO,iBAAiB,SAAUQ,CAAY,EAC9C,OAAO,iBAAiB,SAAUA,CAAY,EAG9CG,GAAiB,QAAQ,SAAS,KAAM,CACtC,WAAY,GACZ,UAAW,GACX,QAAS,GACT,gBAAiB,CAAC,QAAS,QAAS,QAAS,QAAQ,CACvD,CAAC,EAGD,OAAO,OAAO,YAAY,CAAE,KAAM,yBAA0B,EAAG,GAAG,CACpE","names":["isInstrumentedElement","element","htmlEl","getElementSelectorId","ALLOWED_ATTRIBUTES","findElementsById","id","sourceElements","updateElementClasses","elements","classes","updateElementAttribute","attribute","value","collectAllowedAttributes","allowedAttributes","attributes","attr","val","DROPDOWN_CONTAINER_STYLES","DROPDOWN_ITEM_BASE_STYLES","DROPDOWN_ITEM_ACTIVE_COLOR","DROPDOWN_ITEM_ACTIVE_BG","DROPDOWN_ITEM_ACTIVE_FONT_WEIGHT","DROPDOWN_ITEM_HOVER_BG","DEPTH_INDENT_PX","CHEVRON_COLLAPSED","CHEVRON_EXPANDED","BASE_PADDING_PX","LAYER_DROPDOWN_ATTR","MAX_PARENT_DEPTH","MAX_CHILD_DEPTH","applyStyles","element","styles","key","m","getLayerDisplayName","layer","toLayerInfo","depth","info","getElementSelectorId","getInstrumentedDescendants","parent","maxDepth","startDepth","result","walk","el","instrDepth","i","child","isInstrumentedElement","collectInstrumentedParents","selectedElement","parents","current","MAX_PARENT_DEPTH","addParentsToChain","chain","p","addSelfAndDescendantsToChain","selfDepth","descendants","MAX_CHILD_DEPTH","getImmediateInstrParent","collectSiblings","siblings","s","appendSiblingsWithSelected","selectedSelectorId","seen","sibling","id","buildLayerChain","instrParent","activeDropdown","activeLabel","outsideMousedownHandler","activeOnHoverEnd","activeKeydownHandler","createDropdownItem","layer","isActive","onSelect","onHover","onHoverEnd","item","getLayerDisplayName","applyStyles","DROPDOWN_ITEM_BASE_STYLES","depth","BASE_PADDING_PX","DEPTH_INDENT_PX","DROPDOWN_ITEM_ACTIVE_COLOR","DROPDOWN_ITEM_ACTIVE_BG","DROPDOWN_ITEM_ACTIVE_FONT_WEIGHT","DROPDOWN_ITEM_HOVER_BG","e","createDropdownElement","layers","currentElement","callbacks","container","LAYER_DROPDOWN_ATTR","DROPDOWN_CONTAINER_STYLES","enhanceLabelWithChevron","label","t","CHEVRON_COLLAPSED","CHEVRON_EXPANDED","setupKeyboardNavigation","dropdown","items","focusedIndex","l","setFocusedItem","index","prev","cur","closeDropdown","setupOutsideClickHandler","skipFirst","target","showDropdown","overlay","isDropdownOpen","createLayerController","config","layerPreviewOverlay","escapeHandler","dropdownSourceLayer","clearLayerPreview","showLayerPreview","layer","getElementSelectorId","selectLayer","closeDropdown","firstOverlay","attachToOverlay","restoreSelection","handleLabelClick","e","label","element","layers","currentId","isDropdownOpen","ev","showDropdown","overlay","buildLayerChain","enhanceLabelWithChevron","setupVisualEditAgent","isVisualEditMode","isPopoverDragging","isDropdownOpen","hoverOverlays","selectedOverlays","currentHighlightedElements","selectedElementId","createOverlay","isSelected","overlay","positionOverlay","element","rect","label","clearHoverOverlays","clearSelectedOverlays","TEXT_TAGS","notifyElementSelected","htmlElement","svgElement","isTextElement","getElementSelectorId","collectAllowedAttributes","ALLOWED_ATTRIBUTES","selectElement","visualSelectorId","findElementsById","el","notifyDeselection","handleMouseOver","e","target","selectorId","elements","handleMouseOut","handleElementClick","LAYER_DROPDOWN_ATTR","selectedOverlay","layerController","clearSelection","updateElementClassesAndReposition","classes","updateElementClasses","index","updateElementAttributeAndReposition","attribute","value","updateElementAttribute","updateElementContent","content","createLayerController","toggleVisualEditMode","isEnabled","handleScroll","viewportHeight","viewportWidth","isInViewport","elementPosition","handleMessage","event","message","handleResize","htmlEl","id","mutationObserver","mutations","mutation","hasVisualId","node","i"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@base44/vite-plugin",
3
- "version": "0.2.24",
3
+ "version": "0.2.26",
4
4
  "description": "The Vite plugin for base44 based applications",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -0,0 +1,258 @@
1
+ # Layer Dropdown Feature
2
+
3
+ ## Overview
4
+
5
+ The layer dropdown lets users navigate the instrumented DOM hierarchy around a selected element. Clicking the chevron (`▾`) on an element's label reveals a dropdown showing **ancestors**, **siblings**, **the selected element**, and its **children** — all with depth-based indentation.
6
+
7
+ ```
8
+ grandparent (depth 0)
9
+ parent (depth 1)
10
+ sibling-1 (depth 2)
11
+ ★ selected (depth 2) ← highlighted in blue
12
+ child-a (depth 3)
13
+ child-b (depth 3)
14
+ sibling-2 (depth 2)
15
+ ```
16
+
17
+ Children are only expanded for the selected element, not for siblings.
18
+
19
+ ---
20
+
21
+ ## Architecture
22
+
23
+ ```
24
+ ┌─────────────┐ ┌────────────────┐ ┌────────────────┐
25
+ │ types.ts │◄────│ controller.ts │────►│ dropdown-ui.ts│
26
+ │ consts.ts │◄────│ (orchestrator)│ │ (rendering) │
27
+ └─────────────┘ └───────┬────────┘ └────────────────┘
28
+
29
+ ┌─────▼──────┐
30
+ │ utils.ts │
31
+ │ (DOM walk) │
32
+ └────────────┘
33
+ ```
34
+
35
+ | File | Role |
36
+ |------|------|
37
+ | **types.ts** | `LayerInfo`, callback types, `LayerControllerDeps`, `LayerController` |
38
+ | **consts.ts** | Style maps, depth limits, chevron character, attribute name |
39
+ | **utils.ts** | DOM traversal — parent walking, sibling/descendant collection, depth assignment |
40
+ | **dropdown-ui.ts** | Creates the dropdown DOM, positions it, handles hover/click/keyboard |
41
+ | **controller.ts** | Stateful factory that wires everything together: build chain, show dropdown, handle selection |
42
+
43
+ ---
44
+
45
+ ## Data Model
46
+
47
+ ### `LayerInfo`
48
+
49
+ ```typescript
50
+ interface LayerInfo {
51
+ element: Element; // DOM reference
52
+ tagName: string; // lowercase tag name ("div", "button")
53
+ selectorId: string | null; // data-source-location or data-visual-selector-id
54
+ depth?: number; // visual indentation level (set during chain building)
55
+ }
56
+ ```
57
+
58
+ An element is **instrumented** if it has `dataset.sourceLocation` or `dataset.visualSelectorId`. Only instrumented elements appear in the dropdown.
59
+
60
+ ### Key Constants
61
+
62
+ | Constant | Value | Purpose |
63
+ |----------|-------|---------|
64
+ | `MAX_PARENT_DEPTH` | `2` | Max ancestor levels shown above selected |
65
+ | `MAX_CHILD_DEPTH` | `2` | Max descendant levels shown below selected |
66
+ | `DEPTH_INDENT_PX` | `10` | Extra left-padding per depth level |
67
+ | `LABEL_CHEVRON` | `" ▾"` | Appended to label text when dropdown is available |
68
+
69
+ ---
70
+
71
+ ## How the Chain Is Built (`utils.ts`)
72
+
73
+ `buildLayerChain(selectedElement)` is the entry point. It delegates to focused helper functions:
74
+
75
+ ```typescript
76
+ export function buildLayerChain(selectedElement: Element): LayerInfo[] {
77
+ const parents = collectInstrumentedParents(selectedElement);
78
+ const chain: LayerInfo[] = [];
79
+ const selfDepth = appendParentsWithDepth(chain, parents);
80
+
81
+ const instrParent = getImmediateInstrParent(parents);
82
+ if (instrParent) {
83
+ const siblings = collectSiblings(instrParent, selectedElement);
84
+ appendSiblingsWithSelected(chain, siblings, selectedElement, selfDepth);
85
+ } else {
86
+ appendSelfAndDescendants(chain, selectedElement, selfDepth);
87
+ }
88
+
89
+ return chain;
90
+ }
91
+ ```
92
+
93
+ ### Helper Functions
94
+
95
+ | Function | Purpose |
96
+ |----------|---------|
97
+ | `toLayerInfo(element, depth?)` | Convert a DOM element to a `LayerInfo` object |
98
+ | `collectInstrumentedParents(el)` | Walk up the DOM, collect up to `MAX_PARENT_DEPTH` instrumented ancestors, return outermost-first |
99
+ | `appendParentsWithDepth(chain, parents)` | Push parents into chain with `depth = index` (0, 1, ...), return count as `selfDepth` |
100
+ | `getImmediateInstrParent(parents)` | Return the innermost parent's DOM element, or `null` if `parents` is empty |
101
+ | `collectSiblings(parent, selectedEl)` | Call `getInstrumentedDescendants(parent, 1)` to get all first-level instrumented children in DOM order; safety-guard ensures `selectedEl` is always included |
102
+ | `appendSiblingsWithSelected(chain, siblings, selectedEl, depth)` | Iterate siblings at `selfDepth`; for the selected element, expand children via `appendSelfAndDescendants`; for others, just add at `selfDepth` |
103
+ | `appendSelfAndDescendants(chain, el, depth)` | Push element + its descendants (up to `MAX_CHILD_DEPTH` levels) with assigned depths |
104
+ | `getInstrumentedDescendants(parent, maxDepth)` | Recursive DOM walk — instrumented children increment depth, non-instrumented wrappers are transparent. Results in DOM order |
105
+ | `assignDescendantDepths(root, descendants, startDepth)` | Second-pass walk assigning `depth = startDepth + instrDepth - 1` using a `Set`/`Map` for O(1) lookups |
106
+
107
+ ### Chain-Building Steps
108
+
109
+ **Step 1 — `collectInstrumentedParents`**: Walk up from `selectedElement.parentElement`, skipping `document.body` and `document.documentElement`. Collect up to `MAX_PARENT_DEPTH` instrumented ancestors, then reverse so outermost comes first.
110
+
111
+ **Step 2 — `appendParentsWithDepth`**: Each parent gets `depth = index` (0, 1, ...). The count becomes `selfDepth`.
112
+
113
+ **Step 3 — `getImmediateInstrParent`**: Extract the innermost instrumented parent's element. If `parents` is empty, returns `null` (root-level element).
114
+
115
+ **Step 4 — `collectSiblings`** (when parent exists): Call `getInstrumentedDescendants(instrParent, 1)` to get all first-level instrumented children of the parent in DOM order — this naturally includes the selected element among its siblings. A safety guard ensures the selected element is always present.
116
+
117
+ **Step 5 — `appendSiblingsWithSelected`**: Iterate siblings in DOM order, all at `selfDepth`. For the selected element only, delegate to `appendSelfAndDescendants` which also collects and appends children. For other siblings, just push at `selfDepth` with no child expansion.
118
+
119
+ **Fallback** (no parent): If no instrumented parent exists (root-level element), skip sibling collection and call `appendSelfAndDescendants` directly — just self + children.
120
+
121
+ ---
122
+
123
+ ## Controller Lifecycle (`controller.ts`)
124
+
125
+ `createLayerController(deps)` returns `{ attachToOverlay, cleanup }`.
126
+
127
+ ### Dependency Injection
128
+
129
+ | Dep | Called When |
130
+ |-----|------------|
131
+ | `createPreviewOverlay(el)` | User hovers a dropdown item |
132
+ | `getSelectedElementId()` | Checking if hovered item is already selected |
133
+ | `selectElement(el)` | User clicks a dropdown item — performs selection, returns overlay |
134
+ | `onDeselect()` | Dropdown opens — temporarily clears selection for hover previews |
135
+
136
+ ### `attachToOverlay(overlay, element)`
137
+
138
+ 1. Extract the label `<div>` from the overlay.
139
+ 2. Call `buildLayerChain(element)`.
140
+ 3. **Guard**: if `layers.length <= 1`, return early — no chevron, no click handler. This is how the chevron is hidden when there's nothing to navigate to.
141
+ 4. Append chevron via `enhanceLabelWithChevron(label)`.
142
+ 5. Bind click handler to label (toggle behavior).
143
+
144
+ ### Click Handler Flow
145
+
146
+ ```
147
+ Label clicked
148
+ ├─ Dropdown already open → close + reselect source element
149
+ └─ Dropdown closed →
150
+ 1. Save source element (for Escape restore)
151
+ 2. deps.onDeselect() (clear selection visual)
152
+ 3. Register Escape key listener (capture phase)
153
+ 4. showDropdown(label, layers, callbacks...)
154
+ ```
155
+
156
+ ### State Transitions
157
+
158
+ ```
159
+ CLOSED ──[click chevron]──► OPEN
160
+ OPEN ──[click chevron]──► CLOSED (reselect original)
161
+ OPEN ──[Escape]──────────► CLOSED (reselect original)
162
+ OPEN ──[click item]─────► CLOSED → NEW ELEMENT SELECTED → reattach
163
+ OPEN ──[click outside]──► CLOSED
164
+ ```
165
+
166
+ Selection is recursive — `selectElementFromLayer` calls `deps.selectElement()`, gets a new overlay, and calls `attachToOverlay()` again on it.
167
+
168
+ ---
169
+
170
+ ## Dropdown UI (`dropdown-ui.ts`)
171
+
172
+ ### Global State (singleton)
173
+
174
+ Only one dropdown can be active at a time:
175
+
176
+ ```typescript
177
+ let activeDropdown: HTMLDivElement | null = null;
178
+ let outsideMousedownHandler: ((e: MouseEvent) => void) | null = null;
179
+ let activeOnHoverEnd: OnLayerHoverEnd | null = null;
180
+ let activeKeydownHandler: ((e: KeyboardEvent) => void) | null = null;
181
+ ```
182
+
183
+ ### `showDropdown(label, layers, currentSelectorId, onSelect, onHover, onHoverEnd)`
184
+
185
+ 1. Close any existing dropdown.
186
+ 2. Create dropdown element with all layer items.
187
+ 3. Position it below the label (`offsetTop + offsetHeight + 2px` gap).
188
+ 4. Append to the overlay's parent element.
189
+ 5. Set up keyboard navigation and outside-click handler.
190
+
191
+ ### Dropdown Item Rendering
192
+
193
+ Each `LayerInfo` becomes a `<div>` row:
194
+
195
+ - **Display name**: `layer.tagName` (e.g., "div", "section")
196
+ - **Indentation**: `paddingLeft = 12 + depth * 10` px
197
+ - **Active (selected) item**: blue text (`#526cff`), light blue bg (`#DBEAFE`), semi-bold
198
+ - **Hover state**: light gray bg (`#f1f5f9`)
199
+ - **Events**: `mouseenter` → preview, `mouseleave` → clear preview, `click` → select
200
+
201
+ ### Keyboard Navigation
202
+
203
+ - **Arrow Down/Up**: Circular focus movement through items
204
+ - **Enter**: Select focused item
205
+ - All listeners use capture phase to intercept before bubbling
206
+
207
+ ### Outside Click
208
+
209
+ Registered via `setTimeout(..., 0)` to prevent the opening click from immediately closing. Uses `mousedown` in capture phase for responsive dismissal.
210
+
211
+ ---
212
+
213
+ ## Edge Cases
214
+
215
+ | Scenario | Behavior |
216
+ |----------|----------|
217
+ | No instrumented parent (root element) | Falls back to self + children only (no siblings) |
218
+ | Only child (no other siblings) | Siblings list contains just self — same result as before |
219
+ | Parent is `document.body`/`html` | Excluded by parent-walk guard, so `parents` is empty |
220
+ | `layers.length <= 1` | No chevron appended, no click handler attached |
221
+ | Element not in siblings list | Safety guard appends it |
222
+ | Non-instrumented wrapper elements | Walked through transparently during descendant collection |
223
+
224
+ ---
225
+
226
+ ## Data Flow Summary
227
+
228
+ ```
229
+ User selects element
230
+
231
+ attachToOverlay(overlay, element)
232
+
233
+ buildLayerChain(element)
234
+ ├── collectInstrumentedParents() → parents[] (outermost first)
235
+ ├── appendParentsWithDepth() → chain gets parents at depth 0,1,...
236
+ ├── getImmediateInstrParent() → instrParent or null
237
+ ├── collectSiblings(instrParent) → siblings[] (DOM order)
238
+ └── appendSiblingsWithSelected()
239
+ ├── sibling → chain at selfDepth (no expansion)
240
+ ├── ★ selected → appendSelfAndDescendants()
241
+ │ ├── self at selfDepth
242
+ │ ├── getInstrumentedDescendants(self, 2) → children[]
243
+ │ └── assignDescendantDepths() → children get depth values
244
+ └── sibling → chain at selfDepth (no expansion)
245
+
246
+ LayerInfo[] with depth values
247
+
248
+ layers.length > 1 ? enhanceLabelWithChevron() : return
249
+
250
+ User clicks chevron → showDropdown()
251
+
252
+ createDropdownElement(layers, currentId, callbacks)
253
+ └── createDropdownItem() for each layer (indented by depth)
254
+
255
+ User hovers item → showLayerPreview() → preview overlay
256
+ User clicks item → selectElementFromLayer() → new selection → reattach
257
+ User presses Escape → closeDropdown() → reselect original
258
+ ```
@@ -0,0 +1,49 @@
1
+ /** Style constants for the layer dropdown UI */
2
+
3
+ export const DROPDOWN_CONTAINER_STYLES: Record<string, string> = {
4
+ position: "absolute",
5
+ backgroundColor: "#ffffff",
6
+ border: "1px solid #e2e8f0",
7
+ borderRadius: "6px",
8
+ boxShadow: "0 4px 12px rgba(0, 0, 0, 0.15)",
9
+ fontSize: "12px",
10
+ minWidth: "120px",
11
+ maxHeight: "200px",
12
+ overflowY: "auto",
13
+ zIndex: "10001",
14
+ padding: "4px 0",
15
+ pointerEvents: "auto",
16
+ };
17
+
18
+ export const DROPDOWN_ITEM_BASE_STYLES: Record<string, string> = {
19
+ padding: "4px 12px",
20
+ cursor: "pointer",
21
+ color: "#334155",
22
+ backgroundColor: "transparent",
23
+ whiteSpace: "nowrap",
24
+ lineHeight: "1.5",
25
+ fontWeight: "400",
26
+ };
27
+
28
+ export const DROPDOWN_ITEM_ACTIVE_COLOR = "#526cff";
29
+ export const DROPDOWN_ITEM_ACTIVE_BG = "#DBEAFE";
30
+ export const DROPDOWN_ITEM_ACTIVE_FONT_WEIGHT = "600";
31
+
32
+ export const DROPDOWN_ITEM_HOVER_BG = "#f1f5f9";
33
+
34
+ export const DEPTH_INDENT_PX = 10;
35
+
36
+ /** Chevron shown when dropdown is collapsed (click to expand) */
37
+ export const CHEVRON_COLLAPSED = " \u25BE";
38
+ /** Chevron shown when dropdown is expanded (click to collapse) */
39
+ export const CHEVRON_EXPANDED = " \u25B4";
40
+
41
+ export const BASE_PADDING_PX = 12;
42
+
43
+ export const LAYER_DROPDOWN_ATTR = "data-layer-dropdown";
44
+
45
+ /** Max instrumented ancestors to show above the selected element */
46
+ export const MAX_PARENT_DEPTH = 2;
47
+
48
+ /** Max instrumented depth levels to show below the selected element */
49
+ export const MAX_CHILD_DEPTH = 2;
@@ -0,0 +1,109 @@
1
+ /** Controller that encapsulates layer-dropdown integration logic */
2
+
3
+ import { getElementSelectorId } from "../utils.js";
4
+ import { buildLayerChain } from "./utils.js";
5
+ import {
6
+ enhanceLabelWithChevron,
7
+ showDropdown,
8
+ closeDropdown,
9
+ isDropdownOpen,
10
+ } from "./dropdown-ui.js";
11
+ import type { LayerInfo, LayerControllerConfig, LayerController } from "./types.js";
12
+
13
+ export function createLayerController(config: LayerControllerConfig): LayerController {
14
+ let layerPreviewOverlay: HTMLDivElement | null = null;
15
+ let escapeHandler: ((e: KeyboardEvent) => void) | null = null;
16
+ let dropdownSourceLayer: LayerInfo | null = null;
17
+
18
+ const clearLayerPreview = () => {
19
+ if (layerPreviewOverlay && layerPreviewOverlay.parentNode) {
20
+ layerPreviewOverlay.remove();
21
+ }
22
+ layerPreviewOverlay = null;
23
+ };
24
+
25
+ const showLayerPreview = (layer: LayerInfo) => {
26
+ clearLayerPreview();
27
+ if (getElementSelectorId(layer.element) === config.getSelectedElementId()) return;
28
+
29
+ layerPreviewOverlay = config.createPreviewOverlay(layer.element);
30
+ };
31
+
32
+ const selectLayer = (layer: LayerInfo) => {
33
+ clearLayerPreview();
34
+ closeDropdown();
35
+ if (escapeHandler) {
36
+ document.removeEventListener("keydown", escapeHandler, true);
37
+ escapeHandler = null;
38
+ }
39
+ dropdownSourceLayer = null;
40
+
41
+ const firstOverlay = config.selectElement(layer.element);
42
+ attachToOverlay(firstOverlay, layer.element);
43
+ };
44
+
45
+ const restoreSelection = () => {
46
+ if (escapeHandler) {
47
+ document.removeEventListener("keydown", escapeHandler, true);
48
+ escapeHandler = null;
49
+ }
50
+ if (dropdownSourceLayer) {
51
+ selectLayer(dropdownSourceLayer);
52
+ dropdownSourceLayer = null;
53
+ }
54
+ };
55
+
56
+ const handleLabelClick = (e: MouseEvent, label: HTMLDivElement, element: Element, layers: LayerInfo[], currentId: string | null) => {
57
+ e.stopPropagation();
58
+ e.preventDefault();
59
+ if (isDropdownOpen()) {
60
+ closeDropdown();
61
+ restoreSelection();
62
+ } else {
63
+ dropdownSourceLayer = {
64
+ element,
65
+ tagName: element.tagName.toLowerCase(),
66
+ selectorId: currentId,
67
+ };
68
+ config.onDeselect();
69
+
70
+ escapeHandler = (ev: KeyboardEvent) => {
71
+ if (ev.key === "Escape") {
72
+ ev.stopPropagation();
73
+ closeDropdown();
74
+ restoreSelection();
75
+ }
76
+ };
77
+ document.addEventListener("keydown", escapeHandler, true);
78
+
79
+ showDropdown(label, layers, element, { onSelect: selectLayer, onHover: showLayerPreview, onHoverEnd: clearLayerPreview });
80
+ }
81
+ };
82
+
83
+ const attachToOverlay = (
84
+ overlay: HTMLDivElement | undefined,
85
+ element: Element
86
+ ) => {
87
+ if (!overlay) return;
88
+
89
+ const label = overlay.querySelector("div") as HTMLDivElement | null;
90
+ if (!label) return;
91
+
92
+ const layers = buildLayerChain(element);
93
+ if (layers.length <= 1) return;
94
+
95
+ const currentId = getElementSelectorId(element);
96
+ enhanceLabelWithChevron(label);
97
+
98
+ label.addEventListener("click", (e: MouseEvent) => {
99
+ handleLabelClick(e, label, element, layers, currentId);
100
+ });
101
+ };
102
+
103
+ const cleanup = () => {
104
+ clearLayerPreview();
105
+ closeDropdown();
106
+ };
107
+
108
+ return { attachToOverlay, cleanup };
109
+ }