first commit

This commit is contained in:
2026-06-24 09:48:54 +02:00
commit 41e62ddcad
33739 changed files with 4266226 additions and 0 deletions
@@ -0,0 +1,6 @@
export type AutoPopupSuppressorController = {
suppress: () => void;
teardown: () => void;
};
export declare function createAutoPopupSuppressorController(): AutoPopupSuppressorController;
//# sourceMappingURL=auto-popup-suppressor.d.ts.map
@@ -0,0 +1 @@
{"version":3,"file":"auto-popup-suppressor.d.ts","sourceRoot":"","sources":["../../src/injections/auto-popup-suppressor.ts"],"names":[],"mappings":"AAuCA,MAAM,MAAM,6BAA6B,GAAG;IAC1C,QAAQ,EAAE,MAAM,IAAI,CAAC;IACrB,QAAQ,EAAE,MAAM,IAAI,CAAC;CACtB,CAAC;AAIF,wBAAgB,mCAAmC,IAAI,6BAA6B,CAgGnF"}
@@ -0,0 +1,264 @@
// auto-popup-suppressor — hides auto-opening modal popups in the canvas
// preview iframe so the page snapshot isn't obscured by overlays the user
// didn't intend to capture. Driven by `{ type: "suppress-auto-popups" }` from
// the parent; inert until that arrives.
//
// Two-stage heuristic:
//
// 1. BACKDROP MATCH — element must be `position: fixed`, cover ≥90% of the
// viewport on both axes, have a popup-level z-index, and show backdrop-
// like styles (translucent background OR backdrop-filter). This is the
// modal-overlay fingerprint.
//
// 2. PANEL SWEEP — once we've hidden any backdrop, sweep the whole document
// for fixed/high-z elements whose bbox falls in a "modal-shaped" band
// (15–95% on both axes). Picks up the dialog content panel even when it
// isn't a direct sibling of the overlay (Radix wraps content in
// FocusScope + DismissableLayer + focus-guards; shadcn's portals use
// `asChild`, so structural relationships vary).
//
// A sticky `backdropEverDetected` flag keeps the panel-shape check live for
// later MutationObserver ticks — Content sometimes mounts in a different
// batch than its Overlay.
//
// Why the percentage gates aren't based on window.innerHeight: the canvas
// iframe is auto-sized to the document content (e.g. 4958px), so innerHeight
// is the document height, not the visible viewport. page-height-bridge sets
// `--base44-reference-vh-base` to the canvas tile height — the viewport the
// user actually sees — and that's what our gates use.
const SUPPRESSED_ATTR = "data-base44-suppressed-popup";
const REFERENCE_VH_BASE_VAR = "--base44-reference-vh-base";
const FULL_VIEWPORT_RATIO = 0.9;
const MODAL_PANEL_MIN_RATIO = 0.15;
const MODAL_PANEL_MAX_RATIO = 0.95;
const POPUP_Z_INDEX_THRESHOLD = 40;
// ── Public API ──────────────────────────────────────────────────────────────
export function createAutoPopupSuppressorController() {
let observer = null;
let domReadyHandler = null;
let active = false;
// Once a backdrop has been seen, modal-shaped panels appearing in later
// mutation batches are also hidden. Without this, a Content node that
// mounts after its Overlay's batch wouldn't be matched in-flight.
let backdropEverDetected = false;
// Single decision per element. One getComputedStyle call — backdrop and
// panel checks share the position/z-index preconditions. Without sharing,
// every non-matching node in a React commit's added subtree would pay for
// two style recalcs, which is the MutationObserver hot path.
const classify = (el, vp) => {
if (!(el instanceof HTMLElement))
return;
if (el.hasAttribute(SUPPRESSED_ATTR))
return;
const style = window.getComputedStyle(el);
if (style.position !== "fixed")
return;
if (!hasPopupZIndex(style))
return;
if (coversFullViewport(el, vp) && hasBackdropLook(el, style)) {
hideBackdrop(el);
return;
}
if (backdropEverDetected && hasModalShapeBbox(el, vp)) {
applyHide(el);
}
};
const hideBackdrop = (el) => {
if (el.hasAttribute(SUPPRESSED_ATTR))
return;
applyHide(el);
backdropEverDetected = true;
sweepDocumentForModalPanels(viewportForGates());
};
const scanSubtree = (root, vp) => {
classify(root, vp);
const descendants = root.querySelectorAll(`*:not([${SUPPRESSED_ATTR}])`);
for (let i = 0; i < descendants.length; i++) {
const el = descendants[i];
if (el)
classify(el, vp);
}
};
const attachObserver = () => {
if (observer)
return;
// viewportForGates is read once per mutation batch, not per added node —
// a busy React commit can deliver dozens of added subtrees in one tick.
observer = new MutationObserver((mutations) => {
const vp = viewportForGates();
for (const m of mutations) {
if (m.type !== "childList")
continue;
for (let i = 0; i < m.addedNodes.length; i++) {
const node = m.addedNodes[i];
if (node instanceof Element)
scanSubtree(node, vp);
}
}
});
observer.observe(document.documentElement, { childList: true, subtree: true });
};
const start = () => {
if (!document.body)
return;
scanSubtree(document.body, viewportForGates());
attachObserver();
};
return {
suppress: () => {
if (active)
return;
active = true;
if (document.body) {
start();
}
else {
domReadyHandler = () => {
domReadyHandler = null;
start();
};
document.addEventListener("DOMContentLoaded", domReadyHandler);
}
},
teardown: () => {
active = false;
backdropEverDetected = false;
if (observer) {
observer.disconnect();
observer = null;
}
if (domReadyHandler) {
document.removeEventListener("DOMContentLoaded", domReadyHandler);
domReadyHandler = null;
}
},
};
}
// ── Document-wide panel sweep ───────────────────────────────────────────────
// Triggered once per backdrop hide. Walks the whole document for unhidden
// fixed/high-z elements whose bbox falls inside the modal-shape band — picks
// up content panels regardless of how they're nested or which portal they
// went through.
function sweepDocumentForModalPanels(vp) {
if (!document.body)
return;
if (vp.vw <= 0 || vp.vh <= 0)
return;
const candidates = document.body.querySelectorAll(`*:not([${SUPPRESSED_ATTR}])`);
for (let i = 0; i < candidates.length; i++) {
const el = candidates[i];
if (el && isModalPanel(el, vp))
applyHide(el);
}
}
function isModalPanel(el, vp) {
if (el.hasAttribute(SUPPRESSED_ATTR))
return false;
const style = window.getComputedStyle(el);
if (style.position !== "fixed")
return false;
if (!hasPopupZIndex(style))
return false;
return hasModalShapeBbox(el, vp);
}
// ── Gate predicates ─────────────────────────────────────────────────────────
function coversFullViewport(el, vp) {
if (vp.vw <= 0 || vp.vh <= 0)
return false;
const rect = el.getBoundingClientRect();
return (rect.width >= vp.vw * FULL_VIEWPORT_RATIO &&
rect.height >= vp.vh * FULL_VIEWPORT_RATIO);
}
// "Modal-shaped" = small enough not to be a sidebar/full-screen overlay
// (≤95% on both axes), big enough not to be a nav/footer/toast (≥15% on both
// axes). Calibrated against shadcn Dialog content (≈25–50% × 30–50%), top
// nav (height fails ≤15%), sidebar (height fails ≥95%), toast (height fails
// ≤15%).
function hasModalShapeBbox(el, vp) {
const rect = el.getBoundingClientRect();
return (rect.width >= vp.vw * MODAL_PANEL_MIN_RATIO &&
rect.height >= vp.vh * MODAL_PANEL_MIN_RATIO &&
rect.width <= vp.vw * MODAL_PANEL_MAX_RATIO &&
rect.height <= vp.vh * MODAL_PANEL_MAX_RATIO);
}
function hasPopupZIndex(style) {
const z = parseInt(style.zIndex, 10);
return Number.isFinite(z) && z >= POPUP_Z_INDEX_THRESHOLD;
}
// True if the element looks like a modal backdrop: translucent fill OR a
// backdrop-filter (e.g. blur). Also returns true if the element's own bg is
// transparent but a fixed/high-z descendant paints the backdrop — covers
// dialog wrappers that delegate the backdrop to a child element.
function hasBackdropLook(el, style) {
if (isTranslucent(style.backgroundColor))
return true;
if (style.backdropFilter && style.backdropFilter !== "none")
return true;
const descendants = el.querySelectorAll("*");
for (let i = 0; i < descendants.length; i++) {
const child = descendants[i];
if (!child)
continue;
const cs = window.getComputedStyle(child);
if (cs.position !== "fixed" && cs.position !== "absolute")
continue;
if (!hasPopupZIndex(cs))
continue;
if (isTranslucent(cs.backgroundColor))
return true;
if (cs.backdropFilter && cs.backdropFilter !== "none")
return true;
}
return false;
}
function isTranslucent(color) {
const alpha = parseAlpha(color);
return alpha !== null && alpha > 0 && alpha < 1;
}
// Extracts the alpha channel from a computed background-color across legacy
// AND modern color syntaxes:
//
// • `rgb(r, g, b)` / `rgba(r, g, b, a)` — legacy comma syntax.
// • `<func>(... / a)` / `<func>(... / a%)` — modern slash-alpha (oklch,
// oklab, lch, lab, hsl, hsla, color, modern rgb). Tailwind v4 / shadcn
// theme tokens compute to these.
// • A recognized color function call without explicit alpha → 1.
//
// Returns null when unrecognized; callers treat null as "not a backdrop".
function parseAlpha(value) {
if (!value)
return null;
const comma = /^rgba?\(\s*\d+\s*,\s*\d+\s*,\s*\d+\s*(?:,\s*([0-9.]+)\s*)?\)$/.exec(value);
if (comma)
return comma[1] === undefined ? 1 : parseFloat(comma[1]);
const slash = /\/\s*([0-9.]+)(%?)\s*\)$/.exec(value);
if (slash) {
const n = parseFloat(slash[1]);
return slash[2] === "%" ? n / 100 : n;
}
if (/^[a-z]+\s*\(/.test(value))
return 1;
return null;
}
// ── Viewport + DOM ops ──────────────────────────────────────────────────────
// Viewport dimensions used for percentage gates. Width comes from
// `innerWidth` (unaffected by canvas auto-fit). Height prefers the reference
// vh set by page-height-bridge — without that, after the iframe auto-resizes
// to document content, `innerHeight` is the document height and every modal
// panel falls below the 15% floor.
function viewportForGates() {
const vw = window.innerWidth || document.documentElement.clientWidth || 0;
const refStr = document.documentElement.style.getPropertyValue(REFERENCE_VH_BASE_VAR);
const ref = parseFloat(refStr);
const vh = Number.isFinite(ref) && ref > 0
? ref
: (window.innerHeight || document.documentElement.clientHeight || 0);
return { vw, vh };
}
function applyHide(el) {
if (el.hasAttribute(SUPPRESSED_ATTR))
return;
el.setAttribute(SUPPRESSED_ATTR, "1");
el.style.setProperty("display", "none", "important");
}
//# sourceMappingURL=auto-popup-suppressor.js.map
File diff suppressed because one or more lines are too long
@@ -0,0 +1,5 @@
export declare function createCanvasWheelZoomBridgeController(): {
enable: () => void;
disable: () => void;
};
//# sourceMappingURL=canvas-wheel-zoom-bridge.d.ts.map
@@ -0,0 +1 @@
{"version":3,"file":"canvas-wheel-zoom-bridge.d.ts","sourceRoot":"","sources":["../../src/injections/canvas-wheel-zoom-bridge.ts"],"names":[],"mappings":"AAuBA,wBAAgB,qCAAqC;kBAsChC,IAAI;mBAMH,IAAI;EAUzB"}
@@ -0,0 +1,64 @@
import { PLUGIN_ELEMENT_ATTR } from "./utils.js";
function elementFromEventTarget(target) {
if (target instanceof Element)
return target;
if (target instanceof Node)
return target.parentElement;
return null;
}
function isPluginOwnedTarget(target) {
return elementFromEventTarget(target)?.closest(`[${PLUGIN_ELEMENT_ATTR}]`) != null;
}
export function createCanvasWheelZoomBridgeController() {
let isEnabled = false;
const onWheel = (event) => {
if (isPluginOwnedTarget(event.target))
return;
event.preventDefault();
if (event.ctrlKey || event.metaKey) {
window.parent.postMessage({
type: "canvas-wheel-zoom",
data: {
deltaY: event.deltaY,
deltaMode: event.deltaMode,
clientX: event.clientX,
clientY: event.clientY,
ctrlKey: event.ctrlKey,
metaKey: event.metaKey,
},
}, "*");
return;
}
const panData = {
deltaX: event.deltaX,
deltaY: event.deltaY,
deltaMode: event.deltaMode,
clientX: event.clientX,
clientY: event.clientY,
shiftKey: event.shiftKey,
ctrlKey: false,
metaKey: false,
};
window.parent.postMessage({
type: "canvas-wheel-pan",
data: panData,
}, "*");
};
const enable = () => {
if (isEnabled)
return;
isEnabled = true;
window.addEventListener("wheel", onWheel, { capture: true, passive: false });
};
const disable = () => {
if (!isEnabled)
return;
isEnabled = false;
window.removeEventListener("wheel", onWheel, true);
};
return {
enable,
disable,
};
}
//# sourceMappingURL=canvas-wheel-zoom-bridge.js.map
@@ -0,0 +1 @@
{"version":3,"file":"canvas-wheel-zoom-bridge.js","sourceRoot":"","sources":["../../src/injections/canvas-wheel-zoom-bridge.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,mBAAmB,EAAE,MAAM,YAAY,CAAC;AAajD,SAAS,sBAAsB,CAAC,MAA0B;IACxD,IAAI,MAAM,YAAY,OAAO;QAAE,OAAO,MAAM,CAAC;IAC7C,IAAI,MAAM,YAAY,IAAI;QAAE,OAAO,MAAM,CAAC,aAAa,CAAC;IACxD,OAAO,IAAI,CAAC;AACd,CAAC;AAED,SAAS,mBAAmB,CAAC,MAA0B;IACrD,OAAO,sBAAsB,CAAC,MAAM,CAAC,EAAE,OAAO,CAAC,IAAI,mBAAmB,GAAG,CAAC,IAAI,IAAI,CAAC;AACrF,CAAC;AAED,MAAM,UAAU,qCAAqC;IACnD,IAAI,SAAS,GAAG,KAAK,CAAC;IAEtB,MAAM,OAAO,GAAG,CAAC,KAAiB,EAAQ,EAAE;QAC1C,IAAI,mBAAmB,CAAC,KAAK,CAAC,MAAM,CAAC;YAAE,OAAO;QAE9C,KAAK,CAAC,cAAc,EAAE,CAAC;QACvB,IAAI,KAAK,CAAC,OAAO,IAAI,KAAK,CAAC,OAAO,EAAE,CAAC;YACnC,MAAM,CAAC,MAAM,CAAC,WAAW,CAAC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AAO;KACR,CAAC;AACJ,CAAC"}
@@ -0,0 +1,20 @@
/** Style constants for the layer dropdown UI */
export declare const DROPDOWN_CONTAINER_STYLES: Record<string, string>;
export declare const DROPDOWN_ITEM_BASE_STYLES: Record<string, string>;
export declare const DROPDOWN_ITEM_ACTIVE_COLOR = "#526cff";
export declare const DROPDOWN_ITEM_ACTIVE_BG = "#DBEAFE";
export declare const DROPDOWN_ITEM_ACTIVE_FONT_WEIGHT = "600";
export declare const DROPDOWN_ITEM_HOVER_BG = "#f1f5f9";
export declare const DEPTH_INDENT_PX = 10;
/** SVG chevron shown when dropdown is collapsed (click to expand) */
export declare const CHEVRON_COLLAPSED = "<svg width=\"12\" height=\"12\" viewBox=\"0 0 24 24\" style=\"vertical-align:middle;margin-left:4px\"><path d=\"M6 9l6 6 6-6\" stroke=\"currentColor\" stroke-width=\"2\" fill=\"none\"/></svg>";
/** SVG chevron shown when dropdown is expanded (click to collapse) */
export declare const CHEVRON_EXPANDED = "<svg width=\"12\" height=\"12\" viewBox=\"0 0 24 24\" style=\"vertical-align:middle;margin-left:4px\"><path d=\"M18 15l-6-6-6 6\" stroke=\"currentColor\" stroke-width=\"2\" fill=\"none\"/></svg>";
export declare const CHEVRON_ATTR = "data-chevron";
export declare const BASE_PADDING_PX = 12;
export declare const LAYER_DROPDOWN_ATTR = "data-layer-dropdown";
/** Max instrumented ancestors to show above the selected element */
export declare const MAX_PARENT_DEPTH = 2;
/** Max instrumented depth levels to show below the selected element */
export declare const MAX_CHILD_DEPTH = 2;
//# sourceMappingURL=consts.d.ts.map
@@ -0,0 +1 @@
{"version":3,"file":"consts.d.ts","sourceRoot":"","sources":["../../../src/injections/layer-dropdown/consts.ts"],"names":[],"mappings":"AAAA,gDAAgD;AAEhD,eAAO,MAAM,yBAAyB,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAa5D,CAAC;AAEF,eAAO,MAAM,yBAAyB,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAQ5D,CAAC;AAEF,eAAO,MAAM,0BAA0B,YAAY,CAAC;AACpD,eAAO,MAAM,uBAAuB,YAAY,CAAC;AACjD,eAAO,MAAM,gCAAgC,QAAQ,CAAC;AAEtD,eAAO,MAAM,sBAAsB,YAAY,CAAC;AAEhD,eAAO,MAAM,eAAe,KAAK,CAAC;AAElC,qEAAqE;AACrE,eAAO,MAAM,iBAAiB,oMAAoL,CAAC;AACnN,sEAAsE;AACtE,eAAO,MAAM,gBAAgB,uMAAuL,CAAC;AAErN,eAAO,MAAM,YAAY,iBAAiB,CAAC;AAE3C,eAAO,MAAM,eAAe,KAAK,CAAC;AAElC,eAAO,MAAM,mBAAmB,wBAAwB,CAAC;AAEzD,oEAAoE;AACpE,eAAO,MAAM,gBAAgB,IAAI,CAAC;AAElC,uEAAuE;AACvE,eAAO,MAAM,eAAe,IAAI,CAAC"}
@@ -0,0 +1,41 @@
/** Style constants for the layer dropdown UI */
export const DROPDOWN_CONTAINER_STYLES = {
position: "absolute",
backgroundColor: "#ffffff",
border: "1px solid #e2e8f0",
borderRadius: "6px",
boxShadow: "0 4px 12px rgba(0, 0, 0, 0.15)",
fontSize: "12px",
minWidth: "120px",
maxHeight: "200px",
overflowY: "auto",
zIndex: "10001",
padding: "4px 0",
pointerEvents: "auto",
};
export const DROPDOWN_ITEM_BASE_STYLES = {
padding: "4px 12px",
cursor: "pointer",
color: "#334155",
backgroundColor: "transparent",
whiteSpace: "nowrap",
lineHeight: "1.5",
fontWeight: "400",
};
export const DROPDOWN_ITEM_ACTIVE_COLOR = "#526cff";
export const DROPDOWN_ITEM_ACTIVE_BG = "#DBEAFE";
export const DROPDOWN_ITEM_ACTIVE_FONT_WEIGHT = "600";
export const DROPDOWN_ITEM_HOVER_BG = "#f1f5f9";
export const DEPTH_INDENT_PX = 10;
/** SVG chevron shown when dropdown is collapsed (click to expand) */
export const CHEVRON_COLLAPSED = `<svg width="12" height="12" viewBox="0 0 24 24" style="vertical-align:middle;margin-left:4px"><path d="M6 9l6 6 6-6" stroke="currentColor" stroke-width="2" fill="none"/></svg>`;
/** SVG chevron shown when dropdown is expanded (click to collapse) */
export const CHEVRON_EXPANDED = `<svg width="12" height="12" viewBox="0 0 24 24" style="vertical-align:middle;margin-left:4px"><path d="M18 15l-6-6-6 6" stroke="currentColor" stroke-width="2" fill="none"/></svg>`;
export const CHEVRON_ATTR = "data-chevron";
export const BASE_PADDING_PX = 12;
export const LAYER_DROPDOWN_ATTR = "data-layer-dropdown";
/** Max instrumented ancestors to show above the selected element */
export const MAX_PARENT_DEPTH = 2;
/** Max instrumented depth levels to show below the selected element */
export const MAX_CHILD_DEPTH = 2;
//# sourceMappingURL=consts.js.map
@@ -0,0 +1 @@
{"version":3,"file":"consts.js","sourceRoot":"","sources":["../../../src/injections/layer-dropdown/consts.ts"],"names":[],"mappings":"AAAA,gDAAgD;AAEhD,MAAM,CAAC,MAAM,yBAAyB,GAA2B;IAC/D,QAAQ,EAAE,UAAU;IACpB,eAAe,EAAE,SAAS;IAC1B,MAAM,EAAE,mBAAmB;IAC3B,YAAY,EAAE,KAAK;IACnB,SAAS,EAAE,gCAAgC;IAC3C,QAAQ,EAAE,MAAM;IAChB,QAAQ,EAAE,OAAO;IACjB,SAAS,EAAE,OAAO;IAClB,SAAS,EAAE,MAAM;IACjB,MAAM,EAAE,OAAO;IACf,OAAO,EAAE,OAAO;IAChB,aAAa,EAAE,MAAM;CACtB,CAAC;AAEF,MAAM,CAAC,MAAM,yBAAyB,GAA2B;IAC/D,OAAO,EAAE,UAAU;IACnB,MAAM,EAAE,SAAS;IACjB,KAAK,EAAE,SAAS;IAChB,eAAe,EAAE,aAAa;IAC9B,UAAU,EAAE,QAAQ;IACpB,UAAU,EAAE,KAAK;IACjB,UAAU,EAAE,KAAK;CAClB,CAAC;AAEF,MAAM,CAAC,MAAM,0BAA0B,GAAG,SAAS,CAAC;AACpD,MAAM,CAAC,MAAM,uBAAuB,GAAG,SAAS,CAAC;AACjD,MAAM,CAAC,MAAM,gCAAgC,GAAG,KAAK,CAAC;AAEtD,MAAM,CAAC,MAAM,sBAAsB,GAAG,SAAS,CAAC;AAEhD,MAAM,CAAC,MAAM,eAAe,GAAG,EAAE,CAAC;AAElC,qEAAqE;AACrE,MAAM,CAAC,MAAM,iBAAiB,GAAG,iLAAiL,CAAC;AACnN,sEAAsE;AACtE,MAAM,CAAC,MAAM,gBAAgB,GAAG,oLAAoL,CAAC;AAErN,MAAM,CAAC,MAAM,YAAY,GAAG,cAAc,CAAC;AAE3C,MAAM,CAAC,MAAM,eAAe,GAAG,EAAE,CAAC;AAElC,MAAM,CAAC,MAAM,mBAAmB,GAAG,qBAAqB,CAAC;AAEzD,oEAAoE;AACpE,MAAM,CAAC,MAAM,gBAAgB,GAAG,CAAC,CAAC;AAElC,uEAAuE;AACvE,MAAM,CAAC,MAAM,eAAe,GAAG,CAAC,CAAC"}
@@ -0,0 +1,4 @@
/** Controller that encapsulates layer-dropdown integration logic */
import type { LayerControllerConfig, LayerController } from "./types.js";
export declare function createLayerController(config: LayerControllerConfig): LayerController;
//# sourceMappingURL=controller.d.ts.map
@@ -0,0 +1 @@
{"version":3,"file":"controller.d.ts","sourceRoot":"","sources":["../../../src/injections/layer-dropdown/controller.ts"],"names":[],"mappings":"AAAA,oEAAoE;AAUpE,OAAO,KAAK,EAAa,qBAAqB,EAAE,eAAe,EAAE,MAAM,YAAY,CAAC;AAEpF,wBAAgB,qBAAqB,CAAC,MAAM,EAAE,qBAAqB,GAAG,eAAe,CAgGpF"}
@@ -0,0 +1,88 @@
/** Controller that encapsulates layer-dropdown integration logic */
import { getElementSelectorId } from "../utils.js";
import { buildLayerChain } from "./utils.js";
import { enhanceLabelWithChevron, showDropdown, closeDropdown, isDropdownOpen, } from "./dropdown-ui.js";
export function createLayerController(config) {
let layerPreviewOverlay = null;
let escapeHandler = null;
let dropdownSourceLayer = null;
const clearLayerPreview = () => {
if (layerPreviewOverlay && layerPreviewOverlay.parentNode) {
layerPreviewOverlay.remove();
}
layerPreviewOverlay = null;
};
const showLayerPreview = (layer) => {
clearLayerPreview();
if (getElementSelectorId(layer.element) === config.getSelectedElementId())
return;
layerPreviewOverlay = config.createPreviewOverlay(layer.element);
};
const selectLayer = (layer) => {
clearLayerPreview();
closeDropdown();
if (escapeHandler) {
document.removeEventListener("keydown", escapeHandler, true);
escapeHandler = null;
}
dropdownSourceLayer = null;
const firstOverlay = config.selectElement(layer.element);
attachToOverlay(firstOverlay, layer.element);
};
const restoreSelection = () => {
if (escapeHandler) {
document.removeEventListener("keydown", escapeHandler, true);
escapeHandler = null;
}
if (dropdownSourceLayer) {
selectLayer(dropdownSourceLayer);
dropdownSourceLayer = null;
}
};
const handleLabelClick = (e, label, element, layers, currentId) => {
e.stopPropagation();
e.preventDefault();
if (isDropdownOpen()) {
closeDropdown();
restoreSelection();
}
else {
dropdownSourceLayer = {
element,
tagName: element.tagName.toLowerCase(),
selectorId: currentId,
};
config.onDeselect();
escapeHandler = (ev) => {
if (ev.key === "Escape") {
ev.stopPropagation();
closeDropdown();
restoreSelection();
}
};
document.addEventListener("keydown", escapeHandler, true);
showDropdown(label, layers, element, { onSelect: selectLayer, onHover: showLayerPreview, onHoverEnd: clearLayerPreview });
}
};
const attachToOverlay = (overlay, element) => {
if (!overlay)
return;
const label = overlay.querySelector("div");
if (!label)
return;
const layers = buildLayerChain(element);
if (layers.length <= 1)
return;
const currentId = getElementSelectorId(element);
enhanceLabelWithChevron(label);
label.addEventListener("click", (e) => {
handleLabelClick(e, label, element, layers, currentId);
});
};
const cleanup = () => {
clearLayerPreview();
closeDropdown();
};
return { attachToOverlay, cleanup };
}
//# sourceMappingURL=controller.js.map
@@ -0,0 +1 @@
{"version":3,"file":"controller.js","sourceRoot":"","sources":["../../../src/injections/layer-dropdown/controller.ts"],"names":[],"mappings":"AAAA,oEAAoE;AAEpE,OAAO,EAAE,oBAAoB,EAAE,MAAM,aAAa,CAAC;AACnD,OAAO,EAAE,eAAe,EAAE,MAAM,YAAY,CAAC;AAC7C,OAAO,EAC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,OAAO;YAAE,OAAO;QAErB,MAAM,KAAK,GAAG,OAAO,CAAC,aAAa,CAAC,KAAK,CAA0B,CAAC;QACpE,IAAI,CAAC,KAAK;YAAE,OAAO;QAEnB,MAAM,MAAM,GAAG,eAAe,CAAC,OAAO,CAAC,CAAC;QACxC,IAAI,MAAM,CAAC,MAAM,IAAI,CAAC;YAAE,OAAO;QAE/B,MAAM,SAAS,GAAG,oBAAoB,CAAC,OAAO,CAAC,CAAC;QAChD,uBAAuB,CAAC,KAAK,CAAC,CAAC;QAE/B,KAAK,CAAC,gBAAgB,CAAC,OAAO,EAAE,CAAC,CAAa,EAAE,EAAE;YAChD,gBAAgB,CAAC,CAAC,EAAE,KAAK,EAAE,OAAO,EAAE,MAAM,EAAE,SAAS,CAAC,CAAC;QACzD,CAAC,CAAC,CAAC;IACL,CAAC,CAAC;IAEF,MAAM,OAAO,GAAG,GAAG,EAAE;QACnB,iBAAiB,EAAE,CAAC;QACpB,aAAa,EAAE,CAAC;IAClB,CAAC,CAAC;IAEF,OAAO,EAAE,eAAe,EAAE,OAAO,EAAE,CAAC;AACtC,CAAC"}
@@ -0,0 +1,13 @@
/** Dropdown UI component for layer navigation */
import type { LayerInfo, DropdownCallbacks } from "./types.js";
/** Create the dropdown DOM element with layer items */
export declare function createDropdownElement(layers: LayerInfo[], currentElement: Element | null, callbacks: DropdownCallbacks): HTMLDivElement;
/** Add chevron indicator and pointer-events to the label */
export declare function enhanceLabelWithChevron(label: HTMLDivElement): void;
/** Show the dropdown below the label element */
export declare function showDropdown(label: HTMLDivElement, layers: LayerInfo[], currentElement: Element | null, callbacks: DropdownCallbacks): void;
/** Close the active dropdown and clean up listeners */
export declare function closeDropdown(): void;
/** Check if a dropdown is currently visible */
export declare function isDropdownOpen(): boolean;
//# sourceMappingURL=dropdown-ui.d.ts.map
@@ -0,0 +1 @@
{"version":3,"file":"dropdown-ui.d.ts","sourceRoot":"","sources":["../../../src/injections/layer-dropdown/dropdown-ui.ts"],"names":[],"mappings":"AAAA,iDAAiD;AAiBjD,OAAO,KAAK,EAAE,SAAS,EAAE,iBAAiB,EAAE,MAAM,YAAY,CAAC;AAgD/D,uDAAuD;AACvD,wBAAgB,qBAAqB,CACnC,MAAM,EAAE,SAAS,EAAE,EACnB,cAAc,EAAE,OAAO,GAAG,IAAI,EAC9B,SAAS,EAAE,iBAAiB,GAC3B,cAAc,CAYhB;AAED,4DAA4D;AAC5D,wBAAgB,uBAAuB,CAAC,KAAK,EAAE,cAAc,GAAG,IAAI,CAiBnE;AAkED,gDAAgD;AAChD,wBAAgB,YAAY,CAC1B,KAAK,EAAE,cAAc,EACrB,MAAM,EAAE,SAAS,EAAE,EACnB,cAAc,EAAE,OAAO,GAAG,IAAI,EAC9B,SAAS,EAAE,iBAAiB,GAC3B,IAAI,CAiCN;AAED,uDAAuD;AACvD,wBAAgB,aAAa,IAAI,IAAI,CA0BpC;AAED,+CAA+C;AAC/C,wBAAgB,cAAc,IAAI,OAAO,CAExC"}
@@ -0,0 +1,186 @@
/** Dropdown UI component for layer navigation */
import { 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, BASE_PADDING_PX, CHEVRON_COLLAPSED, CHEVRON_EXPANDED, CHEVRON_ATTR, LAYER_DROPDOWN_ATTR, } from "./consts.js";
import { applyStyles, getLayerDisplayName } from "./utils.js";
import { PLUGIN_ELEMENT_ATTR } from "../utils.js";
let activeDropdown = null;
let activeLabel = null;
let outsideMousedownHandler = null;
let activeOnHoverEnd = null;
let activeKeydownHandler = null;
function createDropdownItem(layer, isActive, { onSelect, onHover, onHoverEnd }) {
const item = document.createElement("div");
item.textContent = getLayerDisplayName(layer);
applyStyles(item, DROPDOWN_ITEM_BASE_STYLES);
const depth = layer.depth ?? 0;
if (depth > 0) {
item.style.paddingLeft = `${BASE_PADDING_PX + depth * DEPTH_INDENT_PX}px`;
}
if (isActive) {
item.style.color = DROPDOWN_ITEM_ACTIVE_COLOR;
item.style.backgroundColor = DROPDOWN_ITEM_ACTIVE_BG;
item.style.fontWeight = DROPDOWN_ITEM_ACTIVE_FONT_WEIGHT;
}
item.addEventListener("mouseenter", () => {
if (!isActive)
item.style.backgroundColor = DROPDOWN_ITEM_HOVER_BG;
if (onHover)
onHover(layer);
});
item.addEventListener("mouseleave", () => {
if (!isActive)
item.style.backgroundColor = "transparent";
if (onHoverEnd)
onHoverEnd();
});
item.addEventListener("click", (e) => {
e.stopPropagation();
e.preventDefault();
onSelect(layer);
});
return item;
}
/** Create the dropdown DOM element with layer items */
export function createDropdownElement(layers, currentElement, callbacks) {
const container = document.createElement("div");
container.setAttribute(LAYER_DROPDOWN_ATTR, "true");
container.setAttribute(PLUGIN_ELEMENT_ATTR, "true");
applyStyles(container, DROPDOWN_CONTAINER_STYLES);
layers.forEach((layer) => {
const isActive = layer.element === currentElement;
container.appendChild(createDropdownItem(layer, isActive, callbacks));
});
return container;
}
/** Add chevron indicator and pointer-events to the label */
export function enhanceLabelWithChevron(label) {
if (label.querySelector(`[${CHEVRON_ATTR}]`))
return;
const chevron = document.createElement("span");
chevron.setAttribute(CHEVRON_ATTR, "true");
chevron.style.display = "inline-flex";
chevron.innerHTML = CHEVRON_COLLAPSED;
label.appendChild(chevron);
label.style.display = "inline-flex";
label.style.alignItems = "center";
label.style.cursor = "pointer";
label.style.userSelect = "none";
label.style.whiteSpace = "nowrap";
label.style.pointerEvents = "auto";
label.setAttribute(LAYER_DROPDOWN_ATTR, "true");
label.setAttribute(PLUGIN_ELEMENT_ATTR, "true");
}
function setupKeyboardNavigation(dropdown, layers, currentElement, { onSelect, onHover, onHoverEnd }) {
const items = Array.from(dropdown.children);
let focusedIndex = layers.findIndex((l) => l.element === currentElement);
const setFocusedItem = (index) => {
if (focusedIndex >= 0 && focusedIndex < items.length) {
const prev = items[focusedIndex];
if (prev.style.color !== DROPDOWN_ITEM_ACTIVE_COLOR) {
prev.style.backgroundColor = "transparent";
}
}
focusedIndex = index;
if (focusedIndex >= 0 && focusedIndex < items.length) {
const cur = items[focusedIndex];
if (cur.style.color !== DROPDOWN_ITEM_ACTIVE_COLOR) {
cur.style.backgroundColor = DROPDOWN_ITEM_HOVER_BG;
}
cur.scrollIntoView({ block: "nearest" });
if (onHover && focusedIndex >= 0 && focusedIndex < layers.length) {
onHover(layers[focusedIndex]);
}
}
};
activeKeydownHandler = (e) => {
if (e.key === "ArrowDown") {
e.preventDefault();
e.stopPropagation();
setFocusedItem(focusedIndex < items.length - 1 ? focusedIndex + 1 : 0);
}
else if (e.key === "ArrowUp") {
e.preventDefault();
e.stopPropagation();
setFocusedItem(focusedIndex > 0 ? focusedIndex - 1 : items.length - 1);
}
else if (e.key === "Enter" && focusedIndex >= 0 && focusedIndex < layers.length) {
e.preventDefault();
e.stopPropagation();
if (onHoverEnd)
onHoverEnd();
onSelect(layers[focusedIndex]);
closeDropdown();
}
};
document.addEventListener("keydown", activeKeydownHandler, true);
}
function setupOutsideClickHandler(dropdown, label) {
let skipFirst = true;
outsideMousedownHandler = (e) => {
if (skipFirst) {
skipFirst = false;
return;
}
const target = e.target;
if (!dropdown.contains(target) && target !== label) {
closeDropdown();
}
};
document.addEventListener("mousedown", outsideMousedownHandler, true);
}
/** Show the dropdown below the label element */
export function showDropdown(label, layers, currentElement, callbacks) {
closeDropdown();
const dropdown = createDropdownElement(layers, currentElement, {
...callbacks,
onSelect: (layer) => {
if (callbacks.onHoverEnd)
callbacks.onHoverEnd();
callbacks.onSelect(layer);
closeDropdown();
},
});
const overlay = label.parentElement;
if (!overlay)
return;
dropdown.style.top = `${label.offsetTop + label.offsetHeight + 2}px`;
dropdown.style.left = `${label.offsetLeft}px`;
overlay.appendChild(dropdown);
activeDropdown = dropdown;
activeLabel = label;
const chevronEl = label.querySelector(`[${CHEVRON_ATTR}]`);
if (chevronEl) {
chevronEl.innerHTML = CHEVRON_EXPANDED;
}
activeOnHoverEnd = callbacks.onHoverEnd ?? null;
setupKeyboardNavigation(dropdown, layers, currentElement, callbacks);
setupOutsideClickHandler(dropdown, label);
}
/** Close the active dropdown and clean up listeners */
export function closeDropdown() {
const chevronEl = activeLabel?.querySelector(`[${CHEVRON_ATTR}]`);
if (chevronEl) {
chevronEl.innerHTML = CHEVRON_COLLAPSED;
}
activeLabel = null;
if (activeOnHoverEnd) {
activeOnHoverEnd();
activeOnHoverEnd = null;
}
if (activeDropdown && activeDropdown.parentNode) {
activeDropdown.remove();
}
activeDropdown = null;
if (outsideMousedownHandler) {
document.removeEventListener("mousedown", outsideMousedownHandler, true);
outsideMousedownHandler = null;
}
if (activeKeydownHandler) {
document.removeEventListener("keydown", activeKeydownHandler, true);
activeKeydownHandler = null;
}
}
/** Check if a dropdown is currently visible */
export function isDropdownOpen() {
return activeDropdown !== null;
}
//# sourceMappingURL=dropdown-ui.js.map
File diff suppressed because one or more lines are too long
@@ -0,0 +1,26 @@
/** Shared types for the layer-dropdown module */
export interface LayerInfo {
element: Element;
tagName: string;
selectorId: string | null;
depth?: number;
}
export type OnLayerSelect = (layer: LayerInfo) => void;
export type OnLayerHover = (layer: LayerInfo) => void;
export type OnLayerHoverEnd = () => void;
export interface DropdownCallbacks {
onSelect: OnLayerSelect;
onHover?: OnLayerHover;
onHoverEnd?: OnLayerHoverEnd;
}
export interface LayerControllerConfig {
createPreviewOverlay: (element: Element) => HTMLDivElement;
getSelectedElementId: () => string | null;
selectElement: (element: Element) => HTMLDivElement | undefined;
onDeselect: () => void;
}
export interface LayerController {
attachToOverlay: (overlay: HTMLDivElement | undefined, element: Element) => void;
cleanup: () => void;
}
//# sourceMappingURL=types.d.ts.map
@@ -0,0 +1 @@
{"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../../../src/injections/layer-dropdown/types.ts"],"names":[],"mappings":"AAAA,iDAAiD;AAEjD,MAAM,WAAW,SAAS;IACxB,OAAO,EAAE,OAAO,CAAC;IACjB,OAAO,EAAE,MAAM,CAAC;IAChB,UAAU,EAAE,MAAM,GAAG,IAAI,CAAC;IAC1B,KAAK,CAAC,EAAE,MAAM,CAAC;CAChB;AAED,MAAM,MAAM,aAAa,GAAG,CAAC,KAAK,EAAE,SAAS,KAAK,IAAI,CAAC;AACvD,MAAM,MAAM,YAAY,GAAG,CAAC,KAAK,EAAE,SAAS,KAAK,IAAI,CAAC;AACtD,MAAM,MAAM,eAAe,GAAG,MAAM,IAAI,CAAC;AAEzC,MAAM,WAAW,iBAAiB;IAChC,QAAQ,EAAE,aAAa,CAAC;IACxB,OAAO,CAAC,EAAE,YAAY,CAAC;IACvB,UAAU,CAAC,EAAE,eAAe,CAAC;CAC9B;AAED,MAAM,WAAW,qBAAqB;IACpC,oBAAoB,EAAE,CAAC,OAAO,EAAE,OAAO,KAAK,cAAc,CAAC;IAC3D,oBAAoB,EAAE,MAAM,MAAM,GAAG,IAAI,CAAC;IAC1C,aAAa,EAAE,CAAC,OAAO,EAAE,OAAO,KAAK,cAAc,GAAG,SAAS,CAAC;IAChE,UAAU,EAAE,MAAM,IAAI,CAAC;CACxB;AAED,MAAM,WAAW,eAAe;IAC9B,eAAe,EAAE,CAAC,OAAO,EAAE,cAAc,GAAG,SAAS,EAAE,OAAO,EAAE,OAAO,KAAK,IAAI,CAAC;IACjF,OAAO,EAAE,MAAM,IAAI,CAAC;CACrB"}
@@ -0,0 +1,3 @@
/** Shared types for the layer-dropdown module */
export {};
//# sourceMappingURL=types.js.map
@@ -0,0 +1 @@
{"version":3,"file":"types.js","sourceRoot":"","sources":["../../../src/injections/layer-dropdown/types.ts"],"names":[],"mappings":"AAAA,iDAAiD"}
@@ -0,0 +1,25 @@
/** DOM utilities for the layer-dropdown module */
import type { LayerInfo } from "./types.js";
/** Apply a style map to an element */
export declare function applyStyles(element: HTMLElement, styles: Record<string, string>): void;
/** Display name for a layer — just the real tag name */
export declare function getLayerDisplayName(layer: LayerInfo): string;
/**
* Collect instrumented descendants up to `maxDepth` instrumented nesting levels.
* Non-instrumented wrappers are walked through without counting toward depth.
* Results are in DOM order.
* When `startDepth` is provided, assigns `depth` to each item during collection.
*/
export declare function getInstrumentedDescendants(parent: Element, maxDepth: number, startDepth?: number): LayerInfo[];
/**
* Build the layer chain for the dropdown:
*
* Parents – up to MAX_PARENT_DEPTH instrumented ancestors, outer → inner.
* Siblings – instrumented children of the immediate parent, at the same depth.
* Current – the selected element (highlighted), with children expanded.
* Children – instrumented descendants within MAX_CHILD_DEPTH levels, DOM order.
*
* Each item carries a `depth` for visual indentation.
*/
export declare function buildLayerChain(selectedElement: Element): LayerInfo[];
//# sourceMappingURL=utils.d.ts.map
@@ -0,0 +1 @@
{"version":3,"file":"utils.d.ts","sourceRoot":"","sources":["../../../src/injections/layer-dropdown/utils.ts"],"names":[],"mappings":"AAAA,kDAAkD;AAKlD,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,YAAY,CAAC;AAE5C,sCAAsC;AACtC,wBAAgB,WAAW,CAAC,OAAO,EAAE,WAAW,EAAE,MAAM,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,GAAG,IAAI,CAOtF;AAED,wDAAwD;AACxD,wBAAgB,mBAAmB,CAAC,KAAK,EAAE,SAAS,GAAG,MAAM,CAE5D;AAYD;;;;;GAKG;AACH,wBAAgB,0BAA0B,CACxC,MAAM,EAAE,OAAO,EACf,QAAQ,EAAE,MAAM,EAChB,UAAU,CAAC,EAAE,MAAM,GAClB,SAAS,EAAE,CA0Bb;AAkFD;;;;;;;;;GASG;AACH,wBAAgB,eAAe,CAAC,eAAe,EAAE,OAAO,GAAG,SAAS,EAAE,CAcrE"}
@@ -0,0 +1,143 @@
/** DOM utilities for the layer-dropdown module */
import { isInstrumentedElement, getElementSelectorId } from "../utils.js";
import { MAX_PARENT_DEPTH, MAX_CHILD_DEPTH } from "./consts.js";
/** Apply a style map to an element */
export function applyStyles(element, styles) {
for (const key of Object.keys(styles)) {
element.style.setProperty(key.replace(/[A-Z]/g, (m) => `-${m.toLowerCase()}`), styles[key]);
}
}
/** Display name for a layer — just the real tag name */
export function getLayerDisplayName(layer) {
return layer.tagName;
}
function toLayerInfo(element, depth) {
const info = {
element,
tagName: element.tagName.toLowerCase(),
selectorId: getElementSelectorId(element),
};
if (depth !== undefined)
info.depth = depth;
return info;
}
/**
* Collect instrumented descendants up to `maxDepth` instrumented nesting levels.
* Non-instrumented wrappers are walked through without counting toward depth.
* Results are in DOM order.
* When `startDepth` is provided, assigns `depth` to each item during collection.
*/
export function getInstrumentedDescendants(parent, maxDepth, startDepth) {
const result = [];
function walk(el, instrDepth) {
if (instrDepth > maxDepth)
return;
for (let i = 0; i < el.children.length; i++) {
const child = el.children[i];
if (isInstrumentedElement(child)) {
const info = {
element: child,
tagName: child.tagName.toLowerCase(),
selectorId: getElementSelectorId(child),
};
if (startDepth !== undefined) {
info.depth = startDepth + instrDepth - 1;
}
result.push(info);
walk(child, instrDepth + 1);
}
else {
walk(child, instrDepth);
}
}
}
walk(parent, 1);
return result;
}
/** Collect instrumented ancestors from selected element up to MAX_PARENT_DEPTH (outermost first). */
function collectInstrumentedParents(selectedElement) {
const parents = [];
let current = selectedElement.parentElement;
while (current &&
current !== document.documentElement &&
current !== document.body &&
parents.length < MAX_PARENT_DEPTH) {
if (isInstrumentedElement(current)) {
parents.push(toLayerInfo(current));
}
current = current.parentElement;
}
parents.reverse();
return parents;
}
/** Add parents to chain with depth 0, 1, …; returns depth of selected (parents.length). */
function addParentsToChain(chain, parents) {
parents.forEach((p, i) => {
chain.push({ ...p, depth: i });
});
return parents.length;
}
/** Add selected element and its descendants at the given depth. */
function addSelfAndDescendantsToChain(chain, selectedElement, selfDepth) {
chain.push(toLayerInfo(selectedElement, selfDepth));
const descendants = getInstrumentedDescendants(selectedElement, MAX_CHILD_DEPTH, selfDepth + 1);
chain.push(...descendants);
}
/** Get the innermost instrumented parent's DOM element, or null if none. */
function getImmediateInstrParent(parents) {
return parents.at(-1)?.element ?? null;
}
/** Collect instrumented siblings of the selected element from its parent (DOM order). */
function collectSiblings(parent, selectedElement) {
const siblings = getInstrumentedDescendants(parent, 1);
if (!siblings.some((s) => s.element === selectedElement)) {
siblings.push(toLayerInfo(selectedElement));
}
return siblings;
}
/** Add siblings at selfDepth, expanding children only for the selected element. */
function appendSiblingsWithSelected(chain, siblings, selectedElement, selfDepth) {
const selectedSelectorId = getElementSelectorId(selectedElement);
const seen = new Set();
for (const sibling of siblings) {
if (sibling.element === selectedElement) {
addSelfAndDescendantsToChain(chain, selectedElement, selfDepth);
if (selectedSelectorId)
seen.add(selectedSelectorId);
}
else {
const id = sibling.selectorId;
if (id != null) {
if (id === selectedSelectorId || seen.has(id))
continue;
seen.add(id);
}
chain.push({ ...sibling, depth: selfDepth });
}
}
}
/**
* Build the layer chain for the dropdown:
*
* Parents – up to MAX_PARENT_DEPTH instrumented ancestors, outer → inner.
* Siblings – instrumented children of the immediate parent, at the same depth.
* Current – the selected element (highlighted), with children expanded.
* Children – instrumented descendants within MAX_CHILD_DEPTH levels, DOM order.
*
* Each item carries a `depth` for visual indentation.
*/
export function buildLayerChain(selectedElement) {
const parents = collectInstrumentedParents(selectedElement);
const chain = [];
const selfDepth = addParentsToChain(chain, parents);
const instrParent = getImmediateInstrParent(parents);
if (instrParent) {
const siblings = collectSiblings(instrParent, selectedElement);
appendSiblingsWithSelected(chain, siblings, selectedElement, selfDepth);
}
else {
addSelfAndDescendantsToChain(chain, selectedElement, selfDepth);
}
return chain;
}
//# sourceMappingURL=utils.js.map
@@ -0,0 +1 @@
{"version":3,"file":"utils.js","sourceRoot":"","sources":["../../../src/injections/layer-dropdown/utils.ts"],"names":[],"mappings":"AAAA,kDAAkD;AAElD,OAAO,EAAE,qBAAqB,EAAE,oBAAoB,EAAE,MAAM,aAAa,CAAC;AAC1E,OAAO,EAAE,gBAAgB,EAAE,eAAe,EAAE,MAAM,aAAa,CAAC;AAIhE,sCAAsC;AACtC,MAAM,UAAU,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,4BAA4B,CAAC,KAAK,EAAE,eAAe,EAAE,SAAS,CAAC,CAAC;YAChE,IAAI,kBAAkB;gBAAE,IAAI,CAAC,GAAG,CAAC,kBAAkB,CAAC,CAAC;QACvD,CAAC;aAAM,CAAC;YACN,MAAM,EAAE,GAAG,OAAO,CAAC,UAAU,CAAC;YAC9B,IAAI,EAAE,IAAI,IAAI,EAAE,CAAC;gBACf,IAAI,EAAE,KAAK,kBAAkB,IAAI,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC;oBAAE,SAAS;gBACxD,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,CAAC;YACf,CAAC;YACD,KAAK,CAAC,IAAI,CAAC,EAAE,GAAG,OAAO,EAAE,KAAK,EAAE,SAAS,EAAE,CAAC,CAAC;QAC/C,CAAC;IACH,CAAC;AACH,CAAC;AAED;;;;;;;;;GASG;AACH,MAAM,UAAU,eAAe,CAAC,eAAwB;IACtD,MAAM,OAAO,GAAG,0BAA0B,CAAC,eAAe,CAAC,CAAC;IAC5D,MAAM,KAAK,GAAgB,EAAE,CAAC;IAC9B,MAAM,SAAS,GAAG,iBAAiB,CAAC,KAAK,EAAE,OAAO,CAAC,CAAC;IAEpD,MAAM,WAAW,GAAG,uBAAuB,CAAC,OAAO,CAAC,CAAC;IACrD,IAAI,WAAW,EAAE,CAAC;QAChB,MAAM,QAAQ,GAAG,eAAe,CAAC,WAAW,EAAE,eAAe,CAAC,CAAC;QAC/D,0BAA0B,CAAC,KAAK,EAAE,QAAQ,EAAE,eAAe,EAAE,SAAS,CAAC,CAAC;IAC1E,CAAC;SAAM,CAAC;QACN,4BAA4B,CAAC,KAAK,EAAE,eAAe,EAAE,SAAS,CAAC,CAAC;IAClE,CAAC;IAED,OAAO,KAAK,CAAC;AACf,CAAC"}
@@ -0,0 +1,2 @@
export {};
//# sourceMappingURL=navigation-notifier.d.ts.map
@@ -0,0 +1 @@
{"version":3,"file":"navigation-notifier.d.ts","sourceRoot":"","sources":["../../src/injections/navigation-notifier.ts"],"names":[],"mappings":""}
@@ -0,0 +1,34 @@
if (window.self !== window.top) {
let lastUrl = window.location.href;
function notifyNavigation() {
const currentUrl = window.location.href;
if (currentUrl !== lastUrl) {
lastUrl = currentUrl;
window.parent?.postMessage({
type: "app_changed_url",
url: currentUrl,
}, "*");
}
}
// Intercept history.pushState
const originalPushState = history.pushState.bind(history);
history.pushState = function (...args) {
originalPushState(...args);
notifyNavigation();
};
// Intercept history.replaceState
const originalReplaceState = history.replaceState.bind(history);
history.replaceState = function (...args) {
originalReplaceState(...args);
notifyNavigation();
};
// Handle browser back/forward navigation
window.addEventListener("popstate", notifyNavigation);
// Notify initial URL on load
window.parent?.postMessage({
type: "app_changed_url",
url: window.location.href,
}, "*");
}
export {};
//# sourceMappingURL=navigation-notifier.js.map
@@ -0,0 +1 @@
{"version":3,"file":"navigation-notifier.js","sourceRoot":"","sources":["../../src/injections/navigation-notifier.ts"],"names":[],"mappings":"AAAA,IAAI,MAAM,CAAC,IAAI,KAAK,MAAM,CAAC,GAAG,EAAE,CAAC;IAC/B,IAAI,OAAO,GAAG,MAAM,CAAC,QAAQ,CAAC,IAAI,CAAC;IAEnC,SAAS,gBAAgB;QACvB,MAAM,UAAU,GAAG,MAAM,CAAC,QAAQ,CAAC,IAAI,CAAC;QACxC,IAAI,UAAU,KAAK,OAAO,EAAE,CAAC;YAC3B,OAAO,GAAG,UAAU,CAAC;YACrB,MAAM,CAAC,MAAM,EAAE,WAAW,CACxB;gBACE,IAAI,EAAE,iBAAiB;gBACvB,GAAG,EAAE,UAAU;aAChB,EACD,GAAG,CACJ,CAAC;QACJ,CAAC;IACH,CAAC;IAED,8BAA8B;IAC9B,MAAM,iBAAiB,GAAG,OAAO,CAAC,SAAS,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC;IAC1D,OAAO,CAAC,SAAS,GAAG,UAAU,GAAG,IAAI;QACnC,iBAAiB,CAAC,GAAG,IAAI,CAAC,CAAC;QAC3B,gBAAgB,EAAE,CAAC;IACrB,CAAC,CAAC;IAEF,iCAAiC;IACjC,MAAM,oBAAoB,GAAG,OAAO,CAAC,YAAY,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC;IAChE,OAAO,CAAC,YAAY,GAAG,UAAU,GAAG,IAAI;QACtC,oBAAoB,CAAC,GAAG,IAAI,CAAC,CAAC;QAC9B,gBAAgB,EAAE,CAAC;IACrB,CAAC,CAAC;IAEF,yCAAyC;IACzC,MAAM,CAAC,gBAAgB,CAAC,UAAU,EAAE,gBAAgB,CAAC,CAAC;IAEtD,6BAA6B;IAC7B,MAAM,CAAC,MAAM,EAAE,WAAW,CACxB;QACE,IAAI,EAAE,iBAAiB;QACvB,GAAG,EAAE,MAAM,CAAC,QAAQ,CAAC,IAAI;KAC1B,EACD,GAAG,CACJ,CAAC;AACJ,CAAC"}
@@ -0,0 +1,14 @@
export type PageHeightBridgeController = {
freezeVhUnits: (override?: number) => void;
measurePageHeight: (origin: string, settleMs?: number) => void;
teardown: () => void;
};
/**
* Installs the parent-driven message listener. Returns a teardown that
* removes the listener, disconnects any observers attached as a result of
* `freeze-vh-units`, and clears any pending response timer. Returns a
* no-op when bailed (already started, SSR, top window).
*/
export declare function setupPageHeightBridge(): () => void;
export declare function createPageHeightBridgeController(): PageHeightBridgeController;
//# sourceMappingURL=page-height-bridge.d.ts.map
@@ -0,0 +1 @@
{"version":3,"file":"page-height-bridge.d.ts","sourceRoot":"","sources":["../../src/injections/page-height-bridge.ts"],"names":[],"mappings":"AA4BA,MAAM,MAAM,0BAA0B,GAAG;IACvC,aAAa,EAAE,CAAC,QAAQ,CAAC,EAAE,MAAM,KAAK,IAAI,CAAC;IAC3C,iBAAiB,EAAE,CAAC,MAAM,EAAE,MAAM,EAAE,QAAQ,CAAC,EAAE,MAAM,KAAK,IAAI,CAAC;IAC/D,QAAQ,EAAE,MAAM,IAAI,CAAC;CACtB,CAAC;AAyBF;;;;;GAKG;AACH,wBAAgB,qBAAqB,IAAI,MAAM,IAAI,CAuClD;AAED,wBAAgB,gCAAgC,IAAI,0BAA0B,CA2F7E"}
+510
View File
@@ -0,0 +1,510 @@
// page-height-bridge — postMessage protocol the iframe exposes to its parent.
// Inert until the parent posts a message; no observers, rewrites, or timers
// fire on their own.
//
// parent → child { type: "freeze-vh-units", referenceVhBase?: number }
// Rewrites every viewport-height unit (`vh`/`dvh`/`svh`/`lvh`) in
// <style> + CSSOM to a CSS variable-backed expression (kills the
// vh ↔ auto-resize feedback loop). Repeated calls update the variable,
// so callers can rebase without recovering raw CSS. Idempotent; covers
// HMR-added styles too. Fire-and-forget.
//
// parent → child { type: "measure-page-height", settleMs?: number }
// After `settleMs` (default 2000) posts the page's measured content height
// as `{ type: "page-height-measured", height }` to the requester.
const FALLBACK_VHBASE = 900;
const MIN_VHBASE = 400;
const DEFAULT_SETTLE_MS = 2000;
const NEUTRALIZE_DEBOUNCE_MS = 16;
// Three consecutive same-height samples ≈ ~50ms of "no change". Three is
// enough to filter single-frame jitter from layout passes but short enough
// that responses arrive promptly when the DOM is already settled.
const STABILITY_SAMPLES = 3;
// Interval between stability samples. ~1 frame at 60Hz; chosen as a plain
// setTimeout (not rAF) because jsdom rAFs are unreliably timed for tests and
// in real browsers a 16ms tick is post-layout for any layout work that fits
// inside one frame.
const STABILITY_TICK_MS = 16;
// Hard cap on the stability poll past settleMs. Pages that genuinely never
// stabilize (looping height-animating content) reply with their last sample
// rather than hanging the parent's resize logic.
const STABILITY_MAX_WAIT_MS = 1500;
const REFERENCE_VH_BASE_VAR = "--base44-reference-vh-base";
const noop = () => { };
let started = false;
/**
* Installs the parent-driven message listener. Returns a teardown that
* removes the listener, disconnects any observers attached as a result of
* `freeze-vh-units`, and clears any pending response timer. Returns a
* no-op when bailed (already started, SSR, top window).
*/
export function setupPageHeightBridge() {
if (started)
return noop;
if (typeof window === "undefined")
return noop;
if (window.self === window.top)
return noop;
started = true;
const controller = createPageHeightBridgeController();
const onMessage = (event) => {
const data = (event.data ?? null);
if (!data || typeof data !== "object")
return;
switch (data.type) {
case "freeze-vh-units": {
const override = typeof data.referenceVhBase === "number" ? data.referenceVhBase : undefined;
controller.freezeVhUnits(override);
return;
}
case "measure-page-height": {
const settleMs = typeof data.settleMs === "number" ? data.settleMs : DEFAULT_SETTLE_MS;
const origin = event.origin && event.origin !== "null" ? event.origin : "*";
controller.measurePageHeight(origin, settleMs);
return;
}
}
};
window.addEventListener("message", onMessage);
let torn = false;
return () => {
if (torn)
return;
torn = true;
started = false;
window.removeEventListener("message", onMessage);
controller.teardown();
};
}
export function createPageHeightBridgeController() {
let vhCleanups = null;
let vhForceRun = null;
let pendingSettle;
let pendingTick;
let pendingOrigin = "*";
const cancelPending = () => {
if (pendingSettle !== undefined) {
window.clearTimeout(pendingSettle);
pendingSettle = undefined;
}
if (pendingTick !== undefined) {
window.clearTimeout(pendingTick);
pendingTick = undefined;
}
};
return {
freezeVhUnits: (override) => {
const referenceVhBase = resolveReferenceVhBase(override);
setReferenceVhBase(referenceVhBase);
if (vhCleanups) {
vhForceRun?.();
return;
}
vhCleanups = [];
vhForceRun = startVhNeutralizer(vhCleanups);
},
// Target the requester's origin so the height isn't broadcast to anyone
// who happens to embed us. Falls back to "*" when origin is unavailable
// (jsdom default, sandboxed iframes with `null` origin).
//
// Stability-wait response: after `settleMs`, poll measureContentHeight at
// STABILITY_TICK_MS intervals until it's unchanged for STABILITY_SAMPLES
// consecutive ticks, then send exactly one reply. Catches late React
// mounts (sticky-positioned sections committing after settleMs), debounced
// neutralizer mutations not yet flushed, image/font-driven layout shifts.
// STABILITY_MAX_WAIT_MS caps the poll so a page that genuinely never
// settles still replies eventually.
measurePageHeight: (origin, settleMs = DEFAULT_SETTLE_MS) => {
pendingOrigin = origin;
cancelPending();
pendingSettle = window.setTimeout(() => {
pendingSettle = undefined;
// Flush any debounced unscroll / inline-vh rewrites NOW so the first
// sample sees a DOM that reflects every mutation triggered during the
// settle window. Without this, an `overflow-y: scroll` container that
// mounted mid-settle can still be hiding its children at sample time.
vhForceRun?.();
const deadline = nowMs() + STABILITY_MAX_WAIT_MS;
let lastHeight = -1;
let stableSamples = 0;
const respond = (height) => {
pendingTick = undefined;
window.parent.postMessage({ type: "page-height-measured", height }, pendingOrigin);
};
const tick = () => {
pendingTick = undefined;
const height = measureContentHeight();
if (height === lastHeight) {
stableSamples++;
}
else {
stableSamples = 1;
lastHeight = height;
}
if (stableSamples >= STABILITY_SAMPLES || nowMs() >= deadline) {
respond(height);
return;
}
pendingTick = window.setTimeout(tick, STABILITY_TICK_MS);
};
tick();
}, settleMs);
},
teardown: () => {
if (vhCleanups) {
for (const c of vhCleanups)
c();
vhCleanups = null;
vhForceRun = null;
}
cancelPending();
},
};
}
function nowMs() {
if (typeof performance !== "undefined" && typeof performance.now === "function") {
return performance.now();
}
return Date.now();
}
function resolveReferenceVhBase(override) {
if (override !== undefined)
return override;
const detected = window.innerHeight || 0;
return detected >= MIN_VHBASE ? detected : FALLBACK_VHBASE;
}
function setReferenceVhBase(referenceVhBase) {
document.documentElement.style.setProperty(REFERENCE_VH_BASE_VAR, `${referenceVhBase}px`);
}
// Caches keep work proportional to *new* CSS, not total CSS. <head> observer
// catches `<style>`/`<link>` adds; per-element observers catch HMR text edits.
// Returns a `forceRun` so the caller can re-trigger neutralization on later
// parent requests (idempotent — already-rewritten text is skipped via the
// processed sets).
function startVhNeutralizer(cleanups) {
// Match vh + the dynamic/small/large variants. Tailwind v4 emits `h-screen`
// as `100dvh`; all four collapse to the same frozen `referenceVhBase`.
const VH_RE = /(\d+(?:\.\d+)?)(?:d|s|l)?vh\b/g;
const processedStyles = new WeakSet();
const processedSheets = new WeakMap();
const watchedStyles = new WeakSet();
const styleObservers = new Set();
const unscrolled = new WeakSet();
const rewrite = (input) => input.replace(VH_RE, (_match, n) => `calc(var(${REFERENCE_VH_BASE_VAR}) * ${formatVhFactor(n)})`);
// Defeats internal vertical scrollers. The canvas wants the whole page laid
// out top-to-bottom, but `<div class="overflow-y-auto" style={{height:
// "100vh"}}>` hides its children behind an internal scrollbar — only the
// first child appears in the preview. Forcing `overflow-y: visible` lets
// children paint outside the parent's box; block flow positions them at
// their natural offsets so document.body extends to include them. `auto`
// and `scroll` only — `hidden` and `clip` express intentional clipping (UI
// chrome, rounded-corner masks) we shouldn't undo.
const unscrollY = (el) => {
if (unscrolled.has(el))
return;
const computedStyle = window.getComputedStyle(el);
const ovY = computedStyle.overflowY;
if (ovY !== "auto" && ovY !== "scroll")
return;
unscrolled.add(el);
el.style.setProperty("overflow-y", "visible", "important");
};
const unscrollSubtree = (root) => {
unscrollY(root);
root.querySelectorAll("*").forEach(unscrollY);
};
// Rewrites vh-bearing properties on a single element's inline style. Covers
// React's `style={{ height: "100vh" }}` and imperative `el.style.h = ".vh"`
// — both bypass <style> tags and CSSOM. Per-property setProperty preserves
// `!important`. Snapshotting prop names first guards against iteration-time
// mutation of `style.length`.
const rewriteInlineStyle = (el) => {
const style = el.style;
if (!style || style.length === 0)
return;
const props = [];
for (let i = 0; i < style.length; i++) {
const prop = style[i];
if (prop)
props.push(prop);
}
for (const prop of props) {
const value = style.getPropertyValue(prop);
if (!value || value.indexOf("vh") === -1)
continue;
const next = rewrite(value);
if (next !== value)
style.setProperty(prop, next, style.getPropertyPriority(prop));
}
};
const neutralize = () => {
document.querySelectorAll("style").forEach((el) => {
watchStyleEl(el);
if (processedStyles.has(el))
return;
processedStyles.add(el);
const text = el.textContent;
if (!text || text.indexOf("vh") === -1)
return;
const next = rewrite(text);
if (next !== text)
el.textContent = next;
});
for (let i = 0; i < document.styleSheets.length; i++) {
const sheet = document.styleSheets[i];
if (!sheet)
continue;
let rules;
try {
rules = sheet.cssRules;
}
catch {
continue; // CORS-protected
}
if (processedSheets.get(sheet) === rules.length)
continue;
rewriteVhInRules(rules, rewrite);
processedSheets.set(sheet, rules.length);
}
// Initial sweep of inline `style="...vh..."` attributes already in the DOM
// at freeze time. Future inline-style mutations (React commits, motion
// libraries, imperative assignments) are picked up by inlineStyleObserver.
document.querySelectorAll('[style*="vh"]').forEach(rewriteInlineStyle);
// Defeat internal scrollers — same dual coverage (initial sweep here,
// subtree additions in inlineStyleObserver).
if (document.body)
unscrollSubtree(document.body);
};
const debouncer = createDebouncer(neutralize, NEUTRALIZE_DEBOUNCE_MS);
const debouncedNeutralize = debouncer.trigger;
cleanups.push(debouncer.cancel);
const watchStyleEl = (el) => {
if (watchedStyles.has(el))
return;
watchedStyles.add(el);
const obs = new MutationObserver(() => {
processedStyles.delete(el);
debouncedNeutralize();
});
obs.observe(el, { characterData: true, childList: true, subtree: true });
styleObservers.add(obs);
};
cleanups.push(() => {
for (const obs of styleObservers)
obs.disconnect();
styleObservers.clear();
});
debouncedNeutralize();
if (document.readyState === "loading") {
document.addEventListener("DOMContentLoaded", debouncedNeutralize);
cleanups.push(() => document.removeEventListener("DOMContentLoaded", debouncedNeutralize));
}
window.addEventListener("load", debouncedNeutralize);
cleanups.push(() => window.removeEventListener("load", debouncedNeutralize));
const headObserver = new MutationObserver((mutations) => {
for (const m of mutations) {
if (containsStylesheetNode(m.addedNodes) || containsStylesheetNode(m.removedNodes)) {
debouncedNeutralize();
return;
}
}
});
cleanups.push(() => headObserver.disconnect());
const attachHeadObserver = () => {
if (document.head)
headObserver.observe(document.head, { childList: true, subtree: false });
};
if (document.head) {
attachHeadObserver();
}
else {
document.addEventListener("DOMContentLoaded", attachHeadObserver);
cleanups.push(() => document.removeEventListener("DOMContentLoaded", attachHeadObserver));
}
// Pass 3: inline `style` attributes. One global observer covers every
// element — past, present, and future — without per-node tracking. Two
// mutation kinds matter:
// • attributes: React/JS sets `style` on an element already in the tree
// (`el.style.h = "..vh"`, re-render diff). After rewrite the value has
// no "vh", so the next mutation gates out — single-tick convergence.
// • childList: a node is mounted with its `style` attribute already set
// off-tree (React's initial mount path uses createElement+setAttribute
// BEFORE appendChild, so attribute mutations never fire for them). Scan
// the added subtree for `[style*="vh"]` and rewrite.
// Microtask delivery means rewrites land before layout, so no flash.
const scanSubtreeForInlineVh = (node) => {
if (!(node instanceof Element))
return;
const attr = node.getAttribute("style");
if (attr && attr.indexOf("vh") !== -1)
rewriteInlineStyle(node);
node.querySelectorAll('[style*="vh"]').forEach(rewriteInlineStyle);
// New subtrees may introduce overflow-y: auto|scroll containers (route
// changes, conditional UI). Catch them here too.
unscrollSubtree(node);
};
const inlineStyleObserver = new MutationObserver((mutations) => {
for (const m of mutations) {
if (m.type === "attributes") {
const target = m.target;
if (!(target instanceof Element))
continue;
const attr = target.getAttribute("style");
if (!attr || attr.indexOf("vh") === -1)
continue;
rewriteInlineStyle(target);
}
else if (m.type === "childList") {
for (let i = 0; i < m.addedNodes.length; i++) {
const node = m.addedNodes[i];
if (node)
scanSubtreeForInlineVh(node);
}
}
}
});
cleanups.push(() => inlineStyleObserver.disconnect());
const attachInlineStyleObserver = () => {
const root = document.documentElement;
if (!root)
return;
inlineStyleObserver.observe(root, {
attributes: true,
attributeFilter: ["style"],
childList: true,
subtree: true,
});
};
attachInlineStyleObserver();
return debouncedNeutralize;
}
function formatVhFactor(value) {
return String(Number((parseFloat(value) / 100).toFixed(6)));
}
function rewriteVhInRules(rules, rewrite) {
for (let i = 0; i < rules.length; i++) {
const rule = rules[i];
if (!rule)
continue;
if (rule.cssRules)
rewriteVhInRules(rule.cssRules, rewrite);
const style = rule.style;
if (!style)
continue;
for (let j = 0; j < style.length; j++) {
const prop = style[j];
if (!prop)
continue;
const value = style.getPropertyValue(prop);
if (!value || value.indexOf("vh") === -1)
continue;
const next = rewrite(value);
if (next !== value)
style.setProperty(prop, next, style.getPropertyPriority(prop));
}
}
}
function containsStylesheetNode(nodes) {
for (let i = 0; i < nodes.length; i++) {
const node = nodes[i];
if (node instanceof HTMLStyleElement || node instanceof HTMLLinkElement)
return true;
}
return false;
}
function measureContentHeight() {
const scrollHeight = Math.max(document.documentElement.scrollHeight, document.body?.scrollHeight ?? 0);
const referenceVhBase = readReferenceVhBase();
// Excludes `body.clientHeight`: it grows with content, which makes
// viewportBottom land at the document bottom and trips the stretched-
// container heuristic on the last section. `referenceVhBase` keeps the
// h-screen-wrapper case covered when the iframe is shorter than 100vh.
const viewportHeight = Math.max(window.innerHeight || 0, document.documentElement.clientHeight, referenceVhBase);
const contentBottom = measureElementContentBottom(viewportHeight);
if (contentBottom > 0)
return Math.ceil(Math.max(contentBottom, referenceVhBase));
return Math.ceil(Math.max(scrollHeight, referenceVhBase));
}
function readReferenceVhBase() {
const value = document.documentElement.style.getPropertyValue(REFERENCE_VH_BASE_VAR);
const parsed = parseFloat(value);
return Number.isFinite(parsed) ? parsed : 0;
}
function measureElementContentBottom(viewportHeight) {
if (!document.body)
return 0;
const elements = [document.body, ...Array.from(document.body.querySelectorAll("*"))];
const contentBottoms = new WeakMap();
const viewportBottom = window.scrollY + viewportHeight;
for (let i = elements.length - 1; i >= 0; i--) {
const el = elements[i];
if (!el)
continue;
const childContentBottom = readChildrenContentBottom(el, contentBottoms);
const metrics = readElementMetrics(el);
const selfBottom = isViewportStretchedContainer(metrics, childContentBottom, viewportHeight, viewportBottom)
? 0
: metrics.bottom;
contentBottoms.set(el, Math.max(childContentBottom, selfBottom));
}
return contentBottoms.get(document.body) ?? 0;
}
function readChildrenContentBottom(el, contentBottoms) {
let childContentBottom = 0;
for (let i = 0; i < el.children.length; i++) {
const child = el.children[i];
if (!child)
continue;
childContentBottom = Math.max(childContentBottom, contentBottoms.get(child) ?? 0);
}
return childContentBottom;
}
function readElementMetrics(el) {
const computedStyle = window.getComputedStyle(el);
if (isOutOfFlowDecoration(computedStyle))
return { bottom: 0, height: 0 };
const rect = el.getBoundingClientRect();
if (rect.width === 0 && rect.height === 0)
return { bottom: 0, height: 0 };
return {
bottom: rect.bottom + window.scrollY + readMarginBottom(computedStyle),
height: rect.height,
};
}
function readMarginBottom(computedStyle) {
const marginBottom = parseFloat(computedStyle.marginBottom);
return Number.isFinite(marginBottom) ? marginBottom : 0;
}
function isOutOfFlowDecoration(computedStyle) {
if (computedStyle.position === "fixed")
return true;
return computedStyle.position === "absolute" && computedStyle.pointerEvents === "none";
}
// A "stretched container" spans the full viewport top-to-bottom. Requires
// BOTH `bottom ≈ viewportBottom` AND `height ≈ viewportHeight` — otherwise an
// in-flow section that just happens to end at viewportBottom (e.g. when the
// iframe has been content-sized to the previous measurement) gets falsely
// filtered, undermeasuring the page.
function isViewportStretchedContainer(metrics, childBottom, viewportHeight, viewportBottom) {
return (childBottom > 0 &&
Math.abs(metrics.bottom - viewportBottom) <= 1 &&
Math.abs(metrics.height - viewportHeight) <= 1 &&
metrics.bottom - childBottom > 8);
}
function createDebouncer(fn, delayMs) {
let timer;
return {
trigger: () => {
if (timer !== undefined)
window.clearTimeout(timer);
timer = window.setTimeout(fn, delayMs);
},
cancel: () => {
if (timer !== undefined) {
window.clearTimeout(timer);
timer = undefined;
}
},
};
}
//# sourceMappingURL=page-height-bridge.js.map
File diff suppressed because one or more lines are too long
@@ -0,0 +1,2 @@
export {};
//# sourceMappingURL=sandbox-hmr-notifier.d.ts.map
@@ -0,0 +1 @@
{"version":3,"file":"sandbox-hmr-notifier.d.ts","sourceRoot":"","sources":["../../src/injections/sandbox-hmr-notifier.ts"],"names":[],"mappings":""}
@@ -0,0 +1,10 @@
if (import.meta.hot) {
import.meta.hot.on("vite:beforeUpdate", () => {
window.parent?.postMessage({ type: "sandbox:beforeUpdate" }, "*");
});
import.meta.hot.on("vite:afterUpdate", () => {
window.parent?.postMessage({ type: "sandbox:afterUpdate" }, "*");
});
}
export {};
//# sourceMappingURL=sandbox-hmr-notifier.js.map
@@ -0,0 +1 @@
{"version":3,"file":"sandbox-hmr-notifier.js","sourceRoot":"","sources":["../../src/injections/sandbox-hmr-notifier.ts"],"names":[],"mappings":"AAAA,IAAI,MAAM,CAAC,IAAI,CAAC,GAAG,EAAE,CAAC;IACpB,MAAM,CAAC,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,mBAAmB,EAAE,GAAG,EAAE;QAC3C,MAAM,CAAC,MAAM,EAAE,WAAW,CAAC,EAAE,IAAI,EAAE,sBAAsB,EAAE,EAAE,GAAG,CAAC,CAAC;IACpE,CAAC,CAAC,CAAC;IACH,MAAM,CAAC,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,kBAAkB,EAAE,GAAG,EAAE;QAC1C,MAAM,CAAC,MAAM,EAAE,WAAW,CAAC,EAAE,IAAI,EAAE,qBAAqB,EAAE,EAAE,GAAG,CAAC,CAAC;IACnE,CAAC,CAAC,CAAC;AACL,CAAC"}
@@ -0,0 +1,2 @@
export {};
//# sourceMappingURL=sandbox-mount-observer.d.ts.map
@@ -0,0 +1 @@
{"version":3,"file":"sandbox-mount-observer.d.ts","sourceRoot":"","sources":["../../src/injections/sandbox-mount-observer.ts"],"names":[],"mappings":""}
@@ -0,0 +1,18 @@
if (window.self !== window.top) {
const observer = new MutationObserver((mutations) => {
const nodesAdded = mutations.some((mutation) => mutation.addedNodes.length > 0);
const nodesRemoved = mutations.some((mutation) => mutation.removedNodes.length > 0);
if (nodesAdded || nodesRemoved) {
const foundElmWithDataAttribute = document.body.querySelectorAll("[data-source-location], [data-dynamic-content]").length > 0;
if (foundElmWithDataAttribute) {
window.parent?.postMessage({ type: "sandbox:onMounted" }, "*");
}
else {
window.parent?.postMessage({ type: "sandbox:onUnmounted" }, "*");
}
}
});
observer.observe(document.body, { childList: true, subtree: true });
}
export {};
//# sourceMappingURL=sandbox-mount-observer.js.map
@@ -0,0 +1 @@
{"version":3,"file":"sandbox-mount-observer.js","sourceRoot":"","sources":["../../src/injections/sandbox-mount-observer.ts"],"names":[],"mappings":"AACA,IAAI,MAAM,CAAC,IAAI,KAAK,MAAM,CAAC,GAAG,EAAE,CAAC;IAC/B,MAAM,QAAQ,GAAG,IAAI,gBAAgB,CAAC,CAAC,SAAS,EAAE,EAAE;QAClD,MAAM,UAAU,GAAG,SAAS,CAAC,IAAI,CAC/B,CAAC,QAAQ,EAAE,EAAE,CAAC,QAAQ,CAAC,UAAU,CAAC,MAAM,GAAG,CAAC,CAC7C,CAAC;QACF,MAAM,YAAY,GAAG,SAAS,CAAC,IAAI,CACjC,CAAC,QAAQ,EAAE,EAAE,CAAC,QAAQ,CAAC,YAAY,CAAC,MAAM,GAAG,CAAC,CAC/C,CAAC;QACF,IAAI,UAAU,IAAI,YAAY,EAAE,CAAC;YAC/B,MAAM,yBAAyB,GAC7B,QAAQ,CAAC,IAAI,CAAC,gBAAgB,CAC5B,gDAAgD,CACjD,CAAC,MAAM,GAAG,CAAC,CAAC;YAEf,IAAI,yBAAyB,EAAE,CAAC;gBAC9B,MAAM,CAAC,MAAM,EAAE,WAAW,CAAC,EAAE,IAAI,EAAE,mBAAmB,EAAE,EAAE,GAAG,CAAC,CAAC;YACjE,CAAC;iBAAM,CAAC;gBACN,MAAM,CAAC,MAAM,EAAE,WAAW,CAAC,EAAE,IAAI,EAAE,qBAAqB,EAAE,EAAE,GAAG,CAAC,CAAC;YACnE,CAAC;QACH,CAAC;IACH,CAAC,CAAC,CAAC;IAEH,QAAQ,CAAC,OAAO,CAAC,QAAQ,CAAC,IAAI,EAAE,EAAE,SAAS,EAAE,IAAI,EAAE,OAAO,EAAE,IAAI,EAAE,CAAC,CAAC;AACtE,CAAC"}
@@ -0,0 +1,2 @@
export {};
//# sourceMappingURL=unhandled-errors-handlers.d.ts.map
@@ -0,0 +1 @@
{"version":3,"file":"unhandled-errors-handlers.d.ts","sourceRoot":"","sources":["../../src/injections/unhandled-errors-handlers.ts"],"names":[],"mappings":""}
@@ -0,0 +1,93 @@
/// <reference types="vite/client" />
window.removeEventListener("unhandledrejection", handleUnhandledRejection);
window.removeEventListener("error", handleWindowError);
window.addEventListener("unhandledrejection", handleUnhandledRejection);
window.addEventListener("error", handleWindowError);
let shouldPropagateErrors = true;
let suppressionTimer = null;
let hadSuppressedErrors = false;
if (import.meta.hot) {
import.meta.hot.on("vite:beforeUpdate", () => {
shouldPropagateErrors = false;
hadSuppressedErrors = false;
if (suppressionTimer) {
clearTimeout(suppressionTimer);
}
suppressionTimer = setTimeout(() => {
shouldPropagateErrors = true;
suppressionTimer = null;
hadSuppressedErrors = false;
// No vite:afterUpdate after timeout — treat the stuck update as an error
window.parent?.postMessage({ type: "sandbox:hmrErrorsSuppressed" }, "*");
}, import.meta.env.VITE_HMR_ERROR_SUPPRESSION_DELAY ?? 10000);
});
import.meta.hot.on("vite:afterUpdate", () => {
shouldPropagateErrors = true;
if (suppressionTimer) {
clearTimeout(suppressionTimer);
suppressionTimer = null;
}
if (hadSuppressedErrors) {
window.parent?.postMessage({ type: "sandbox:hmrErrorsSuppressed" }, "*");
hadSuppressedErrors = false;
}
});
import.meta.hot.on("vite:beforeFullReload", () => {
shouldPropagateErrors = false;
hadSuppressedErrors = false;
if (suppressionTimer) {
clearTimeout(suppressionTimer);
suppressionTimer = null;
}
});
}
function onAppError({ title, details, componentName, originalError, }) {
if (originalError?.response?.status === 402) {
return;
}
if (!shouldPropagateErrors) {
hadSuppressedErrors = true;
return;
}
window.parent?.postMessage({
type: "app_error",
error: {
title: title.toString(),
details: details?.toString(),
componentName: componentName?.toString(),
stack: originalError?.stack?.toString(),
},
}, "*");
}
function handleUnhandledRejection(event) {
const stack = event.reason.stack;
// extract function name from "at X (eval" where x is the function name
const functionName = stack.match(/at\s+(\w+)\s+\(eval/)?.[1];
const msg = functionName
? `Error in ${functionName}: ${event.reason.toString()}`
: event.reason.toString();
onAppError({
title: msg,
details: event.reason.toString(),
componentName: functionName,
originalError: event.reason,
});
}
function handleWindowError(event) {
const stack = event.error?.stack;
let functionName = stack.match(/at\s+(\w+)\s+\(eval/)?.[1];
if (functionName === "eval") {
functionName = null;
}
const msg = functionName
? `in ${functionName}: ${event.error.toString()}`
: event.error.toString();
onAppError({
title: msg,
details: event.error.toString(),
componentName: functionName,
originalError: event.error,
});
}
export {};
//# sourceMappingURL=unhandled-errors-handlers.js.map
@@ -0,0 +1 @@
{"version":3,"file":"unhandled-errors-handlers.js","sourceRoot":"","sources":["../../src/injections/unhandled-errors-handlers.ts"],"names":[],"mappings":"AAAA,qCAAqC;AAErC,MAAM,CAAC,mBAA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AAK,CAAC,qBAAqB,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC;IAC7D,MAAM,GAAG,GAAG,YAAY;QACtB,CAAC,CAAC,YAAY,YAAY,KAAK,KAAK,CAAC,MAAM,CAAC,QAAQ,EAAE,EAAE;QACxD,CAAC,CAAC,KAAK,CAAC,MAAM,CAAC,QAAQ,EAAE,CAAC;IAC5B,UAAU,CAAC;QACT,KAAK,EAAE,GAAG;QACV,OAAO,EAAE,KAAK,CAAC,MAAM,CAAC,QAAQ,EAAE;QAChC,aAAa,EAAE,YAAY;QAC3B,aAAa,EAAE,KAAK,CAAC,MAAM;KAC5B,CAAC,CAAC;AACL,CAAC;AAED,SAAS,iBAAiB,CAAC,KAAU;IACnC,MAAM,KAAK,GAAG,KAAK,CAAC,KAAK,EAAE,KAAK,CAAC;IACjC,IAAI,YAAY,GAAG,KAAK,CAAC,KAAK,CAAC,qBAAqB,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC;IAC3D,IAAI,YAAY,KAAK,MAAM,EAAE,CAAC;QAC5B,YAAY,GAAG,IAAI,CAAC;IACtB,CAAC;IAED,MAAM,GAAG,GAAG,YAAY;QACtB,CAAC,CAAC,MAAM,YAAY,KAAK,KAAK,CAAC,KAAK,CAAC,QAAQ,EAAE,EAAE;QACjD,CAAC,CAAC,KAAK,CAAC,KAAK,CAAC,QAAQ,EAAE,CAAC;IAC3B,UAAU,CAAC;QACT,KAAK,EAAE,GAAG;QACV,OAAO,EAAE,KAAK,CAAC,KAAK,CAAC,QAAQ,EAAE;QAC/B,aAAa,EAAE,YAAY;QAC3B,aAAa,EAAE,KAAK,CAAC,KAAK;KAC3B,CAAC,CAAC;AACL,CAAC"}
+66
View File
@@ -0,0 +1,66 @@
/**
* Positions an element-tag label relative to its highlighted overlay.
*
* Strategy (in priority order):
* 1. If the element is near the viewport top AND tall enough (>= 2x label height),
* place the label **inside** the element at the top-left.
* 2. If the element is near the viewport top but too short, place the label
* **below** the element.
* 3. Otherwise, place the label **above** the element (default).
*
* For full-width elements (spanning nearly the entire viewport), the left offset
* is nudged inward (6px) to prevent clipping against the viewport edge.
*
* @param label - The label div to position (style.top and style.left are set).
* @param rect - The bounding client rect of the highlighted element.
*/
export declare function positionLabel(label: HTMLDivElement, rect: DOMRect): void;
/** Check if an element has instrumentation attributes */
export declare function isInstrumentedElement(element: Element): boolean;
/** Get the selector ID from an element's data attributes (prefers source-location) */
export declare function getElementSelectorId(element: Element): string | null;
export declare const ALLOWED_ATTRIBUTES: string[];
export declare const PLUGIN_ELEMENT_ATTR = "data-vite-plugin-element";
/** Find elements by ID - first try data-source-location, fallback to data-visual-selector-id */
export declare function findElementsById(id: string | null): Element[];
/**
* Update element classes by visual selector ID.
* Uses setAttribute instead of className to support both HTML and SVG elements.
*/
export declare function updateElementClasses(elements: Element[], classes: string): void;
/** Set a single attribute on all provided elements. */
export declare function updateElementAttribute(elements: Element[], attribute: string, value: string, arrIndex?: number | string): void;
/** Collect attribute values from an element for a given allowlist. */
export declare function collectAllowedAttributes(element: Element, allowedAttributes: string[]): Record<string, string>;
/**
* Freeze all CSS animations and transitions on the page by injecting
* scoped styles under `[data-visual-edit-active]` and programmatically
* finishing (or pausing) every running animation.
*
* Plugin-owned elements (`[data-vite-plugin-element]`) are excluded so
* the plugin UI stays animated.
*/
export declare function stopAnimations(): void;
/**
* Resume all previously frozen animations and remove the injected
* freeze styles. Cleans up the `data-visual-edit-active` attribute
* from `<html>` so scoped selectors no longer match.
*/
export declare function resumeAnimations(): void;
/**
* Hit-test the page at (`x`, `y`) and walk up the DOM to find the
* nearest ancestor that carries instrumentation attributes
* (`data-source-location` or `data-visual-selector-id`).
*
* Temporarily disables the pointer-events freeze sheet so the
* browser's native `elementFromPoint` can reach the real target.
*/
export declare function findInstrumentedElement(x: number, y: number): Element | null;
/**
* Resolve which element should be hovered at (`x`, `y`), skipping the
* currently selected element. Returns the selector ID of the hovered
* element, or `null` if the point is empty or hits the selected element.
*/
export declare function resolveHoverTarget(x: number, y: number, selectedElementId: string | null): string | null;
export declare function injectFontFaceCss(id: string, css: string): void;
//# sourceMappingURL=utils.d.ts.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"utils.d.ts","sourceRoot":"","sources":["../../src/injections/utils.ts"],"names":[],"mappings":"AAEA;;;;;;;;;;;;;;;GAeG;AACH,wBAAgB,aAAa,CAAC,KAAK,EAAE,cAAc,EAAE,IAAI,EAAE,OAAO,GAAG,IAAI,CAiBxE;AAED,yDAAyD;AACzD,wBAAgB,qBAAqB,CAAC,OAAO,EAAE,OAAO,GAAG,OAAO,CAK/D;AAED,sFAAsF;AACtF,wBAAgB,oBAAoB,CAAC,OAAO,EAAE,OAAO,GAAG,MAAM,GAAG,IAAI,CAOpE;AAED,eAAO,MAAM,kBAAkB,EAAE,MAAM,EAAY,CAAC;AAEpD,eAAO,MAAM,mBAAmB,6BAA6B,CAAC;AAE9D,gGAAgG;AAChG,wBAAgB,gBAAgB,CAAC,EAAE,EAAE,MAAM,GAAG,IAAI,GAAG,OAAO,EAAE,CAW7D;AAED;;;GAGG;AACH,wBAAgB,oBAAoB,CAAC,QAAQ,EAAE,OAAO,EAAE,EAAE,OAAO,EAAE,MAAM,GAAG,IAAI,CAI/E;AAED,uDAAuD;AACvD,wBAAgB,sBAAsB,CAAC,QAAQ,EAAE,OAAO,EAAE,EAAE,SAAS,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,EAAE,QAAQ,CAAC,EAAE,MAAM,GAAG,MAAM,GAAG,IAAI,CAc9H;AAED,sEAAsE;AACtE,wBAAgB,wBAAwB,CAAC,OAAO,EAAE,OAAO,EAAE,iBAAiB,EAAE,MAAM,EAAE,GAAG,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAS9G;AAED;;;;;;;GAOG;AACH,wBAAgB,cAAc,IAAI,IAAI,CAsCrC;AAED;;;;GAIG;AACH,wBAAgB,gBAAgB,IAAI,IAAI,CAavC;AAED;;;;;;;GAOG;AACH,wBAAgB,uBAAuB,CAAC,CAAC,EAAE,MAAM,EAAE,CAAC,EAAE,MAAM,GAAG,OAAO,GAAG,IAAI,CAS5E;AAED;;;;GAIG;AACH,wBAAgB,kBAAkB,CAAC,CAAC,EAAE,MAAM,EAAE,CAAC,EAAE,MAAM,EAAE,iBAAiB,EAAE,MAAM,GAAG,IAAI,GAAG,MAAM,GAAG,IAAI,CASxG;AAyBD,wBAAgB,iBAAiB,CAAC,EAAE,EAAE,MAAM,EAAE,GAAG,EAAE,MAAM,GAAG,IAAI,CAY/D"}
+226
View File
@@ -0,0 +1,226 @@
const LABEL_HEIGHT = 27;
/**
* Positions an element-tag label relative to its highlighted overlay.
*
* Strategy (in priority order):
* 1. If the element is near the viewport top AND tall enough (>= 2x label height),
* place the label **inside** the element at the top-left.
* 2. If the element is near the viewport top but too short, place the label
* **below** the element.
* 3. Otherwise, place the label **above** the element (default).
*
* For full-width elements (spanning nearly the entire viewport), the left offset
* is nudged inward (6px) to prevent clipping against the viewport edge.
*
* @param label - The label div to position (style.top and style.left are set).
* @param rect - The bounding client rect of the highlighted element.
*/
export function positionLabel(label, rect) {
const nearTop = rect.top < LABEL_HEIGHT;
const tallEnough = rect.height >= LABEL_HEIGHT * 2;
const isFullWidth = rect.width >= window.innerWidth - 4;
const edgeLeft = isFullWidth ? "8px" : "-2px";
const insideLeft = isFullWidth ? "8px" : "4px";
if (nearTop && tallEnough) {
label.style.top = "2px";
label.style.left = insideLeft;
}
else if (nearTop) {
label.style.top = `${rect.height + 2}px`;
label.style.left = edgeLeft;
}
else {
label.style.top = `-${LABEL_HEIGHT}px`;
label.style.left = edgeLeft;
}
}
/** Check if an element has instrumentation attributes */
export function isInstrumentedElement(element) {
const htmlEl = element;
return !!(htmlEl.dataset?.sourceLocation || htmlEl.dataset?.visualSelectorId);
}
/** Get the selector ID from an element's data attributes (prefers source-location) */
export function getElementSelectorId(element) {
const htmlEl = element;
return (htmlEl.dataset?.sourceLocation ||
htmlEl.dataset?.visualSelectorId ||
null);
}
export const ALLOWED_ATTRIBUTES = ["src"];
export const PLUGIN_ELEMENT_ATTR = "data-vite-plugin-element";
/** Find elements by ID - first try data-source-location, fallback to data-visual-selector-id */
export function findElementsById(id) {
if (!id)
return [];
const sourceElements = Array.from(document.querySelectorAll(`[data-source-location="${id}"]`));
if (sourceElements.length > 0) {
return sourceElements;
}
return Array.from(document.querySelectorAll(`[data-visual-selector-id="${id}"]`));
}
/**
* Update element classes by visual selector ID.
* Uses setAttribute instead of className to support both HTML and SVG elements.
*/
export function updateElementClasses(elements, classes) {
elements.forEach((element) => {
element.setAttribute("class", classes);
});
}
/** Set a single attribute on all provided elements. */
export function updateElementAttribute(elements, attribute, value, arrIndex) {
if (!ALLOWED_ATTRIBUTES.includes(attribute)) {
return;
}
const targetArrIndex = arrIndex != null ? String(arrIndex) : null;
elements.forEach((element) => {
if (targetArrIndex === null ||
element.dataset.arrIndex === targetArrIndex) {
element.setAttribute(attribute, value);
}
});
}
/** Collect attribute values from an element for a given allowlist. */
export function collectAllowedAttributes(element, allowedAttributes) {
const attributes = {};
for (const attr of allowedAttributes) {
const val = element.getAttribute(attr);
if (val !== null) {
attributes[attr] = val;
}
}
return attributes;
}
/**
* Freeze all CSS animations and transitions on the page by injecting
* scoped styles under `[data-visual-edit-active]` and programmatically
* finishing (or pausing) every running animation.
*
* Plugin-owned elements (`[data-vite-plugin-element]`) are excluded so
* the plugin UI stays animated.
*/
export function stopAnimations() {
if (document.getElementById('freeze-animations'))
return;
document.documentElement.setAttribute('data-visual-edit-active', '');
const animStyle = document.createElement('style');
animStyle.id = 'freeze-animations';
animStyle.textContent = `
[data-visual-edit-active] *:not([${PLUGIN_ELEMENT_ATTR}]):not([${PLUGIN_ELEMENT_ATTR}] *),
[data-visual-edit-active] *:not([${PLUGIN_ELEMENT_ATTR}]):not([${PLUGIN_ELEMENT_ATTR}] *)::before,
[data-visual-edit-active] *:not([${PLUGIN_ELEMENT_ATTR}]):not([${PLUGIN_ELEMENT_ATTR}] *)::after {
animation-play-state: paused !important;
transition: none !important;
}
`;
const pointerStyle = document.createElement('style');
pointerStyle.id = 'freeze-pointer-events';
pointerStyle.textContent = `
[data-visual-edit-active] * { pointer-events: none !important; }
[${PLUGIN_ELEMENT_ATTR}], [${PLUGIN_ELEMENT_ATTR}] * { pointer-events: auto !important; }
`;
const target = document.head || document.documentElement;
target.appendChild(animStyle);
target.appendChild(pointerStyle);
document.getAnimations().forEach((a) => {
// Skip animations on plugin UI elements
const animTarget = a.effect?.target;
if (animTarget instanceof Element && animTarget.closest(`[${PLUGIN_ELEMENT_ATTR}]`))
return;
try {
a.finish(); // fast-forward to end state
}
catch {
a.pause(); // finish() throws on infinite animations — pause instead
}
});
}
/**
* Resume all previously frozen animations and remove the injected
* freeze styles. Cleans up the `data-visual-edit-active` attribute
* from `<html>` so scoped selectors no longer match.
*/
export function resumeAnimations() {
const animStyle = document.getElementById('freeze-animations');
if (!animStyle)
return;
animStyle.remove();
document.getElementById('freeze-pointer-events')?.remove();
document.documentElement.removeAttribute('data-visual-edit-active');
document.getAnimations().forEach((a) => {
if (a.playState === 'paused') {
try {
a.play();
}
catch { /* animation target may have been removed */ }
}
});
}
/**
* Hit-test the page at (`x`, `y`) and walk up the DOM to find the
* nearest ancestor that carries instrumentation attributes
* (`data-source-location` or `data-visual-selector-id`).
*
* Temporarily disables the pointer-events freeze sheet so the
* browser's native `elementFromPoint` can reach the real target.
*/
export function findInstrumentedElement(x, y) {
const pointerStyle = document.getElementById('freeze-pointer-events');
if (pointerStyle)
pointerStyle.disabled = true;
const el = document.elementFromPoint(x, y);
if (pointerStyle)
pointerStyle.disabled = false;
return el?.closest('[data-source-location], [data-visual-selector-id]') ?? null;
}
/**
* Resolve which element should be hovered at (`x`, `y`), skipping the
* currently selected element. Returns the selector ID of the hovered
* element, or `null` if the point is empty or hits the selected element.
*/
export function resolveHoverTarget(x, y, selectedElementId) {
const element = findInstrumentedElement(x, y);
if (!element)
return null;
const selectorId = getElementSelectorId(element);
if (selectorId === selectedElementId)
return null;
return selectorId;
}
const VISUAL_EDIT_FONT_FACE_ID_PREFIX = "visual-edit-font-face-";
function isValidFontFaceCss(css) {
const trimmed = css.trim();
if (!trimmed.startsWith("@font-face"))
return false;
if (trimmed.includes("\\"))
return false; // Prevent CSS escapes
const openBraces = (trimmed.match(/{/g) || []).length;
const closeBraces = (trimmed.match(/}/g) || []).length;
if (openBraces !== 1 || closeBraces !== 1 || !trimmed.endsWith("}"))
return false;
const chunks = trimmed.split(/url\(/i);
for (let i = 1; i < chunks.length; i++) {
const end = chunks[i].indexOf(")");
if (end === -1)
return false;
const url = chunks[i].slice(0, end).trim().replace(/^['"]|['"]$/g, "").trim();
if (!/^https:\/\//i.test(url))
return false;
}
return true;
}
export function injectFontFaceCss(id, css) {
if (typeof id !== "string" || !id.trim())
return;
if (typeof css !== "string" || !isValidFontFaceCss(css))
return;
const styleId = `${VISUAL_EDIT_FONT_FACE_ID_PREFIX}${id}`;
if (document.getElementById(styleId))
return;
const style = document.createElement("style");
style.id = styleId;
style.dataset.visualEditFontFace = "true";
style.textContent = css;
document.head.appendChild(style);
}
//# sourceMappingURL=utils.js.map
File diff suppressed because one or more lines are too long
@@ -0,0 +1,2 @@
export declare function setupVisualEditAgent(): void;
//# sourceMappingURL=visual-edit-agent.d.ts.map
@@ -0,0 +1 @@
{"version":3,"file":"visual-edit-agent.d.ts","sourceRoot":"","sources":["../../src/injections/visual-edit-agent.ts"],"names":[],"mappings":"AAWA,wBAAgB,oBAAoB,SAuvBnC"}
+631
View File
@@ -0,0 +1,631 @@
import { findElementsById, updateElementClasses, updateElementAttribute, collectAllowedAttributes, ALLOWED_ATTRIBUTES, getElementSelectorId, stopAnimations, resumeAnimations, findInstrumentedElement, resolveHoverTarget, positionLabel, injectFontFaceCss } from "./utils.js";
import { createLayerController } from "./layer-dropdown/controller.js";
import { LAYER_DROPDOWN_ATTR } from "./layer-dropdown/consts.js";
import { createInlineEditController } from "../capabilities/inline-edit/index.js";
import { THEME_FONT_PREVIEW_ID } from "../consts.js";
import { createCanvasWheelZoomBridgeController } from "./canvas-wheel-zoom-bridge.js";
import { createPageHeightBridgeController } from "./page-height-bridge.js";
import { createAutoPopupSuppressorController } from "./auto-popup-suppressor.js";
const REPOSITION_DELAY_MS = 50;
export function setupVisualEditAgent() {
const canvasWheelZoomBridge = createCanvasWheelZoomBridgeController();
const pageHeightBridge = createPageHeightBridgeController();
const autoPopupSuppressor = createAutoPopupSuppressorController();
// State variables (replacing React useState/useRef)
let isVisualEditMode = false;
let isPopoverDragging = false;
let isDropdownOpen = false;
let hoverOverlays = [];
let selectedOverlays = [];
let currentHighlightedElements = [];
let selectedElementId = null;
let selectedElement = null;
// Create overlay element
const createOverlay = (isSelected = false) => {
const overlay = document.createElement("div");
overlay.style.position = "absolute";
overlay.style.pointerEvents = "none";
overlay.style.transition = "all 0.1s ease-in-out";
overlay.style.zIndex = "9999";
if (isSelected) {
overlay.style.border = "2px solid #2563EB";
}
else {
overlay.style.border = "2px solid #95a5fc";
overlay.style.backgroundColor = "rgba(99, 102, 241, 0.05)";
}
return overlay;
};
// Position overlay relative to element
const positionOverlay = (overlay, element, isSelected = false) => {
if (!element || !isVisualEditMode)
return;
const htmlElement = element;
// Force layout recalculation
void htmlElement.offsetWidth;
const rect = element.getBoundingClientRect();
overlay.style.top = `${rect.top + window.scrollY}px`;
overlay.style.left = `${rect.left + window.scrollX}px`;
overlay.style.width = `${rect.width}px`;
overlay.style.height = `${rect.height}px`;
// Check if label already exists in overlay
let label = overlay.querySelector("div");
if (!label) {
label = document.createElement("div");
label.textContent = element.tagName.toLowerCase();
label.style.position = "absolute";
label.style.left = "-2px";
label.style.padding = "2px 8px";
label.style.fontSize = "11px";
label.style.fontWeight = isSelected ? "500" : "400";
label.style.color = isSelected ? "#ffffff" : "#526cff";
label.style.backgroundColor = isSelected ? "#2563EB" : "#DBEAFE";
label.style.borderRadius = "3px";
label.style.minWidth = "24px";
label.style.textAlign = "center";
overlay.appendChild(label);
}
positionLabel(label, rect);
};
// --- Inline edit controller ---
const inlineEdit = createInlineEditController({
findElementsById,
getSelectedElementId: () => selectedElementId,
getSelectedOverlays: () => selectedOverlays,
positionOverlay,
clearSelection: () => {
inlineEdit.clearSelectedMarks(selectedElementId);
clearSelectedOverlays();
selectedElementId = null;
selectedElement = null;
},
createSelectionOverlays: (elements, elementId) => {
elements.forEach((el) => {
const overlay = createOverlay(true);
document.body.appendChild(overlay);
selectedOverlays.push(overlay);
positionOverlay(overlay, el, true);
});
selectedElementId = elementId;
},
});
const clearSelection = () => {
inlineEdit.clearSelectedMarks(selectedElementId);
clearSelectedOverlays();
selectedElementId = null;
selectedElement = null;
};
// Clear hover overlays
const clearHoverOverlays = () => {
hoverOverlays.forEach((overlay) => {
if (overlay && overlay.parentNode) {
overlay.remove();
}
});
hoverOverlays = [];
currentHighlightedElements = [];
};
const clearSelectedOverlays = () => {
selectedOverlays.forEach((overlay) => {
if (overlay && overlay.parentNode) {
overlay.remove();
}
});
selectedOverlays = [];
};
const TEXT_TAGS = ['p', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'span', 'a', 'label'];
const notifyElementSelected = (element) => {
const htmlElement = element;
const rect = element.getBoundingClientRect();
const svgElement = element;
const isTextElement = TEXT_TAGS.includes(element.tagName?.toLowerCase());
const arrEl = htmlElement.closest("[data-arr-variable-name]");
const staticArrayName = arrEl?.dataset?.arrVariableName || null;
const rawIdx = arrEl?.dataset?.arrIndex;
const staticArrayIndex = rawIdx != null ? parseInt(rawIdx, 10) : null;
const staticArrayField = htmlElement.dataset?.arrField || null;
const collectionEl = htmlElement.closest("[data-collection-id]");
const itemFieldEl = htmlElement.closest("[data-collection-item-field]");
const itemIdEl = htmlElement.closest("[data-collection-item-id]");
window.parent.postMessage({
type: "element-selected",
tagName: element.tagName,
classes: svgElement.className?.baseVal ||
element.className ||
"",
visualSelectorId: getElementSelectorId(element),
content: isTextElement ? htmlElement.innerText : undefined,
dataSourceLocation: htmlElement.dataset.sourceLocation,
isDynamicContent: htmlElement.dataset.dynamicContent === "true",
linenumber: htmlElement.dataset.linenumber,
filename: htmlElement.dataset.filename,
position: {
top: rect.top,
left: rect.left,
right: rect.right,
bottom: rect.bottom,
width: rect.width,
height: rect.height,
centerX: rect.left + rect.width / 2,
centerY: rect.top + rect.height / 2,
},
attributes: collectAllowedAttributes(element, ALLOWED_ATTRIBUTES),
isTextElement,
staticArrayName,
staticArrayIndex,
staticArrayField,
collectionId: collectionEl?.dataset?.collectionId || null,
collectionItemField: itemFieldEl?.dataset?.collectionItemField || null,
collectionItemId: itemIdEl?.dataset?.collectionItemId || null,
}, "*");
};
// Select an element: create overlays, update state, notify parent
const selectElement = (element) => {
const visualSelectorId = getElementSelectorId(element);
clearSelectedOverlays();
const elements = findElementsById(visualSelectorId || null);
elements.forEach((el) => {
const overlay = createOverlay(true);
document.body.appendChild(overlay);
selectedOverlays.push(overlay);
positionOverlay(overlay, el, true);
});
selectedElementId = visualSelectorId || null;
selectedElement = element;
clearHoverOverlays();
notifyElementSelected(element);
return selectedOverlays[0];
};
const notifyDeselection = () => {
selectedElementId = null;
window.parent.postMessage({ type: "unselect-element" }, "*");
};
// Hover detection via mousemove + elementFromPoint (since app elements have pointer-events: none)
let lastHoveredSelectorId = null;
let pendingMouseMoveRaf = null;
const clearHoverState = () => {
clearHoverOverlays();
lastHoveredSelectorId = null;
};
const applyHoverOverlays = (selectorId) => {
const elements = findElementsById(selectorId);
clearHoverOverlays();
elements.forEach((el) => {
const overlay = createOverlay(false);
document.body.appendChild(overlay);
hoverOverlays.push(overlay);
positionOverlay(overlay, el);
});
currentHighlightedElements = elements;
lastHoveredSelectorId = selectorId;
};
const handleMouseMove = (e) => {
if (!isVisualEditMode || isPopoverDragging || inlineEdit.isEditing())
return;
if (pendingMouseMoveRaf !== null)
return;
pendingMouseMoveRaf = requestAnimationFrame(() => {
pendingMouseMoveRaf = null;
if (isDropdownOpen) {
clearHoverState();
return;
}
const selectorId = resolveHoverTarget(e.clientX, e.clientY, selectedElementId);
if (!selectorId) {
clearHoverState();
return;
}
if (lastHoveredSelectorId === selectorId)
return;
applyHoverOverlays(selectorId);
});
};
// Clear hover overlays when mouse leaves the viewport
const handleMouseLeave = () => {
if (pendingMouseMoveRaf !== null) {
cancelAnimationFrame(pendingMouseMoveRaf);
pendingMouseMoveRaf = null;
}
clearHoverState();
};
// Handle element click
const handleElementClick = (e) => {
if (!isVisualEditMode)
return;
const target = e.target;
// Let layer dropdown clicks pass through without interference
if (target.closest(`[${LAYER_DROPDOWN_ATTR}]`))
return;
// Let clicks inside the editable element pass through to the browser
// so the user can reposition the cursor and select text naturally.
if (inlineEdit.enabled && target instanceof HTMLElement && target.contentEditable === "true") {
return;
}
// Clicking outside the editable element exits inline editing mode.
if (inlineEdit.isEditing()) {
e.preventDefault();
e.stopPropagation();
e.stopImmediatePropagation();
inlineEdit.stopEditing();
return;
}
// Close dropdowns when clicking anywhere in iframe if a dropdown is open
if (isDropdownOpen) {
e.preventDefault();
e.stopPropagation();
e.stopImmediatePropagation();
window.parent.postMessage({ type: "close-dropdowns" }, "*");
return;
}
// Prevent default behavior immediately when in visual edit mode
e.preventDefault();
e.stopPropagation();
e.stopImmediatePropagation();
const element = findInstrumentedElement(e.clientX, e.clientY);
if (!element) {
return;
}
const htmlElement = element;
const visualSelectorId = getElementSelectorId(element);
const isAlreadySelected = selectedElementId === visualSelectorId &&
htmlElement.dataset.selected === "true";
if (isAlreadySelected && inlineEdit.enabled && inlineEdit.canEdit(htmlElement)) {
inlineEdit.startEditing(htmlElement);
return;
}
inlineEdit.stopEditing();
if (inlineEdit.enabled) {
inlineEdit.markElementsSelected(findElementsById(visualSelectorId));
}
const selectedOverlay = selectElement(element);
layerController.attachToOverlay(selectedOverlay, element);
};
const unselectElement = () => {
inlineEdit.stopEditing();
clearSelection();
};
const updateElementClassesAndReposition = (visualSelectorId, classes) => {
const elements = findElementsById(visualSelectorId);
if (elements.length === 0)
return;
updateElementClasses(elements, classes);
// Use a small delay to allow the browser to recalculate layout before repositioning
setTimeout(() => {
// Reposition selected overlays
if (selectedElementId === visualSelectorId) {
selectedOverlays.forEach((overlay, index) => {
if (index < elements.length) {
positionOverlay(overlay, elements[index]);
}
});
}
// Reposition hover overlays if needed
if (currentHighlightedElements.length > 0) {
const hoveredElement = currentHighlightedElements[0];
const hoveredId = hoveredElement?.dataset?.visualSelectorId;
if (hoveredId === visualSelectorId) {
hoverOverlays.forEach((overlay, index) => {
if (index < currentHighlightedElements.length) {
positionOverlay(overlay, currentHighlightedElements[index]);
}
});
}
}
}, REPOSITION_DELAY_MS);
};
// Update element attribute by visual selector ID
const updateElementAttributeAndReposition = (visualSelectorId, attribute, value, arrIndex) => {
const elements = findElementsById(visualSelectorId);
if (elements.length === 0)
return;
const targetArrIndex = arrIndex ??
(selectedElementId === visualSelectorId
? selectedElement?.dataset.arrIndex
: undefined);
updateElementAttribute(elements, attribute, value, targetArrIndex);
// Reposition overlays after attribute change (e.g. image src swap can affect layout)
setTimeout(() => {
if (selectedElementId === visualSelectorId) {
selectedOverlays.forEach((overlay, index) => {
if (index < elements.length) {
positionOverlay(overlay, elements[index]);
}
});
}
}, REPOSITION_DELAY_MS);
};
const updateElementContent = (visualSelectorId, content, arrIndex) => {
let elements = findElementsById(visualSelectorId);
if (elements.length === 0) {
return;
}
if (arrIndex != null) {
elements = elements.filter((el) => el.dataset.arrIndex === String(arrIndex));
}
elements.forEach((element) => {
element.innerText = content;
});
setTimeout(() => {
if (selectedElementId === visualSelectorId) {
selectedOverlays.forEach((overlay, index) => {
if (index < elements.length) {
positionOverlay(overlay, elements[index]);
}
});
}
}, REPOSITION_DELAY_MS);
};
// --- Layer dropdown controller ---
const layerController = createLayerController({
createPreviewOverlay: (element) => {
const overlay = createOverlay(false);
overlay.style.zIndex = "9998";
document.body.appendChild(overlay);
positionOverlay(overlay, element);
return overlay;
},
getSelectedElementId: () => selectedElementId,
selectElement,
onDeselect: notifyDeselection,
});
// Toggle visual edit mode
const toggleVisualEditMode = (isEnabled) => {
isVisualEditMode = isEnabled;
if (!isEnabled) {
canvasWheelZoomBridge.disable();
resumeAnimations();
inlineEdit.stopEditing();
clearSelection();
layerController.cleanup();
handleMouseLeave();
document.body.style.cursor = "default";
document.removeEventListener("mousemove", handleMouseMove);
document.removeEventListener("mouseleave", handleMouseLeave);
document.removeEventListener("click", handleElementClick, true);
}
else {
document.body.style.cursor = "crosshair";
stopAnimations();
document.addEventListener("mousemove", handleMouseMove);
document.addEventListener("mouseleave", handleMouseLeave);
document.addEventListener("click", handleElementClick, true);
}
};
// Handle scroll events to update popover position
const handleScroll = () => {
if (selectedElementId) {
const element = selectedElement;
if (element && element.isConnected) {
const rect = element.getBoundingClientRect();
const viewportHeight = window.innerHeight;
const viewportWidth = window.innerWidth;
const isInViewport = rect.top < viewportHeight &&
rect.bottom > 0 &&
rect.left < viewportWidth &&
rect.right > 0;
const elementPosition = {
top: rect.top,
left: rect.left,
right: rect.right,
bottom: rect.bottom,
width: rect.width,
height: rect.height,
centerX: rect.left + rect.width / 2,
centerY: rect.top + rect.height / 2,
};
window.parent.postMessage({
type: "element-position-update",
position: elementPosition,
isInViewport: isInViewport,
visualSelectorId: selectedElementId,
}, "*");
}
}
};
// Handle messages from parent window
const handleMessage = (event) => {
const message = event.data;
switch (message.type) {
case "toggle-visual-edit-mode":
toggleVisualEditMode(message.data.enabled);
if (message.data.specs?.newInlineEditEnabled !== undefined) {
inlineEdit.enabled = message.data.specs.newInlineEditEnabled;
}
break;
case "update-classes":
if (message.data && message.data.classes !== undefined) {
updateElementClassesAndReposition(message.data.visualSelectorId, message.data.classes);
}
else {
console.warn("[VisualEditAgent] Invalid update-classes message:", message);
}
break;
case "update-attribute":
if (message.data &&
message.data.visualSelectorId &&
message.data.attribute !== undefined &&
message.data.value !== undefined) {
updateElementAttributeAndReposition(message.data.visualSelectorId, message.data.attribute, message.data.value, message.data.arrIndex);
}
else {
console.warn("[VisualEditAgent] Invalid update-attribute message:", message);
}
break;
case "unselect-element":
unselectElement();
break;
case "refresh-page":
window.location.reload();
break;
case "update-content":
if (message.data && message.data.content !== undefined) {
updateElementContent(message.data.visualSelectorId, message.data.content, message.data.arrIndex);
}
else {
console.warn("[VisualEditAgent] Invalid update-content message:", message);
}
break;
case "request-element-position":
if (selectedElementId && selectedElement && selectedElement.isConnected) {
const rect = selectedElement.getBoundingClientRect();
const viewportHeight = window.innerHeight;
const viewportWidth = window.innerWidth;
const isInViewport = rect.top < viewportHeight &&
rect.bottom > 0 &&
rect.left < viewportWidth &&
rect.right > 0;
const elementPosition = {
top: rect.top,
left: rect.left,
right: rect.right,
bottom: rect.bottom,
width: rect.width,
height: rect.height,
centerX: rect.left + rect.width / 2,
centerY: rect.top + rect.height / 2,
};
window.parent.postMessage({
type: "element-position-update",
position: elementPosition,
isInViewport: isInViewport,
visualSelectorId: selectedElementId,
}, "*");
}
break;
case "popover-drag-state":
if (message.data && message.data.isDragging !== undefined) {
isPopoverDragging = message.data.isDragging;
if (message.data.isDragging) {
clearHoverOverlays();
}
}
break;
case "dropdown-state":
if (message.data && message.data.isOpen !== undefined) {
isDropdownOpen = message.data.isOpen;
if (message.data.isOpen) {
clearHoverOverlays();
}
}
break;
case "update-theme-variables":
if (message.data?.variables) {
const target = message.data.mode === 'dark'
? document.querySelector('.dark')
: document.documentElement;
if (target) {
for (const [name, value] of Object.entries(message.data.variables)) {
target.style.setProperty(name, value);
}
}
}
break;
case "inject-font-import":
if (message.data?.fontUrl) {
let fontStyle = document.getElementById(THEME_FONT_PREVIEW_ID);
if (!fontStyle) {
fontStyle = document.createElement('style');
fontStyle.id = THEME_FONT_PREVIEW_ID;
document.head.appendChild(fontStyle);
}
fontStyle.textContent = `@import url('${message.data.fontUrl}');`;
}
break;
case "inject-font-face":
if (message.data) {
injectFontFaceCss(message.data.id, message.data.css);
}
break;
case "toggle-inline-edit-mode":
if (message.data) {
inlineEdit.handleToggleMessage(message.data);
}
break;
case "freeze-vh-units":
pageHeightBridge.freezeVhUnits(typeof message.referenceVhBase === "number"
? message.referenceVhBase
: undefined);
break;
case "measure-page-height":
pageHeightBridge.measurePageHeight(event.origin && event.origin !== "null" ? event.origin : "*", typeof message.settleMs === "number" ? message.settleMs : undefined);
break;
case "suppress-auto-popups":
autoPopupSuppressor.suppress();
break;
case "toggle-canvas-wheel-zoom-bridge":
canvasWheelZoomBridge.enable();
break;
default:
break;
}
};
// Handle window resize to reposition overlays
const handleResize = () => {
if (selectedElementId) {
const elements = findElementsById(selectedElementId);
selectedOverlays.forEach((overlay, index) => {
if (index < elements.length) {
positionOverlay(overlay, elements[index]);
}
});
}
if (currentHighlightedElements.length > 0) {
hoverOverlays.forEach((overlay, index) => {
if (index < currentHighlightedElements.length) {
positionOverlay(overlay, currentHighlightedElements[index]);
}
});
}
};
// Initialize: Add IDs to elements that don't have them but have linenumbers
const elementsWithLineNumber = document.querySelectorAll("[data-linenumber]:not([data-visual-selector-id])");
elementsWithLineNumber.forEach((el, index) => {
const htmlEl = el;
const id = `visual-id-${htmlEl.dataset.filename}-${htmlEl.dataset.linenumber}-${index}`;
htmlEl.dataset.visualSelectorId = id;
});
// Create mutation observer to detect layout changes
const mutationObserver = new MutationObserver((mutations) => {
const needsUpdate = mutations.some((mutation) => {
const hasVisualId = (node) => {
if (node.nodeType === Node.ELEMENT_NODE) {
const el = node;
if (el.dataset && el.dataset.visualSelectorId) {
return true;
}
for (let i = 0; i < el.children.length; i++) {
if (hasVisualId(el.children[i])) {
return true;
}
}
}
return false;
};
const isLayoutChange = mutation.type === "attributes" &&
(mutation.attributeName === "style" ||
mutation.attributeName === "class" ||
mutation.attributeName === "width" ||
mutation.attributeName === "height");
return isLayoutChange && hasVisualId(mutation.target);
});
if (needsUpdate) {
setTimeout(handleResize, REPOSITION_DELAY_MS);
}
});
// Set up event listeners
window.addEventListener("message", handleMessage);
window.addEventListener("scroll", handleScroll, true);
document.addEventListener("scroll", handleScroll, true);
window.addEventListener("resize", handleResize);
window.addEventListener("scroll", handleResize);
// Start observing DOM mutations
mutationObserver.observe(document.body, {
attributes: true,
childList: true,
subtree: true,
attributeFilter: ["style", "class", "width", "height"],
});
// Send ready message to parent
window.parent.postMessage({ type: "visual-edit-agent-ready" }, "*");
}
//# sourceMappingURL=visual-edit-agent.js.map
File diff suppressed because one or more lines are too long