@builderx/bridge
Advanced tools
Comparing version 1.0.4 to 1.0.5
@@ -1,23 +0,10 @@ | ||
(function (factory) { | ||
if (typeof module === "object" && typeof module.exports === "object") { | ||
var v = factory(require, exports); | ||
if (v !== undefined) module.exports = v; | ||
} | ||
else if (typeof define === "function" && define.amd) { | ||
define(["require", "exports", "react", "./initBridge"], factory); | ||
} | ||
})(function (require, exports) { | ||
"use strict"; | ||
'use client'; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
exports.Bridge = void 0; | ||
const react_1 = require("react"); | ||
const initBridge_1 = require("./initBridge"); | ||
const Bridge = () => { | ||
(0, react_1.useEffect)(() => { | ||
(0, initBridge_1.initBridge)(); | ||
}, []); | ||
return null; | ||
}; | ||
exports.Bridge = Bridge; | ||
}); | ||
'use client'; | ||
import { useEffect } from 'react'; | ||
import { initBridge } from './initBridge'; | ||
export const Bridge = () => { | ||
useEffect(() => { | ||
initBridge(); | ||
}, []); | ||
return null; | ||
}; | ||
//# sourceMappingURL=Bridge.js.map |
@@ -1,30 +0,20 @@ | ||
(function (factory) { | ||
if (typeof module === "object" && typeof module.exports === "object") { | ||
var v = factory(require, exports); | ||
if (v !== undefined) module.exports = v; | ||
class BridgeStore { | ||
constructor() { | ||
this._layerResizing = false; | ||
this._artboardId = ""; | ||
} | ||
else if (typeof define === "function" && define.amd) { | ||
define(["require", "exports"], factory); | ||
get layerResizing() { | ||
return this._layerResizing; | ||
} | ||
})(function (require, exports) { | ||
"use strict"; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
exports.bridgeStore = void 0; | ||
class BridgeStore { | ||
_layerResizing = false; | ||
_artboardId = ""; | ||
get layerResizing() { | ||
return this._layerResizing; | ||
} | ||
setLayerResizing(value) { | ||
this._layerResizing = value; | ||
} | ||
get artboardId() { | ||
return this._artboardId; | ||
} | ||
setArtboardId(value) { | ||
this._artboardId = value; | ||
} | ||
setLayerResizing(value) { | ||
this._layerResizing = value; | ||
} | ||
exports.bridgeStore = new BridgeStore(); | ||
}); | ||
get artboardId() { | ||
return this._artboardId; | ||
} | ||
setArtboardId(value) { | ||
this._artboardId = value; | ||
} | ||
} | ||
export const bridgeStore = new BridgeStore(); | ||
//# sourceMappingURL=BridgeStore.js.map |
@@ -1,2 +0,3 @@ | ||
export { initBridge } from './initBridge'; | ||
export { Bridge } from './Bridge'; | ||
import { initBridge } from './initBridge'; | ||
import { Bridge } from './Bridge'; | ||
export { initBridge, Bridge }; |
@@ -1,17 +0,5 @@ | ||
(function (factory) { | ||
if (typeof module === "object" && typeof module.exports === "object") { | ||
var v = factory(require, exports); | ||
if (v !== undefined) module.exports = v; | ||
} | ||
else if (typeof define === "function" && define.amd) { | ||
define(["require", "exports", "./initBridge", "./Bridge"], factory); | ||
} | ||
})(function (require, exports) { | ||
"use strict"; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
exports.Bridge = exports.initBridge = void 0; | ||
var initBridge_1 = require("./initBridge"); | ||
Object.defineProperty(exports, "initBridge", { enumerable: true, get: function () { return initBridge_1.initBridge; } }); | ||
var Bridge_1 = require("./Bridge"); | ||
Object.defineProperty(exports, "Bridge", { enumerable: true, get: function () { return Bridge_1.Bridge; } }); | ||
}); | ||
'use client'; | ||
import { initBridge } from './initBridge'; | ||
import { Bridge } from './Bridge'; | ||
export { initBridge, Bridge }; | ||
//# sourceMappingURL=index.js.map |
// Add debug logging for import | ||
(function (factory) { | ||
if (typeof module === "object" && typeof module.exports === "object") { | ||
var v = factory(require, exports); | ||
if (v !== undefined) module.exports = v; | ||
} | ||
else if (typeof define === "function" && define.amd) { | ||
define(["require", "exports"], factory); | ||
} | ||
})(function (require, exports) { | ||
"use strict"; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
exports.initBridge = void 0; | ||
// Add more detailed logging | ||
console.log("Before initBridge function definition"); | ||
function initBridge() { | ||
if (typeof window !== "undefined") { | ||
window.isInitialized = true; | ||
window.addEventListener("load", () => { | ||
window.parent.postMessage({ type: "preview-ready", message: "" }, "*"); | ||
}); | ||
function sendMessageToParent(message) { | ||
if (typeof window !== "undefined") { | ||
try { | ||
window.parent.postMessage(message, "*"); // Target origin should match the parent's origin | ||
// window.postMessage(message, '*'); // Target origin should match the parent's origin | ||
} | ||
catch (error) { | ||
console.error("Error sending message to parent:", error); | ||
} | ||
// Add more detailed logging | ||
console.log("Before initBridge function definition"); | ||
export function initBridge() { | ||
if (typeof window !== "undefined") { | ||
window.isInitialized = true; | ||
window.addEventListener("load", () => { | ||
window.parent.postMessage({ type: "preview-ready", message: "" }, "*"); | ||
}); | ||
function sendMessageToParent(message) { | ||
if (typeof window !== "undefined") { | ||
try { | ||
window.parent.postMessage(message, "*"); // Target origin should match the parent's origin | ||
// window.postMessage(message, '*'); // Target origin should match the parent's origin | ||
} | ||
} | ||
function updateReactTree() { | ||
const rootFiber = getRootFiberNode(); | ||
if (rootFiber) { | ||
const initialReactTree = buildReactElementTree(rootFiber, false); | ||
// const iframeDom = getSelfIframeDom(); | ||
sendMessageToParent({ | ||
type: "onUpdateTree", | ||
data: initialReactTree, | ||
//@ts-ignore | ||
artboardId: window["artboardId"], | ||
}); | ||
catch (error) { | ||
console.error("Error sending message to parent:", error); | ||
} | ||
} | ||
// Function to poll for the React root fiber node | ||
function pollForRootFiberNode(attempts = 10, interval = 500) { | ||
let attempt = 0; | ||
const poll = setInterval(() => { | ||
const rootFiber = getRootFiberNode(); | ||
} | ||
function updateReactTree() { | ||
const rootFiber = getRootFiberNode(); | ||
if (rootFiber) { | ||
const initialReactTree = buildReactElementTree(rootFiber, false); | ||
// const iframeDom = getSelfIframeDom(); | ||
sendMessageToParent({ | ||
type: "onUpdateTree", | ||
data: initialReactTree, | ||
//@ts-ignore | ||
if (rootFiber && window["artboardId"]) { | ||
clearInterval(poll); | ||
updateReactTree(); | ||
} | ||
else if (attempt >= attempts) { | ||
clearInterval(poll); | ||
console.error("Failed to find React root fiber node after multiple attempts"); | ||
} | ||
attempt++; | ||
}, interval); | ||
artboardId: window["artboardId"], | ||
}); | ||
} | ||
function getDomNodeFromFiber(fiber) { | ||
let node = null; | ||
// Traverse the Fiber tree to find the DOM node | ||
while (fiber) { | ||
// Check if this fiber's stateNode is a DOM node | ||
if (fiber.stateNode instanceof HTMLElement || | ||
fiber.stateNode instanceof SVGElement) { | ||
node = fiber.stateNode; | ||
break; | ||
} | ||
// Move up the tree to the parent | ||
if (fiber.child) { | ||
fiber = fiber.child; | ||
} | ||
else { | ||
fiber = fiber.return; | ||
} | ||
} | ||
// Function to poll for the React root fiber node | ||
function pollForRootFiberNode(attempts = 10, interval = 500) { | ||
let attempt = 0; | ||
const poll = setInterval(() => { | ||
const rootFiber = getRootFiberNode(); | ||
//@ts-ignore | ||
if (rootFiber && window["artboardId"]) { | ||
clearInterval(poll); | ||
updateReactTree(); | ||
} | ||
return node; | ||
} | ||
const handleWindowLoad = () => { | ||
sendMessageToParent({ | ||
type: "onAppLoaded", | ||
}); | ||
pollForRootFiberNode(); | ||
detectHotModuleReload(); | ||
}; | ||
const handleMessage = (event) => { | ||
// console.log('initBridge', window, window.document); | ||
// Add new handlers for navigation | ||
if (event.data && event.data.type === "navigate/back") { | ||
window.history.back(); | ||
pollForRootFiberNode(); | ||
else if (attempt >= attempts) { | ||
clearInterval(poll); | ||
console.error("Failed to find React root fiber node after multiple attempts"); | ||
} | ||
if (event.data && event.data.type === "navigate/forward") { | ||
window.history.forward(); | ||
pollForRootFiberNode(); | ||
attempt++; | ||
}, interval); | ||
} | ||
function getDomNodeFromFiber(fiber) { | ||
let node = null; | ||
// Traverse the Fiber tree to find the DOM node | ||
while (fiber) { | ||
// Check if this fiber's stateNode is a DOM node | ||
if (fiber.stateNode instanceof HTMLElement || | ||
fiber.stateNode instanceof SVGElement) { | ||
node = fiber.stateNode; | ||
break; | ||
} | ||
if (event.data && event.data.type === "rpc") { | ||
handleRPC(event.data); | ||
// Move up the tree to the parent | ||
if (fiber.child) { | ||
fiber = fiber.child; | ||
} | ||
if (event?.data?.type == "setDOMStyleUntilHMR") { | ||
var doms = document.querySelectorAll('[data-bx-path="' + event.data.payload.path + '"]'); | ||
Array.from(doms).forEach((dom) => { | ||
updateDOMUntilHMR(dom, event.data.payload.style); | ||
}); | ||
else { | ||
fiber = fiber.return; | ||
} | ||
if (event.data && event.data.type === "setArtboardId") { | ||
//@ts-ignore | ||
window["artboardId"] = event.data.payload.artboardId; | ||
// bridgeStore.setArtboardId(event.data.payload.artboardId); | ||
} | ||
}; | ||
function handleRPC(data) { | ||
const { id, fnName, fnArgs } = data.payload; | ||
let result; | ||
switch (fnName) { | ||
case "add": | ||
result = fnArgs.a + fnArgs.b; | ||
break; | ||
case "getLayerById": | ||
result = getLayerById(fnArgs); | ||
break; | ||
case "getLayerComputedStyle": | ||
result = getLayerComputedStyle(fnArgs); | ||
break; | ||
case "getLayerAtXY": | ||
result = getLayerAtXY(fnArgs); | ||
// if (id.startsWith('main')) { | ||
// } | ||
break; | ||
case "setLayerResizing": | ||
result = setLayerResizing(fnArgs); | ||
break; | ||
// Then in your message handler switch statement: | ||
case "findContainerForDimensions": | ||
result = findContainerForDimensions(fnArgs); | ||
break; | ||
case "getPositionedAncestorOffset": | ||
result = getPositionedAncestorOffset(fnArgs); | ||
break; | ||
case "getPathOfChildFromParent": | ||
result = getPathOfChildFromParent(fnArgs); | ||
break; | ||
/*case 'getSelectedLayerComputedStyle': | ||
result = getSelectedLayerComputedStyle(fnArgs); | ||
break;*/ | ||
default: | ||
console.warn(`Unknown RPC function: ${fnName}`); | ||
return; | ||
} | ||
sendMessageToParent({ | ||
type: "rpcResolved", | ||
calledMethod: fnName, | ||
id: id, | ||
result: result, | ||
} | ||
return node; | ||
} | ||
const handleWindowLoad = () => { | ||
sendMessageToParent({ | ||
type: "onAppLoaded", | ||
}); | ||
pollForRootFiberNode(); | ||
detectHotModuleReload(); | ||
}; | ||
const handleMessage = (event) => { | ||
// console.log('initBridge', window, window.document); | ||
var _a; | ||
// Add new handlers for navigation | ||
if (event.data && event.data.type === "navigate/back") { | ||
window.history.back(); | ||
pollForRootFiberNode(); | ||
} | ||
if (event.data && event.data.type === "navigate/forward") { | ||
window.history.forward(); | ||
pollForRootFiberNode(); | ||
} | ||
if (event.data && event.data.type === "rpc") { | ||
handleRPC(event.data); | ||
} | ||
if (((_a = event === null || event === void 0 ? void 0 : event.data) === null || _a === void 0 ? void 0 : _a.type) == "setDOMStyleUntilHMR") { | ||
var doms = document.querySelectorAll('[data-bx-path="' + event.data.payload.path + '"]'); | ||
Array.from(doms).forEach((dom) => { | ||
updateDOMUntilHMR(dom, event.data.payload.style); | ||
}); | ||
} | ||
function setLayerResizing({ isResizing }) { | ||
if (event.data && event.data.type === "setArtboardId") { | ||
//@ts-ignore | ||
window["layerResizing"] = isResizing; | ||
window["artboardId"] = event.data.payload.artboardId; | ||
// bridgeStore.setArtboardId(event.data.payload.artboardId); | ||
} | ||
function getSelfIframeDom() { | ||
// const iframes = window.parent.frames; | ||
// for (const iframe of iframes) { | ||
// console.log(iframe, ">>>>>>>> frames"); | ||
// if (iframe.contentWindow === window) { | ||
// return iframe; | ||
// } | ||
// } | ||
return null; | ||
}; | ||
function handleRPC(data) { | ||
const { id, fnName, fnArgs } = data.payload; | ||
let result; | ||
switch (fnName) { | ||
case "add": | ||
result = fnArgs.a + fnArgs.b; | ||
break; | ||
case "getLayerById": | ||
result = getLayerById(fnArgs); | ||
break; | ||
case "getLayerComputedStyle": | ||
result = getLayerComputedStyle(fnArgs); | ||
break; | ||
case "getLayerAtXY": | ||
result = getLayerAtXY(fnArgs); | ||
// if (id.startsWith('main')) { | ||
// } | ||
break; | ||
case "setLayerResizing": | ||
result = setLayerResizing(fnArgs); | ||
break; | ||
// Then in your message handler switch statement: | ||
case "findContainerForDimensions": | ||
result = findContainerForDimensions(fnArgs); | ||
break; | ||
case "getPositionedAncestorOffset": | ||
result = getPositionedAncestorOffset(fnArgs); | ||
break; | ||
case "getPathOfChildFromParent": | ||
result = getPathOfChildFromParent(fnArgs); | ||
break; | ||
/*case 'getSelectedLayerComputedStyle': | ||
result = getSelectedLayerComputedStyle(fnArgs); | ||
break;*/ | ||
default: | ||
console.warn(`Unknown RPC function: ${fnName}`); | ||
return; | ||
} | ||
// Define the new function | ||
function getLayerAtXY(args) { | ||
let { x, y, inLayers, zoomLevel } = args; | ||
// const iframeDom = getSelfIframeDom(); | ||
// let offsetX = 0; | ||
// let offsetY = 0; | ||
// if (iframeDom) { | ||
// const rect = iframeDom?.getBoundingClientRect(); | ||
// offsetX = rect ? rect.left : 0; | ||
// offsetY = rect ? rect.top : 0; | ||
// } | ||
// x = (x - offsetX) / zoomLevel; | ||
// y = (y - offsetY) / zoomLevel; | ||
const elementAtPoint = document.elementFromPoint(x, y); | ||
let dataPath; | ||
let fiberNode = getFiberFromDOMNode(elementAtPoint); | ||
let element = null; | ||
if (inLayers && Array.isArray(inLayers)) { | ||
while (fiberNode) { | ||
const memoizedProps = fiberNode.memoizedProps; | ||
if (memoizedProps && "data-bx-path" in memoizedProps) { | ||
dataPath = memoizedProps["data-bx-path"]; | ||
if (dataPath && inLayers.includes(dataPath)) { | ||
element = getDomNodeFromFiber(fiberNode); | ||
break; | ||
} | ||
sendMessageToParent({ | ||
type: "rpcResolved", | ||
calledMethod: fnName, | ||
id: id, | ||
result: result, | ||
}); | ||
} | ||
function setLayerResizing({ isResizing }) { | ||
//@ts-ignore | ||
window["layerResizing"] = isResizing; | ||
} | ||
function getSelfIframeDom() { | ||
// const iframes = window.parent.frames; | ||
// for (const iframe of iframes) { | ||
// console.log(iframe, ">>>>>>>> frames"); | ||
// if (iframe.contentWindow === window) { | ||
// return iframe; | ||
// } | ||
// } | ||
return null; | ||
} | ||
// Define the new function | ||
function getLayerAtXY(args) { | ||
let { x, y, inLayers, zoomLevel } = args; | ||
// const iframeDom = getSelfIframeDom(); | ||
// let offsetX = 0; | ||
// let offsetY = 0; | ||
// if (iframeDom) { | ||
// const rect = iframeDom?.getBoundingClientRect(); | ||
// offsetX = rect ? rect.left : 0; | ||
// offsetY = rect ? rect.top : 0; | ||
// } | ||
// x = (x - offsetX) / zoomLevel; | ||
// y = (y - offsetY) / zoomLevel; | ||
const elementAtPoint = document.elementFromPoint(x, y); | ||
let dataPath; | ||
let fiberNode = getFiberFromDOMNode(elementAtPoint); | ||
let element = null; | ||
if (inLayers && Array.isArray(inLayers)) { | ||
while (fiberNode) { | ||
const memoizedProps = fiberNode.memoizedProps; | ||
if (memoizedProps && "data-bx-path" in memoizedProps) { | ||
dataPath = memoizedProps["data-bx-path"]; | ||
if (dataPath && inLayers.includes(dataPath)) { | ||
element = getDomNodeFromFiber(fiberNode); | ||
break; | ||
} | ||
fiberNode = fiberNode.return; | ||
} | ||
fiberNode = fiberNode.return; | ||
} | ||
else { | ||
element = elementAtPoint; | ||
dataPath = fiberNode?.memoizedProps["data-bx-path"]; | ||
} | ||
if (element) { | ||
const rect = element.getBoundingClientRect(); | ||
const result = { | ||
x: rect.left, | ||
y: rect.top, | ||
width: rect.width, | ||
height: rect.height, | ||
path: dataPath, | ||
}; | ||
result.container = getContainerData(fiberNode); | ||
return result; | ||
} | ||
return null; | ||
} | ||
function getDomNodeFromPath(path) { | ||
const fiberNode = getFibreNodeFromPath(path); | ||
// Get the DOM node from the fiber node | ||
let domNode; | ||
if (fiberNode) { | ||
// console.log(fiberNode,"fiberNode 269") | ||
domNode = getDomNodeFromFiber(fiberNode); | ||
else { | ||
element = elementAtPoint; | ||
dataPath = fiberNode === null || fiberNode === void 0 ? void 0 : fiberNode.memoizedProps["data-bx-path"]; | ||
} | ||
if (element) { | ||
const rect = element.getBoundingClientRect(); | ||
const result = { | ||
x: rect.left, | ||
y: rect.top, | ||
width: rect.width, | ||
height: rect.height, | ||
path: dataPath, | ||
}; | ||
result.container = getContainerData(fiberNode); | ||
return result; | ||
} | ||
return null; | ||
} | ||
function getDomNodeFromPath(path) { | ||
const fiberNode = getFibreNodeFromPath(path); | ||
// Get the DOM node from the fiber node | ||
let domNode; | ||
if (fiberNode) { | ||
// console.log(fiberNode,"fiberNode 269") | ||
domNode = getDomNodeFromFiber(fiberNode); | ||
} | ||
else { | ||
//TODO: not getting dom node but path log is correct | ||
domNode = document.querySelector(`[data-bx-path="${path}"]`); | ||
// console.log({domNode,path},"getDomNodeFromPath at 277;;") | ||
} | ||
// console.log(domNode,"layerId 282") | ||
return domNode; | ||
} | ||
// Update this function | ||
function getLayerById(args) { | ||
const { layerId } = args; | ||
const element = getDomNodeFromPath(layerId); | ||
if (element) { | ||
const rect = element.getBoundingClientRect(); | ||
// console.log('event>>>>>>', args, layerId, element); | ||
const style = window.getComputedStyle(element); | ||
const transform = style.transform; | ||
const rotate = style.rotate; | ||
// Extract rotation from either transform matrix or rotate property | ||
let rotation = 0; | ||
if (rotate && rotate !== "none") { | ||
// Parse rotate value (e.g., "45deg" -> 45) | ||
rotation = parseFloat(rotate); | ||
} | ||
else { | ||
//TODO: not getting dom node but path log is correct | ||
domNode = document.querySelector(`[data-bx-path="${path}"]`); | ||
// console.log({domNode,path},"getDomNodeFromPath at 277;;") | ||
else if (transform && transform !== "none") { | ||
const values = transform.split("(")[1].split(")")[0].split(","); | ||
rotation = Math.round(Math.atan2(Number(values[1]), Number(values[0])) * (180 / Math.PI)); | ||
} | ||
// console.log(domNode,"layerId 282") | ||
return domNode; | ||
const result = { | ||
x: rect.left, | ||
y: rect.top, | ||
width: rect.width, | ||
height: rect.height, | ||
path: layerId, | ||
rotation: rotation, | ||
}; | ||
let fiberNode = getFiberFromDOMNode(element); | ||
result.container = getContainerData(fiberNode); | ||
return result; | ||
} | ||
// Update this function | ||
function getLayerById(args) { | ||
const { layerId } = args; | ||
const element = getDomNodeFromPath(layerId); | ||
if (element) { | ||
const rect = element.getBoundingClientRect(); | ||
// console.log('event>>>>>>', args, layerId, element); | ||
const style = window.getComputedStyle(element); | ||
const transform = style.transform; | ||
const rotate = style.rotate; | ||
// Extract rotation from either transform matrix or rotate property | ||
let rotation = 0; | ||
if (rotate && rotate !== "none") { | ||
// Parse rotate value (e.g., "45deg" -> 45) | ||
rotation = parseFloat(rotate); | ||
} | ||
else if (transform && transform !== "none") { | ||
const values = transform.split("(")[1].split(")")[0].split(","); | ||
rotation = Math.round(Math.atan2(Number(values[1]), Number(values[0])) * (180 / Math.PI)); | ||
} | ||
const result = { | ||
x: rect.left, | ||
y: rect.top, | ||
width: rect.width, | ||
height: rect.height, | ||
path: layerId, | ||
rotation: rotation, | ||
}; | ||
let fiberNode = getFiberFromDOMNode(element); | ||
result.container = getContainerData(fiberNode); | ||
return result; | ||
} | ||
return null; | ||
} | ||
// Add this function alongside other bridge functions like getLayerAtXY | ||
function findContainerForDimensions({ x, y, width, height, artboardId, }) { | ||
// Locate the artboard first | ||
const artboard = document.querySelector(`[data-bx-path^="${artboardId}"]`); | ||
console.log(artboard, "abcde"); | ||
if (!artboard) { | ||
console.error(`Artboard with ID ${artboardId} not found`); | ||
return null; | ||
} | ||
// Add this function alongside other bridge functions like getLayerAtXY | ||
function findContainerForDimensions({ x, y, width, height, artboardId, }) { | ||
// Locate the artboard first | ||
const artboard = document.querySelector(`[data-bx-path^="${artboardId}"]`); | ||
console.log(artboard, "abcde"); | ||
if (!artboard) { | ||
console.error(`Artboard with ID ${artboardId} not found`); | ||
return null; | ||
} | ||
// Search for containers within the artboard | ||
const allLayers = artboard.querySelectorAll("[data-bx-path]"); | ||
let bestContainer = null; | ||
let smallestArea = Infinity; | ||
allLayers.forEach((element) => { | ||
const rect = element.getBoundingClientRect(); | ||
const path = element.getAttribute("data-bx-path"); | ||
// Check if the element can contain the target dimensions | ||
if (rect.left <= x && | ||
rect.top <= y && | ||
rect.left + rect.width >= x + width && | ||
rect.top + rect.height >= y + height) { | ||
const area = rect.width * rect.height; | ||
if (area < smallestArea) { | ||
smallestArea = area; | ||
bestContainer = { | ||
path: path, | ||
x: rect.left, | ||
y: rect.top, | ||
width: rect.width, | ||
height: rect.height, | ||
container: { x: 0, y: 0 }, | ||
}; | ||
} | ||
// Search for containers within the artboard | ||
const allLayers = artboard.querySelectorAll("[data-bx-path]"); | ||
let bestContainer = null; | ||
let smallestArea = Infinity; | ||
allLayers.forEach((element) => { | ||
const rect = element.getBoundingClientRect(); | ||
const path = element.getAttribute("data-bx-path"); | ||
// Check if the element can contain the target dimensions | ||
if (rect.left <= x && | ||
rect.top <= y && | ||
rect.left + rect.width >= x + width && | ||
rect.top + rect.height >= y + height) { | ||
const area = rect.width * rect.height; | ||
if (area < smallestArea) { | ||
smallestArea = area; | ||
bestContainer = { | ||
path: path, | ||
x: rect.left, | ||
y: rect.top, | ||
width: rect.width, | ||
height: rect.height, | ||
container: { x: 0, y: 0 }, | ||
}; | ||
} | ||
}); | ||
// Fallback to the artboard itself if no container found | ||
if (!bestContainer) { | ||
const rect = artboard.getBoundingClientRect(); | ||
const path = artboard.getAttribute("data-bx-path"); | ||
bestContainer = { | ||
path: path, | ||
x: rect.left, | ||
y: rect.top, | ||
width: rect.width, | ||
height: rect.height, | ||
container: { x: 0, y: 0 }, | ||
}; | ||
} | ||
return bestContainer; | ||
} | ||
function getPositionedAncestorOffset({ elementPath, artboardId, position, }) { | ||
// Locate the artboard first | ||
const artboard = document.querySelector(`[data-bx-path^="${artboardId}"]`); | ||
if (!artboard) { | ||
console.error(`Artboard with ID ${artboardId} not found`); | ||
return null; | ||
} | ||
const elements = artboard?.querySelectorAll(`[data-bx-path="${elementPath}"]`); | ||
console.log(elements, "elements"); | ||
if (!elements) | ||
return { x: 0, y: 0 }; | ||
// Find the closest element to the given position | ||
let closestElement = null; | ||
let minDistance = Infinity; | ||
elements.forEach((element) => { | ||
const rect = element.getBoundingClientRect(); | ||
const elementCenterX = rect.left + rect.width / 2; | ||
const elementCenterY = rect.top + rect.height / 2; | ||
// Calculate distance using Pythagorean theorem | ||
const distance = Math.sqrt(Math.pow(elementCenterX - position.x, 2) + | ||
Math.pow(elementCenterY - position.y, 2)); | ||
if (distance < minDistance) { | ||
minDistance = distance; | ||
closestElement = element; | ||
} | ||
}); | ||
if (!closestElement) | ||
return { x: 0, y: 0 }; | ||
//@ts-ignore | ||
const rect = closestElement.getBoundingClientRect(); | ||
console.log({ | ||
}); | ||
// Fallback to the artboard itself if no container found | ||
if (!bestContainer) { | ||
const rect = artboard.getBoundingClientRect(); | ||
const path = artboard.getAttribute("data-bx-path"); | ||
bestContainer = { | ||
path: path, | ||
x: rect.left, | ||
y: rect.top, | ||
}, "rect"); | ||
return { | ||
x: rect.left, | ||
y: rect.top, | ||
width: rect.width, | ||
height: rect.height, | ||
container: { x: 0, y: 0 }, | ||
}; | ||
} | ||
function getPathOfChildFromParent({ path, artboardId, index, }) { | ||
const parentNode = document?.querySelector(`[data-bx-path="${path}"]`); | ||
if (!parentNode) | ||
return null; | ||
const children = parentNode.children; | ||
if (children.length === 0) | ||
return null; | ||
// Get target child (last child if no index provided) | ||
const targetIndex = typeof index === "number" ? index : children.length - 1; | ||
// Validate index | ||
if (targetIndex < 0 || targetIndex >= children.length) | ||
return null; | ||
// Get the target child and return its path | ||
const targetChild = children[targetIndex]; | ||
return targetChild.getAttribute("data-bx-path"); | ||
return bestContainer; | ||
} | ||
function getPositionedAncestorOffset({ elementPath, artboardId, position, }) { | ||
// Locate the artboard first | ||
const artboard = document.querySelector(`[data-bx-path^="${artboardId}"]`); | ||
if (!artboard) { | ||
console.error(`Artboard with ID ${artboardId} not found`); | ||
return null; | ||
} | ||
function getLayerComputedStyle(args) { | ||
const { layerId } = args; | ||
// Get the DOM node from the fiber node | ||
const domNode = getDomNodeFromPath(layerId); | ||
// console.log(layerId,"layerId",domNode) | ||
if (domNode) { | ||
// Get the computed style of the DOM node | ||
const computedStyle = window.getComputedStyle(domNode); | ||
// console.log(computedStyle, "computedStyle in getLayerComputedStyle",layerId) | ||
return JSON.parse(JSON.stringify(computedStyle)); | ||
const elements = artboard === null || artboard === void 0 ? void 0 : artboard.querySelectorAll(`[data-bx-path="${elementPath}"]`); | ||
console.log(elements, "elements"); | ||
if (!elements) | ||
return { x: 0, y: 0 }; | ||
// Find the closest element to the given position | ||
let closestElement = null; | ||
let minDistance = Infinity; | ||
elements.forEach((element) => { | ||
const rect = element.getBoundingClientRect(); | ||
const elementCenterX = rect.left + rect.width / 2; | ||
const elementCenterY = rect.top + rect.height / 2; | ||
// Calculate distance using Pythagorean theorem | ||
const distance = Math.sqrt(Math.pow(elementCenterX - position.x, 2) + | ||
Math.pow(elementCenterY - position.y, 2)); | ||
if (distance < minDistance) { | ||
minDistance = distance; | ||
closestElement = element; | ||
} | ||
else { | ||
// console.error("DOM node okkk not found for the given layerId"); | ||
return null; | ||
} | ||
}); | ||
if (!closestElement) | ||
return { x: 0, y: 0 }; | ||
//@ts-ignore | ||
const rect = closestElement.getBoundingClientRect(); | ||
console.log({ | ||
x: rect.left, | ||
y: rect.top, | ||
}, "rect"); | ||
return { | ||
x: rect.left, | ||
y: rect.top, | ||
}; | ||
} | ||
function getPathOfChildFromParent({ path, artboardId, index, }) { | ||
const parentNode = document === null || document === void 0 ? void 0 : document.querySelector(`[data-bx-path="${path}"]`); | ||
if (!parentNode) | ||
return null; | ||
const children = parentNode.children; | ||
if (children.length === 0) | ||
return null; | ||
// Get target child (last child if no index provided) | ||
const targetIndex = typeof index === "number" ? index : children.length - 1; | ||
// Validate index | ||
if (targetIndex < 0 || targetIndex >= children.length) | ||
return null; | ||
// Get the target child and return its path | ||
const targetChild = children[targetIndex]; | ||
return targetChild.getAttribute("data-bx-path"); | ||
} | ||
function getLayerComputedStyle(args) { | ||
const { layerId } = args; | ||
// Get the DOM node from the fiber node | ||
const domNode = getDomNodeFromPath(layerId); | ||
// console.log(layerId,"layerId",domNode) | ||
if (domNode) { | ||
// Get the computed style of the DOM node | ||
const computedStyle = window.getComputedStyle(domNode); | ||
// console.log(computedStyle, "computedStyle in getLayerComputedStyle",layerId) | ||
return JSON.parse(JSON.stringify(computedStyle)); | ||
} | ||
function getFiberFromDOMNode(domElement) { | ||
if (!domElement) | ||
return null; | ||
const key = Object.keys(domElement).find((key) => key.startsWith("__reactFiber$") || | ||
key.startsWith("__reactContainer$") || | ||
key.startsWith("__reactInternalInstance$")); | ||
return key ? domElement[key] : null; | ||
else { | ||
// console.error("DOM node okkk not found for the given layerId"); | ||
return null; | ||
} | ||
function getRootFiberNode() { | ||
const bodyElement = document.querySelector("body"); | ||
// console.log(bodyElement, 'bodyElement in getRootFiberNode'); | ||
const rootElement = bodyElement?.querySelector("[data-bx-path]"); | ||
if (!rootElement) { | ||
// console.error("No element with data-bx-path attribute found"); | ||
return null; | ||
} | ||
const rootFiber = getFiberFromDOMNode(rootElement); | ||
return rootFiber; | ||
} | ||
function getFiberFromDOMNode(domElement) { | ||
if (!domElement) | ||
return null; | ||
const key = Object.keys(domElement).find((key) => key.startsWith("__reactFiber$") || | ||
key.startsWith("__reactContainer$") || | ||
key.startsWith("__reactInternalInstance$")); | ||
return key ? domElement[key] : null; | ||
} | ||
function getRootFiberNode() { | ||
const bodyElement = document.querySelector("body"); | ||
// console.log(bodyElement, 'bodyElement in getRootFiberNode'); | ||
const rootElement = bodyElement === null || bodyElement === void 0 ? void 0 : bodyElement.querySelector("[data-bx-path]"); | ||
if (!rootElement) { | ||
// console.error("No element with data-bx-path attribute found"); | ||
return null; | ||
} | ||
function isValidElement(object) { | ||
return (typeof object === "object" && | ||
object !== null && | ||
"type" in object && | ||
"props" in object && | ||
"key" in object); | ||
const rootFiber = getFiberFromDOMNode(rootElement); | ||
return rootFiber; | ||
} | ||
function isValidElement(object) { | ||
return (typeof object === "object" && | ||
object !== null && | ||
"type" in object && | ||
"props" in object && | ||
"key" in object); | ||
} | ||
function getDebugInfo(element) { | ||
if (!element || !element._debugInfo) | ||
return null; | ||
return { | ||
name: element._debugInfo.name, | ||
env: element._debugInfo.env, | ||
}; | ||
} | ||
function getFiberNodeInOwner(ownerFiber, targetPath, reactElement) { | ||
if (!ownerFiber || !targetPath) { | ||
return null; | ||
} | ||
function getDebugInfo(element) { | ||
if (!element || !element._debugInfo) | ||
function traverseFiber(fiber) { | ||
if (!fiber) { | ||
return null; | ||
return { | ||
name: element._debugInfo.name, | ||
env: element._debugInfo.env, | ||
}; | ||
} | ||
function getFiberNodeInOwner(ownerFiber, targetPath, reactElement) { | ||
if (!ownerFiber || !targetPath) { | ||
return null; | ||
} | ||
function traverseFiber(fiber) { | ||
if (!fiber) { | ||
return null; | ||
} | ||
// Check if the current fiber node matches the target path | ||
if (fiber?.memoizedProps && | ||
fiber?.memoizedProps["data-bx-path"] === targetPath) { | ||
return fiber; | ||
} | ||
// Check child | ||
if (fiber.child) { | ||
const childResult = traverseFiber(fiber.child); | ||
if (childResult) | ||
return childResult; | ||
} | ||
// Check sibling | ||
if (fiber.sibling) { | ||
const siblingResult = traverseFiber(fiber.sibling); | ||
if (siblingResult) | ||
return siblingResult; | ||
} | ||
return null; | ||
// Check if the current fiber node matches the target path | ||
if ((fiber === null || fiber === void 0 ? void 0 : fiber.memoizedProps) && | ||
(fiber === null || fiber === void 0 ? void 0 : fiber.memoizedProps["data-bx-path"]) === targetPath) { | ||
return fiber; | ||
} | ||
return traverseFiber(ownerFiber); | ||
} | ||
function getComponentName(child) { | ||
const displayName = child?.displayName || | ||
child?.type?.displayName || | ||
child?.type?.name || | ||
(typeof child?.type === "string" ? child?.type : "AnonymousComponent"); | ||
return displayName; | ||
} | ||
function prepareChildrenTree(children, withFiber = false) { | ||
function processChild(child) { | ||
const fiber = getFiberNodeInOwner(child?._owner, child?.props?.["data-bx-path"], child); | ||
if (!fiber && !isValidElement(child)) { | ||
return null; | ||
} | ||
let componentTree = buildReactFiberTree(fiber, withFiber); | ||
const childElement = { | ||
displayName: getComponentName(child), | ||
path: child.props?.["data-bx-path"] || null, | ||
fiber: withFiber ? fiber : null, | ||
componentTree: componentTree, | ||
debugInfo: getDebugInfo(child), | ||
children: [], | ||
}; | ||
// Only process children if they exist and we haven't processed this path before | ||
if (child.props?.children) { | ||
if (Array.isArray(child.props.children)) { | ||
childElement.children = child.props.children | ||
.map((c) => processChild(c)) | ||
.filter(Boolean); | ||
} | ||
else { | ||
const processed = processChild(child.props.children); | ||
if (processed) { | ||
childElement.children = [processed]; | ||
} | ||
} | ||
} | ||
// Filter out duplicate children that exist in component tree | ||
if (isComponent(fiber) && | ||
childElement?.children && | ||
componentTree?.children) { | ||
childElement.children = childElement.children.filter((child) => !componentTree.children.some((treeChild) => treeChild.path === child.path)); | ||
} | ||
return childElement; | ||
// Check child | ||
if (fiber.child) { | ||
const childResult = traverseFiber(fiber.child); | ||
if (childResult) | ||
return childResult; | ||
} | ||
if (Array.isArray(children)) { | ||
return children.map(processChild).filter(Boolean); | ||
// Check sibling | ||
if (fiber.sibling) { | ||
const siblingResult = traverseFiber(fiber.sibling); | ||
if (siblingResult) | ||
return siblingResult; | ||
} | ||
else if (isValidElement(children)) { | ||
const processedChild = processChild(children); | ||
return processedChild ? [processedChild] : []; | ||
} | ||
return []; | ||
return null; | ||
} | ||
function isComponent(fiber) { | ||
const propsChildren = fiber?.memoizedProps?.children; | ||
if (!propsChildren && !fiber?.child) { | ||
return false; // If there are no children in props, we assume it's a component | ||
return traverseFiber(ownerFiber); | ||
} | ||
function getComponentName(child) { | ||
var _a, _b; | ||
const displayName = (child === null || child === void 0 ? void 0 : child.displayName) || | ||
((_a = child === null || child === void 0 ? void 0 : child.type) === null || _a === void 0 ? void 0 : _a.displayName) || | ||
((_b = child === null || child === void 0 ? void 0 : child.type) === null || _b === void 0 ? void 0 : _b.name) || | ||
(typeof (child === null || child === void 0 ? void 0 : child.type) === "string" ? child === null || child === void 0 ? void 0 : child.type : "AnonymousComponent"); | ||
return displayName; | ||
} | ||
function prepareChildrenTree(children, withFiber = false) { | ||
function processChild(child) { | ||
var _a, _b, _c; | ||
const fiber = getFiberNodeInOwner(child === null || child === void 0 ? void 0 : child._owner, (_a = child === null || child === void 0 ? void 0 : child.props) === null || _a === void 0 ? void 0 : _a["data-bx-path"], child); | ||
if (!fiber && !isValidElement(child)) { | ||
return null; | ||
} | ||
if (!propsChildren) { | ||
return true; // If there are no children in props, we assume it's a component | ||
} | ||
let fiberChild = fiber.child; | ||
const fiberChildren = []; | ||
// Collect all immediate children of the fiber | ||
while (fiberChild) { | ||
fiberChildren.push(fiberChild); | ||
fiberChild = fiberChild.sibling; | ||
} | ||
// Helper function to compare a React element with a fiber node | ||
const compareElementToFiber = (element, fiberNode) => { | ||
if (typeof element === "string") { | ||
return fiberNode?.memoizedProps === element; | ||
} | ||
return (element?.props?.["data-bx-path"] === | ||
fiberNode?.memoizedProps?.["data-bx-path"]); | ||
let componentTree = buildReactFiberTree(fiber, withFiber); | ||
const childElement = { | ||
displayName: getComponentName(child), | ||
path: ((_b = child.props) === null || _b === void 0 ? void 0 : _b["data-bx-path"]) || null, | ||
fiber: withFiber ? fiber : null, | ||
componentTree: componentTree, | ||
debugInfo: getDebugInfo(child), | ||
children: [], | ||
}; | ||
// Check if propsChildren is an array or a single child | ||
if (Array.isArray(propsChildren)) { | ||
if (propsChildren.length !== fiberChildren.length) { | ||
return true; // Different number of children, so it's a component | ||
// Only process children if they exist and we haven't processed this path before | ||
if ((_c = child.props) === null || _c === void 0 ? void 0 : _c.children) { | ||
if (Array.isArray(child.props.children)) { | ||
childElement.children = child.props.children | ||
.map((c) => processChild(c)) | ||
.filter(Boolean); | ||
} | ||
// Check if all children in props match the fiber children | ||
return !propsChildren.every((propsChild, index) => compareElementToFiber(propsChild, fiberChildren[index])); | ||
else { | ||
const processed = processChild(child.props.children); | ||
if (processed) { | ||
childElement.children = [processed]; | ||
} | ||
} | ||
} | ||
else { | ||
// Single child case | ||
return (fiberChildren.length !== 1 || | ||
!compareElementToFiber(propsChildren, fiberChildren[0])); | ||
// Filter out duplicate children that exist in component tree | ||
if (isComponent(fiber) && | ||
(childElement === null || childElement === void 0 ? void 0 : childElement.children) && | ||
(componentTree === null || componentTree === void 0 ? void 0 : componentTree.children)) { | ||
childElement.children = childElement.children.filter((child) => !componentTree.children.some((treeChild) => treeChild.path === child.path)); | ||
} | ||
return childElement; | ||
} | ||
function fiberToChildrenArray(fiber, withFiber = false) { | ||
let children = []; | ||
let componentTree = null; | ||
let child = fiber.child; | ||
while (child) { | ||
const fiberChildren = fiberToChildrenArray(child, withFiber); | ||
const childChildren = fiberChildren.children; | ||
// Check if child.memoizedProps.children is not present in childChildren and then push | ||
if (child.memoizedProps?.["children"]) { | ||
const memoizedChildren = Array.isArray(child.memoizedProps["children"]) | ||
? child.memoizedProps["children"] | ||
: [child.memoizedProps["children"]]; | ||
memoizedChildren.forEach((memoizedChild) => { | ||
if (!childChildren.some((existingChild) => existingChild.path === memoizedChild?.props?.["data-bx-path"])) { | ||
childChildren.push({ | ||
displayName: getComponentName(memoizedChild), | ||
debugInfo: getDebugInfo(memoizedChild?._owner), | ||
path: memoizedChild?.props?.["data-bx-path"] || null, | ||
props: { ...memoizedChild?.props }, | ||
_owner: memoizedChild?._owner, | ||
}); | ||
} | ||
}); | ||
} | ||
const element = { | ||
displayName: getComponentName(child), | ||
debugInfo: getDebugInfo(child), | ||
path: child.memoizedProps?.["data-bx-path"] || null, | ||
props: { ...child.memoizedProps, children: childChildren }, | ||
componentTree: fiberChildren.componentTree, | ||
_owner: child, | ||
}; | ||
children.push(element); | ||
child = child.sibling; | ||
} | ||
return { children, componentTree }; | ||
if (Array.isArray(children)) { | ||
return children.map(processChild).filter(Boolean); | ||
} | ||
function buildReactFiberTree(fiber, withFiber = false) { | ||
if (!fiber) { | ||
return null; | ||
else if (isValidElement(children)) { | ||
const processedChild = processChild(children); | ||
return processedChild ? [processedChild] : []; | ||
} | ||
return []; | ||
} | ||
function isComponent(fiber) { | ||
var _a; | ||
const propsChildren = (_a = fiber === null || fiber === void 0 ? void 0 : fiber.memoizedProps) === null || _a === void 0 ? void 0 : _a.children; | ||
if (!propsChildren && !(fiber === null || fiber === void 0 ? void 0 : fiber.child)) { | ||
return false; // If there are no children in props, we assume it's a component | ||
} | ||
if (!propsChildren) { | ||
return true; // If there are no children in props, we assume it's a component | ||
} | ||
let fiberChild = fiber.child; | ||
const fiberChildren = []; | ||
// Collect all immediate children of the fiber | ||
while (fiberChild) { | ||
fiberChildren.push(fiberChild); | ||
fiberChild = fiberChild.sibling; | ||
} | ||
// Helper function to compare a React element with a fiber node | ||
const compareElementToFiber = (element, fiberNode) => { | ||
var _a, _b; | ||
if (typeof element === "string") { | ||
return (fiberNode === null || fiberNode === void 0 ? void 0 : fiberNode.memoizedProps) === element; | ||
} | ||
if (!isComponent(fiber)) { | ||
return null; | ||
return (((_a = element === null || element === void 0 ? void 0 : element.props) === null || _a === void 0 ? void 0 : _a["data-bx-path"]) === | ||
((_b = fiberNode === null || fiberNode === void 0 ? void 0 : fiberNode.memoizedProps) === null || _b === void 0 ? void 0 : _b["data-bx-path"])); | ||
}; | ||
// Check if propsChildren is an array or a single child | ||
if (Array.isArray(propsChildren)) { | ||
if (propsChildren.length !== fiberChildren.length) { | ||
return true; // Different number of children, so it's a component | ||
} | ||
const element = { | ||
displayName: "Component-" + getComponentName(fiber), | ||
debugInfo: getDebugInfo(fiber), | ||
path: fiber.memoizedProps?.["data-bx-path"] || null, | ||
fiber: withFiber ? fiber : null, | ||
children: [], | ||
componentTree: null, | ||
props: {}, | ||
}; | ||
const fiberChildren = fiberToChildrenArray(fiber, withFiber); | ||
element.children = prepareChildrenTree(fiberChildren.children, withFiber); | ||
return element; | ||
// Check if all children in props match the fiber children | ||
return !propsChildren.every((propsChild, index) => compareElementToFiber(propsChild, fiberChildren[index])); | ||
} | ||
function buildReactElementTree(fiber, withFiber = false) { | ||
if (!fiber) { | ||
return null; | ||
else { | ||
// Single child case | ||
return (fiberChildren.length !== 1 || | ||
!compareElementToFiber(propsChildren, fiberChildren[0])); | ||
} | ||
} | ||
function fiberToChildrenArray(fiber, withFiber = false) { | ||
var _a, _b; | ||
let children = []; | ||
let componentTree = null; | ||
let child = fiber.child; | ||
while (child) { | ||
const fiberChildren = fiberToChildrenArray(child, withFiber); | ||
const childChildren = fiberChildren.children; | ||
// Check if child.memoizedProps.children is not present in childChildren and then push | ||
if ((_a = child.memoizedProps) === null || _a === void 0 ? void 0 : _a["children"]) { | ||
const memoizedChildren = Array.isArray(child.memoizedProps["children"]) | ||
? child.memoizedProps["children"] | ||
: [child.memoizedProps["children"]]; | ||
memoizedChildren.forEach((memoizedChild) => { | ||
var _a; | ||
if (!childChildren.some((existingChild) => { var _a; return existingChild.path === ((_a = memoizedChild === null || memoizedChild === void 0 ? void 0 : memoizedChild.props) === null || _a === void 0 ? void 0 : _a["data-bx-path"]); })) { | ||
childChildren.push({ | ||
displayName: getComponentName(memoizedChild), | ||
debugInfo: getDebugInfo(memoizedChild === null || memoizedChild === void 0 ? void 0 : memoizedChild._owner), | ||
path: ((_a = memoizedChild === null || memoizedChild === void 0 ? void 0 : memoizedChild.props) === null || _a === void 0 ? void 0 : _a["data-bx-path"]) || null, | ||
props: Object.assign({}, memoizedChild === null || memoizedChild === void 0 ? void 0 : memoizedChild.props), | ||
_owner: memoizedChild === null || memoizedChild === void 0 ? void 0 : memoizedChild._owner, | ||
}); | ||
} | ||
}); | ||
} | ||
// Check if this fiber node has a data-bx-path | ||
const hasDataPath = fiber.memoizedProps && | ||
fiber.memoizedProps["data-bx-path"] && | ||
fiber.memoizedProps["data-bx-path"]?.includes("node_modules") === false; | ||
// If this node doesn't have a data-bx-path, check its children | ||
if (!hasDataPath) { | ||
const childElement = fiber.child | ||
? buildReactElementTree(fiber.child, withFiber) | ||
: null; | ||
if (childElement) { | ||
return childElement; | ||
} | ||
// If no child has a data-bx-path, check the next sibling | ||
return fiber.sibling | ||
? buildReactElementTree(fiber.sibling, withFiber) | ||
: null; | ||
} | ||
// If we reach here, this node has a data-bx-path, so we build the element | ||
const element = { | ||
displayName: getComponentName(fiber), | ||
debugInfo: getDebugInfo(fiber), | ||
path: fiber.memoizedProps["data-bx-path"], | ||
fiber: withFiber ? fiber : null, | ||
componentTree: buildReactFiberTree(fiber, withFiber), | ||
children: [], | ||
props: {}, | ||
displayName: getComponentName(child), | ||
debugInfo: getDebugInfo(child), | ||
path: ((_b = child.memoizedProps) === null || _b === void 0 ? void 0 : _b["data-bx-path"]) || null, | ||
props: Object.assign(Object.assign({}, child.memoizedProps), { children: childChildren }), | ||
componentTree: fiberChildren.componentTree, | ||
_owner: child, | ||
}; | ||
// Add relevant props | ||
for (const [key, value] of Object.entries(fiber.memoizedProps)) { | ||
if (key !== "children" && | ||
key !== "data-bx-path" && | ||
typeof value !== "function") { | ||
element.props[key] = value; | ||
} | ||
children.push(element); | ||
child = child.sibling; | ||
} | ||
return { children, componentTree }; | ||
} | ||
function buildReactFiberTree(fiber, withFiber = false) { | ||
var _a; | ||
if (!fiber) { | ||
return null; | ||
} | ||
if (!isComponent(fiber)) { | ||
return null; | ||
} | ||
const element = { | ||
displayName: "Component-" + getComponentName(fiber), | ||
debugInfo: getDebugInfo(fiber), | ||
path: ((_a = fiber.memoizedProps) === null || _a === void 0 ? void 0 : _a["data-bx-path"]) || null, | ||
fiber: withFiber ? fiber : null, | ||
children: [], | ||
componentTree: null, | ||
props: {}, | ||
}; | ||
const fiberChildren = fiberToChildrenArray(fiber, withFiber); | ||
element.children = prepareChildrenTree(fiberChildren.children, withFiber); | ||
return element; | ||
} | ||
function buildReactElementTree(fiber, withFiber = false) { | ||
var _a; | ||
if (!fiber) { | ||
return null; | ||
} | ||
// Check if this fiber node has a data-bx-path | ||
const hasDataPath = fiber.memoizedProps && | ||
fiber.memoizedProps["data-bx-path"] && | ||
((_a = fiber.memoizedProps["data-bx-path"]) === null || _a === void 0 ? void 0 : _a.includes("node_modules")) === false; | ||
// If this node doesn't have a data-bx-path, check its children | ||
if (!hasDataPath) { | ||
const childElement = fiber.child | ||
? buildReactElementTree(fiber.child, withFiber) | ||
: null; | ||
if (childElement) { | ||
return childElement; | ||
} | ||
// Process children from memoizedProps | ||
const children = fiber.memoizedProps.children; | ||
if (children) { | ||
element.children = prepareChildrenTree(children, withFiber); | ||
// If no child has a data-bx-path, check the next sibling | ||
return fiber.sibling | ||
? buildReactElementTree(fiber.sibling, withFiber) | ||
: null; | ||
} | ||
// If we reach here, this node has a data-bx-path, so we build the element | ||
const element = { | ||
displayName: getComponentName(fiber), | ||
debugInfo: getDebugInfo(fiber), | ||
path: fiber.memoizedProps["data-bx-path"], | ||
fiber: withFiber ? fiber : null, | ||
componentTree: buildReactFiberTree(fiber, withFiber), | ||
children: [], | ||
props: {}, | ||
}; | ||
// Add relevant props | ||
for (const [key, value] of Object.entries(fiber.memoizedProps)) { | ||
if (key !== "children" && | ||
key !== "data-bx-path" && | ||
typeof value !== "function") { | ||
element.props[key] = value; | ||
} | ||
return element; | ||
} | ||
function getFibreNodeFromPath(path) { | ||
const rootFiber = getRootFiberNode(); | ||
const elementTree = buildReactElementTree(rootFiber, true); | ||
// Helper function to traverse the fiber tree | ||
function traverseFiber(element) { | ||
if (element?.path === path && element?.fiber) { | ||
return element.fiber; | ||
} | ||
if (element?.children) { | ||
if (Array.isArray(element.children)) { | ||
for (let child of element.children) { | ||
const result = traverseFiber(child); | ||
if (result) | ||
return result; | ||
} | ||
// Process children from memoizedProps | ||
const children = fiber.memoizedProps.children; | ||
if (children) { | ||
element.children = prepareChildrenTree(children, withFiber); | ||
} | ||
return element; | ||
} | ||
function getFibreNodeFromPath(path) { | ||
const rootFiber = getRootFiberNode(); | ||
const elementTree = buildReactElementTree(rootFiber, true); | ||
// Helper function to traverse the fiber tree | ||
function traverseFiber(element) { | ||
if ((element === null || element === void 0 ? void 0 : element.path) === path && (element === null || element === void 0 ? void 0 : element.fiber)) { | ||
return element.fiber; | ||
} | ||
if (element === null || element === void 0 ? void 0 : element.children) { | ||
if (Array.isArray(element.children)) { | ||
for (let child of element.children) { | ||
const result = traverseFiber(child); | ||
if (result) | ||
return result; | ||
} | ||
else if (typeof element.children === "object") { | ||
return traverseFiber(element.children); | ||
} | ||
} | ||
// Traverse componentTree | ||
if (element?.componentTree) { | ||
const result = traverseFiber(element.componentTree); | ||
if (result) | ||
return result; | ||
else if (typeof element.children === "object") { | ||
return traverseFiber(element.children); | ||
} | ||
return null; | ||
} | ||
return traverseFiber(elementTree); | ||
} | ||
function getContainerData(fiberNode) { | ||
let parentFiberNode = null; | ||
if (fiberNode) | ||
parentFiberNode = fiberNode.return; | ||
if (!parentFiberNode) | ||
return null; | ||
const parentElement = getDomNodeFromFiber(parentFiberNode); | ||
if (!parentElement) | ||
return null; | ||
const parentRect = parentElement.getBoundingClientRect(); | ||
const parentStyle = window.getComputedStyle(parentElement); | ||
const flexDirection = parentStyle.flexDirection; | ||
const containerPadding = { | ||
top: parseFloat(parentStyle.paddingTop), | ||
right: parseFloat(parentStyle.paddingRight), | ||
bottom: parseFloat(parentStyle.paddingBottom), | ||
left: parseFloat(parentStyle.paddingLeft), | ||
}; | ||
const containerData = { | ||
x: parentRect.left, | ||
y: parentRect.top, | ||
width: parentRect.width, | ||
height: parentRect.height, | ||
flexDirection: flexDirection, | ||
padding: containerPadding, | ||
contentBox: { | ||
x: parentRect.left + containerPadding.left, | ||
y: parentRect.top + containerPadding.top, | ||
width: parentRect.width - (containerPadding.left + containerPadding.right), | ||
height: parentRect.height - | ||
(containerPadding.top + containerPadding.bottom), | ||
}, | ||
children: [], | ||
}; | ||
let childFiberNode = parentFiberNode.child; | ||
while (childFiberNode) { | ||
const childElement = getDomNodeFromFiber(childFiberNode); | ||
if (childElement) { | ||
const childRect = childElement.getBoundingClientRect(); | ||
containerData.children.push({ | ||
path: childFiberNode.memoizedProps?.["data-bx-path"] || "", | ||
width: childRect.width, | ||
height: childRect.height, | ||
x: childRect.left - parentRect.left, | ||
y: childRect.top - parentRect.top, | ||
}); | ||
} | ||
childFiberNode = childFiberNode.sibling; | ||
// Traverse componentTree | ||
if (element === null || element === void 0 ? void 0 : element.componentTree) { | ||
const result = traverseFiber(element.componentTree); | ||
if (result) | ||
return result; | ||
} | ||
return containerData; | ||
return null; | ||
} | ||
if (typeof window !== "undefined") { | ||
window.addEventListener("message", handleMessage); | ||
// Function to handle navigation changes | ||
function handleNavigation() { | ||
pollForRootFiberNode(); | ||
sendMessageToParent({ | ||
type: "navigation", | ||
url: window.location.href, | ||
return traverseFiber(elementTree); | ||
} | ||
function getContainerData(fiberNode) { | ||
var _a; | ||
let parentFiberNode = null; | ||
if (fiberNode) | ||
parentFiberNode = fiberNode.return; | ||
if (!parentFiberNode) | ||
return null; | ||
const parentElement = getDomNodeFromFiber(parentFiberNode); | ||
if (!parentElement) | ||
return null; | ||
const parentRect = parentElement.getBoundingClientRect(); | ||
const parentStyle = window.getComputedStyle(parentElement); | ||
const flexDirection = parentStyle.flexDirection; | ||
const containerPadding = { | ||
top: parseFloat(parentStyle.paddingTop), | ||
right: parseFloat(parentStyle.paddingRight), | ||
bottom: parseFloat(parentStyle.paddingBottom), | ||
left: parseFloat(parentStyle.paddingLeft), | ||
}; | ||
const containerData = { | ||
x: parentRect.left, | ||
y: parentRect.top, | ||
width: parentRect.width, | ||
height: parentRect.height, | ||
flexDirection: flexDirection, | ||
padding: containerPadding, | ||
contentBox: { | ||
x: parentRect.left + containerPadding.left, | ||
y: parentRect.top + containerPadding.top, | ||
width: parentRect.width - (containerPadding.left + containerPadding.right), | ||
height: parentRect.height - | ||
(containerPadding.top + containerPadding.bottom), | ||
}, | ||
children: [], | ||
}; | ||
let childFiberNode = parentFiberNode.child; | ||
while (childFiberNode) { | ||
const childElement = getDomNodeFromFiber(childFiberNode); | ||
if (childElement) { | ||
const childRect = childElement.getBoundingClientRect(); | ||
containerData.children.push({ | ||
path: ((_a = childFiberNode.memoizedProps) === null || _a === void 0 ? void 0 : _a["data-bx-path"]) || "", | ||
width: childRect.width, | ||
height: childRect.height, | ||
x: childRect.left - parentRect.left, | ||
y: childRect.top - parentRect.top, | ||
}); | ||
} | ||
window.addEventListener("load", handleWindowLoad); | ||
// Listen for popstate events (back/forward buttons) | ||
window.addEventListener("popstate", handleNavigation); | ||
// Intercept pushState and replaceState | ||
const originalPushState = history.pushState; | ||
const originalReplaceState = history.replaceState; | ||
history.pushState = function (data, unused, url) { | ||
originalPushState.call(this, data, unused, url); | ||
handleNavigation(); | ||
}; | ||
history.replaceState = function (data, unused, url) { | ||
originalReplaceState.call(this, data, unused, url); | ||
handleNavigation(); | ||
}; | ||
childFiberNode = childFiberNode.sibling; | ||
} | ||
return containerData; | ||
} | ||
if (typeof window !== "undefined") { | ||
window.addEventListener("message", handleMessage); | ||
// Function to handle navigation changes | ||
function handleNavigation() { | ||
pollForRootFiberNode(); | ||
sendMessageToParent({ | ||
type: "builderxToolsLoaded", | ||
value: true, | ||
type: "navigation", | ||
url: window.location.href, | ||
}); | ||
// Start polling for the React root fiber node | ||
pollForRootFiberNode(); | ||
// Create and configure the MutationObserver | ||
const observer = new MutationObserver(() => { | ||
//@ts-ignore | ||
if (!window["layerResizing"]) { | ||
} | ||
window.addEventListener("load", handleWindowLoad); | ||
// Listen for popstate events (back/forward buttons) | ||
window.addEventListener("popstate", handleNavigation); | ||
// Intercept pushState and replaceState | ||
const originalPushState = history.pushState; | ||
const originalReplaceState = history.replaceState; | ||
history.pushState = function (data, unused, url) { | ||
originalPushState.call(this, data, unused, url); | ||
handleNavigation(); | ||
}; | ||
history.replaceState = function (data, unused, url) { | ||
originalReplaceState.call(this, data, unused, url); | ||
handleNavigation(); | ||
}; | ||
sendMessageToParent({ | ||
type: "builderxToolsLoaded", | ||
value: true, | ||
}); | ||
// Start polling for the React root fiber node | ||
pollForRootFiberNode(); | ||
// Create and configure the MutationObserver | ||
const observer = new MutationObserver(() => { | ||
//@ts-ignore | ||
if (!window["layerResizing"]) { | ||
setTimeout(() => { | ||
setTimeout(() => { | ||
setTimeout(() => { | ||
pollForRootFiberNode(); | ||
}, 2000); | ||
}, 500); | ||
} | ||
}); | ||
// Function to start observing | ||
function startObserving() { | ||
// Target node to observe (the first div inside body) | ||
const targetNode = document.querySelector("html"); | ||
const config = { | ||
// attributes: true, | ||
childList: true, | ||
subtree: true, | ||
// attributes: true, // Observe attribute changes | ||
}; | ||
if (targetNode) { | ||
observer.observe(targetNode, config); | ||
// console.log('MutationObserver started'); | ||
} | ||
else { | ||
setTimeout(startObserving); // Retry after 1 second | ||
} | ||
pollForRootFiberNode(); | ||
}, 2000); | ||
}, 500); | ||
} | ||
// Start observing when the DOM is ready | ||
if (document.readyState === "loading") { | ||
document.addEventListener("DOMContentLoaded", startObserving); | ||
}); | ||
// Function to start observing | ||
function startObserving() { | ||
// Target node to observe (the first div inside body) | ||
const targetNode = document.querySelector("html"); | ||
const config = { | ||
// attributes: true, | ||
childList: true, | ||
subtree: true, | ||
// attributes: true, // Observe attribute changes | ||
}; | ||
if (targetNode) { | ||
observer.observe(targetNode, config); | ||
// console.log('MutationObserver started'); | ||
} | ||
else { | ||
startObserving(); | ||
setTimeout(startObserving); // Retry after 1 second | ||
} | ||
} | ||
console.log("BuilderX Tools initialized v2"); | ||
//@ts-ignore | ||
// Start observing when the DOM is ready | ||
if (document.readyState === "loading") { | ||
document.addEventListener("DOMContentLoaded", startObserving); | ||
} | ||
else { | ||
startObserving(); | ||
} | ||
} | ||
else if (typeof window !== "undefined" && window.isInitialized) { | ||
console.log("BuilderX Tools already initialized, skipping re-initialization"); | ||
console.log("BuilderX Tools initialized v2"); | ||
//@ts-ignore | ||
} | ||
else if (typeof window !== "undefined" && window.isInitialized) { | ||
console.log("BuilderX Tools already initialized, skipping re-initialization"); | ||
} | ||
// Function to get DOM update actions | ||
function getDOMUpdateActions() { | ||
if (typeof window !== "undefined") { | ||
window.domUpdateActions = window.domUpdateActions || []; | ||
return window.domUpdateActions; | ||
} | ||
// Function to get DOM update actions | ||
function getDOMUpdateActions() { | ||
if (typeof window !== "undefined") { | ||
window.domUpdateActions = window.domUpdateActions || []; | ||
return window.domUpdateActions; | ||
} | ||
return []; | ||
return []; | ||
} | ||
// Function to update DOM until HMR | ||
function updateDOMUntilHMR(DOM, newStyleObject) { | ||
const originalStyles = {}; | ||
const updateAction = { | ||
DOM, | ||
originalStyles: {}, | ||
newStyles: {}, | ||
}; | ||
for (const [property, value] of Object.entries(newStyleObject)) { | ||
originalStyles[property] = DOM.style.getPropertyValue(property); | ||
DOM.style.setProperty(property, `${value}`); | ||
updateAction.originalStyles[property] = originalStyles[property]; | ||
updateAction.newStyles[property] = value; | ||
} | ||
// Function to update DOM until HMR | ||
function updateDOMUntilHMR(DOM, newStyleObject) { | ||
const originalStyles = {}; | ||
const updateAction = { | ||
DOM, | ||
originalStyles: {}, | ||
newStyles: {}, | ||
}; | ||
for (const [property, value] of Object.entries(newStyleObject)) { | ||
originalStyles[property] = DOM.style.getPropertyValue(property); | ||
DOM.style.setProperty(property, `${value}`); | ||
updateAction.originalStyles[property] = originalStyles[property]; | ||
updateAction.newStyles[property] = value; | ||
} | ||
const domUpdateActions = getDOMUpdateActions(); | ||
domUpdateActions.push(updateAction); | ||
} | ||
// Function to revert DOM changes | ||
function revertDOMChanges() { | ||
const actions = getDOMUpdateActions(); | ||
actions.forEach((action) => { | ||
const { DOM, originalStyles } = action; | ||
if (DOM && document.contains(DOM)) { | ||
for (const [property, value] of Object.entries(originalStyles)) { | ||
if (value) { | ||
DOM.style.setProperty(property, value); | ||
} | ||
else { | ||
DOM.style.removeProperty(property); | ||
} | ||
const domUpdateActions = getDOMUpdateActions(); | ||
domUpdateActions.push(updateAction); | ||
} | ||
// Function to revert DOM changes | ||
function revertDOMChanges() { | ||
const actions = getDOMUpdateActions(); | ||
actions.forEach((action) => { | ||
const { DOM, originalStyles } = action; | ||
if (DOM && document.contains(DOM)) { | ||
for (const [property, value] of Object.entries(originalStyles)) { | ||
if (value) { | ||
DOM.style.setProperty(property, value); | ||
} | ||
else { | ||
DOM.style.removeProperty(property); | ||
} | ||
} | ||
} | ||
}); | ||
actions.length = 0; | ||
} | ||
// test | ||
// Function to detect hot module reload | ||
function detectHotModuleReload() { | ||
function addStatusHandler(hmr) { | ||
hmr.addStatusHandler((status) => { | ||
if (status === "idle") { | ||
// Revert DOM changes when HMR update is completed | ||
revertDOMChanges(); | ||
} | ||
}); | ||
actions.length = 0; | ||
} | ||
// test | ||
// Function to detect hot module reload | ||
function detectHotModuleReload() { | ||
function addStatusHandler(hmr) { | ||
hmr.addStatusHandler((status) => { | ||
if (status === "idle") { | ||
// Revert DOM changes when HMR update is completed | ||
revertDOMChanges(); | ||
} | ||
}); | ||
} | ||
// if (typeof module !== 'undefined' && module.hot) { | ||
// // Next.js and some other environments | ||
// addStatusHandler(module.hot); | ||
// module.hot.accept(undefined, () => { | ||
// // Module reloaded | ||
// revertDOMChanges(); | ||
// }); | ||
// return true; | ||
// } else if (import.meta && import.meta.hot) { | ||
// // Vite and some other environments | ||
// addStatusHandler(import.meta.hot); | ||
// return true; | ||
// } else if ( | ||
// typeof __webpack_module__ !== 'undefined' && | ||
// __webpack_module__.hot | ||
// ) { | ||
// // Webpack (used by Create React App and others) | ||
// addStatusHandler(__webpack_module__.hot); | ||
// return true; | ||
// } else if ( | ||
// typeof process !== 'undefined' && | ||
// process.env && | ||
// process.env.NODE_ENV === 'development' | ||
// ) { | ||
// // Generic development environment check (including Expo) | ||
// // Note: We can't add a specific listener here as there's no standard HMR API for this case | ||
// console.warn( | ||
// 'HMR not detected. DOM changes will not be automatically reverted.' | ||
// ); | ||
// return true; | ||
// } | ||
return false; | ||
} | ||
console.log("Bridge initialized"); | ||
// Add your bridge initialization logic here | ||
// if (typeof module !== 'undefined' && module.hot) { | ||
// // Next.js and some other environments | ||
// addStatusHandler(module.hot); | ||
// module.hot.accept(undefined, () => { | ||
// // Module reloaded | ||
// revertDOMChanges(); | ||
// }); | ||
// return true; | ||
// } else if (import.meta && import.meta.hot) { | ||
// // Vite and some other environments | ||
// addStatusHandler(import.meta.hot); | ||
// return true; | ||
// } else if ( | ||
// typeof __webpack_module__ !== 'undefined' && | ||
// __webpack_module__.hot | ||
// ) { | ||
// // Webpack (used by Create React App and others) | ||
// addStatusHandler(__webpack_module__.hot); | ||
// return true; | ||
// } else if ( | ||
// typeof process !== 'undefined' && | ||
// process.env && | ||
// process.env.NODE_ENV === 'development' | ||
// ) { | ||
// // Generic development environment check (including Expo) | ||
// // Note: We can't add a specific listener here as there's no standard HMR API for this case | ||
// console.warn( | ||
// 'HMR not detected. DOM changes will not be automatically reverted.' | ||
// ); | ||
// return true; | ||
// } | ||
return false; | ||
} | ||
exports.initBridge = initBridge; | ||
}); | ||
console.log("Bridge initialized"); | ||
// Add your bridge initialization logic here | ||
} | ||
//# sourceMappingURL=initBridge.js.map |
@@ -1,13 +0,3 @@ | ||
(function (factory) { | ||
if (typeof module === "object" && typeof module.exports === "object") { | ||
var v = factory(require, exports); | ||
if (v !== undefined) module.exports = v; | ||
} | ||
else if (typeof define === "function" && define.amd) { | ||
define(["require", "exports"], factory); | ||
} | ||
})(function (require, exports) { | ||
"use strict"; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
}); | ||
export {}; | ||
// Add other shared types as needed | ||
//# sourceMappingURL=types.js.map |
{ | ||
"name": "@builderx/bridge", | ||
"version": "1.0.4", | ||
"version": "1.0.5", | ||
"main": "dist/index.js", | ||
"types": "dist/index.d.ts", | ||
"type": "module", | ||
"files": [ | ||
@@ -8,0 +7,0 @@ "dist" |
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Major refactor
Supply chain riskPackage has recently undergone a major refactor. It may be unstable or indicate significant internal changes. Use caution when updating to versions that include significant changes.
Found 1 instance in 1 package
0
70584
16
958
No