updated folder structure

This commit is contained in:
Nalvazhuthi
2025-04-11 18:08:47 +05:30
50 changed files with 4346 additions and 4216 deletions

View File

@@ -50,26 +50,39 @@ const ZoneGroup: React.FC = () => {
new THREE.ShaderMaterial({
side: THREE.DoubleSide,
vertexShader: `
varying vec2 vUv;
void main(){
gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);
varying vec2 vUv;
void main() {
vUv = uv;
}
gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);
}
`,
fragmentShader: `
varying vec2 vUv;
uniform vec3 uColor;
void main(){
varying vec2 vUv;
uniform vec3 uColor;
// Simple function for stripes
float stripePattern(vec2 uv, float thickness) {
return step(0.5, abs(sin((uv.x + uv.y) * 40.0)) - thickness);
}
void main() {
float alpha = 1.0 - vUv.y;
gl_FragColor = vec4(uColor, alpha);
}
// Stripe pattern
float stripes = stripePattern(vUv, 0.3);
vec3 color = uColor * 1.5; // brighten the color
gl_FragColor = vec4(color, alpha * stripes);
}
`,
uniforms: {
uColor: { value: new THREE.Color(CONSTANTS.zoneConfig.color) },
},
transparent: true,
depthWrite: false,
}), []);
}),
[]
);
useEffect(() => {
const fetchZones = async () => {

View File

@@ -10,190 +10,227 @@ import { useNavigate } from "react-router-dom";
import { Html } from "@react-three/drei";
import CollabUserIcon from "./collabUserIcon";
import { getAvatarColor } from "./users/functions/getAvatarColor";
import useModuleStore from "../../store/useModuleStore";
const CamModelsGroup = () => {
const navigate = useNavigate();
const groupRef = useRef<THREE.Group>(null);
const email = localStorage.getItem("email");
const { activeUsers, setActiveUsers } = useActiveUsers();
const { socket } = useSocketStore();
const navigate = useNavigate();
const groupRef = useRef<THREE.Group>(null);
const email = localStorage.getItem("email");
const { setActiveUsers } = useActiveUsers();
const { socket } = useSocketStore();
const { activeModule } = useModuleStore();
const loader = new GLTFLoader();
const dracoLoader = new DRACOLoader();
dracoLoader.setDecoderPath("three/examples/jsm/libs/draco/gltf/");
loader.setDRACOLoader(dracoLoader);
const loader = new GLTFLoader();
const dracoLoader = new DRACOLoader();
dracoLoader.setDecoderPath("three/examples/jsm/libs/draco/gltf/");
loader.setDRACOLoader(dracoLoader);
const [cams, setCams] = useState<any[]>([]);
const [models, setModels] = useState<Record<string, { targetPosition: THREE.Vector3; targetRotation: THREE.Euler }>>({});
const [cams, setCams] = useState<any[]>([]);
const [models, setModels] = useState<
Record<
string,
{ targetPosition: THREE.Vector3; targetRotation: THREE.Euler }
>
>({});
const dedupeCams = (cams: any[]) => {
const seen = new Set();
return cams.filter((cam) => {
if (seen.has(cam.uuid)) return false;
seen.add(cam.uuid);
return true;
});
};
const dedupeCams = (cams: any[]) => {
const seen = new Set();
return cams.filter((cam) => {
if (seen.has(cam.uuid)) return false;
seen.add(cam.uuid);
return true;
});
};
const dedupeUsers = (users: any[]) => {
const seen = new Set();
return users.filter((user) => {
if (seen.has(user._id)) return false;
seen.add(user._id);
return true;
});
};
const dedupeUsers = (users: any[]) => {
const seen = new Set();
return users.filter((user) => {
if (seen.has(user._id)) return false;
seen.add(user._id);
return true;
});
};
useEffect(() => {
if (!email) navigate("/");
useEffect(() => {
if (!email) navigate("/");
if (!socket) return;
const organization = email!.split("@")[1].split(".")[0];
if (!socket) return;
const organization = email!.split("@")[1].split(".")[0];
socket.on("userConnectResponse", (data: any) => {
if (!groupRef.current) return;
if (data.data.userData.email === email) return;
if (socket.id === data.socketId || organization !== data.organization) return;
socket.on("userConnectResponse", (data: any) => {
if (!groupRef.current) return;
if (data.data.userData.email === email) return;
if (socket.id === data.socketId || organization !== data.organization)
return;
const model = groupRef.current.getObjectByProperty("uuid", data.data.userData._id);
if (model) {
groupRef.current.remove(model);
}
const model = groupRef.current.getObjectByProperty(
"uuid",
data.data.userData._id
);
if (model) {
groupRef.current.remove(model);
}
loader.load(camModel, (gltf) => {
const newModel = gltf.scene.clone();
newModel.uuid = data.data.userData._id;
newModel.position.set(
data.data.position.x,
data.data.position.y,
data.data.position.z
);
newModel.rotation.set(
data.data.rotation.x,
data.data.rotation.y,
data.data.rotation.z
);
newModel.userData = data.data.userData;
loader.load(camModel, (gltf) => {
const newModel = gltf.scene.clone();
newModel.uuid = data.data.userData._id;
newModel.position.set(
data.data.position.x,
data.data.position.y,
data.data.position.z
);
newModel.rotation.set(
data.data.rotation.x,
data.data.rotation.y,
data.data.rotation.z
);
newModel.userData = data.data.userData;
setCams((prev) => dedupeCams([...prev, newModel]));
setActiveUsers((prev: any) =>
dedupeUsers([...prev, data.data.userData])
);
});
});
setCams((prev) => dedupeCams([...prev, newModel]));
setActiveUsers((prev: any) =>
dedupeUsers([...prev, data.data.userData])
);
});
});
socket.on("userDisConnectResponse", (data: any) => {
if (!groupRef.current) return;
if (socket.id === data.socketId || organization !== data.organization) return;
socket.on("userDisConnectResponse", (data: any) => {
if (!groupRef.current) return;
if (socket.id === data.socketId || organization !== data.organization)
return;
setCams((prev) =>
prev.filter((cam) => cam.uuid !== data.data.userData._id)
);
setActiveUsers((prev: any) =>
prev.filter((user: any) => user._id !== data.data.userData._id)
);
});
setCams((prev) =>
prev.filter((cam) => cam.uuid !== data.data.userData._id)
);
setActiveUsers((prev: any) =>
prev.filter((user: any) => user._id !== data.data.userData._id)
);
});
socket.on("cameraUpdateResponse", (data: any) => {
if (
!groupRef.current ||
socket.id === data.socketId ||
organization !== data.organization
)
return;
socket.on("cameraUpdateResponse", (data: any) => {
if (
!groupRef.current ||
socket.id === data.socketId ||
organization !== data.organization
)
return;
setModels((prev) => ({
...prev,
[data.data.userId]: {
targetPosition: new THREE.Vector3(
data.data.position.x,
data.data.position.y,
data.data.position.z
),
targetRotation: new THREE.Euler(
data.data.rotation.x,
data.data.rotation.y,
data.data.rotation.z
),
},
}));
});
setModels((prev) => ({
...prev,
[data.data.userId]: {
targetPosition: new THREE.Vector3(
data.data.position.x,
data.data.position.y,
data.data.position.z
),
targetRotation: new THREE.Euler(
data.data.rotation.x,
data.data.rotation.y,
data.data.rotation.z
),
},
}));
});
return () => {
socket.off("userConnectResponse");
socket.off("userDisConnectResponse");
socket.off("cameraUpdateResponse");
};
}, [socket]);
return () => {
socket.off("userConnectResponse");
socket.off("userDisConnectResponse");
socket.off("cameraUpdateResponse");
};
}, [socket]);
useFrame(() => {
if (!groupRef.current) return;
Object.keys(models).forEach((uuid) => {
const model = groupRef.current!.getObjectByProperty("uuid", uuid);
if (!model) return;
useFrame(() => {
if (!groupRef.current) return;
Object.keys(models).forEach((uuid) => {
const model = groupRef.current!.getObjectByProperty("uuid", uuid);
if (!model) return;
const { targetPosition, targetRotation } = models[uuid];
model.position.lerp(targetPosition, 0.1);
model.rotation.x = THREE.MathUtils.lerp(model.rotation.x, targetRotation.x, 0.1);
model.rotation.y = THREE.MathUtils.lerp(model.rotation.y, targetRotation.y, 0.1);
model.rotation.z = THREE.MathUtils.lerp(model.rotation.z, targetRotation.z, 0.1);
});
});
const { targetPosition, targetRotation } = models[uuid];
model.position.lerp(targetPosition, 0.1);
model.rotation.x = THREE.MathUtils.lerp(
model.rotation.x,
targetRotation.x,
0.1
);
model.rotation.y = THREE.MathUtils.lerp(
model.rotation.y,
targetRotation.y,
0.1
);
model.rotation.z = THREE.MathUtils.lerp(
model.rotation.z,
targetRotation.z,
0.1
);
});
});
useEffect(() => {
if (!groupRef.current) return;
const organization = email!.split("@")[1].split(".")[0];
useEffect(() => {
if (!groupRef.current) return;
const organization = email!.split("@")[1].split(".")[0];
getActiveUsersData(organization).then((data) => {
const filteredData = data.cameraDatas.filter(
(camera: any) => camera.userData.email !== email
);
getActiveUsersData(organization).then((data) => {
const filteredData = data.cameraDatas.filter(
(camera: any) => camera.userData.email !== email
);
if (filteredData.length > 0) {
loader.load(camModel, (gltf) => {
const newCams = filteredData.map((cam: any) => {
const newModel = gltf.scene.clone();
newModel.uuid = cam.userData._id;
newModel.position.set(cam.position.x, cam.position.y, cam.position.z);
newModel.rotation.set(cam.rotation.x, cam.rotation.y, cam.rotation.z);
newModel.userData = cam.userData;
return newModel;
});
if (filteredData.length > 0) {
loader.load(camModel, (gltf) => {
const newCams = filteredData.map((cam: any) => {
const newModel = gltf.scene.clone();
newModel.uuid = cam.userData._id;
newModel.position.set(
cam.position.x,
cam.position.y,
cam.position.z
);
newModel.rotation.set(
cam.rotation.x,
cam.rotation.y,
cam.rotation.z
);
newModel.userData = cam.userData;
return newModel;
});
const users = filteredData.map((cam: any) => cam.userData);
setActiveUsers((prev: any) => dedupeUsers([...prev, ...users]));
setCams((prev) => dedupeCams([...prev, ...newCams]));
});
}
});
}, []);
const users = filteredData.map((cam: any) => cam.userData);
setActiveUsers((prev: any) => dedupeUsers([...prev, ...users]));
setCams((prev) => dedupeCams([...prev, ...newCams]));
});
}
});
}, []);
return (
<group ref={groupRef} name="Cam-Model-Group">
{cams.map((cam, index) => (
<primitive key={cam.uuid} object={cam}>
<Html
as="div"
center
zIndexRange={[1, 0]}
sprite
style={{
color: "white",
textAlign: "center",
fontFamily: "Arial, sans-serif",
}}
position={[-0.015, 0, 0.7]}
>
<CollabUserIcon
userImage={cam.userData.userImage ||""}
userName={cam.userData.userName}
color={getAvatarColor(index, cam.userData.userName)}
/>
</Html>
</primitive>
))}
</group>
);
return (
<group
ref={groupRef}
name="Cam-Model-Group"
visible={activeModule !== "visualization" ? true : false}
>
{cams.map((cam, index) => (
<primitive key={cam.uuid} object={cam}>
<Html
as="div"
center
zIndexRange={[1, 0]}
sprite
style={{
color: "white",
textAlign: "center",
fontFamily: "Arial, sans-serif",
display: `${activeModule !== "visualization" ? "" : "none"}`,
}}
position={[-0.015, 0, 0.7]}
>
<CollabUserIcon
userImage={cam.userData.userImage || ""}
userName={cam.userData.userName}
color={getAvatarColor(index, cam.userData.userName)}
/>
</Html>
</primitive>
))}
</group>
);
};
export default CamModelsGroup;

View File

@@ -18,8 +18,8 @@ import Simulation from "../simulation/simulation";
// import Simulation from "./simulationtemp/simulation";
import ZoneCentreTarget from "../../components/ui/componets/zoneCameraTarget";
import Dropped3dWidgets from "../../components/ui/componets/Dropped3dWidget";
import ZoneAssets from "../../components/ui/componets/zoneAssets";
import Dropped3dWidgets from "../../modules/visualization/widgets/3d/Dropped3dWidget";
import ZoneAssets from "../visualization/zoneAssets";
export default function Scene() {
const map = useMemo(

View File

@@ -0,0 +1,257 @@
import React, { useEffect, useRef, useState, useCallback } from "react";
import { useWidgetStore, Widget } from "../../store/useWidgetStore";
import {
useDroppedObjectsStore,
useFloatingWidget,
} from "../../store/useDroppedObjectsStore";
import { getSelect2dZoneData } from "../../services/realTimeVisulization/zoneData/getSelect2dZoneData";
import { getFloatingZoneData } from "../../services/realTimeVisulization/zoneData/getFloatingData";
import { get3dWidgetZoneData } from "../../services/realTimeVisulization/zoneData/get3dWidgetData";
import {
MoveArrowLeft,
MoveArrowRight,
} from "../../components/icons/SimulationIcons";
import { InfoIcon } from "../../components/icons/ExportCommonIcons";
// Define the type for `Side`
type Side = "top" | "bottom" | "left" | "right";
interface HiddenPanels {
[zoneId: string]: Side[];
}
interface DisplayZoneProps {
zonesData: {
[key: string]: {
activeSides: Side[];
panelOrder: Side[];
lockedPanels: Side[];
points: [];
widgets: Widget[];
zoneId: string;
zoneViewPortTarget: number[];
zoneViewPortPosition: number[];
};
};
selectedZone: {
zoneName: string;
activeSides: Side[];
panelOrder: Side[];
lockedPanels: Side[];
zoneId: string;
points: [];
zoneViewPortTarget: number[];
zoneViewPortPosition: number[];
widgets: {
id: string;
type: string;
title: string;
panel: Side;
data: any;
}[];
};
setSelectedZone: React.Dispatch<
React.SetStateAction<{
zoneName: string;
activeSides: Side[];
panelOrder: Side[];
lockedPanels: Side[];
points: [];
zoneId: string;
zoneViewPortTarget: number[];
zoneViewPortPosition: number[];
widgets: {
id: string;
type: string;
title: string;
panel: Side;
data: any;
}[];
}>
>;
hiddenPanels: HiddenPanels; // Updated prop type
setHiddenPanels: React.Dispatch<React.SetStateAction<HiddenPanels>>; // Updated prop type
}
const DisplayZone: React.FC<DisplayZoneProps> = ({
zonesData,
selectedZone,
setSelectedZone,
hiddenPanels,
}) => {
// Ref for the container element
const containerRef = useRef<HTMLDivElement | null>(null);
const scrollContainerRef = useRef<HTMLDivElement | null>(null);
// State to track overflow visibility
const [showLeftArrow, setShowLeftArrow] = useState(false);
const [showRightArrow, setShowRightArrow] = useState(false);
const { floatingWidget, setFloatingWidget } = useFloatingWidget();
const { setSelectedChartId } = useWidgetStore();
// Function to calculate overflow state
const updateOverflowState = useCallback(() => {
const container = scrollContainerRef.current;
if (container) {
const isOverflowing = container.scrollWidth > container.clientWidth;
const canScrollLeft = container.scrollLeft > 0;
const canScrollRight =
container.scrollLeft + container.clientWidth < container.scrollWidth;
setShowLeftArrow(isOverflowing && canScrollLeft);
setShowRightArrow(isOverflowing && canScrollRight);
}
}, []);
useEffect(() => {
const container = scrollContainerRef.current;
if (!container) return;
// Initial calculation after the DOM has been rendered
const observer = new ResizeObserver(updateOverflowState);
observer.observe(container);
// Update on scroll
const handleScroll = () => updateOverflowState();
container.addEventListener("scroll", handleScroll);
// Add mouse wheel listener for horizontal scrolling
const handleWheel = (event: WheelEvent) => {
if (Math.abs(event.deltaY) > Math.abs(event.deltaX)) {
event.preventDefault();
container.scrollBy({
left: event.deltaY * 2,
behavior: "smooth",
});
}
};
container.addEventListener("wheel", handleWheel, { passive: false });
// Initial check
updateOverflowState();
return () => {
observer.disconnect();
container.removeEventListener("scroll", handleScroll);
container.removeEventListener("wheel", handleWheel);
};
}, [updateOverflowState]);
// Handle scrolling with navigation arrows
const handleScrollLeft = () => {
const container = scrollContainerRef.current;
if (container) {
container.scrollBy({
left: -200,
behavior: "smooth",
});
}
};
const handleScrollRight = () => {
const container = scrollContainerRef.current;
if (container) {
container.scrollBy({
left: 200,
behavior: "smooth",
});
}
};
async function handleSelect2dZoneData(zoneId: string, zoneName: string) {
try {
if (selectedZone?.zoneId === zoneId) {
return;
}
setSelectedChartId(null);
const email = localStorage.getItem("email") || "";
const organization = email?.split("@")[1]?.split(".")[0];
let response = await getSelect2dZoneData(zoneId, organization);
console.log("response: ", response);
let res = await getFloatingZoneData(zoneId, organization);
console.log("res: ", res);
setFloatingWidget(res);
// Set the selected zone in the store
useDroppedObjectsStore.getState().setZone(zoneName, zoneId);
if (Array.isArray(res)) {
res.forEach((val) => {
useDroppedObjectsStore.getState().addObject(zoneName, val);
});
}
setSelectedZone({
zoneName,
activeSides: response.activeSides || [],
panelOrder: response.panelOrder || [],
lockedPanels: response.lockedPanels || [],
widgets: response.widgets || [],
points: response.points || [],
zoneId: zoneId,
zoneViewPortTarget: response.viewPortCenter || {},
zoneViewPortPosition: response.viewPortposition || {},
});
} catch (error) {}
}
return (
<div
ref={containerRef}
className={`zone-wrapper ${
selectedZone?.activeSides?.includes("bottom") &&
!hiddenPanels[selectedZone.zoneId]?.includes("bottom")
? "bottom"
: ""
}`}
>
{/* Left Arrow */}
{showLeftArrow && (
<button className="arrow left-arrow" onClick={handleScrollLeft}>
<MoveArrowLeft />
</button>
)}
{/* Scrollable Zones Container */}
<div
ref={scrollContainerRef}
className="zones-wrapper"
style={{ overflowX: "auto", whiteSpace: "nowrap" }}
>
{Object.keys(zonesData).length !== 0 ? (
<>
{Object.keys(zonesData).map((zoneName, index) => (
<div
key={index}
className={`zone ${
selectedZone.zoneName === zoneName ? "active" : ""
}`}
onClick={() =>
handleSelect2dZoneData(zonesData[zoneName]?.zoneId, zoneName)
}
>
{zoneName}
</div>
))}
</>
) : (
<div className="no-zone">
<InfoIcon />
No zones? Create one!
</div>
)}
</div>
{/* Right Arrow */}
{showRightArrow && (
<button className="arrow right-arrow" onClick={handleScrollRight}>
<MoveArrowRight />
</button>
)}
</div>
);
};
export default DisplayZone;

View File

@@ -0,0 +1,361 @@
import React, { useEffect, useState, useRef } from "react";
import { usePlayButtonStore } from "../../store/usePlayButtonStore";
import Panel from "./widgets/panel/Panel";
import AddButtons from "./widgets/panel/AddButtons";
import { useSelectedZoneStore } from "../../store/useZoneStore";
import DisplayZone from "./DisplayZone";
import Scene from "../scene/scene";
import useModuleStore from "../../store/useModuleStore";
import {
useDroppedObjectsStore,
useFloatingWidget,
} from "../../store/useDroppedObjectsStore";
import {
useAsset3dWidget,
useSocketStore,
useWidgetSubOption,
useZones,
} from "../../store/store";
import { getZone2dData } from "../../services/realTimeVisulization/zoneData/getZoneData";
import { generateUniqueId } from "../../functions/generateUniqueId";
import { determinePosition } from "./functions/determinePosition";
import { addingFloatingWidgets } from "../../services/realTimeVisulization/zoneData/addFloatingWidgets";
import SocketRealTimeViz from "./socket/realTimeVizSocket.dev";
import RenderOverlay from "../../components/templates/Overlay";
import ConfirmationPopup from "../../components/layout/confirmationPopup/ConfirmationPopup";
import DroppedObjects from "./widgets/floating/DroppedFloatingWidgets";
import EditWidgetOption from "../../components/ui/menu/EditWidgetOption";
import {
useEditWidgetOptionsStore,
useRightClickSelected,
useRightSelected,
} from "../../store/useZone3DWidgetStore";
import Dropped3dWidgets from "./widgets/3d/Dropped3dWidget";
import OuterClick from "../../utils/outerClick";
import { useWidgetStore } from "../../store/useWidgetStore";
type Side = "top" | "bottom" | "left" | "right";
type FormattedZoneData = Record<
string,
{
activeSides: Side[];
panelOrder: Side[];
points: [];
lockedPanels: Side[];
zoneId: string;
zoneViewPortTarget: number[];
zoneViewPortPosition: number[];
widgets: Widget[];
}
>;
type Widget = {
id: string;
type: string;
title: string;
panel: Side;
data: any;
};
// Define the type for HiddenPanels, where keys are zone IDs and values are arrays of hidden sides
interface HiddenPanels {
[zoneId: string]: Side[];
}
const RealTimeVisulization: React.FC = () => {
const [hiddenPanels, setHiddenPanels] = React.useState<HiddenPanels>({});
const containerRef = useRef<HTMLDivElement>(null);
const { isPlaying } = usePlayButtonStore();
const { activeModule } = useModuleStore();
const [droppedObjects, setDroppedObjects] = useState<any[]>([]);
const [zonesData, setZonesData] = useState<FormattedZoneData>({});
const { selectedZone, setSelectedZone } = useSelectedZoneStore();
const { rightSelect, setRightSelect } = useRightSelected();
const { editWidgetOptions, setEditWidgetOptions } =
useEditWidgetOptionsStore();
const { rightClickSelected, setRightClickSelected } = useRightClickSelected();
const [openConfirmationPopup, setOpenConfirmationPopup] = useState(false);
// const [floatingWidgets, setFloatingWidgets] = useState<Record<string, { zoneName: string; zoneId: string; objects: any[] }>>({});
const { floatingWidget, setFloatingWidget } = useFloatingWidget();
const { widgetSelect, setWidgetSelect } = useAsset3dWidget();
const { widgetSubOption, setWidgetSubOption } = useWidgetSubOption();
const { visualizationSocket } = useSocketStore();
const { setSelectedChartId } = useWidgetStore();
OuterClick({
contextClassName: [
"chart-container",
"floating",
"sidebar-right-wrapper",
"card",
"dropdown-menu",
],
setMenuVisible: () => setSelectedChartId(null),
});
useEffect(() => {
async function GetZoneData() {
const email = localStorage.getItem("email") || "";
const organization = email?.split("@")[1]?.split(".")[0];
try {
const response = await getZone2dData(organization);
if (!Array.isArray(response)) {
return;
}
const formattedData = response.reduce<FormattedZoneData>(
(acc, zone) => {
acc[zone.zoneName] = {
activeSides: [],
panelOrder: [],
lockedPanels: [],
points: zone.points,
zoneId: zone.zoneId,
zoneViewPortTarget: zone.viewPortCenter,
zoneViewPortPosition: zone.viewPortposition,
widgets: [],
};
return acc;
},
{}
);
setZonesData(formattedData);
} catch (error) {}
}
GetZoneData();
}, [activeModule]); // Removed `zones` from dependencies
useEffect(() => {
setZonesData((prev) => {
if (!selectedZone) return prev;
return {
...prev,
[selectedZone.zoneName]: {
...prev[selectedZone.zoneName], // Keep existing properties
activeSides: selectedZone.activeSides || [],
panelOrder: selectedZone.panelOrder || [],
lockedPanels: selectedZone.lockedPanels || [],
points: selectedZone.points || [],
zoneId: selectedZone.zoneId || "",
zoneViewPortTarget: selectedZone.zoneViewPortTarget || [],
zoneViewPortPosition: selectedZone.zoneViewPortPosition || [],
widgets: selectedZone.widgets || [],
},
};
});
}, [selectedZone]);
// useEffect(() => {}, [floatingWidgets]);
const handleDrop = async (event: React.DragEvent<HTMLDivElement>) => {
event.preventDefault();
try {
const email = localStorage.getItem("email") || "";
const organization = email?.split("@")[1]?.split(".")[0];
const data = event.dataTransfer.getData("text/plain");
if (widgetSubOption === "3D") return;
if (!data || selectedZone.zoneName === "") return;
const droppedData = JSON.parse(data);
const canvasElement = document.getElementById("real-time-vis-canvas");
if (!canvasElement) throw new Error("Canvas element not found");
// Get canvas dimensions and mouse position
const rect = canvasElement.getBoundingClientRect();
let relativeX = (event.clientX - rect.left) ;
let relativeY = event.clientY - rect.top;
// Widget dimensions (with defaults)
const widgetWidth = droppedData.width || 125; // 250/2 as default
const widgetHeight = droppedData.height || 100; // 83/2 as default
// Clamp to ensure widget stays fully inside canvas
const clampedX = Math.max(
0, // Prevent going beyond left edge
Math.min(
relativeX,
rect.width - widgetWidth // Prevent going beyond right edge
)
);
console.log('clampedX: ', clampedX);
const clampedY = Math.max(
0, // Prevent going beyond top edge
Math.min(
relativeY,
rect.height - widgetHeight // Prevent going beyond bottom edge
)
);
// Debug logging (optional)
console.log("Drop coordinates:", {
rawX: relativeX,
rawY: relativeY,
clampedX,
clampedY,
canvasWidth: rect.width,
canvasHeight: rect.height,
widgetWidth,
widgetHeight
});
const finalPosition = determinePosition(rect, clampedX, clampedY);
const newObject = {
...droppedData,
id: generateUniqueId(),
position: finalPosition,
};
// Zone management
const existingZone = useDroppedObjectsStore.getState().zones[selectedZone.zoneName];
if (!existingZone) {
useDroppedObjectsStore.getState().setZone(selectedZone.zoneName, selectedZone.zoneId);
}
// Socket emission
const addFloatingWidget = {
organization,
widget: newObject,
zoneId: selectedZone.zoneId,
};
if (visualizationSocket) {
visualizationSocket.emit("v2:viz-float:add", addFloatingWidget);
}
// Store update
useDroppedObjectsStore.getState().addObject(selectedZone.zoneName, newObject);
// Post-drop verification
const droppedObjectsStore = useDroppedObjectsStore.getState();
const currentZone = droppedObjectsStore.zones[selectedZone.zoneName];
if (currentZone && currentZone.zoneId === selectedZone.zoneId) {
console.log(`Objects for Zone ${selectedZone.zoneId}:`, currentZone.objects);
setFloatingWidget(currentZone.objects);
} else {
console.warn("Zone not found or zoneId mismatch");
}
} catch (error) {
console.error("Error in handleDrop:", error);
// Consider adding user feedback here (e.g., toast notification)
}
};
useEffect(() => {
const handleClickOutside = (event: MouseEvent) => {
const editWidgetOptions = document.querySelector(
".editWidgetOptions-wrapper"
);
if (
editWidgetOptions &&
!editWidgetOptions.contains(event.target as Node)
) {
setRightClickSelected(null);
setRightSelect(null);
}
};
document.addEventListener("mousedown", handleClickOutside);
return () => {
document.removeEventListener("mousedown", handleClickOutside);
};
}, [setRightClickSelected]);
return (
<>
<div
ref={containerRef}
id="real-time-vis-canvas"
className={`realTime-viz canvas ${isPlaying ? "playingFlase" : ""}`}
style={{
height: isPlaying || activeModule !== "visualization" ? "100vh" : "",
width: isPlaying || activeModule !== "visualization" ? "100vw" : "",
left: isPlaying || activeModule !== "visualization" ? "0%" : "",
}}
>
<div className="realTime-viz-wrapper">
{openConfirmationPopup && (
<RenderOverlay>
<ConfirmationPopup
message={"Are you sure want to delete?"}
onConfirm={() => console.log("Confirmed")}
onCancel={() => setOpenConfirmationPopup(false)}
/>
</RenderOverlay>
)}
<div
className="scene-container"
style={{
height: "100%",
width: "100%",
borderRadius:
isPlaying || activeModule !== "visualization" ? "" : "6px",
}}
onDrop={(event) => handleDrop(event)}
onDragOver={(event) => event.preventDefault()}
>
<Scene />
</div>
{activeModule === "visualization" && selectedZone.zoneName !== "" && (
<DroppedObjects />
)}
{activeModule === "visualization" && <SocketRealTimeViz />}
{activeModule === "visualization" &&
editWidgetOptions &&
rightClickSelected && (
<EditWidgetOption
options={[
"Duplicate",
"Vertical Move",
"Horizontal Move",
"RotateX",
"RotateY",
"RotateZ",
"Delete",
]}
/>
)}
{activeModule === "visualization" && (
<>
<DisplayZone
zonesData={zonesData}
selectedZone={selectedZone}
setSelectedZone={setSelectedZone}
hiddenPanels={hiddenPanels}
setHiddenPanels={setHiddenPanels}
/>
{!isPlaying && selectedZone?.zoneName !== "" && (
<AddButtons
hiddenPanels={hiddenPanels}
setHiddenPanels={setHiddenPanels}
selectedZone={selectedZone}
setSelectedZone={setSelectedZone}
/>
)}
<Panel
selectedZone={selectedZone}
setSelectedZone={setSelectedZone}
hiddenPanels={hiddenPanels}
setZonesData={setZonesData}
/>
</>
)}
</div>
</div>
</>
);
};
export default RealTimeVisulization;

View File

@@ -1,33 +1,33 @@
import html2canvas from "html2canvas";
export const captureVisualization = async (): Promise<string | null> => {
const container = document.getElementById("real-time-vis-canvas");
if (!container) {
console.error("Container element not found");
return null;
}
try {
// Hide any elements you don't want in the screenshot
const originalVisibility = container.style.visibility;
container.style.visibility = 'visible';
const canvas = await html2canvas(container, {
scale: 2, // Higher scale for better quality
logging: false, // Disable console logging
useCORS: true, // Handle cross-origin images
allowTaint: true, // Allow tainted canvas
backgroundColor: '#ffffff', // Set white background
removeContainer: true // Clean up temporary containers
});
// Restore original visibility
container.style.visibility = originalVisibility;
// Convert to PNG with highest quality
return canvas.toDataURL('image/png', 1.0);
} catch (error) {
console.error("Error capturing visualization:", error);
return null;
}
};
import html2canvas from "html2canvas";
export const captureVisualization = async (): Promise<string | null> => {
const container = document.getElementById("real-time-vis-canvas");
if (!container) {
console.error("Container element not found");
return null;
}
try {
// Hide any elements you don't want in the screenshot
const originalVisibility = container.style.visibility;
container.style.visibility = 'visible';
const canvas = await html2canvas(container, {
scale: 2, // Higher scale for better quality
logging: false, // Disable console logging
useCORS: true, // Handle cross-origin images
allowTaint: true, // Allow tainted canvas
backgroundColor: '#ffffff', // Set white background
removeContainer: true // Clean up temporary containers
});
// Restore original visibility
container.style.visibility = originalVisibility;
// Convert to PNG with highest quality
return canvas.toDataURL('image/png', 1.0);
} catch (error) {
console.error("Error capturing visualization:", error);
return null;
}
};

View File

@@ -0,0 +1,77 @@
export function determinePosition(
canvasRect: DOMRect,
relativeX: number,
relativeY: number
): {
top: number | "auto";
left: number | "auto";
right: number | "auto";
bottom: number | "auto";
} {
const centerX = canvasRect.width / 2;
const centerY = canvasRect.height / 2;
// Define a threshold for considering a point as "centered"
const centerThreshold = 10; // Adjust this value as needed
// Check if the point is within the center threshold
const isCenterX = Math.abs(relativeX - centerX) <= centerThreshold;
const isCenterY = Math.abs(relativeY - centerY) <= centerThreshold;
// If the point is centered, return a special "centered" position
if (isCenterX && isCenterY) {
return {
top: "auto",
left: "auto",
right: "auto",
bottom: "auto",
};
}
let position: {
top: number | "auto";
left: number | "auto";
right: number | "auto";
bottom: number | "auto";
};
if (relativeY < centerY) {
if (relativeX < centerX) {
// Top-left quadrant
position = {
top: relativeY - 41.5,
left: relativeX - 125,
right: "auto",
bottom: "auto",
};
} else {
// Top-right quadrant
position = {
top: relativeY - 41.5,
right: canvasRect.width - relativeX - 125,
left: "auto",
bottom: "auto",
};
}
} else {
if (relativeX < centerX) {
// Bottom-left quadrant
position = {
bottom: canvasRect.height - relativeY - 41.5,
left: relativeX - 125,
right: "auto",
top: "auto",
};
} else {
// Bottom-right quadrant
position = {
bottom: canvasRect.height - relativeY - 41.5,
right: canvasRect.width - relativeX - 125,
left: "auto",
top: "auto",
};
}
}
return position;
}

View File

@@ -0,0 +1,11 @@
export function getActiveProperties(position: any): [string, string] {
if (position.top !== "auto" && position.left !== "auto") {
return ["top", "left"]; // Top-left
} else if (position.top !== "auto" && position.right !== "auto") {
return ["top", "right"]; // Top-right
} else if (position.bottom !== "auto" && position.left !== "auto") {
return ["bottom", "left"]; // Bottom-left
} else {
return ["bottom", "right"]; // Bottom-right
}
}

View File

@@ -1,97 +1,97 @@
import { Template } from "../../store/useTemplateStore";
import { captureVisualization } from "./captureVisualization";
type HandleSaveTemplateProps = {
addTemplate: (template: Template) => void;
floatingWidget: []; // Updated type from `[]` to `any[]` for clarity
widgets3D: []; // Updated type from `[]` to `any[]` for clarity
selectedZone: {
panelOrder: string[];
widgets: any[];
};
templates?: Template[];
visualizationSocket: any;
};
// Generate a unique ID
const generateUniqueId = (): string => {
return `${Date.now()}-${Math.random().toString(36).substring(2, 15)}`;
};
export const handleSaveTemplate = async ({
addTemplate,
floatingWidget,
widgets3D,
selectedZone,
templates = [],
visualizationSocket,
}: HandleSaveTemplateProps): Promise<void> => {
console.log("floatingWidget: ", floatingWidget);
try {
// Check if the selected zone has any widgets
if (!selectedZone.panelOrder || selectedZone.panelOrder.length === 0) {
return;
}
// Check if the template already exists
const isDuplicate = templates.some(
(template) =>
JSON.stringify(template.panelOrder) ===
JSON.stringify(selectedZone.panelOrder) &&
JSON.stringify(template.widgets) ===
JSON.stringify(selectedZone.widgets)
);
if (isDuplicate) {
return;
}
// Capture visualization snapshot
const snapshot = await captureVisualization();
if (!snapshot) {
return;
}
// Create a new template
const newTemplate: Template = {
id: generateUniqueId(),
name: `Template ${new Date().toISOString()}`, // Better name formatting
panelOrder: selectedZone.panelOrder,
widgets: selectedZone.widgets,
snapshot,
floatingWidget,
widgets3D,
};
// Extract organization from email
const email = localStorage.getItem("email") || "";
const organization = email.includes("@")
? email.split("@")[1]?.split(".")[0]
: "";
if (!organization) {
return;
}
let saveTemplate = {
organization: organization,
template: newTemplate,
};
if (visualizationSocket) {
visualizationSocket.emit("v2:viz-template:add", saveTemplate);
}
// Save the template
try {
addTemplate(newTemplate);
// const response = await saveTemplateApi(organization, newTemplate);
//
// Add template only if API call succeeds
} catch (apiError) {
//
}
} catch (error) {
//
}
};
import { Template } from "../../../store/useTemplateStore";
import { captureVisualization } from "./captureVisualization";
type HandleSaveTemplateProps = {
addTemplate: (template: Template) => void;
floatingWidget: []; // Updated type from `[]` to `any[]` for clarity
widgets3D: []; // Updated type from `[]` to `any[]` for clarity
selectedZone: {
panelOrder: string[];
widgets: any[];
};
templates?: Template[];
visualizationSocket: any;
};
// Generate a unique ID
const generateUniqueId = (): string => {
return `${Date.now()}-${Math.random().toString(36).substring(2, 15)}`;
};
export const handleSaveTemplate = async ({
addTemplate,
floatingWidget,
widgets3D,
selectedZone,
templates = [],
visualizationSocket,
}: HandleSaveTemplateProps): Promise<void> => {
try {
// Check if the selected zone has any widgets
if (!selectedZone.panelOrder || selectedZone.panelOrder.length === 0) {
return;
}
// Check if the template already exists
const isDuplicate = templates.some(
(template) =>
JSON.stringify(template.panelOrder) ===
JSON.stringify(selectedZone.panelOrder) &&
JSON.stringify(template.widgets) ===
JSON.stringify(selectedZone.widgets)
);
if (isDuplicate) {
return;
}
// Capture visualization snapshot
const snapshot = await captureVisualization();
if (!snapshot) {
return;
}
// Create a new template
const newTemplate: Template = {
id: generateUniqueId(),
name: `Template ${new Date().toISOString()}`, // Better name formatting
panelOrder: selectedZone.panelOrder,
widgets: selectedZone.widgets,
snapshot,
floatingWidget,
widgets3D,
};
// Extract organization from email
const email = localStorage.getItem("email") || "";
const organization = email.includes("@")
? email.split("@")[1]?.split(".")[0]
: "";
if (!organization) {
return;
}
let saveTemplate = {
organization: organization,
template: newTemplate,
};
if (visualizationSocket) {
visualizationSocket.emit("v2:viz-template:add", saveTemplate);
}
// Save the template
try {
addTemplate(newTemplate);
// const response = await saveTemplateApi(organization, newTemplate);
//
// Add template only if API call succeeds
} catch (apiError) {
//
}
} catch (error) {
//
}
};

View File

@@ -0,0 +1,20 @@
import { useEffect } from "react";
export const useClickOutside = (
ref: React.RefObject<HTMLElement>,
callback: () => void
) => {
useEffect(() => {
const handleClickOutside = (event: MouseEvent) => {
if (ref.current && !event.composedPath().includes(ref.current)) {
callback();
}
};
document.addEventListener("mousedown", handleClickOutside);
return () => {
document.removeEventListener("mousedown", handleClickOutside);
};
}, [ref, callback]);
};

View File

@@ -1,238 +0,0 @@
import { useEffect } from "react";
import { useSocketStore } from "../../store/store";
import { useSelectedZoneStore } from "../../store/useZoneStore";
import { useDroppedObjectsStore } from "../../store/useDroppedObjectsStore";
import { useZoneWidgetStore } from "../../store/useZone3DWidgetStore";
import useTemplateStore from "../../store/useTemplateStore";
type WidgetData = {
id: string;
type: string;
position: [number, number, number];
rotation?: [number, number, number];
tempPosition?: [number, number, number];
};
export default function SocketRealTimeViz() {
const { visualizationSocket } = useSocketStore();
const { setSelectedZone } = useSelectedZoneStore();
const deleteObject = useDroppedObjectsStore((state) => state.deleteObject);
const updateObjectPosition = useDroppedObjectsStore((state) => state.updateObjectPosition);
const { addWidget } = useZoneWidgetStore()
const { removeTemplate } = useTemplateStore();
const { setTemplates } = useTemplateStore();
const { zoneWidgetData, setZoneWidgetData, updateWidgetPosition, updateWidgetRotation } = useZoneWidgetStore();
useEffect(() => {
if (visualizationSocket) {
//add panel response
visualizationSocket.on("viz-panel:response:updates", (addPanel: any) => {
if (addPanel.success) {
let addPanelData = addPanel.data.data
setSelectedZone(addPanelData)
}
})
//delete panel response
visualizationSocket.on("viz-panel:response:delete", (deletePanel: any) => {
if (deletePanel.success) {
let deletePanelData = deletePanel.data.data
setSelectedZone(deletePanelData)
}
})
//clear Panel response
visualizationSocket.on("viz-panel:response:clear", (clearPanel: any) => {
if (clearPanel.success && clearPanel.message === "PanelWidgets cleared successfully") {
let clearPanelData = clearPanel.data.data
setSelectedZone(clearPanelData)
}
})
//lock Panel response
visualizationSocket.on("viz-panel:response:locked", (lockPanel: any) => {
if (lockPanel.success && lockPanel.message === "locked panel updated successfully") {
let lockPanelData = lockPanel.data.data
setSelectedZone(lockPanelData)
}
})
// add 2dWidget response
visualizationSocket.on("viz-widget:response:updates", (add2dWidget: any) => {
if (add2dWidget.success && add2dWidget.data) {
setSelectedZone((prev) => {
const isWidgetAlreadyAdded = prev.widgets.some(
(widget) => widget.id === add2dWidget.data.widgetData.id
);
if (isWidgetAlreadyAdded) return prev; // Prevent duplicate addition
return {
...prev,
zoneId: add2dWidget.data.zoneId,
zoneName: add2dWidget.data.zoneName,
widgets: [...prev.widgets, add2dWidget.data.widgetData], // Append new widget
};
});
}
});
//delete 2D Widget response
visualizationSocket.on("viz-widget:response:delete", (deleteWidget: any) => {
if (deleteWidget?.success && deleteWidget.data) {
setSelectedZone((prevZone: any) => ({
...prevZone,
zoneId: deleteWidget.data.zoneId,
zoneName: deleteWidget.data.zoneName,
widgets: deleteWidget.data.widgetDeleteDatas, // Replace with new widget list
}));
}
});
//add Floating Widget response
visualizationSocket.on("viz-float:response:updates", (addFloatingWidget: any) => {
if (addFloatingWidget.success) {
if (addFloatingWidget.success && addFloatingWidget.message === "FloatWidget created successfully") {
const state = useDroppedObjectsStore.getState();
const zone = state.zones[addFloatingWidget.data.zoneName];
if (!zone) {
state.setZone(addFloatingWidget.data.zoneName, addFloatingWidget.data.zoneId);
}
const existingObjects = zone ? zone.objects : [];
const newWidget = addFloatingWidget.data.widget;
// ✅ Check if the widget ID already exists before adding
const isAlreadyAdded = existingObjects.some(obj => obj.id === newWidget.id);
if (isAlreadyAdded) {
return; // Don't add the widget if it already exists
}
// Add widget only if it doesn't exist
state.addObject(addFloatingWidget.data.zoneName, newWidget);
}
if (addFloatingWidget.message === "Widget updated successfully") {
updateObjectPosition(addFloatingWidget.data.zoneName, addFloatingWidget.data.index, addFloatingWidget.data.position);
}
}
});
//duplicate Floating Widget response
visualizationSocket.on("viz-float:response:addDuplicate", (duplicateFloatingWidget: any) => {
if (duplicateFloatingWidget.success && duplicateFloatingWidget.message === "duplicate FloatWidget created successfully") {
useDroppedObjectsStore.setState((state) => {
const zone = state.zones[duplicateFloatingWidget.data.zoneName];
if (!zone) return state; // Zone doesn't exist, return state as is
const existingObjects = zone.objects;
const newWidget = duplicateFloatingWidget.data.widget;
// ✅ Check if the object with the same ID already exists
const isAlreadyAdded = existingObjects.some(obj => obj.id === newWidget.id);
if (isAlreadyAdded) {
return state; // Don't update state if it's already there
}
return {
zones: {
...state.zones,
[duplicateFloatingWidget.data.zoneName]: {
...zone,
objects: [...existingObjects, newWidget], // Append only if it's not a duplicate
},
},
};
});
}
});
//delete Floating Widget response
visualizationSocket.on("viz-float:response:delete", (deleteFloatingWidget: any) => {
if (deleteFloatingWidget.success) {
deleteObject(deleteFloatingWidget.data.zoneName, deleteFloatingWidget.data.floatWidgetID);
}
});
//add 3D Widget response
visualizationSocket.on("viz-widget3D:response:updates", (add3DWidget: any) => {
if (add3DWidget.success) {
if (add3DWidget.message === "Widget created successfully") {
addWidget(add3DWidget.data.zoneId, add3DWidget.data.widget);
}
}
});
//delete 3D Widget response
visualizationSocket.on("viz-widget3D:response:delete", (delete3DWidget: any) => {
// "3DWidget delete unsuccessfull"
if (delete3DWidget.success && delete3DWidget.message === "3DWidget delete successfull") {
const activeZoneWidgets = zoneWidgetData[delete3DWidget.data.zoneId] || [];
setZoneWidgetData(
delete3DWidget.data.zoneId,
activeZoneWidgets.filter((w: WidgetData) => w.id !== delete3DWidget.data.id)
);
}
});
//update3D widget response
visualizationSocket.on("viz-widget3D:response:modifyPositionRotation", (update3DWidget: any) => {
if (update3DWidget.success && update3DWidget.message === "widget update successfully") {
updateWidgetPosition(update3DWidget.data.zoneId, update3DWidget.data.widget.id, update3DWidget.data.widget.position);
updateWidgetRotation(update3DWidget.data.zoneId, update3DWidget.data.widget.id, update3DWidget.data.widget.rotation);
}
});
// add Template response
visualizationSocket.on("viz-template:response:add", (addingTemplate: any) => {
if (addingTemplate.success) {
if (addingTemplate.message === "Template saved successfully") {
setTemplates(addingTemplate.data);
}
}
});
//load Template response
visualizationSocket.on("viz-template:response:addTemplateZone", (loadTemplate: any) => {
if (loadTemplate.success) {
if (loadTemplate.message === "Template placed in Zone") {
let template = loadTemplate.data.template
setSelectedZone({
panelOrder: template.panelOrder,
activeSides: Array.from(new Set(template.panelOrder)), // No merging with previous `activeSides`
widgets: template.widgets,
});
useDroppedObjectsStore.getState().setZone(template.zoneName, template.zoneId);
if (Array.isArray(template.floatingWidget)) {
template.floatingWidget.forEach((val: any) => {
useDroppedObjectsStore.getState().addObject(template.zoneName, val);
});
}
}
}
});
//delete Template response
visualizationSocket.on("viz-template:response:delete", (deleteTemplate: any) => {
if (deleteTemplate.success) {
if (deleteTemplate.message === 'Template deleted successfully') {
removeTemplate(deleteTemplate.data);
}
}
});
}
}, [visualizationSocket])
return (
<></>
)
}

View File

@@ -0,0 +1,296 @@
import { useEffect } from "react";
import { useSocketStore } from "../../../store/store";
import { useSelectedZoneStore } from "../../../store/useZoneStore";
import { useDroppedObjectsStore } from "../../../store/useDroppedObjectsStore";
import { useZoneWidgetStore } from "../../../store/useZone3DWidgetStore";
import useTemplateStore from "../../../store/useTemplateStore";
type WidgetData = {
id: string;
type: string;
position: [number, number, number];
rotation?: [number, number, number];
tempPosition?: [number, number, number];
};
export default function SocketRealTimeViz() {
const { visualizationSocket } = useSocketStore();
const { setSelectedZone } = useSelectedZoneStore();
const deleteObject = useDroppedObjectsStore((state) => state.deleteObject);
const updateObjectPosition = useDroppedObjectsStore(
(state) => state.updateObjectPosition
);
const { addWidget } = useZoneWidgetStore();
const { removeTemplate } = useTemplateStore();
const { setTemplates } = useTemplateStore();
const {
zoneWidgetData,
setZoneWidgetData,
updateWidgetPosition,
updateWidgetRotation,
} = useZoneWidgetStore();
useEffect(() => {
if (visualizationSocket) {
//add panel response
visualizationSocket.on("viz-panel:response:updates", (addPanel: any) => {
if (addPanel.success) {
let addPanelData = addPanel.data.data;
setSelectedZone(addPanelData);
}
});
//delete panel response
visualizationSocket.on(
"viz-panel:response:delete",
(deletePanel: any) => {
if (deletePanel.success) {
let deletePanelData = deletePanel.data.data;
setSelectedZone(deletePanelData);
}
}
);
//clear Panel response
visualizationSocket.on("viz-panel:response:clear", (clearPanel: any) => {
if (
clearPanel.success &&
clearPanel.message === "PanelWidgets cleared successfully"
) {
let clearPanelData = clearPanel.data.data;
setSelectedZone(clearPanelData);
}
});
//lock Panel response
visualizationSocket.on("viz-panel:response:locked", (lockPanel: any) => {
if (
lockPanel.success &&
lockPanel.message === "locked panel updated successfully"
) {
let lockPanelData = lockPanel.data.data;
setSelectedZone(lockPanelData);
}
});
// add 2dWidget response
visualizationSocket.on(
"viz-widget:response:updates",
(add2dWidget: any) => {
if (add2dWidget.success && add2dWidget.data) {
setSelectedZone((prev) => {
const isWidgetAlreadyAdded = prev.widgets.some(
(widget) => widget.id === add2dWidget.data.widgetData.id
);
if (isWidgetAlreadyAdded) return prev; // Prevent duplicate addition
return {
...prev,
zoneId: add2dWidget.data.zoneId,
zoneName: add2dWidget.data.zoneName,
widgets: [...prev.widgets, add2dWidget.data.widgetData], // Append new widget
};
});
}
}
);
//delete 2D Widget response
visualizationSocket.on(
"viz-widget:response:delete",
(deleteWidget: any) => {
if (deleteWidget?.success && deleteWidget.data) {
setSelectedZone((prevZone: any) => ({
...prevZone,
zoneId: deleteWidget.data.zoneId,
zoneName: deleteWidget.data.zoneName,
widgets: deleteWidget.data.widgetDeleteDatas, // Replace with new widget list
}));
}
}
);
//add Floating Widget response
visualizationSocket.on(
"viz-float:response:updates",
(addFloatingWidget: any) => {
if (addFloatingWidget.success) {
if (
addFloatingWidget.success &&
addFloatingWidget.message === "FloatWidget created successfully"
) {
const state = useDroppedObjectsStore.getState();
const zone = state.zones[addFloatingWidget.data.zoneName];
if (!zone) {
state.setZone(
addFloatingWidget.data.zoneName,
addFloatingWidget.data.zoneId
);
}
const existingObjects = zone ? zone.objects : [];
const newWidget = addFloatingWidget.data.widget;
// ✅ Check if the widget ID already exists before adding
const isAlreadyAdded = existingObjects.some(
(obj) => obj.id === newWidget.id
);
if (isAlreadyAdded) {
return; // Don't add the widget if it already exists
}
// Add widget only if it doesn't exist
state.addObject(addFloatingWidget.data.zoneName, newWidget);
}
if (addFloatingWidget.message === "Widget updated successfully") {
updateObjectPosition(
addFloatingWidget.data.zoneName,
addFloatingWidget.data.index,
addFloatingWidget.data.position
);
}
}
}
);
//duplicate Floating Widget response
visualizationSocket.on(
"viz-float:response:addDuplicate",
(duplicateFloatingWidget: any) => {
if (
duplicateFloatingWidget.success &&
duplicateFloatingWidget.message ===
"duplicate FloatWidget created successfully"
) {
useDroppedObjectsStore.setState((state) => {
const zone = state.zones[duplicateFloatingWidget.data.zoneName];
if (!zone) return state; // Zone doesn't exist, return state as is
const existingObjects = zone.objects;
const newWidget = duplicateFloatingWidget.data.widget;
// ✅ Check if the object with the same ID already exists
const isAlreadyAdded = existingObjects.some(
(obj) => obj.id === newWidget.id
);
if (isAlreadyAdded) {
return state; // Don't update state if it's already there
}
return {
zones: {
...state.zones,
[duplicateFloatingWidget.data.zoneName]: {
...zone,
objects: [...existingObjects, newWidget], // Append only if it's not a duplicate
},
},
};
});
}
}
);
//delete Floating Widget response
visualizationSocket.on(
"viz-float:response:delete",
(deleteFloatingWidget: any) => {
if (deleteFloatingWidget.success) {
deleteObject(
deleteFloatingWidget.data.zoneName,
deleteFloatingWidget.data.floatWidgetID
);
}
}
);
//add 3D Widget response
visualizationSocket.on(
"viz-widget3D:response:updates",
(add3DWidget: any) => {
if (add3DWidget.success) {
if (add3DWidget.message === "Widget created successfully") {
addWidget(add3DWidget.data.zoneId, add3DWidget.data.widget);
}
}
}
);
//delete 3D Widget response
visualizationSocket.on(
"viz-widget3D:response:delete",
(delete3DWidget: any) => {
// "3DWidget delete unsuccessfull"
if (
delete3DWidget.success &&
delete3DWidget.message === "3DWidget delete successfull"
) {
const activeZoneWidgets =
zoneWidgetData[delete3DWidget.data.zoneId] || [];
setZoneWidgetData(
delete3DWidget.data.zoneId,
activeZoneWidgets.filter(
(w: WidgetData) => w.id !== delete3DWidget.data.id
)
);
}
}
);
//update3D widget response
visualizationSocket.on(
"viz-widget3D:response:modifyPositionRotation",
(update3DWidget: any) => {
if (
update3DWidget.success &&
update3DWidget.message === "widget update successfully"
) {
updateWidgetPosition(
update3DWidget.data.zoneId,
update3DWidget.data.widget.id,
update3DWidget.data.widget.position
);
updateWidgetRotation(
update3DWidget.data.zoneId,
update3DWidget.data.widget.id,
update3DWidget.data.widget.rotation
);
}
}
);
// add Template response
visualizationSocket.on(
"viz-template:response:add",
(addingTemplate: any) => {
if (addingTemplate.success) {
if (addingTemplate.message === "Template saved successfully") {
setTemplates(addingTemplate.data);
}
}
}
);
//load Template response
visualizationSocket.on(
"viz-template:response:addTemplateZone",
(loadTemplate: any) => {
if (loadTemplate.success) {
if (loadTemplate.message === "Template placed in Zone") {
let template = loadTemplate.data.template;
setSelectedZone({
panelOrder: template.panelOrder,
activeSides: Array.from(new Set(template.panelOrder)), // No merging with previous `activeSides`
widgets: template.widgets,
});
useDroppedObjectsStore
.getState()
.setZone(template.zoneName, template.zoneId);
if (Array.isArray(template.floatingWidget)) {
template.floatingWidget.forEach((val: any) => {
useDroppedObjectsStore
.getState()
.addObject(template.zoneName, val);
});
}
}
}
}
);
//delete Template response
visualizationSocket.on(
"viz-template:response:delete",
(deleteTemplate: any) => {
if (deleteTemplate.success) {
if (deleteTemplate.message === "Template deleted successfully") {
removeTemplate(deleteTemplate.data);
}
}
}
);
}
}, [visualizationSocket]);
return <></>;
}

View File

@@ -0,0 +1,133 @@
import { useEffect } from "react";
import { useDroppedObjectsStore } from "../../../store/useDroppedObjectsStore";
import useTemplateStore from "../../../store/useTemplateStore";
import { useSelectedZoneStore } from "../../../store/useZoneStore";
import { getTemplateData } from "../../../services/realTimeVisulization/zoneData/getTemplate";
import { useSocketStore } from "../../../store/store";
import RenameInput from "../../../components/ui/inputs/RenameInput";
const Templates = () => {
const { templates, removeTemplate, setTemplates } = useTemplateStore();
const { setSelectedZone, selectedZone } = useSelectedZoneStore();
const { visualizationSocket } = useSocketStore();
useEffect(() => {
async function templateData() {
try {
const email = localStorage.getItem("email") || "";
const organization = email?.split("@")[1]?.split(".")[0];
let response = await getTemplateData(organization);
setTemplates(response);
} catch (error) {
console.error("Error fetching template data:", error);
}
}
templateData();
}, []);
const handleDeleteTemplate = async (
e: React.MouseEvent<HTMLButtonElement>,
id: string
) => {
try {
e.stopPropagation();
const email = localStorage.getItem("email") || "";
const organization = email?.split("@")[1]?.split(".")[0];
let deleteTemplate = {
organization: organization,
templateID: id,
};
if (visualizationSocket) {
visualizationSocket.emit(
"v2:viz-template:deleteTemplate",
deleteTemplate
);
}
removeTemplate(id);
} catch (error) {
console.error("Error deleting template:", error);
}
};
const handleLoadTemplate = async (template: any) => {
try {
if (selectedZone.zoneName === "") return;
const email = localStorage.getItem("email") || "";
const organization = email?.split("@")[1]?.split(".")[0];
let loadingTemplate = {
organization: organization,
zoneId: selectedZone.zoneId,
templateID: template.id,
};
if (visualizationSocket) {
visualizationSocket.emit("v2:viz-template:addToZone", loadingTemplate);
}
setSelectedZone({
panelOrder: template.panelOrder,
activeSides: Array.from(new Set(template.panelOrder)), // No merging with previous `activeSides`
widgets: template.widgets,
});
useDroppedObjectsStore
.getState()
.setZone(selectedZone.zoneName, selectedZone.zoneId);
if (Array.isArray(template.floatingWidget)) {
template.floatingWidget.forEach((val: any) => {
useDroppedObjectsStore
.getState()
.addObject(selectedZone.zoneName, val);
});
}
} catch (error) {
console.error("Error loading template:", error);
}
};
return (
<div className="template-list widgets-wrapper">
{templates.map((template, index) => (
<div
key={template.id}
className="template-item"
onClick={() => handleLoadTemplate(template)}
>
{template?.snapshot && (
<div className="template-image-container">
<img
src={template.snapshot}
alt={`${template.name} preview`}
className="template-image"
/>
</div>
)}
<div className="template-details">
<div className="template-name">
{/* {`Template ${index + 1}`} */}
<RenameInput value={`Template ${index + 1}`} />
</div>
<button
onClick={(e) => handleDeleteTemplate(e, template.id)}
className="delete-button"
aria-label="Delete template"
>
Delete
</button>
</div>
</div>
))}
{templates.length === 0 && (
<div className="no-templates">
No saved templates yet. Create one in the visualization view!
</div>
)}
</div>
);
};
export default Templates;

View File

@@ -0,0 +1,393 @@
import { useWidgetStore } from "../../../../store/useWidgetStore";
import ProgressCard from "../2d/charts/ProgressCard";
import PieGraphComponent from "../2d/charts/PieGraphComponent";
import BarGraphComponent from "../2d/charts/BarGraphComponent";
import LineGraphComponent from "../2d/charts/LineGraphComponent";
import DoughnutGraphComponent from "../2d/charts/DoughnutGraphComponent";
import PolarAreaGraphComponent from "../2d/charts/PolarAreaGraphComponent";
import ProgressCard1 from "../2d/charts/ProgressCard1";
import ProgressCard2 from "../2d/charts/ProgressCard2";
import {
DeleteIcon,
DublicateIcon,
KebabIcon,
} from "../../../../components/icons/ExportCommonIcons";
import { useEffect, useRef, useState } from "react";
import { duplicateWidgetApi } from "../../../../services/realTimeVisulization/zoneData/duplicateWidget";
import { deleteWidgetApi } from "../../../../services/realTimeVisulization/zoneData/deleteWidgetApi";
import { useClickOutside } from "../../functions/handleWidgetsOuterClick";
import { useSocketStore } from "../../../../store/store";
import { usePlayButtonStore } from "../../../../store/usePlayButtonStore";
import OuterClick from "../../../../utils/outerClick";
type Side = "top" | "bottom" | "left" | "right";
interface Widget {
id: string;
type: string;
title: string;
panel: Side;
data: any;
}
export const DraggableWidget = ({
widget,
hiddenPanels,
index,
onReorder,
openKebabId,
setOpenKebabId,
selectedZone,
setSelectedZone,
}: {
selectedZone: {
zoneName: string;
zoneId: string;
activeSides: Side[];
points: [];
panelOrder: Side[];
lockedPanels: Side[];
widgets: Widget[];
};
setSelectedZone: React.Dispatch<
React.SetStateAction<{
zoneName: string;
activeSides: Side[];
panelOrder: Side[];
points: [];
lockedPanels: Side[];
zoneId: string;
zoneViewPortTarget: number[];
zoneViewPortPosition: number[];
widgets: {
id: string;
type: string;
title: string;
panel: Side;
data: any;
}[];
}>
>;
widget: any;
hiddenPanels: string[];
index: number;
onReorder: (fromIndex: number, toIndex: number) => void;
openKebabId: string | null;
setOpenKebabId: (id: string | null) => void;
}) => {
const { visualizationSocket } = useSocketStore();
const { selectedChartId, setSelectedChartId } = useWidgetStore();
const [panelDimensions, setPanelDimensions] = useState<{
[side in Side]?: { width: number; height: number };
}>({});
const handlePointerDown = () => {
if (selectedChartId?.id !== widget.id) {
setSelectedChartId(widget);
}
};
const chartWidget = useRef<HTMLDivElement>(null);
const deleteSelectedChart = async () => {
try {
const email = localStorage.getItem("email") || "";
const organization = email?.split("@")[1]?.split(".")[0];
let deleteWidget = {
zoneId: selectedZone.zoneId,
widgetID: widget.id,
organization: organization,
};
if (visualizationSocket) {
visualizationSocket.emit("v2:viz-widget:delete", deleteWidget);
}
const updatedWidgets = selectedZone.widgets.filter(
(w: Widget) => w.id !== widget.id
);
setSelectedZone((prevZone: any) => ({
...prevZone,
widgets: updatedWidgets,
}));
setOpenKebabId(null);
// const response = await deleteWidgetApi(widget.id, organization);
// if (response?.message === "Widget deleted successfully") {
// const updatedWidgets = selectedZone.widgets.filter(
// (w: Widget) => w.id !== widget.id
// );
// setSelectedZone((prevZone: any) => ({
// ...prevZone,
// widgets: updatedWidgets,
// }));
// }
} catch (error) {
} finally {
setOpenKebabId(null);
}
};
const getCurrentWidgetCount = (panel: Side) =>
selectedZone.widgets.filter((w) => w.panel === panel).length;
const calculatePanelCapacity = (panel: Side) => {
const CHART_WIDTH = 150;
const CHART_HEIGHT = 150;
const FALLBACK_HORIZONTAL_CAPACITY = 5;
const FALLBACK_VERTICAL_CAPACITY = 3;
const dimensions = panelDimensions[panel];
if (!dimensions) {
return panel === "top" || panel === "bottom"
? FALLBACK_HORIZONTAL_CAPACITY
: FALLBACK_VERTICAL_CAPACITY;
}
return panel === "top" || panel === "bottom"
? Math.floor(dimensions.width / CHART_WIDTH)
: Math.floor(dimensions.height / CHART_HEIGHT);
};
const isPanelFull = (panel: Side) => {
const currentWidgetCount = getCurrentWidgetCount(panel);
const panelCapacity = calculatePanelCapacity(panel);
return currentWidgetCount >= panelCapacity;
};
const duplicateWidget = async () => {
try {
const email = localStorage.getItem("email") || "";
const organization = email?.split("@")[1]?.split(".")[0];
const duplicatedWidget: Widget = {
...widget,
id: `${widget.id}-copy-${Date.now()}`,
};
console.log("duplicatedWidget: ", duplicatedWidget);
let duplicateWidget = {
organization: organization,
zoneId: selectedZone.zoneId,
widget: duplicatedWidget,
};
if (visualizationSocket) {
visualizationSocket.emit("v2:viz-widget:add", duplicateWidget);
}
setSelectedZone((prevZone: any) => ({
...prevZone,
widgets: [...prevZone.widgets, duplicatedWidget],
}));
// const response = await duplicateWidgetApi(selectedZone.zoneId, organization, duplicatedWidget);
// if (response?.message === "Widget created successfully") {
// setSelectedZone((prevZone: any) => ({
// ...prevZone,
// widgets: [...prevZone.widgets, duplicatedWidget],
// }));
// }
} catch (error) {
} finally {
setOpenKebabId(null);
}
};
const handleKebabClick = (event: React.MouseEvent<HTMLDivElement>) => {
event.stopPropagation();
if (openKebabId === widget.id) {
setOpenKebabId(null);
} else {
setOpenKebabId(widget.id);
}
};
const widgetRef = useRef<HTMLDivElement | null>(null);
useEffect(() => {
const handleClickOutside = (event: MouseEvent) => {
if (
widgetRef.current &&
!widgetRef.current.contains(event.target as Node)
) {
setOpenKebabId(null);
}
};
document.addEventListener("mousedown", handleClickOutside);
return () => {
document.removeEventListener("mousedown", handleClickOutside);
};
}, [setOpenKebabId]);
const handleDragStart = (event: React.DragEvent<HTMLDivElement>) => {
event.dataTransfer.setData("text/plain", index.toString()); // Store the index of the dragged widget
};
const handleDragEnter = (event: React.DragEvent<HTMLDivElement>) => {
event.preventDefault(); // Allow drop
};
const handleDragOver = (event: React.DragEvent<HTMLDivElement>) => {
event.preventDefault(); // Allow drop
};
const handleDrop = (event: React.DragEvent<HTMLDivElement>) => {
event.preventDefault();
const fromIndex = parseInt(event.dataTransfer.getData("text/plain"), 10); // Get the dragged widget's index
const toIndex = index; // The index of the widget where the drop occurred
if (fromIndex !== toIndex) {
onReorder(fromIndex, toIndex); // Call the reorder function passed as a prop
}
};
// useClickOutside(chartWidget, () => {
// setSelectedChartId(null);
// });
const { isPlaying } = usePlayButtonStore();
const [canvasDimensions, setCanvasDimensions] = useState({
width: 0,
height: 0,
});
// Track canvas dimensions
// Current: Two identical useEffect hooks for canvas dimensions
// Remove the duplicate and keep only one
useEffect(() => {
const canvas = document.getElementById("real-time-vis-canvas");
if (!canvas) return;
const updateCanvasDimensions = () => {
const rect = canvas.getBoundingClientRect();
setCanvasDimensions({
width: rect.width,
height: rect.height,
});
};
updateCanvasDimensions();
const resizeObserver = new ResizeObserver(updateCanvasDimensions);
resizeObserver.observe(canvas);
return () => resizeObserver.unobserve(canvas);
}, []);
return (
<>
<style>
{`
:root {
--realTimeViz-container-width: ${canvasDimensions.width}px;
--realTimeViz-container-height: ${canvasDimensions.height}px;
}
`}
</style>
<div
draggable
key={widget.id}
className={`chart-container ${
selectedChartId?.id === widget.id && !isPlaying && "activeChart"
}`}
onPointerDown={handlePointerDown}
onDragStart={handleDragStart}
onDragEnter={handleDragEnter}
onDragOver={handleDragOver}
onDrop={handleDrop}
style={{
width: ["top", "bottom"].includes(widget.panel)
? `calc(${canvasDimensions.width}px / 6)`
: undefined,
height: ["left", "right"].includes(widget.panel)
? `calc(${canvasDimensions.height - 10}px / 4)`
: undefined,
}}
ref={chartWidget}
onClick={() => setSelectedChartId(widget)}
>
{/* Kebab Icon */}
<div className="icon kebab" onClick={handleKebabClick}>
<KebabIcon />
</div>
{/* Kebab Options */}
{openKebabId === widget.id && (
<div className="kebab-options" ref={widgetRef}>
<div
className={`edit btn ${
isPanelFull(widget.panel) ? "btn-blur" : ""
}`}
onClick={isPanelFull(widget.panel) ? undefined : duplicateWidget}
>
<div className="icon">
<DublicateIcon />
</div>
<div className="label">Duplicate</div>
</div>
<div className="edit btn" onClick={deleteSelectedChart}>
<div className="icon">
<DeleteIcon />
</div>
<div className="label">Delete</div>
</div>
</div>
)}
{/* Render charts based on widget type */}
{widget.type === "progress 1" && (
<ProgressCard1 title={widget.title} id={widget.id} />
)}
{widget.type === "progress 2" && (
<ProgressCard2 title={widget.title} id={widget.id} />
)}
{widget.type === "line" && (
<LineGraphComponent
id={widget.id}
type={widget.type}
title={widget.title}
fontSize={widget.fontSize}
fontWeight={widget.fontWeight}
/>
)}
{widget.type === "bar" && (
<BarGraphComponent
id={widget.id}
type={widget.type}
title={widget.title}
fontSize={widget.fontSize}
fontWeight={widget.fontWeight}
/>
)}
{widget.type === "pie" && (
<PieGraphComponent
id={widget.id}
type={widget.type}
title={widget.title}
fontSize={widget.fontSize}
fontWeight={widget.fontWeight}
/>
)}
{widget.type === "doughnut" && (
<DoughnutGraphComponent
id={widget.id}
type={widget.type}
title={widget.title}
fontSize={widget.fontSize}
fontWeight={widget.fontWeight}
/>
)}
{widget.type === "polarArea" && (
<PolarAreaGraphComponent
id={widget.id}
type={widget.type}
title={widget.title}
fontSize={widget.fontSize}
fontWeight={widget.fontWeight}
/>
)}
</div>
</>
);
};

View File

@@ -0,0 +1,377 @@
// import React, { useEffect, useRef, useMemo, useState } from "react";
// import { Chart } from "chart.js/auto";
// import { useThemeStore } from "../../../../store/useThemeStore";
// import io from "socket.io-client";
// import { Bar } from 'react-chartjs-2';
// import useChartStore from "../../../../store/useChartStore";
// // WebSocket Connection
// // const socket = io("http://localhost:5000"); // Adjust to your backend URL
// interface ChartComponentProps {
// type: any;
// title: string;
// fontFamily?: string;
// fontSize?: string;
// fontWeight?: "Light" | "Regular" | "Bold";
// data: any;
// }
// const LineGraphComponent = ({
// type,
// title,
// fontFamily,
// fontSize,
// fontWeight = "Regular",
// data,
// }: ChartComponentProps) => {
// const canvasRef = useRef<HTMLCanvasElement>(null);
// const { themeColor } = useThemeStore();
// const [chartData, setChartData] = useState<{ labels: string[]; datasets: any[] }>({
// labels: [],
// datasets: [],
// });
// const iotApiUrl = process.env.REACT_APP_IOT_SOCKET_SERVER_URL;
// const defaultData = {
// labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
// datasets: [
// {
// label: "Dataset",
// data: [12, 19, 3, 5, 2, 3],
// backgroundColor: ["#6f42c1"],
// borderColor: "#ffffff",
// borderWidth: 2,
// },
// ],
// };
// // Memoize Theme Colors to Prevent Unnecessary Recalculations
// const buttonActionColor = useMemo(
// () => themeColor[0] || "#5c87df",
// [themeColor]
// );
// const buttonAbortColor = useMemo(
// () => themeColor[1] || "#ffffff",
// [themeColor]
// );
// // Memoize Font Weight Mapping
// const chartFontWeightMap = useMemo(
// () => ({
// Light: "lighter" as const,
// Regular: "normal" as const,
// Bold: "bold" as const,
// }),
// []
// );
// // Parse and Memoize Font Size
// const fontSizeValue = useMemo(
// () => (fontSize ? parseInt(fontSize) : 12),
// [fontSize]
// );
// // Determine and Memoize Font Weight
// const fontWeightValue = useMemo(
// () => chartFontWeightMap[fontWeight],
// [fontWeight, chartFontWeightMap]
// );
// // Memoize Chart Font Style
// const chartFontStyle = useMemo(
// () => ({
// family: fontFamily || "Arial",
// size: fontSizeValue,
// weight: fontWeightValue,
// }),
// [fontFamily, fontSizeValue, fontWeightValue]
// );
// // Memoize Chart Data
// // const data = useMemo(() => propsData, [propsData]);
// // Memoize Chart Options
// const options = useMemo(
// () => ({
// responsive: true,
// maintainAspectRatio: false,
// plugins: {
// title: {
// display: true,
// text: title,
// font: chartFontStyle,
// },
// legend: {
// display: false,
// },
// },
// scales: {
// x: {
// ticks: {
// display: true, // This hides the x-axis labels
// },
// },
// },
// }),
// [title, chartFontStyle]
// );
// const { measurements, setMeasurements, updateDuration, duration } = useChartStore();
// useEffect(() => {
// const socket = io(`http://${iotApiUrl}`);
// if ( measurements.length > 0 ) {
// var inputes = {
// measurements: measurements,
// duration: duration,
// interval: 1000,
// }
// // Start stream
// const startStream = () => {
// socket.emit("lineInput", inputes);
// }
// socket.on('connect', startStream);
// socket.on("lineOutput", (response) => {
// const responceData = response.data;
// console.log("Received data:", responceData);
// // Extract timestamps and values
// const labels = responceData.time;
// const datasets = measurements.map((measurement: any) => {
// const key = `${measurement.name}.${measurement.fields}`;
// return {
// label: key,
// data: responceData[key]?.values ?? [], // Ensure it exists
// backgroundColor: "#6f42c1",
// borderColor: "#ffffff",
// };
// });
// setChartData({ labels, datasets });
// });
// }
// return () => {
// socket.off("lineOutput");
// socket.emit("stop_stream"); // Stop streaming when component unmounts
// };
// }, [measurements, duration]);
// // useEffect(() => {
// // if (!canvasRef.current) return;
// // const ctx = canvasRef.current.getContext("2d");
// // if (!ctx) return;
// // const chart = new Chart(ctx, {
// // type,
// // data: chartData,
// // options: options,
// // });
// // return () => chart.destroy();
// // }, [chartData, type, title]);
// return <Bar data={measurements && measurements.length > 0 ? chartData : defaultData} options={options} />;
// };
// export default LineGraphComponent;
import React, { useEffect, useMemo, useState } from "react";
import { Bar } from "react-chartjs-2";
import io from "socket.io-client";
import axios from "axios";
import { useThemeStore } from "../../../../../store/useThemeStore";
import { useWidgetStore } from "../../../../../store/useWidgetStore";
import useChartStore from "../../../../../store/useChartStore";
interface ChartComponentProps {
id: string;
type: any;
title: string;
fontFamily?: string;
fontSize?: string;
fontWeight?: "Light" | "Regular" | "Bold";
}
const BarGraphComponent = ({
id,
type,
title,
fontFamily,
fontSize,
fontWeight = "Regular",
}: ChartComponentProps) => {
const { themeColor } = useThemeStore();
const { measurements: chartMeasurements, duration: chartDuration, name: widgetName } = useChartStore();
const [measurements, setmeasurements] = useState<any>({});
const [duration, setDuration] = useState("1h")
const [name, setName] = useState("Widget")
const [chartData, setChartData] = useState<{ labels: string[]; datasets: any[] }>({
labels: [],
datasets: [],
});
const { selectedChartId } = useWidgetStore();
const iotApiUrl = process.env.REACT_APP_IOT_SOCKET_SERVER_URL;
const email = localStorage.getItem("email") || "";
const organization = email?.split("@")[1]?.split(".")[0]
const defaultData = {
labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
datasets: [
{
label: "Dataset",
data: [12, 19, 3, 5, 2, 3],
backgroundColor: ["#6f42c1"],
borderColor: "#b392f0",
borderWidth: 1,
},
],
};
useEffect(() => {
},[])
// Memoize Theme Colors
const buttonActionColor = useMemo(() => themeColor[0] || "#5c87df", [themeColor]);
const buttonAbortColor = useMemo(() => themeColor[1] || "#ffffff", [themeColor]);
// Memoize Font Styling
const chartFontWeightMap = useMemo(
() => ({
Light: "lighter" as const,
Regular: "normal" as const,
Bold: "bold" as const,
}),
[]
);
const fontSizeValue = useMemo(() => (fontSize ? parseInt(fontSize) : 12), [fontSize]);
const fontWeightValue = useMemo(() => chartFontWeightMap[fontWeight], [fontWeight, chartFontWeightMap]);
const chartFontStyle = useMemo(
() => ({
family: fontFamily || "Arial",
size: fontSizeValue,
weight: fontWeightValue,
}),
[fontFamily, fontSizeValue, fontWeightValue]
);
// Memoize Chart Options
const options = useMemo(
() => ({
responsive: true,
maintainAspectRatio: false,
plugins: {
title: {
display: true,
text: name,
font: chartFontStyle,
},
legend: {
display: false,
},
},
scales: {
x: {
ticks: {
display: true, // This hides the x-axis labels
},
},
},
}),
[title, chartFontStyle, name]
);
// useEffect(() => {console.log(measurements);
// },[measurements])
useEffect(() => {
if (!iotApiUrl || !measurements || Object.keys(measurements).length === 0) return;
const socket = io(`http://${iotApiUrl}`);
const inputData = {
measurements,
duration,
interval: 1000,
};
const startStream = () => {
socket.emit("lineInput", inputData);
};
socket.on("connect", startStream);
socket.on("lineOutput", (response) => {
const responseData = response.data;
// Extract timestamps and values
const labels = responseData.time;
const datasets = Object.keys(measurements).map((key) => {
const measurement = measurements[key];
const datasetKey = `${measurement.name}.${measurement.fields}`;
return {
label: datasetKey,
data: responseData[datasetKey]?.values ?? [],
backgroundColor: "#6f42c1",
borderColor: "#b392f0",
borderWidth: 1,
};
});
setChartData({ labels, datasets });
});
return () => {
socket.off("lineOutput");
socket.emit("stop_stream"); // Stop streaming when component unmounts
socket.disconnect();
};
}, [measurements, duration, iotApiUrl]);
const fetchSavedInputes = async() => {
if (id !== "") {
try {
const response = await axios.get(`http://${process.env.REACT_APP_SERVER_REST_API_BASE_URL}/api/v2/WidgetData/${id}/${organization}`);
if (response.status === 200) {
setmeasurements(response.data.Data.measurements)
setDuration(response.data.Data.duration)
setName(response.data.widgetName)
} else {
console.log("Unexpected response:", response);
}
} catch (error) {
console.error("There was an error!", error);
}
}
}
useEffect(() => {
fetchSavedInputes();
}, []);
useEffect(() => {
if (selectedChartId?.id === id) {
fetchSavedInputes();
}
}
,[chartMeasurements, chartDuration, widgetName])
return <Bar data={Object.keys(measurements).length > 0 ? chartData : defaultData} options={options} />;
};
export default BarGraphComponent;

View File

@@ -0,0 +1,190 @@
import React, { useEffect, useMemo, useState } from "react";
import { Doughnut } from "react-chartjs-2";
import io from "socket.io-client";
import axios from "axios";
import { useThemeStore } from "../../../../../store/useThemeStore";
import { useWidgetStore } from "../../../../../store/useWidgetStore";
import useChartStore from "../../../../../store/useChartStore";
interface ChartComponentProps {
id: string;
type: any;
title: string;
fontFamily?: string;
fontSize?: string;
fontWeight?: "Light" | "Regular" | "Bold";
}
const DoughnutGraphComponent = ({
id,
type,
title,
fontFamily,
fontSize,
fontWeight = "Regular",
}: ChartComponentProps) => {
const { themeColor } = useThemeStore();
const { measurements: chartMeasurements, duration: chartDuration, name: widgetName } = useChartStore();
const [measurements, setmeasurements] = useState<any>({});
const [duration, setDuration] = useState("1h")
const [name, setName] = useState("Widget")
const [chartData, setChartData] = useState<{ labels: string[]; datasets: any[] }>({
labels: [],
datasets: [],
});
const { selectedChartId } = useWidgetStore();
const iotApiUrl = process.env.REACT_APP_IOT_SOCKET_SERVER_URL;
const email = localStorage.getItem("email") || "";
const organization = email?.split("@")[1]?.split(".")[0]
const defaultData = {
labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
datasets: [
{
label: "Dataset",
data: [12, 19, 3, 5, 2, 3],
backgroundColor: ["#6f42c1"],
borderColor: "#b392f0",
borderWidth: 1,
},
],
};
useEffect(() => {
},[])
// Memoize Theme Colors
const buttonActionColor = useMemo(() => themeColor[0] || "#5c87df", [themeColor]);
const buttonAbortColor = useMemo(() => themeColor[1] || "#ffffff", [themeColor]);
// Memoize Font Styling
const chartFontWeightMap = useMemo(
() => ({
Light: "lighter" as const,
Regular: "normal" as const,
Bold: "bold" as const,
}),
[]
);
const fontSizeValue = useMemo(() => (fontSize ? parseInt(fontSize) : 12), [fontSize]);
const fontWeightValue = useMemo(() => chartFontWeightMap[fontWeight], [fontWeight, chartFontWeightMap]);
const chartFontStyle = useMemo(
() => ({
family: fontFamily || "Arial",
size: fontSizeValue,
weight: fontWeightValue,
}),
[fontFamily, fontSizeValue, fontWeightValue]
);
// Memoize Chart Options
const options = useMemo(
() => ({
responsive: true,
maintainAspectRatio: false,
plugins: {
title: {
display: true,
text: name,
font: chartFontStyle,
},
legend: {
display: false,
},
},
scales: {
// x: {
// ticks: {
// display: true, // This hides the x-axis labels
// },
// },
},
}),
[title, chartFontStyle, name]
);
// useEffect(() => {console.log(measurements);
// },[measurements])
useEffect(() => {
if (!iotApiUrl || !measurements || Object.keys(measurements).length === 0) return;
const socket = io(`http://${iotApiUrl}`);
const inputData = {
measurements,
duration,
interval: 1000,
};
const startStream = () => {
socket.emit("lineInput", inputData);
};
socket.on("connect", startStream);
socket.on("lineOutput", (response) => {
const responseData = response.data;
// Extract timestamps and values
const labels = responseData.time;
const datasets = Object.keys(measurements).map((key) => {
const measurement = measurements[key];
const datasetKey = `${measurement.name}.${measurement.fields}`;
return {
label: datasetKey,
data: responseData[datasetKey]?.values ?? [],
backgroundColor: "#6f42c1",
borderColor: "#b392f0",
borderWidth: 1,
};
});
setChartData({ labels, datasets });
});
return () => {
socket.off("lineOutput");
socket.emit("stop_stream"); // Stop streaming when component unmounts
socket.disconnect();
};
}, [measurements, duration, iotApiUrl]);
const fetchSavedInputes = async() => {
if (id !== "") {
try {
const response = await axios.get(`http://${process.env.REACT_APP_SERVER_REST_API_BASE_URL}/api/v2/WidgetData/${id}/${organization}`);
if (response.status === 200) {
setmeasurements(response.data.Data.measurements)
setDuration(response.data.Data.duration)
setName(response.data.widgetName)
} else {
console.log("Unexpected response:", response);
}
} catch (error) {
console.error("There was an error!", error);
}
}
}
useEffect(() => {
fetchSavedInputes();
}, []);
useEffect(() => {
if (selectedChartId?.id === id) {
fetchSavedInputes();
}
}
,[chartMeasurements, chartDuration, widgetName])
return <Doughnut data={Object.keys(measurements).length > 0 ? chartData : defaultData} options={options} />;
};
export default DoughnutGraphComponent;

View File

@@ -0,0 +1,212 @@
import React, { useEffect, useMemo, useState } from "react";
import { Line } from "react-chartjs-2";
import io from "socket.io-client";
import axios from "axios";
import { useThemeStore } from "../../../../../store/useThemeStore";
import useChartStore from "../../../../../store/useChartStore";
import { useWidgetStore } from "../../../../../store/useWidgetStore";
interface ChartComponentProps {
id: string;
type: any;
title: string;
fontFamily?: string;
fontSize?: string;
fontWeight?: "Light" | "Regular" | "Bold";
}
const LineGraphComponent = ({
id,
type,
title,
fontFamily,
fontSize,
fontWeight = "Regular",
}: ChartComponentProps) => {
const { themeColor } = useThemeStore();
const {
measurements: chartMeasurements,
duration: chartDuration,
name: widgetName,
} = useChartStore();
const [measurements, setmeasurements] = useState<any>({});
const [duration, setDuration] = useState("1h");
const [name, setName] = useState("Widget");
const [chartData, setChartData] = useState<{
labels: string[];
datasets: any[];
}>({
labels: [],
datasets: [],
});
const { selectedChartId } = useWidgetStore();
const iotApiUrl = process.env.REACT_APP_IOT_SOCKET_SERVER_URL;
const email = localStorage.getItem("email") || "";
const organization = email?.split("@")[1]?.split(".")[0];
const defaultData = {
labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
datasets: [
{
label: "Dataset",
data: [12, 19, 3, 5, 2, 3],
backgroundColor: ["#6f42c1"],
borderColor: "#b392f0",
borderWidth: 1,
},
],
};
useEffect(() => {}, []);
// Memoize Theme Colors
const buttonActionColor = useMemo(
() => themeColor[0] || "#5c87df",
[themeColor]
);
const buttonAbortColor = useMemo(
() => themeColor[1] || "#ffffff",
[themeColor]
);
// Memoize Font Styling
const chartFontWeightMap = useMemo(
() => ({
Light: "lighter" as const,
Regular: "normal" as const,
Bold: "bold" as const,
}),
[]
);
const fontSizeValue = useMemo(
() => (fontSize ? parseInt(fontSize) : 12),
[fontSize]
);
const fontWeightValue = useMemo(
() => chartFontWeightMap[fontWeight],
[fontWeight, chartFontWeightMap]
);
const chartFontStyle = useMemo(
() => ({
family: fontFamily || "Arial",
size: fontSizeValue,
weight: fontWeightValue,
}),
[fontFamily, fontSizeValue, fontWeightValue]
);
// Memoize Chart Options
const options = useMemo(
() => ({
responsive: true,
maintainAspectRatio: false,
plugins: {
title: {
display: true,
text: name,
font: chartFontStyle,
},
legend: {
display: false,
},
},
scales: {
x: {
ticks: {
display: true, // This hides the x-axis labels
},
},
},
}),
[title, chartFontStyle, name]
);
// useEffect(() => {console.log(measurements);
// },[measurements])
useEffect(() => {
if (!iotApiUrl || !measurements || Object.keys(measurements).length === 0)
return;
const socket = io(`http://${iotApiUrl}`);
const inputData = {
measurements,
duration,
interval: 1000,
};
const startStream = () => {
socket.emit("lineInput", inputData);
};
socket.on("connect", startStream);
socket.on("lineOutput", (response) => {
const responseData = response.data;
// Extract timestamps and values
const labels = responseData.time;
const datasets = Object.keys(measurements).map((key) => {
const measurement = measurements[key];
const datasetKey = `${measurement.name}.${measurement.fields}`;
return {
label: datasetKey,
data: responseData[datasetKey]?.values ?? [],
backgroundColor: "#6f42c1",
borderColor: "#b392f0",
borderWidth: 1,
};
});
setChartData({ labels, datasets });
});
return () => {
socket.off("lineOutput");
socket.emit("stop_stream"); // Stop streaming when component unmounts
socket.disconnect();
};
}, [measurements, duration, iotApiUrl]);
const fetchSavedInputes = async () => {
if (id !== "") {
try {
const response = await axios.get(
`http://${process.env.REACT_APP_SERVER_REST_API_BASE_URL}/api/v2/WidgetData/${id}/${organization}`
);
if (response.status === 200) {
setmeasurements(response.data.Data.measurements);
setDuration(response.data.Data.duration);
setName(response.data.widgetName);
} else {
console.log("Unexpected response:", response);
}
} catch (error) {
console.error("There was an error!", error);
}
}
};
useEffect(() => {
fetchSavedInputes();
}, []);
useEffect(() => {
if (selectedChartId?.id === id) {
fetchSavedInputes();
}
}, [chartMeasurements, chartDuration, widgetName]);
return (
<Line
data={Object.keys(measurements).length > 0 ? chartData : defaultData}
options={options}
/>
);
};
export default LineGraphComponent;

View File

@@ -0,0 +1,397 @@
// import React, { useEffect, useRef, useMemo, useState } from "react";
// import { Chart } from "chart.js/auto";
// import { useThemeStore } from "../../../../store/useThemeStore";
// import io from "socket.io-client";
// import { Pie } from 'react-chartjs-2';
// import useChartStore from "../../../../store/useChartStore";
// // WebSocket Connection
// // const socket = io("http://localhost:5000"); // Adjust to your backend URL
// interface ChartComponentProps {
// type: any;
// title: string;
// fontFamily?: string;
// fontSize?: string;
// fontWeight?: "Light" | "Regular" | "Bold";
// data: any;
// }
// const PieChartComponent = ({
// type,
// title,
// fontFamily,
// fontSize,
// fontWeight = "Regular",
// data,
// }: ChartComponentProps) => {
// const canvasRef = useRef<HTMLCanvasElement>(null);
// const { themeColor } = useThemeStore();
// const [chartData, setChartData] = useState<{ labels: string[]; datasets: any[] }>({
// labels: [],
// datasets: [],
// });
// const iotApiUrl = process.env.REACT_APP_IOT_SOCKET_SERVER_URL;
// const defaultData = {
// labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
// datasets: [
// {
// label: "Dataset",
// data: [12, 19, 3, 5, 2, 3],
// backgroundColor: ["#6f42c1"],
// borderColor: "#ffffff",
// borderWidth: 2,
// },
// ],
// };
// // Memoize Theme Colors to Prevent Unnecessary Recalculations
// const buttonActionColor = useMemo(
// () => themeColor[0] || "#6f42c1",
// [themeColor]
// );
// const buttonAbortColor = useMemo(
// () => themeColor[1] || "#ffffff",
// [themeColor]
// );
// // Memoize Font Weight Mapping
// const chartFontWeightMap = useMemo(
// () => ({
// Light: "lighter" as const,
// Regular: "normal" as const,
// Bold: "bold" as const,
// }),
// []
// );
// // Parse and Memoize Font Size
// const fontSizeValue = useMemo(
// () => (fontSize ? parseInt(fontSize) : 12),
// [fontSize]
// );
// // Determine and Memoize Font Weight
// const fontWeightValue = useMemo(
// () => chartFontWeightMap[fontWeight],
// [fontWeight, chartFontWeightMap]
// );
// // Memoize Chart Font Style
// const chartFontStyle = useMemo(
// () => ({
// family: fontFamily || "Arial",
// size: fontSizeValue,
// weight: fontWeightValue,
// }),
// [fontFamily, fontSizeValue, fontWeightValue]
// );
// // Memoize Chart Data
// // const data = useMemo(() => propsData, [propsData]);
// // Memoize Chart Options
// const options = useMemo(
// () => ({
// responsive: true,
// maintainAspectRatio: false,
// plugins: {
// title: {
// display: true,
// text: title,
// font: chartFontStyle,
// },
// legend: {
// display: false,
// },
// },
// scales: {
// // x: {
// // ticks: {
// // display: true, // This hides the x-axis labels
// // },
// // },
// },
// }),
// [title, chartFontStyle]
// );
// const { measurements, setMeasurements, updateDuration, duration } = useChartStore();
// useEffect(() => {
// const socket = io(`http://${iotApiUrl}`);
// if ( measurements.length > 0 ) {
// var inputes = {
// measurements: measurements,
// duration: duration,
// interval: 1000,
// }
// // Start stream
// const startStream = () => {
// socket.emit("lineInput", inputes);
// }
// socket.on('connect', startStream);
// socket.on("lineOutput", (response) => {
// const responceData = response.data;
// console.log("Received data:", responceData);
// // Extract timestamps and values
// const labels = responceData.time;
// const datasets = measurements.map((measurement: any) => {
// const key = `${measurement.name}.${measurement.fields}`;
// return {
// label: key,
// data: responceData[key]?.values ?? [], // Ensure it exists
// backgroundColor: "#6f42c1",
// borderColor: "#ffffff",
// };
// });
// setChartData({ labels, datasets });
// });
// }
// return () => {
// socket.off("lineOutput");
// socket.emit("stop_stream"); // Stop streaming when component unmounts
// };
// }, [measurements, duration]);
// // useEffect(() => {
// // if (!canvasRef.current) return;
// // const ctx = canvasRef.current.getContext("2d");
// // if (!ctx) return;
// // const chart = new Chart(ctx, {
// // type,
// // data: chartData,
// // options: options,
// // });
// // return () => chart.destroy();
// // }, [chartData, type, title]);
// return <Pie data={measurements && measurements.length > 0 ? chartData : defaultData} options={options} />;
// };
// export default PieChartComponent;
import React, { useEffect, useMemo, useState } from "react";
import { Pie } from "react-chartjs-2";
import io from "socket.io-client";
import axios from "axios";
import { useThemeStore } from "../../../../../store/useThemeStore";
import useChartStore from "../../../../../store/useChartStore";
import { useWidgetStore } from "../../../../../store/useWidgetStore";
interface ChartComponentProps {
id: string;
type: any;
title: string;
fontFamily?: string;
fontSize?: string;
fontWeight?: "Light" | "Regular" | "Bold";
}
const PieChartComponent = ({
id,
type,
title,
fontFamily,
fontSize,
fontWeight = "Regular",
}: ChartComponentProps) => {
const { themeColor } = useThemeStore();
const {
measurements: chartMeasurements,
duration: chartDuration,
name: widgetName,
} = useChartStore();
const [measurements, setmeasurements] = useState<any>({});
const [duration, setDuration] = useState("1h");
const [name, setName] = useState("Widget");
const [chartData, setChartData] = useState<{
labels: string[];
datasets: any[];
}>({
labels: [],
datasets: [],
});
const { selectedChartId } = useWidgetStore();
const iotApiUrl = process.env.REACT_APP_IOT_SOCKET_SERVER_URL;
const email = localStorage.getItem("email") || "";
const organization = email?.split("@")[1]?.split(".")[0];
const defaultData = {
labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
datasets: [
{
label: "Dataset",
data: [12, 19, 3, 5, 2, 3],
backgroundColor: ["#6f42c1"],
borderColor: "#b392f0",
borderWidth: 1,
},
],
};
useEffect(() => {}, []);
// Memoize Theme Colors
const buttonActionColor = useMemo(
() => themeColor[0] || "#5c87df",
[themeColor]
);
const buttonAbortColor = useMemo(
() => themeColor[1] || "#ffffff",
[themeColor]
);
// Memoize Font Styling
const chartFontWeightMap = useMemo(
() => ({
Light: "lighter" as const,
Regular: "normal" as const,
Bold: "bold" as const,
}),
[]
);
const fontSizeValue = useMemo(
() => (fontSize ? parseInt(fontSize) : 12),
[fontSize]
);
const fontWeightValue = useMemo(
() => chartFontWeightMap[fontWeight],
[fontWeight, chartFontWeightMap]
);
const chartFontStyle = useMemo(
() => ({
family: fontFamily || "Arial",
size: fontSizeValue,
weight: fontWeightValue,
}),
[fontFamily, fontSizeValue, fontWeightValue]
);
// Memoize Chart Options
const options = useMemo(
() => ({
responsive: true,
maintainAspectRatio: false,
plugins: {
title: {
display: true,
text: name,
font: chartFontStyle,
},
legend: {
display: false,
},
},
scales: {
// x: {
// ticks: {
// display: true, // This hides the x-axis labels
// },
// },
},
}),
[title, chartFontStyle, name]
);
// useEffect(() => {console.log(measurements);
// },[measurements])
useEffect(() => {
if (!iotApiUrl || !measurements || Object.keys(measurements).length === 0)
return;
const socket = io(`http://${iotApiUrl}`);
const inputData = {
measurements,
duration,
interval: 1000,
};
const startStream = () => {
socket.emit("lineInput", inputData);
};
socket.on("connect", startStream);
socket.on("lineOutput", (response) => {
const responseData = response.data;
// Extract timestamps and values
const labels = responseData.time;
const datasets = Object.keys(measurements).map((key) => {
const measurement = measurements[key];
const datasetKey = `${measurement.name}.${measurement.fields}`;
return {
label: datasetKey,
data: responseData[datasetKey]?.values ?? [],
backgroundColor: "#6f42c1",
borderColor: "#b392f0",
borderWidth: 1,
};
});
setChartData({ labels, datasets });
});
return () => {
socket.off("lineOutput");
socket.emit("stop_stream"); // Stop streaming when component unmounts
socket.disconnect();
};
}, [measurements, duration, iotApiUrl]);
const fetchSavedInputes = async () => {
if (id !== "") {
try {
const response = await axios.get(
`http://${process.env.REACT_APP_SERVER_REST_API_BASE_URL}/api/v2/WidgetData/${id}/${organization}`
);
if (response.status === 200) {
setmeasurements(response.data.Data.measurements);
setDuration(response.data.Data.duration);
setName(response.data.widgetName);
} else {
console.log("Unexpected response:", response);
}
} catch (error) {
console.error("There was an error!", error);
}
}
};
useEffect(() => {
fetchSavedInputes();
}, []);
useEffect(() => {
if (selectedChartId?.id === id) {
fetchSavedInputes();
}
}, [chartMeasurements, chartDuration, widgetName]);
return (
<Pie
data={Object.keys(measurements).length > 0 ? chartData : defaultData}
options={options}
/>
);
};
export default PieChartComponent;

View File

@@ -0,0 +1,212 @@
import React, { useEffect, useMemo, useState } from "react";
import { PolarArea } from "react-chartjs-2";
import io from "socket.io-client";
import axios from "axios";
import { useThemeStore } from "../../../../../store/useThemeStore";
import useChartStore from "../../../../../store/useChartStore";
import { useWidgetStore } from "../../../../../store/useWidgetStore";
interface ChartComponentProps {
id: string;
type: any;
title: string;
fontFamily?: string;
fontSize?: string;
fontWeight?: "Light" | "Regular" | "Bold";
}
const PolarAreaGraphComponent = ({
id,
type,
title,
fontFamily,
fontSize,
fontWeight = "Regular",
}: ChartComponentProps) => {
const { themeColor } = useThemeStore();
const {
measurements: chartMeasurements,
duration: chartDuration,
name: widgetName,
} = useChartStore();
const [measurements, setmeasurements] = useState<any>({});
const [duration, setDuration] = useState("1h");
const [name, setName] = useState("Widget");
const [chartData, setChartData] = useState<{
labels: string[];
datasets: any[];
}>({
labels: [],
datasets: [],
});
const { selectedChartId } = useWidgetStore();
const iotApiUrl = process.env.REACT_APP_IOT_SOCKET_SERVER_URL;
const email = localStorage.getItem("email") || "";
const organization = email?.split("@")[1]?.split(".")[0];
const defaultData = {
labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
datasets: [
{
label: "Dataset",
data: [12, 19, 3, 5, 2, 3],
backgroundColor: ["#6f42c1"],
borderColor: "#b392f0",
borderWidth: 1,
},
],
};
useEffect(() => {}, []);
// Memoize Theme Colors
const buttonActionColor = useMemo(
() => themeColor[0] || "#5c87df",
[themeColor]
);
const buttonAbortColor = useMemo(
() => themeColor[1] || "#ffffff",
[themeColor]
);
// Memoize Font Styling
const chartFontWeightMap = useMemo(
() => ({
Light: "lighter" as const,
Regular: "normal" as const,
Bold: "bold" as const,
}),
[]
);
const fontSizeValue = useMemo(
() => (fontSize ? parseInt(fontSize) : 12),
[fontSize]
);
const fontWeightValue = useMemo(
() => chartFontWeightMap[fontWeight],
[fontWeight, chartFontWeightMap]
);
const chartFontStyle = useMemo(
() => ({
family: fontFamily || "Arial",
size: fontSizeValue,
weight: fontWeightValue,
}),
[fontFamily, fontSizeValue, fontWeightValue]
);
// Memoize Chart Options
const options = useMemo(
() => ({
responsive: true,
maintainAspectRatio: false,
plugins: {
title: {
display: true,
text: name,
font: chartFontStyle,
},
legend: {
display: false,
},
},
scales: {
// x: {
// ticks: {
// display: true, // This hides the x-axis labels
// },
// },
},
}),
[title, chartFontStyle, name]
);
// useEffect(() => {console.log(measurements);
// },[measurements])
useEffect(() => {
if (!iotApiUrl || !measurements || Object.keys(measurements).length === 0)
return;
const socket = io(`http://${iotApiUrl}`);
const inputData = {
measurements,
duration,
interval: 1000,
};
const startStream = () => {
socket.emit("lineInput", inputData);
};
socket.on("connect", startStream);
socket.on("lineOutput", (response) => {
const responseData = response.data;
// Extract timestamps and values
const labels = responseData.time;
const datasets = Object.keys(measurements).map((key) => {
const measurement = measurements[key];
const datasetKey = `${measurement.name}.${measurement.fields}`;
return {
label: datasetKey,
data: responseData[datasetKey]?.values ?? [],
backgroundColor: "#6f42c1",
borderColor: "#b392f0",
borderWidth: 1,
};
});
setChartData({ labels, datasets });
});
return () => {
socket.off("lineOutput");
socket.emit("stop_stream"); // Stop streaming when component unmounts
socket.disconnect();
};
}, [measurements, duration, iotApiUrl]);
const fetchSavedInputes = async () => {
if (id !== "") {
try {
const response = await axios.get(
`http://${process.env.REACT_APP_SERVER_REST_API_BASE_URL}/api/v2/WidgetData/${id}/${organization}`
);
if (response.status === 200) {
setmeasurements(response.data.Data.measurements);
setDuration(response.data.Data.duration);
setName(response.data.widgetName);
} else {
console.log("Unexpected response:", response);
}
} catch (error) {
console.error("There was an error!", error);
}
}
};
useEffect(() => {
fetchSavedInputes();
}, []);
useEffect(() => {
if (selectedChartId?.id === id) {
fetchSavedInputes();
}
}, [chartMeasurements, chartDuration, widgetName]);
return (
<PolarArea
data={Object.keys(measurements).length > 0 ? chartData : defaultData}
options={options}
/>
);
};
export default PolarAreaGraphComponent;

View File

@@ -0,0 +1,29 @@
import { StockIncreseIcon } from "../../../../../components/icons/RealTimeVisulationIcons";
const ProgressCard = ({
title,
data,
}: {
title: string;
data: { stocks: Array<{ key: string; value: number; description: string }> };
}) => (
<div className="chart progressBar">
<div className="header">{title}</div>
{data?.stocks?.map((stock, index) => (
<div key={index} className="stock">
<span className="stock-item">
<span className="stockValues">
<div className="key">{stock.key}</div>
<div className="value">{stock.value}</div>
</span>
<div className="stock-description">{stock.description}</div>
</span>
<div className="icon">
<StockIncreseIcon />
</div>
</div>
))}
</div>
);
export default ProgressCard;

View File

@@ -0,0 +1,105 @@
import React, { useEffect, useMemo, useState } from "react";
import { Line } from "react-chartjs-2";
import io from "socket.io-client";
import axios from "axios";
import useChartStore from "../../../../../store/useChartStore";
import { useWidgetStore } from "../../../../../store/useWidgetStore";
import { StockIncreseIcon } from "../../../../../components/icons/RealTimeVisulationIcons";
const ProgressCard1 = ({ id, title }: { id: string; title: string }) => {
const {
measurements: chartMeasurements,
duration: chartDuration,
name: widgetName,
} = useChartStore();
const [measurements, setmeasurements] = useState<any>({});
const [duration, setDuration] = useState("1h");
const [name, setName] = useState(title);
const [value, setValue] = useState<any>("");
const { selectedChartId } = useWidgetStore();
const iotApiUrl = process.env.REACT_APP_IOT_SOCKET_SERVER_URL;
const email = localStorage.getItem("email") || "";
const organization = email?.split("@")[1]?.split(".")[0];
useEffect(() => {
const socket = io(`http://${iotApiUrl}`);
if (!iotApiUrl || !measurements || Object.keys(measurements).length === 0)
return;
const inputData = {
measurements,
duration,
interval: 1000,
};
const startStream = () => {
socket.emit("lastInput", inputData);
};
socket.on("connect", startStream);
socket.on("lastOutput", (response) => {
const responseData = response.input1;
setValue(responseData);
});
return () => {
socket.off("lastOutput");
socket.emit("stop_stream"); // Stop streaming when component unmounts
socket.disconnect();
};
}, [measurements, duration]);
const fetchSavedInputes = async () => {
if (id !== "") {
try {
const response = await axios.get(
`http://${process.env.REACT_APP_SERVER_REST_API_BASE_URL}/api/v2/WidgetData/${id}/${organization}`
);
if (response.status === 200) {
setmeasurements(response.data.Data.measurements);
setDuration(response.data.Data.duration);
setName(response.data.widgetName);
} else {
console.log("Unexpected response:", response);
}
} catch (error) {
console.error("There was an error!", error);
}
}
};
useEffect(() => {
fetchSavedInputes();
}, []);
useEffect(() => {
if (selectedChartId?.id === id) {
fetchSavedInputes();
}
}, [chartMeasurements, chartDuration, widgetName]);
return (
<div className="chart progressBar">
<div className="header">{name}</div>
<div className="stock">
<span className="stock-item">
<span className="stockValues">
<div className="value">{value}</div>
<div className="key">Units</div>
</span>
<div className="stock-description">
{measurements ? `${measurements?.input1?.fields}` : "description"}
</div>
</span>
<div className="icon">
<StockIncreseIcon />
</div>
</div>
</div>
);
};
export default ProgressCard1;

View File

@@ -0,0 +1,125 @@
import React, { useEffect, useMemo, useState } from "react";
import { Line } from "react-chartjs-2";
import io from "socket.io-client";
import axios from "axios";
import useChartStore from "../../../../../store/useChartStore";
import { useWidgetStore } from "../../../../../store/useWidgetStore";
import { StockIncreseIcon } from "../../../../../components/icons/RealTimeVisulationIcons";
const ProgressCard2 = ({ id, title }: { id: string; title: string }) => {
const {
measurements: chartMeasurements,
duration: chartDuration,
name: widgetName,
} = useChartStore();
const [measurements, setmeasurements] = useState<any>({});
const [duration, setDuration] = useState("1h");
const [name, setName] = useState(title);
const [value1, setValue1] = useState<any>("");
const [value2, setValue2] = useState<any>("");
const { selectedChartId } = useWidgetStore();
const iotApiUrl = process.env.REACT_APP_IOT_SOCKET_SERVER_URL;
const email = localStorage.getItem("email") || "";
const organization = email?.split("@")[1]?.split(".")[0];
useEffect(() => {
if (!iotApiUrl || !measurements || Object.keys(measurements).length === 0)
return;
const socket = io(`http://${iotApiUrl}`);
const inputData = {
measurements,
duration,
interval: 1000,
};
const startStream = () => {
socket.emit("lastInput", inputData);
};
socket.on("connect", startStream);
socket.on("lastOutput", (response) => {
const responseData1 = response.input1;
const responseData2 = response.input2;
setValue1(responseData1);
setValue2(responseData2);
});
return () => {
socket.off("lastOutput");
socket.emit("stop_stream"); // Stop streaming when component unmounts
socket.disconnect();
};
}, [measurements, duration]);
const fetchSavedInputes = async () => {
if (id !== "") {
try {
const response = await axios.get(
`http://${process.env.REACT_APP_SERVER_REST_API_BASE_URL}/api/v2/WidgetData/${id}/${organization}`
);
if (response.status === 200) {
setmeasurements(response.data.Data.measurements);
setDuration(response.data.Data.duration);
setName(response.data.widgetName);
} else {
console.log("Unexpected response:", response);
}
} catch (error) {
console.error("There was an error!", error);
}
}
};
useEffect(() => {
fetchSavedInputes();
}, []);
useEffect(() => {
if (selectedChartId?.id === id) {
fetchSavedInputes();
}
}, [chartMeasurements, chartDuration, widgetName]);
return (
<div className="chart progressBar">
<div className="header">{name}</div>
<div className="stock">
<span className="stock-item">
<span className="stockValues">
<div className="value">{value1}</div>
<div className="key">Units</div>
</span>
<div className="stock-description">
{measurements ? `${measurements?.input1?.fields}` : "description"}
</div>
</span>
<div className="icon">
<StockIncreseIcon />
</div>
</div>
<div className="stock">
<span className="stock-item">
<span className="stockValues">
<div className="value">{value2}</div>
<div className="key">Units</div>
</span>
<div className="stock-description">
{measurements ? `${measurements?.input2?.fields}` : "description"}
</div>
</span>
<div className="icon">
<StockIncreseIcon />
</div>
</div>
</div>
);
};
export default ProgressCard2;

View File

@@ -0,0 +1,102 @@
import React, { useMemo } from "react";
import { Radar } from "react-chartjs-2";
import { ChartOptions, ChartData, RadialLinearScaleOptions } from "chart.js";
interface ChartComponentProps {
type: string;
title: string;
fontFamily?: string;
fontSize?: string;
fontWeight?: "Light" | "Regular" | "Bold";
data: number[]; // Expecting an array of numbers for radar chart data
}
const RadarGraphComponent = ({
title,
fontFamily,
fontSize,
fontWeight = "Regular",
data, // Now guaranteed to be number[]
}: ChartComponentProps) => {
// Memoize Font Weight Mapping
const chartFontWeightMap = useMemo(
() => ({
Light: "lighter" as const,
Regular: "normal" as const,
Bold: "bold" as const,
}),
[]
);
const fontSizeValue = useMemo(
() => (fontSize ? parseInt(fontSize) : 12),
[fontSize]
);
const fontWeightValue = useMemo(
() => chartFontWeightMap[fontWeight],
[fontWeight, chartFontWeightMap]
);
const chartFontStyle = useMemo(
() => ({
family: fontFamily || "Arial",
size: fontSizeValue,
weight: fontWeightValue,
}),
[fontFamily, fontSizeValue, fontWeightValue]
);
const options: ChartOptions<"radar"> = useMemo(
() => ({
responsive: true,
maintainAspectRatio: false,
plugins: {
title: {
display: true,
text: title,
font: chartFontStyle,
},
legend: {
display: false,
position: "top",
},
},
scales: {
r: {
min: 0,
max: 100,
angleLines: {
display: true,
},
ticks: {
display: true,
stepSize: 20,
},
} as RadialLinearScaleOptions,
},
}),
[title, chartFontStyle]
);
const chartData: ChartData<"radar"> = useMemo(
() => ({
labels: ["January", "February", "March", "April", "May", "June", "July"],
datasets: [
{
label: "Dataset 1",
data, // Use the data passed as a prop
backgroundColor: "rgba(111, 66, 193, 0.2)",
borderColor: "#6f42c1",
borderWidth: 2,
fill: true,
},
],
}),
[data]
);
return <Radar data={chartData} options={options} />;
};
export default RadarGraphComponent;

View File

@@ -0,0 +1,626 @@
import * as THREE from "three";
import { useThree } from "@react-three/fiber";
import React, { useEffect, useRef, useState } from "react";
import { useAsset3dWidget, useSocketStore, useWidgetSubOption } from "../../../../store/store";
import useModuleStore from "../../../../store/useModuleStore";
import { ThreeState } from "../../../../types/world/worldTypes";
import { useSelectedZoneStore } from "../../../../store/useZoneStore";
import { useEditWidgetOptionsStore, useLeftData, useRightClickSelected, useRightSelected, useTopData, useZoneWidgetStore } from "../../../../store/useZone3DWidgetStore";
import { use3DWidget } from "../../../../store/useDroppedObjectsStore";
import { get3dWidgetZoneData } from "../../../../services/realTimeVisulization/zoneData/get3dWidgetData";
import { generateUniqueId } from "../../../../functions/generateUniqueId";
import ProductionCapacity from "./cards/ProductionCapacity";
import ReturnOfInvestment from "./cards/ReturnOfInvestment";
import StateWorking from "./cards/StateWorking";
import Throughput from "./cards/Throughput";
type WidgetData = {
id: string;
type: string;
position: [number, number, number];
rotation?: [number, number, number];
tempPosition?: [number, number, number];
};
export default function Dropped3dWidgets() {
const { widgetSelect } = useAsset3dWidget();
const { activeModule } = useModuleStore();
const { raycaster, gl, scene, mouse, camera }: ThreeState = useThree();
const { widgetSubOption } = useWidgetSubOption();
const { selectedZone } = useSelectedZoneStore();
const { top, setTop } = useTopData();
const { left, setLeft } = useLeftData();
const { rightSelect, setRightSelect } = useRightSelected();
const { editWidgetOptions, setEditWidgetOptions } = useEditWidgetOptionsStore();
const { zoneWidgetData, setZoneWidgetData, addWidget, updateWidgetPosition, updateWidgetRotation, tempWidget, tempWidgetPosition } = useZoneWidgetStore();
const { setWidgets3D } = use3DWidget();
const { visualizationSocket } = useSocketStore();
const { rightClickSelected, setRightClickSelected } = useRightClickSelected();
const plane = useRef(new THREE.Plane(new THREE.Vector3(0, 1, 0), 0)); // Floor plane for horizontal move
const verticalPlane = useRef(new THREE.Plane(new THREE.Vector3(0, 0, 1), 0)); // Vertical plane for vertical move
const planeIntersect = useRef(new THREE.Vector3());
const rotationStartRef = useRef<[number, number, number]>([0, 0, 0]);
const mouseStartRef = useRef<{ x: number; y: number }>({ x: 0, y: 0 });
let [floorPlanesVertical, setFloorPlanesVertical] = useState(
new THREE.Plane(new THREE.Vector3(0, 1, 0))
);
const activeZoneWidgets = zoneWidgetData[selectedZone.zoneId] || [];
useEffect(() => {
if (activeModule !== "visualization") return;
if (!selectedZone.zoneId) return;
const email = localStorage.getItem("email") || "";
const organization = email?.split("@")[1]?.split(".")[0];
async function get3dWidgetData() {
const result = await get3dWidgetZoneData(
selectedZone.zoneId,
organization
);
setWidgets3D(result);
if (result.length < 0) return
const formattedWidgets = result?.map((widget: WidgetData) => ({
id: widget.id,
type: widget.type,
position: widget.position,
rotation: widget.rotation || [0, 0, 0],
}));
setZoneWidgetData(selectedZone.zoneId, formattedWidgets);
}
get3dWidgetData();
}, [selectedZone.zoneId, activeModule]);
const createdWidgetRef = useRef<WidgetData | null>(null);
useEffect(() => {
if (activeModule !== "visualization") return;
if (widgetSubOption === "Floating" || widgetSubOption === "2D") return;
if (selectedZone.zoneName === "") return;
const canvasElement = document.getElementById("real-time-vis-canvas");
if (!canvasElement) return;
const hasEntered = { current: false };
const handleDragEnter = (event: DragEvent) => {
event.preventDefault();
event.stopPropagation();
if (hasEntered.current || !widgetSelect.startsWith("ui")) return;
hasEntered.current = true;
const group1 = scene.getObjectByName("itemsGroup");
if (!group1) return;
const rect = canvasElement.getBoundingClientRect();
mouse.x = ((event.clientX - rect.left) / rect.width) * 2 - 1;
mouse.y = -((event.clientY - rect.top) / rect.height) * 2 + 1;
raycaster.setFromCamera(mouse, camera);
const intersects = raycaster
.intersectObjects(scene.children, true)
.filter(
(intersect) =>
!intersect.object.name.includes("Roof") &&
!intersect.object.name.includes("agv-collider") &&
!intersect.object.name.includes("MeasurementReference") &&
!intersect.object.userData.isPathObject &&
!(intersect.object.type === "GridHelper")
);
if (intersects.length > 0) {
const { x, y, z } = intersects[0].point;
const newWidget: WidgetData = {
id: generateUniqueId(),
type: widgetSelect,
position: [x, y, z],
rotation: [0, 0, 0],
};
createdWidgetRef.current = newWidget;
tempWidget(selectedZone.zoneId, newWidget); // temp add in UI
}
};
const handleDragOver = (event: DragEvent) => {
event.preventDefault();
event.stopPropagation();
event.dataTransfer!.dropEffect = "move"; // ✅ Add this line
const widget = createdWidgetRef.current;
if (!widget) return;
const rect = canvasElement.getBoundingClientRect();
mouse.x = ((event.clientX - rect.left) / rect.width) * 2 - 1;
mouse.y = -((event.clientY - rect.top) / rect.height) * 2 + 1;
raycaster.setFromCamera(mouse, camera);
const intersects = raycaster
.intersectObjects(scene.children, true)
.filter(
(intersect) =>
!intersect.object.name.includes("Roof") &&
!intersect.object.name.includes("agv-collider") &&
!intersect.object.name.includes("MeasurementReference") &&
!intersect.object.userData.isPathObject &&
!(intersect.object.type === "GridHelper")
);
// Update widget's position in memory
if (intersects.length > 0) {
const { x, y, z } = intersects[0].point;
tempWidgetPosition(selectedZone.zoneId, widget.id, [x, y, z]);
widget.position = [x, y, z];
}
};
const onDrop = (event: any) => {
event.preventDefault();
event.stopPropagation();
hasEntered.current = false;
const email = localStorage.getItem("email") || "";
const organization = email?.split("@")[1]?.split(".")[0];
const newWidget = createdWidgetRef.current;
if (!newWidget || !widgetSelect.startsWith("ui")) return;
// ✅ Extract 2D drop position
const [x, , z] = newWidget.position;
// ✅ Prepare polygon from selectedZone.points
const points3D = selectedZone.points as Array<[number, number, number]>;
const zonePolygonXZ = points3D.map(([x, , z]) => [x, z] as [number, number]);
const isInside = isPointInPolygon([x, z], zonePolygonXZ);
// ✅ Remove temp widget
const prevWidgets = useZoneWidgetStore.getState().zoneWidgetData[selectedZone.zoneId] || [];
const cleanedWidgets = prevWidgets.filter(w => w.id !== newWidget.id);
useZoneWidgetStore.setState((state) => ({
zoneWidgetData: {
...state.zoneWidgetData,
[selectedZone.zoneId]: cleanedWidgets,
},
}));
// if (!isInside) {
// createdWidgetRef.current = null;
// return; // Stop here
// }
// ✅ Add widget if inside polygon
addWidget(selectedZone.zoneId, newWidget);
const add3dWidget = {
organization,
widget: newWidget,
zoneId: selectedZone.zoneId,
};
if (visualizationSocket) {
visualizationSocket.emit("v2:viz-3D-widget:add", add3dWidget);
}
createdWidgetRef.current = null;
};
canvasElement.addEventListener("dragenter", handleDragEnter);
canvasElement.addEventListener("dragover", handleDragOver);
canvasElement.addEventListener("drop", onDrop);
return () => {
canvasElement.removeEventListener("dragenter", handleDragEnter);
canvasElement.removeEventListener("dragover", handleDragOver);
canvasElement.removeEventListener("drop", onDrop);
};
}, [widgetSelect, activeModule, selectedZone.zoneId, widgetSubOption, camera,]);
useEffect(() => {
if (!rightClickSelected) return;
const email = localStorage.getItem("email") || "";
const organization = email?.split("@")[1]?.split(".")[0];
if (rightSelect === "Duplicate") {
async function duplicateWidget() {
const widgetToDuplicate = activeZoneWidgets.find(
(w: WidgetData) => w.id === rightClickSelected
);
if (!widgetToDuplicate) return;
const newWidget: WidgetData = {
id: generateUniqueId(),
type: widgetToDuplicate.type,
position: [
widgetToDuplicate.position[0] + 0.5,
widgetToDuplicate.position[1],
widgetToDuplicate.position[2] + 0.5,
],
rotation: widgetToDuplicate.rotation || [0, 0, 0],
};
const adding3dWidget = {
organization: organization,
widget: newWidget,
zoneId: selectedZone.zoneId,
};
if (visualizationSocket) {
visualizationSocket.emit("v2:viz-3D-widget:add", adding3dWidget);
}
// let response = await adding3dWidgets(selectedZone.zoneId, organization, newWidget)
//
addWidget(selectedZone.zoneId, newWidget);
setRightSelect(null);
setRightClickSelected(null);
}
duplicateWidget();
}
if (rightSelect === "Delete") {
const deleteWidgetApi = async () => {
try {
const deleteWidget = {
organization,
id: rightClickSelected,
zoneId: selectedZone.zoneId,
};
if (visualizationSocket) {
visualizationSocket.emit("v2:viz-3D-widget:delete", deleteWidget);
}
// Call the API to delete the widget
// const response = await delete3dWidgetApi(selectedZone.zoneId, organization, rightClickSelected);
setZoneWidgetData(
selectedZone.zoneId,
activeZoneWidgets.filter(
(w: WidgetData) => w.id !== rightClickSelected
)
);
} catch (error) {
} finally {
setRightClickSelected(null);
setRightSelect(null);
}
};
deleteWidgetApi();
}
}, [rightSelect, rightClickSelected]);
function isPointInPolygon(
point: [number, number],
polygon: Array<[number, number]>
): boolean {
const [x, z] = point;
let inside = false;
for (let i = 0, j = polygon.length - 1; i < polygon.length; j = i++) {
const [xi, zi] = polygon[i];
const [xj, zj] = polygon[j];
const intersect =
zi > z !== zj > z &&
x < ((xj - xi) * (z - zi)) / (zj - zi) + xi;
if (intersect) inside = !inside;
}
return inside;
}
const [prevX, setPrevX] = useState(0);
useEffect(() => {
const email = localStorage.getItem("email") || "";
const organization = email?.split("@")[1]?.split(".")[0];
const handleMouseDown = (event: MouseEvent) => {
if (!rightClickSelected || !rightSelect) return;
const cameraDirection = new THREE.Vector3();
camera.getWorldDirection(cameraDirection);
// Plane normal should be perpendicular to screen (XZ move), so use screen right direction
const right = new THREE.Vector3();
camera.getWorldDirection(cameraDirection);
cameraDirection.y = 0;
cameraDirection.normalize();
right.crossVectors(new THREE.Vector3(0, 1, 0), cameraDirection).normalize();
// Create a plane that allows vertical movement
const verticalPlane = new THREE.Plane().setFromNormalAndCoplanarPoint(right, new THREE.Vector3(0, 0, 0));
setFloorPlanesVertical(verticalPlane);
if (rightSelect === "RotateX" || rightSelect === "RotateY") {
mouseStartRef.current = { x: event.clientX, y: event.clientY };
const selectedZoneId = Object.keys(zoneWidgetData).find(
(zoneId: string) =>
zoneWidgetData[zoneId].some(
(widget: WidgetData) => widget.id === rightClickSelected
)
);
if (!selectedZoneId) return;
const selectedWidget = zoneWidgetData[selectedZoneId].find(
(widget: WidgetData) => widget.id === rightClickSelected
);
if (selectedWidget) {
rotationStartRef.current = selectedWidget.rotation || [0, 0, 0];
}
}
};
const handleMouseMove = (event: MouseEvent) => {
if (!rightClickSelected || !rightSelect) return;
const selectedZoneId = Object.keys(zoneWidgetData).find((zoneId: string) =>
zoneWidgetData[zoneId].some(
(widget: WidgetData) => widget.id === rightClickSelected
)
);
if (!selectedZoneId) return;
const selectedWidget = zoneWidgetData[selectedZoneId].find(
(widget: WidgetData) => widget.id === rightClickSelected
);
if (!selectedWidget) return;
const rect = gl.domElement.getBoundingClientRect();
mouse.x = ((event.clientX - rect.left) / rect.width) * 2 - 1;
mouse.y = -((event.clientY - rect.top) / rect.height) * 2 + 1;
raycaster.setFromCamera(mouse, camera);
if (rightSelect === "Horizontal Move" &&raycaster.ray.intersectPlane(plane.current, planeIntersect.current)) {
const points3D = selectedZone.points as Array<[number, number, number]>;
const zonePolygonXZ = points3D.map(([x, , z]) => [x, z] as [number, number]);
const newPosition: [number, number, number] = [
planeIntersect.current.x,
selectedWidget.position[1],
planeIntersect.current.z,
];
const isInside = isPointInPolygon(
[newPosition[0], newPosition[2]],
zonePolygonXZ
);
// if (isInside) {
updateWidgetPosition(selectedZoneId, rightClickSelected, newPosition);
// }
}
if (rightSelect === "Vertical Move") {
if (raycaster.ray.intersectPlane(floorPlanesVertical, planeIntersect.current)) {
const currentY = selectedWidget.position[1];
const newY = planeIntersect.current.y;
console.log('planeIntersect.current: ', planeIntersect.current);
const deltaY = newY - currentY;
// Reject if jump is too large (safety check)
if (Math.abs(deltaY) > 200) return;
// Clamp jump or apply smoothing
const clampedY = currentY + THREE.MathUtils.clamp(deltaY, -10, 10);
if (clampedY > 0) {
updateWidgetPosition(selectedZoneId, rightClickSelected, [
selectedWidget.position[0],
clampedY,
selectedWidget.position[2],
]);
}
}
}
if (rightSelect === "RotateX") {
const currentX = event.pageX;
const sign = currentX > prevX ? 1 : currentX < prevX ? -1 : 0;
setPrevX(currentX);
if (selectedWidget?.rotation && selectedWidget.rotation.length >= 3) {
const newRotation: [number, number, number] = [
selectedWidget.rotation[0] + 0.05 * sign,
selectedWidget.rotation[1],
selectedWidget.rotation[2],
];
updateWidgetRotation(selectedZoneId, rightClickSelected, newRotation);
}
}
if (rightSelect === "RotateY") {
const currentX = event.pageX;
const sign = currentX > prevX ? 1 : currentX < prevX ? -1 : 0;
setPrevX(currentX);
if (selectedWidget?.rotation && selectedWidget.rotation.length >= 3) {
const newRotation: [number, number, number] = [
selectedWidget.rotation[0] ,
selectedWidget.rotation[1]+ 0.05 * sign,
selectedWidget.rotation[2],
];
updateWidgetRotation(selectedZoneId, rightClickSelected, newRotation);
}
}
if (rightSelect === "RotateZ") {
const currentX = event.pageX;
const sign = currentX > prevX ? 1 : currentX < prevX ? -1 : 0;
setPrevX(currentX);
if (selectedWidget?.rotation && selectedWidget.rotation.length >= 3) {
const newRotation: [number, number, number] = [
selectedWidget.rotation[0] ,
selectedWidget.rotation[1],
selectedWidget.rotation[2]+ 0.05 * sign,
];
updateWidgetRotation(selectedZoneId, rightClickSelected, newRotation);
}
}
};
const handleMouseUp = () => {
if (!rightClickSelected || !rightSelect) return;
const selectedZoneId = Object.keys(zoneWidgetData).find((zoneId) =>
zoneWidgetData[zoneId].some(
(widget) => widget.id === rightClickSelected
)
);
if (!selectedZoneId) return;
const selectedWidget = zoneWidgetData[selectedZoneId].find(
(widget) => widget.id === rightClickSelected
);
if (!selectedWidget) return;
// Format values to 2 decimal places
const formatValues = (vals: number[]) =>
vals.map((val) => parseFloat(val.toFixed(2)));
if (
rightSelect === "Horizontal Move" ||
rightSelect === "Vertical Move"
) {
let lastPosition = formatValues(selectedWidget.position) as [
number,
number,
number
];
// (async () => {
// let response = await update3dWidget(selectedZoneId, organization, rightClickSelected, lastPosition);
//
// if (response) {
//
// }
// })();
let updatingPosition = {
organization: organization,
zoneId: selectedZoneId,
id: rightClickSelected,
position: lastPosition,
};
if (visualizationSocket) {
visualizationSocket.emit(
"v2:viz-3D-widget:modifyPositionRotation",
updatingPosition
);
}
} else if (rightSelect.includes("Rotate")) {
const rotation = selectedWidget.rotation || [0, 0, 0];
let lastRotation = formatValues(rotation) as [number, number, number];
// (async () => {
// let response = await update3dWidgetRotation(selectedZoneId, organization, rightClickSelected, lastRotation);
//
// if (response) {
//
// }
// })();
let updatingRotation = {
organization: organization,
zoneId: selectedZoneId,
id: rightClickSelected,
rotation: lastRotation,
};
if (visualizationSocket) {
visualizationSocket.emit(
"v2:viz-3D-widget:modifyPositionRotation",
updatingRotation
);
}
}
// Reset selection
setTimeout(() => {
setRightClickSelected(null);
setRightSelect(null);
}, 50);
};
window.addEventListener("mousedown", handleMouseDown);
window.addEventListener("mousemove", handleMouseMove);
window.addEventListener("mouseup", handleMouseUp);
return () => {
window.removeEventListener("mousedown", handleMouseDown);
window.removeEventListener("mousemove", handleMouseMove);
window.removeEventListener("mouseup", handleMouseUp);
};
}, [rightClickSelected, rightSelect, zoneWidgetData, gl]);
return (
<>
{activeZoneWidgets.map(
({ id, type, position, rotation = [0, 0, 0] }: WidgetData) => {
const handleRightClick = (event: React.MouseEvent, id: string) => {
event.preventDefault();
const canvasElement = document.getElementById(
"real-time-vis-canvas"
);
if (!canvasElement) throw new Error("Canvas element not found");
const canvasRect = canvasElement.getBoundingClientRect();
const relativeX = event.clientX - canvasRect.left;
const relativeY = event.clientY - canvasRect.top;
setEditWidgetOptions(true);
setRightClickSelected(id);
setTop(relativeY);
setLeft(relativeX);
};
switch (type) {
case "ui-Widget 1":
return (
<ProductionCapacity
key={id}
id={id}
type={type}
position={position}
rotation={rotation}
onContextMenu={(e) => handleRightClick(e, id)}
/>
);
case "ui-Widget 2":
return (
<ReturnOfInvestment
key={id}
id={id}
type={type}
position={position}
rotation={rotation}
onContextMenu={(e) => handleRightClick(e, id)}
/>
);
case "ui-Widget 3":
return (
<StateWorking
key={id}
id={id}
type={type}
position={position}
rotation={rotation}
onContextMenu={(e) => handleRightClick(e, id)}
/>
);
case "ui-Widget 4":
return (
<Throughput
key={id}
id={id}
type={type}
position={position}
rotation={rotation}
onContextMenu={(e) => handleRightClick(e, id)}
/>
);
default:
return null;
}
}
)}
</>
);
}

View File

@@ -0,0 +1,264 @@
import { Html } from "@react-three/drei";
import React, { useEffect, useMemo, useState } from "react";
import { Bar } from "react-chartjs-2";
import {
Chart as ChartJS,
CategoryScale,
LinearScale,
BarElement,
Title,
Tooltip,
Legend,
TooltipItem, // Import TooltipItem for typing
} from "chart.js";
import axios from "axios";
import io from "socket.io-client";
import { useWidgetStore } from "../../../../../store/useWidgetStore";
import useChartStore from "../../../../../store/useChartStore";
// Register ChartJS components
ChartJS.register(
CategoryScale,
LinearScale,
BarElement,
Title,
Tooltip,
Legend
);
interface ProductionCapacityProps {
id: string;
type: string;
position: [number, number, number];
rotation: [number, number, number];
onContextMenu?: (event: React.MouseEvent) => void;
// onPointerDown:any
}
const ProductionCapacity: React.FC<ProductionCapacityProps> = ({
id,
type,
position,
rotation,
onContextMenu,
}) => {
const { selectedChartId, setSelectedChartId } = useWidgetStore();
const {
measurements: chartMeasurements,
duration: chartDuration,
name: widgetName,
} = useChartStore();
const [measurements, setmeasurements] = useState<any>({});
const [duration, setDuration] = useState("1h");
const [name, setName] = useState("Widget");
const [chartData, setChartData] = useState<{
labels: string[];
datasets: any[];
}>({
labels: [],
datasets: [],
});
const iotApiUrl = process.env.REACT_APP_IOT_SOCKET_SERVER_URL;
const email = localStorage.getItem("email") || "";
const organization = email?.split("@")[1]?.split(".")[0];
// Chart data for a week
const defaultChartData = {
labels: ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"], // Days of the week
datasets: [
{
label: "Production Capacity (units/day)",
data: [1500, 1600, 1400, 1700, 1800, 1900, 2000], // Example daily production data
backgroundColor: "#6f42c1", // Theme color
borderColor: "#6f42c1",
borderWidth: 1,
borderRadius: 8, // Rounded corners for the bars
borderSkipped: false, // Ensure all corners are rounded
},
],
};
// Chart options
const chartOptions = {
responsive: true,
plugins: {
legend: {
display: false, // Hide legend
},
title: {
display: true,
text: "Weekly Production Capacity",
font: {
size: 16,
},
},
tooltip: {
callbacks: {
// Explicitly type the context parameter
label: (context: TooltipItem<"bar">) => {
const value = context.parsed.y; // Extract the y-axis value
return `${value} units`; // Customize tooltip to display "units"
},
},
},
},
scales: {
x: {
grid: {
display: false, // Hide x-axis grid lines
},
},
y: {
display: false, // Remove the y-axis completely
},
},
};
useEffect(() => {
if (!iotApiUrl || !measurements || Object.keys(measurements).length === 0)
return;
const socket = io(`http://${iotApiUrl}`);
const inputData = {
measurements,
duration,
interval: 1000,
};
const startStream = () => {
socket.emit("lineInput", inputData);
};
socket.on("connect", startStream);
socket.on("lineOutput", (response) => {
const responseData = response.data;
// Extract timestamps and values
const labels = responseData.time;
const datasets = Object.keys(measurements).map((key) => {
const measurement = measurements[key];
const datasetKey = `${measurement.name}.${measurement.fields}`;
return {
label: datasetKey,
data: responseData[datasetKey]?.values ?? [],
backgroundColor: "#6f42c1", // Theme color
borderColor: "#6f42c1",
borderWidth: 1,
borderRadius: 8, // Rounded corners for the bars
borderSkipped: false, // Ensure all corners are rounded
};
});
setChartData({ labels, datasets });
});
return () => {
socket.off("lineOutput");
socket.emit("stop_stream"); // Stop streaming when component unmounts
socket.disconnect();
};
}, [measurements, duration, iotApiUrl]);
const fetchSavedInputes = async () => {
if (id !== "") {
try {
const response = await axios.get(
`http://${process.env.REACT_APP_SERVER_REST_API_BASE_URL}/api/v2/widget3D/${id}/${organization}`
);
if (response.status === 200) {
setmeasurements(response.data.Data.measurements);
setDuration(response.data.Data.duration);
setName(response.data.widgetName);
} else {
}
} catch (error) {}
}
};
useEffect(() => {
fetchSavedInputes();
}, []);
useEffect(() => {
if (selectedChartId?.id === id) {
fetchSavedInputes();
}
}, [chartMeasurements, chartDuration, widgetName]);
useEffect(() => {}, [rotation]);
return (
<Html
position={position}
scale={[0.5, 0.5, 0.5]}
rotation={rotation}
transform
sprite={false}
zIndexRange={[1, 0]}
// style={{
// transform: transformStyle.transform,
// transformStyle: "preserve-3d",
// transition: "transform 0.1s ease-out",
// }}
onDragOver={(e) => {
e.preventDefault();
e.stopPropagation();
}}
onDrop={(e) => {
e.preventDefault();
// e.stopPropagation();
}}
wrapperClass="pointer-none"
>
<div
className={`productionCapacity-wrapper card ${
selectedChartId?.id === id ? "activeChart" : ""
}`}
onClick={() => setSelectedChartId({ id: id, type: type })}
onContextMenu={onContextMenu}
style={{
width: "300px", // Original width
height: "300px", // Original height
// transform: transformStyle.transform,
transformStyle: "preserve-3d",
position: "absolute",
transform: "translate(-50%, -50%)",
}}
>
<div className="headeproductionCapacityr-wrapper">
<div className="header">Production Capacity</div>
<div className="production-capacity">
<div className="value">1,200</div>{" "}
<div className="value">units/hour</div>
</div>
<div className="production-capacity">
<div className="current">
<div className="key">Current</div>
<div className="value">1500</div>
</div>
<div className="target">
<div className="key">Target</div>
<div className="value">2.345</div>
</div>
{/* <div className="value">units/hour</div> */}
</div>
</div>{" "}
<div className="bar-chart charts">
{/* Bar Chart */}
<Bar
data={
Object.keys(measurements).length > 0
? chartData
: defaultChartData
}
options={chartOptions}
/>
</div>
</div>
</Html>
);
};
export default ProductionCapacity;

View File

@@ -0,0 +1,276 @@
import { Html } from "@react-three/drei";
import React, { useEffect, useMemo, useState } from "react";
import { Line } from "react-chartjs-2";
import {
Chart as ChartJS,
CategoryScale,
LinearScale,
PointElement,
LineElement,
Tooltip,
ChartData,
ChartOptions,
} from "chart.js";
import axios from "axios";
import io from "socket.io-client";
import { useWidgetStore } from "../../../../../store/useWidgetStore";
import useChartStore from "../../../../../store/useChartStore";
import { WavyIcon } from "../../../../../components/icons/3dChartIcons";
// Register Chart.js components
ChartJS.register(
CategoryScale,
LinearScale,
PointElement,
LineElement,
Tooltip
);
// Define Props for SmoothLineGraphComponent
interface SmoothLineGraphProps {
data: ChartData<"line">; // Type for chart data
options?: ChartOptions<"line">; // Type for chart options (optional)
}
// SmoothLineGraphComponent using react-chartjs-2
const SmoothLineGraphComponent: React.FC<SmoothLineGraphProps> = ({
data,
options,
}) => {
return <Line data={data} options={options} />;
};
interface ReturnOfInvestmentProps {
id: string;
type: string;
position: [number, number, number];
rotation: [number, number, number];
onContextMenu?: (event: React.MouseEvent) => void;
}
const ReturnOfInvestment: React.FC<ReturnOfInvestmentProps> = ({
id,
type,
position,
rotation,
onContextMenu,
}) => {
const { selectedChartId, setSelectedChartId } = useWidgetStore();
const {
measurements: chartMeasurements,
duration: chartDuration,
name: widgetName,
} = useChartStore();
const [measurements, setmeasurements] = useState<any>({});
const [duration, setDuration] = useState("1h");
const [name, setName] = useState("Widget");
const [chartData, setChartData] = useState<{
labels: string[];
datasets: any[];
}>({
labels: [],
datasets: [],
});
const iotApiUrl = process.env.REACT_APP_IOT_SOCKET_SERVER_URL;
const email = localStorage.getItem("email") || "";
const organization = email?.split("@")[1]?.split(".")[0];
// Improved sample data for the smooth curve graph (single day)
const graphData: ChartData<"line"> = {
labels: [
"12 AM",
"3 AM",
"6 AM",
"9 AM",
"12 PM",
"3 PM",
"6 PM",
"9 PM",
"12 AM",
],
datasets: [
{
label: "Investment",
data: [100, 250, 400, 400, 500, 600, 700, 800, 900], // Example investment growth
borderColor: "rgba(75, 192, 192, 1)", // Light blue color
backgroundColor: "rgba(75, 192, 192, 0.2)",
fill: true,
tension: 0.4, // Smooth curve effect
pointRadius: 0, // Hide dots
pointHoverRadius: 0, // Hide hover dots
},
{
label: "Return",
data: [100, 200, 500, 250, 300, 350, 400, 450, 500], // Example return values
borderColor: "rgba(255, 99, 132, 1)", // Pink color
backgroundColor: "rgba(255, 99, 132, 0.2)",
fill: true,
tension: 0.4, // Smooth curve effect
pointRadius: 0, // Hide dots
pointHoverRadius: 0, // Hide hover dots
},
],
};
// Options for the smooth curve graph
const graphOptions: ChartOptions<"line"> = {
responsive: true,
maintainAspectRatio: false,
plugins: {
tooltip: {
enabled: true, // Enable tooltips on hover
mode: "index", // Show both datasets' values at the same index
intersect: false, // Allow hovering anywhere on the graph
},
},
scales: {
x: {
grid: {
display: false, // Hide x-axis grid lines
},
ticks: {
display: false, // Hide x-axis labels
},
},
y: {
grid: {
display: false, // Hide y-axis grid lines
},
ticks: {
display: false, // Hide y-axis labels
},
},
},
};
useEffect(() => {
if (!iotApiUrl || !measurements || Object.keys(measurements).length === 0)
return;
const socket = io(`http://${iotApiUrl}`);
const inputData = {
measurements,
duration,
interval: 1000,
};
const startStream = () => {
socket.emit("lineInput", inputData);
};
socket.on("connect", startStream);
socket.on("lineOutput", (response) => {
const responseData = response.data;
// Extract timestamps and values
const labels = responseData.time;
const datasets = Object.keys(measurements).map((key, index) => {
const measurement = measurements[key];
const datasetKey = `${measurement.name}.${measurement.fields}`;
return {
label: datasetKey,
data: responseData[datasetKey]?.values ?? [],
borderColor:
index === 0 ? "rgba(75, 192, 192, 1)" : "rgba(255, 99, 132, 1)", // Light blue color
backgroundColor:
index === 0 ? "rgba(75, 192, 192, 0.2)" : "rgba(255, 99, 132, 0.2)",
fill: true,
tension: 0.4, // Smooth curve effect
pointRadius: 0, // Hide dots
pointHoverRadius: 0, // Hide hover dots
};
});
setChartData({ labels, datasets });
});
return () => {
socket.off("lineOutput");
socket.emit("stop_stream"); // Stop streaming when component unmounts
socket.disconnect();
};
}, [measurements, duration, iotApiUrl]);
const fetchSavedInputes = async () => {
if (id !== "") {
try {
const response = await axios.get(
`http://${process.env.REACT_APP_SERVER_REST_API_BASE_URL}/api/v2/widget3D/${id}/${organization}`
);
if (response.status === 200) {
setmeasurements(response.data.Data.measurements);
setDuration(response.data.Data.duration);
setName(response.data.widgetName);
} else {
console.log("Unexpected response:", response);
}
} catch (error) {
console.error("There was an error!", error);
}
}
};
useEffect(() => {
fetchSavedInputes();
}, []);
useEffect(() => {
if (selectedChartId?.id === id) {
fetchSavedInputes();
}
}, [chartMeasurements, chartDuration, widgetName]);
const rotationDegrees = {
x: (rotation[0] * 180) / Math.PI,
y: (rotation[1] * 180) / Math.PI,
z: (rotation[2] * 180) / Math.PI,
};
const transformStyle = {
transform: `rotateX(${rotationDegrees.x}deg) rotateY(${rotationDegrees.y}deg) rotateZ(${rotationDegrees.z}deg)`,
};
return (
<Html
position={[position[0], position[1], position[2]]}
rotation={rotation}
scale={[0.5, 0.5, 0.5]}
transform
zIndexRange={[1, 0]}
sprite={false}
// style={{
// transform: transformStyle.transform,
// transformStyle: "preserve-3d",
// transition: "transform 0.1s ease-out",
// }}
>
<div
className={`returnOfInvestment card ${
selectedChartId?.id === id ? "activeChart" : ""
}`}
onClick={() => setSelectedChartId({ id: id, type: type })}
onContextMenu={onContextMenu}
>
<div className="header">Return of Investment</div>
<div className="lineGraph charts">
{/* Smooth curve graph with two datasets */}
<SmoothLineGraphComponent
data={Object.keys(measurements).length > 0 ? chartData : graphData}
options={graphOptions}
/>
</div>
<div className="returns-wrapper">
<div className="icon">
<WavyIcon />
</div>
<div className="value">5.78</div>
<div className="key">Years</div>
</div>
<div className="footer">
in <span>5y</span> with avg <span>7%</span> yearly return
</div>
</div>
</Html>
);
};
export default ReturnOfInvestment;

View File

@@ -0,0 +1,202 @@
import { Html } from "@react-three/drei";
import React, { useEffect, useMemo, useState } from "react";
import axios from "axios";
import io from "socket.io-client";
import { useWidgetStore } from "../../../../../store/useWidgetStore";
import useChartStore from "../../../../../store/useChartStore";
// import image from "../../../../assets/image/temp/image.png";
interface StateWorkingProps {
id: string;
type: string;
position: [number, number, number];
rotation: [number, number, number];
onContextMenu?: (event: React.MouseEvent) => void;
}
const StateWorking: React.FC<StateWorkingProps> = ({
id,
type,
position,
rotation,
onContextMenu,
}) => {
const { selectedChartId, setSelectedChartId } = useWidgetStore();
const {
measurements: chartMeasurements,
duration: chartDuration,
name: widgetName,
} = useChartStore();
const [measurements, setmeasurements] = useState<any>({});
const [duration, setDuration] = useState("1h");
const [name, setName] = useState("Widget");
const [datas, setDatas] = useState<any>({});
const iotApiUrl = process.env.REACT_APP_IOT_SOCKET_SERVER_URL;
const email = localStorage.getItem("email") || "";
const organization = email?.split("@")[1]?.split(".")[0];
// const datas = [
// { key: "Oil Tank:", value: "24/341" },
// { key: "Oil Refin:", value: 36.023 },
// { key: "Transmission:", value: 36.023 },
// { key: "Fuel:", value: 36732 },
// { key: "Power:", value: 1300 },
// { key: "Time:", value: 13 - 9 - 2023 },
// ];
useEffect(() => {
if (!iotApiUrl || !measurements || Object.keys(measurements).length === 0)
return;
const socket = io(`http://${iotApiUrl}`);
const inputData = {
measurements,
duration,
interval: 1000,
};
const startStream = () => {
socket.emit("lastInput", inputData);
};
socket.on("connect", startStream);
socket.on("lastOutput", (response) => {
const responseData = response;
setDatas(responseData);
});
return () => {
socket.off("lastOutput");
socket.emit("stop_stream"); // Stop streaming when component unmounts
socket.disconnect();
};
}, [measurements, duration, iotApiUrl]);
const fetchSavedInputes = async () => {
if (id !== "") {
try {
const response = await axios.get(
`http://${process.env.REACT_APP_SERVER_REST_API_BASE_URL}/api/v2/widget3D/${id}/${organization}`
);
if (response.status === 200) {
setmeasurements(response.data.Data.measurements);
setDuration(response.data.Data.duration);
setName(response.data.widgetName);
} else {
console.log("Unexpected response:", response);
}
} catch (error) {
console.error("There was an error!", error);
}
}
};
useEffect(() => {
fetchSavedInputes();
}, []);
useEffect(() => {
if (selectedChartId?.id === id) {
fetchSavedInputes();
}
}, [chartMeasurements, chartDuration, widgetName]);
const rotationDegrees = {
x: (rotation[0] * 180) / Math.PI,
y: (rotation[1] * 180) / Math.PI,
z: (rotation[2] * 180) / Math.PI,
};
const transformStyle = {
transform: `rotateX(${rotationDegrees.x}deg) rotateY(${rotationDegrees.y}deg) rotateZ(${rotationDegrees.z}deg)`,
};
return (
<Html
position={[position[0], position[1], position[2]]}
rotation={rotation}
scale={[0.5, 0.5, 0.5]}
transform
zIndexRange={[1, 0]}
sprite={false}
// style={{
// transform: transformStyle.transform,
// transformStyle: "preserve-3d",
// transition: "transform 0.1s ease-out",
// }}
>
<div
className={`stateWorking-wrapper card ${
selectedChartId?.id === id ? "activeChart" : ""
}`}
onClick={() => setSelectedChartId({ id: id, type: type })}
onContextMenu={onContextMenu}
>
<div className="header-wrapper">
<div className="header">
<span>State</span>
<span>
{datas?.input1 ? datas.input1 : "input1"} <span>.</span>
</span>
</div>
<div className="img">{/* <img src={image} alt="" /> */}</div>
</div>
{/* Data */}
<div className="data-wrapper">
{/* {datas.map((data, index) => (
<div className="data-table" key={index}>
<div className="data">{data.key}</div>
<div className="key">{data.value}</div>
</div>
))} */}
<div className="data-table">
<div className="data">
{measurements?.input2?.fields
? measurements.input2.fields
: "input2"}
</div>
<div className="key">{datas?.input2 ? datas.input2 : "data"}</div>
</div>
<div className="data-table">
<div className="data">
{measurements?.input3?.fields
? measurements.input3.fields
: "input3"}
</div>
<div className="key">{datas?.input3 ? datas.input3 : "data"}</div>
</div>
<div className="data-table">
<div className="data">
{measurements?.input4?.fields
? measurements.input4.fields
: "input4"}
</div>
<div className="key">{datas?.input4 ? datas.input4 : "data"}</div>
</div>
<div className="data-table">
<div className="data">
{measurements?.input5?.fields
? measurements.input5.fields
: "input5"}
</div>
<div className="key">{datas?.input5 ? datas.input5 : "data"}</div>
</div>
<div className="data-table">
<div className="data">
{measurements?.input6?.fields
? measurements.input6.fields
: "input6"}
</div>
<div className="key">{datas?.input6 ? datas.input6 : "data"}</div>
</div>
<div className="data-table">
<div className="data">
{measurements?.input7?.fields
? measurements.input7.fields
: "input7"}
</div>
<div className="key">{datas?.input7 ? datas.input7 : "data"}</div>
</div>
</div>
</div>
</Html>
);
};
export default StateWorking;

View File

@@ -0,0 +1,267 @@
import { Html } from "@react-three/drei";
import React, { useEffect, useMemo, useState } from "react";
import { Line } from "react-chartjs-2";
import {
Chart as ChartJS,
CategoryScale,
LinearScale,
PointElement,
LineElement,
Title,
Tooltip,
Legend,
ChartData,
ChartOptions,
} from "chart.js";
import axios from "axios";
import io from "socket.io-client";
import { useWidgetStore } from "../../../../../store/useWidgetStore";
import useChartStore from "../../../../../store/useChartStore";
import { ThroughputIcon } from "../../../../../components/icons/3dChartIcons";
// Register Chart.js components
ChartJS.register(
CategoryScale,
LinearScale,
PointElement,
LineElement,
Title,
Tooltip,
Legend
);
// Define Props for LineGraphComponent
interface LineGraphProps {
data: ChartData<"line">; // Type for chart data
options?: ChartOptions<"line">; // Type for chart options (optional)
}
// LineGraphComponent using react-chartjs-2
const LineGraphComponent: React.FC<LineGraphProps> = ({ data, options }) => {
return <Line data={data} options={options} />;
};
interface ThroughputProps {
id: string;
type: string;
position: [number, number, number];
rotation: [number, number, number];
onContextMenu?: (event: React.MouseEvent) => void;
}
const Throughput: React.FC<ThroughputProps> = ({
id,
type,
position,
rotation,
onContextMenu,
}) => {
const { selectedChartId, setSelectedChartId } = useWidgetStore();
const {
measurements: chartMeasurements,
duration: chartDuration,
name: widgetName,
} = useChartStore();
const [measurements, setmeasurements] = useState<any>({});
const [duration, setDuration] = useState("1h");
const [name, setName] = useState("Widget");
const [chartData, setChartData] = useState<{
labels: string[];
datasets: any[];
}>({
labels: [],
datasets: [],
});
const iotApiUrl = process.env.REACT_APP_IOT_SOCKET_SERVER_URL;
const email = localStorage.getItem("email") || "";
const organization = email?.split("@")[1]?.split(".")[0];
// Sample data for the line graph
const graphData: ChartData<"line"> = {
labels: ["Jan", "Feb", "Mar", "Apr", "May", "Jun"],
datasets: [
{
label: "Throughput",
data: [1000, 1200, 1100, 1300, 1250, 1400], // Example throughput values
borderColor: "rgba(75, 192, 192, 1)",
backgroundColor: "rgba(75, 192, 192, 0.2)",
fill: true,
},
],
};
// Options for the line graph
const graphOptions: ChartOptions<"line"> = {
responsive: true,
plugins: {
legend: {
position: "top",
display: false,
},
title: {
display: true,
text: "Throughput Over Time",
},
},
scales: {
x: {
grid: {
display: true, // Show vertical grid lines
},
ticks: {
display: false, // Hide x-axis labels
},
},
y: {
grid: {
display: false, // Hide horizontal grid lines
},
ticks: {
display: false, // Hide y-axis labels
},
},
},
};
useEffect(() => {
if (!iotApiUrl || !measurements || Object.keys(measurements).length === 0)
return;
const socket = io(`http://${iotApiUrl}`);
const inputData = {
measurements,
duration,
interval: 1000,
};
const startStream = () => {
socket.emit("lineInput", inputData);
};
socket.on("connect", startStream);
socket.on("lineOutput", (response) => {
const responseData = response.data;
// Extract timestamps and values
const labels = responseData.time;
const datasets = Object.keys(measurements).map((key) => {
const measurement = measurements[key];
const datasetKey = `${measurement.name}.${measurement.fields}`;
return {
label: datasetKey,
data: responseData[datasetKey]?.values ?? [],
borderColor: "rgba(75, 192, 192, 1)",
backgroundColor: "rgba(75, 192, 192, 0.2)",
fill: true,
};
});
setChartData({ labels, datasets });
});
return () => {
socket.off("lineOutput");
socket.emit("stop_stream"); // Stop streaming when component unmounts
socket.disconnect();
};
}, [measurements, duration, iotApiUrl]);
const fetchSavedInputes = async () => {
if (id !== "") {
try {
const response = await axios.get(
`http://${process.env.REACT_APP_SERVER_REST_API_BASE_URL}/api/v2/widget3D/${id}/${organization}`
);
if (response.status === 200) {
setmeasurements(response.data.Data.measurements);
setDuration(response.data.Data.duration);
setName(response.data.widgetName);
} else {
console.log("Unexpected response:", response);
}
} catch (error) {
console.error("There was an error!", error);
}
}
};
useEffect(() => {
fetchSavedInputes();
}, []);
useEffect(() => {
if (selectedChartId?.id === id) {
fetchSavedInputes();
}
}, [chartMeasurements, chartDuration, widgetName]);
const rotationDegrees = {
x: (rotation[0] * 180) / Math.PI,
y: (rotation[1] * 180) / Math.PI,
z: (rotation[2] * 180) / Math.PI,
};
const transformStyle = {
transform: `rotateX(${rotationDegrees.x}deg) rotateY(${rotationDegrees.y}deg) rotateZ(${rotationDegrees.z}deg)`,
};
return (
<Html
position={[position[0], position[1], position[2]]}
rotation={rotation}
scale={[0.5, 0.5, 0.5]}
transform
zIndexRange={[1, 0]}
sprite={false}
// style={{
// transform: transformStyle.transform,
// transformStyle: "preserve-3d",
// transition: "transform 0.1s ease-out",
// }}
>
<div
className={`throughput-wrapper card ${
selectedChartId?.id === id ? "activeChart" : ""
}`}
onClick={() => setSelectedChartId({ id: id, type: type })}
onContextMenu={onContextMenu}
>
<div className="header">{name}</div>
<div className="display-value">
<div className="left">
<div className="icon">
<ThroughputIcon />
</div>
<div className="value-container">
<div className="value-wrapper">
<div className="value">1,200</div>
<div className="key"> Units/hr</div>
</div>
<div className="total-sales">
<div className="value">316</div>
<div className="key">sales</div>
</div>
</div>
</div>
<div className="right">
<div className="percent-increase">5.77%</div>
</div>
</div>
<div className="line-graph">
{/* Line graph using react-chartjs-2 */}
<LineGraphComponent
data={Object.keys(measurements).length > 0 ? chartData : graphData}
options={graphOptions}
/>
</div>
<div className="footer">
You made an extra <span className="value">$1256.13</span> this month
</div>
</div>
</Html>
);
};
export default Throughput;

View File

@@ -0,0 +1,130 @@
import React from "react";
interface DistanceLinesProps {
obj: {
position: {
top?: number | "auto";
left?: number | "auto";
right?: number | "auto";
bottom?: number | "auto";
};
};
activeEdges: {
vertical: "top" | "bottom";
horizontal: "left" | "right";
} | null;
}
const DistanceLines: React.FC<DistanceLinesProps> = ({ obj, activeEdges }) => {
if (!activeEdges) return null;
return (
<>
{activeEdges.vertical === "top" &&
typeof obj.position.top === "number" && (
<div
className="distance-line top"
style={{
top: 0,
left:
activeEdges.horizontal === "left"
? `${(obj.position.left as number) + 125}px`
: `calc(100% - ${(obj.position.right as number) + 125}px)`,
height: `${obj.position.top}px`,
}}
>
<span
className="distance-label"
style={{
position: "absolute",
top: "50%",
transform: "translate(-50%,0%)",
}}
>
{obj.position.top}px
</span>
</div>
)}
{activeEdges.vertical === "bottom" &&
typeof obj.position.bottom === "number" && (
<div
className="distance-line bottom"
style={{
bottom: 0,
left:
activeEdges.horizontal === "left"
? `${(obj.position.left as number) + 125}px`
: `calc(100% - ${(obj.position.right as number) + 125}px)`,
height: `${obj.position.bottom}px`,
}}
>
<span
className="distance-label"
style={{
position: "absolute",
bottom: "50%",
transform: "translate(-50%,0%)",
}}
>
{obj.position.bottom}px
</span>
</div>
)}
{activeEdges.horizontal === "left" &&
typeof obj.position.left === "number" && (
<div
className="distance-line left"
style={{
left: 0,
top:
activeEdges.vertical === "top"
? `${(obj.position.top as number) + 41.5}px`
: `calc(100% - ${(obj.position.bottom as number) + 41.5}px)`,
width: `${obj.position.left}px`,
}}
>
<span
className="distance-label"
style={{
position: "absolute",
left: "50%",
transform: "translate(0,-50%)",
}}
>
{obj.position.left}px
</span>
</div>
)}
{activeEdges.horizontal === "right" &&
typeof obj.position.right === "number" && (
<div
className="distance-line right"
style={{
right: 0,
top:
activeEdges.vertical === "top"
? `${(obj.position.top as number) + 41.5}px`
: `calc(100% - ${(obj.position.bottom as number) + 41.5}px)`,
width: `${obj.position.right}px`,
}}
>
<span
className="distance-label"
style={{
position: "absolute",
right: "50%",
transform: "translate(0,-50%)",
}}
>
{obj.position.right}px
</span>
</div>
)}
</>
);
};
export default DistanceLines;

View File

@@ -0,0 +1,666 @@
import { WalletIcon } from "../../../../components/icons/3dChartIcons";
import { useEffect, useRef, useState } from "react";
import {
useDroppedObjectsStore,
Zones,
} from "../../../../store/useDroppedObjectsStore";
import useModuleStore from "../../../../store/useModuleStore";
import { determinePosition } from "../../functions/determinePosition";
import { getActiveProperties } from "../../functions/getActiveProperties";
import { addingFloatingWidgets } from "../../../../services/realTimeVisulization/zoneData/addFloatingWidgets";
import {
DublicateIcon,
KebabIcon,
DeleteIcon,
} from "../../../../components/icons/ExportCommonIcons";
import DistanceLines from "./DistanceLines"; // Import the DistanceLines component
import { deleteFloatingWidgetApi } from "../../../../services/realTimeVisulization/zoneData/deleteFloatingWidget";
import TotalCardComponent from "./cards/TotalCardComponent";
import WarehouseThroughputComponent from "./cards/WarehouseThroughputComponent";
import FleetEfficiencyComponent from "./cards/FleetEfficiencyComponent";
import { useWidgetStore } from "../../../../store/useWidgetStore";
import { useSocketStore } from "../../../../store/store";
import { useClickOutside } from "../../functions/handleWidgetsOuterClick";
import { usePlayButtonStore } from "../../../../store/usePlayButtonStore";
import { useSelectedZoneStore } from "../../../../store/useZoneStore";
interface DraggingState {
zone: string;
index: number;
initialPosition: {
top: number | "auto";
left: number | "auto";
right: number | "auto";
bottom: number | "auto";
};
}
interface DraggingState {
zone: string;
index: number;
initialPosition: {
top: number | "auto";
left: number | "auto";
right: number | "auto";
bottom: number | "auto";
};
}
const DroppedObjects: React.FC = () => {
const { visualizationSocket } = useSocketStore();
const { isPlaying } = usePlayButtonStore();
const zones = useDroppedObjectsStore((state) => state.zones);
const [openKebabId, setOpenKebabId] = useState<string | null>(null);
const updateObjectPosition = useDroppedObjectsStore(
(state) => state.updateObjectPosition
);
const { setSelectedZone, selectedZone } = useSelectedZoneStore();
const deleteObject = useDroppedObjectsStore((state) => state.deleteObject);
const duplicateObject = useDroppedObjectsStore(
(state) => state.duplicateObject
);
const [draggingIndex, setDraggingIndex] = useState<DraggingState | null>(
null
);
const [offset, setOffset] = useState<[number, number] | null>(null);
const { selectedChartId, setSelectedChartId } = useWidgetStore();
const [activeEdges, setActiveEdges] = useState<{
vertical: "top" | "bottom";
horizontal: "left" | "right";
} | null>(null); // State to track active edges for distance lines
const [currentPosition, setCurrentPosition] = useState<{
top: number | "auto";
left: number | "auto";
right: number | "auto";
bottom: number | "auto";
} | null>(null); // State to track the current position during drag
const animationRef = useRef<number | null>(null);
const { activeModule } = useModuleStore();
const chartWidget = useRef<HTMLDivElement>(null);
// useClickOutside(chartWidget, () => {
// setSelectedChartId(null);
// });
const kebabRef = useRef<HTMLDivElement>(null);
// Clean up animation frame on unmount
useEffect(() => {
return () => {
if (animationRef.current) {
cancelAnimationFrame(animationRef.current);
}
};
}, []);
useEffect(() => {
const handleClickOutside = (event: MouseEvent) => {
if (
kebabRef.current &&
!kebabRef.current.contains(event.target as Node)
) {
setOpenKebabId(null);
}
};
// Add event listener when component mounts
document.addEventListener("mousedown", handleClickOutside);
// Clean up event listener when component unmounts
return () => {
document.removeEventListener("mousedown", handleClickOutside);
};
}, []);
const zoneEntries = Object.entries(zones);
if (zoneEntries.length === 0) return null;
const [zoneName, zone] = zoneEntries[0];
function handleDuplicate(zoneName: string, index: number) {
setOpenKebabId(null);
duplicateObject(zoneName, index); // Call the duplicateObject method from the store
}
async function handleDelete(zoneName: string, id: string) {
try {
const email = localStorage.getItem("email") || "";
const organization = email?.split("@")[1]?.split(".")[0];
let deleteFloatingWidget = {
floatWidgetID: id,
organization: organization,
zoneId: zone.zoneId,
};
if (visualizationSocket) {
visualizationSocket.emit("v2:viz-float:delete", deleteFloatingWidget);
}
deleteObject(zoneName, id);
// let res = await deleteFloatingWidgetApi(id, organization);
// s
// if (res.message === "FloatingWidget deleted successfully") {
// deleteObject(zoneName, id, index); // Call the deleteObject method from the store
// }
} catch (error) {}
}
const handlePointerDown = (event: React.PointerEvent, index: number) => {
if (
(event.target as HTMLElement).closest(".kebab-options") ||
(event.target as HTMLElement).closest(".kebab")
) {
return; // Prevent dragging when clicking on the kebab menu or its options
}
const obj = zone.objects[index];
const element = event.currentTarget as HTMLElement;
element.setPointerCapture(event.pointerId);
const container = document.getElementById("real-time-vis-canvas");
if (!container) return;
const rect = container.getBoundingClientRect();
const relativeX = event.clientX - rect.left;
const relativeY = event.clientY - rect.top;
// Determine active properties for the initial position
const [activeProp1, activeProp2] = getActiveProperties(obj.position);
// Set active edges for distance lines
const vertical = activeProp1 === "top" ? "top" : "bottom";
const horizontal = activeProp2 === "left" ? "left" : "right";
setActiveEdges({ vertical, horizontal });
// Store the initial position strategy and active edges
setDraggingIndex({
zone: zoneName,
index,
initialPosition: { ...obj.position },
});
// Calculate offset from mouse to object edges
let offsetX = 0;
let offsetY = 0;
if (activeProp1 === "top") {
offsetY = relativeY - (obj.position.top as number);
} else {
offsetY = rect.height - relativeY - (obj.position.bottom as number);
}
if (activeProp2 === "left") {
offsetX = relativeX - (obj.position.left as number);
} else {
offsetX = rect.width - relativeX - (obj.position.right as number);
}
setOffset([offsetY, offsetX]);
// Add native event listeners for smoother tracking
const handlePointerMoveNative = (e: PointerEvent) => {
if (!draggingIndex || !offset) return;
if (isPlaying === true) return;
const rect = container.getBoundingClientRect();
const relativeX = e.clientX - rect.left;
const relativeY = e.clientY - rect.top;
// Use requestAnimationFrame for smooth updates
animationRef.current = requestAnimationFrame(() => {
// Dynamically determine the current position strategy
const newPositionStrategy = determinePosition(
rect,
relativeX,
relativeY
);
const [activeProp1, activeProp2] =
getActiveProperties(newPositionStrategy);
// Update active edges for distance lines
const vertical = activeProp1 === "top" ? "top" : "bottom";
const horizontal = activeProp2 === "left" ? "left" : "right";
setActiveEdges({ vertical, horizontal });
// Calculate new position based on the active properties
let newY = 0;
let newX = 0;
if (activeProp1 === "top") {
newY = relativeY - offset[0];
} else {
newY = rect.height - (relativeY + offset[0]);
}
if (activeProp2 === "left") {
newX = relativeX - offset[1];
} else {
newX = rect.width - (relativeX + offset[1]);
}
// Apply boundaries
newX = Math.max(0, Math.min(rect.width - 50, newX));
newY = Math.max(0, Math.min(rect.height - 50, newY));
// Create new position object
const newPosition = {
...newPositionStrategy,
[activeProp1]: newY,
[activeProp2]: newX,
// Clear opposite properties
[activeProp1 === "top" ? "bottom" : "top"]: "auto",
[activeProp2 === "left" ? "right" : "left"]: "auto",
};
// Update the current position state for DistanceLines
setCurrentPosition(newPosition);
updateObjectPosition(zoneName, draggingIndex.index, newPosition);
});
};
const handlePointerUpNative = async (e: PointerEvent) => {
// Clean up native event listeners
element.removeEventListener("pointermove", handlePointerMoveNative);
element.removeEventListener("pointerup", handlePointerUpNative);
element.releasePointerCapture(e.pointerId);
if (!draggingIndex || !offset) return;
const rect = container.getBoundingClientRect();
const relativeX = e.clientX - rect.left;
const relativeY = e.clientY - rect.top;
// Determine final position strategy
const finalPosition = determinePosition(rect, relativeX, relativeY);
const [activeProp1, activeProp2] = getActiveProperties(finalPosition);
// Calculate final position
let finalY = 0;
let finalX = 0;
if (activeProp1 === "top") {
finalY = relativeY - offset[0];
} else {
finalY = rect.height - (relativeY + offset[0]);
}
if (activeProp2 === "left") {
finalX = relativeX - offset[1];
} else {
finalX = rect.width - (relativeX + offset[1]);
}
// Apply boundaries
finalX = Math.max(0, Math.min(rect.width - 50, finalX));
finalY = Math.max(0, Math.min(rect.height - 50, finalY));
const boundedPosition = {
...finalPosition,
[activeProp1]: finalY,
[activeProp2]: finalX,
[activeProp1 === "top" ? "bottom" : "top"]: "auto",
[activeProp2 === "left" ? "right" : "left"]: "auto",
};
try {
// Save to backend
const email = localStorage.getItem("email") || "";
const organization = email?.split("@")[1]?.split(".")[0];
const response = await addingFloatingWidgets(
zone.zoneId,
organization,
{
...zone.objects[draggingIndex.index],
position: boundedPosition,
}
);
if (response.message === "Widget updated successfully") {
updateObjectPosition(zoneName, draggingIndex.index, boundedPosition);
}
} catch (error) {
} finally {
setDraggingIndex(null);
setOffset(null);
setActiveEdges(null);
setCurrentPosition(null);
if (animationRef.current) {
cancelAnimationFrame(animationRef.current);
animationRef.current = null;
}
}
};
// Add native event listeners
element.addEventListener("pointermove", handlePointerMoveNative);
element.addEventListener("pointerup", handlePointerUpNative);
};
const handlePointerMove = (event: React.PointerEvent) => {
if (!draggingIndex || !offset) return;
if (isPlaying === true) return;
const container = document.getElementById("real-time-vis-canvas");
if (!container) return;
const rect = container.getBoundingClientRect();
const relativeX = event.clientX - rect.left;
const relativeY = event.clientY - rect.top;
// Dynamically determine the current position strategy
const newPositionStrategy = determinePosition(rect, relativeX, relativeY);
const [activeProp1, activeProp2] = getActiveProperties(newPositionStrategy);
// Update active edges for distance lines
const vertical = activeProp1 === "top" ? "top" : "bottom";
const horizontal = activeProp2 === "left" ? "left" : "right";
setActiveEdges({ vertical, horizontal });
// Calculate new position based on the active properties
let newY = 0;
let newX = 0;
if (activeProp1 === "top") {
newY = relativeY - offset[0];
} else {
newY = rect.height - (relativeY + offset[0]);
}
if (activeProp2 === "left") {
newX = relativeX - offset[1];
} else {
newX = rect.width - (relativeX + offset[1]);
}
// Apply boundaries
newX = Math.max(0, Math.min(rect.width - 50, newX));
newY = Math.max(0, Math.min(rect.height - 50, newY));
// Create new position object
const newPosition = {
...newPositionStrategy,
[activeProp1]: newY,
[activeProp2]: newX,
// Clear opposite properties
[activeProp1 === "top" ? "bottom" : "top"]: "auto",
[activeProp2 === "left" ? "right" : "left"]: "auto",
};
// Update the current position state for DistanceLines
setCurrentPosition(newPosition);
// Update position immediately without animation frame
updateObjectPosition(zoneName, draggingIndex.index, newPosition);
// if (!animationRef.current) {
// animationRef.current = requestAnimationFrame(() => {
// updateObjectPosition(zoneName, draggingIndex.index, newPosition);
// animationRef.current = null;
// });
// }
};
const handlePointerUp = async (event: React.PointerEvent<HTMLDivElement>) => {
try {
if (!draggingIndex || !offset) return;
if (isPlaying === true) return;
const container = document.getElementById("real-time-vis-canvas");
if (!container) return;
const rect = container.getBoundingClientRect();
const relativeX = event.clientX - rect.left;
const relativeY = event.clientY - rect.top;
// Determine final position strategy
const finalPosition = determinePosition(rect, relativeX, relativeY);
const [activeProp1, activeProp2] = getActiveProperties(finalPosition);
// Calculate final position
let finalY = 0;
let finalX = 0;
if (activeProp1 === "top") {
finalY = relativeY - offset[0];
} else {
finalY = rect.height - (relativeY + offset[0]);
}
if (activeProp2 === "left") {
finalX = relativeX - offset[1];
} else {
finalX = rect.width - (relativeX + offset[1]);
}
// Apply boundaries
finalX = Math.max(0, Math.min(rect.width - 50, finalX));
finalY = Math.max(0, Math.min(rect.height - 50, finalY));
const boundedPosition = {
...finalPosition,
[activeProp1]: finalY,
[activeProp2]: finalX,
// Clear opposite properties
[activeProp1 === "top" ? "bottom" : "top"]: "auto",
[activeProp2 === "left" ? "right" : "left"]: "auto",
};
// Save to backend
const email = localStorage.getItem("email") || "";
const organization = email?.split("@")[1]?.split(".")[0];
// const response = await addingFloatingWidgets(zone.zoneId, organization, {
// ...zone.objects[draggingIndex.index],
// position: boundedPosition,
// });
let updateFloatingWidget = {
organization: organization,
widget: {
...zone.objects[draggingIndex.index],
position: boundedPosition,
},
index: draggingIndex.index,
zoneId: zone.zoneId,
};
if (visualizationSocket) {
visualizationSocket.emit("v2:viz-float:add", updateFloatingWidget);
}
// if (response.message === "Widget updated successfully") {
updateObjectPosition(zoneName, draggingIndex.index, boundedPosition);
// }
// // Clean up
// setDraggingIndex(null);
// setOffset(null);
// setActiveEdges(null); // Clear active edges
// setCurrentPosition(null); // Reset current position
// if (animationRef.current) {
// cancelAnimationFrame(animationRef.current);
// animationRef.current = null;
// }
} catch (error) {
} finally {
// Clean up regardless of success or failure
setDraggingIndex(null);
setOffset(null);
setActiveEdges(null);
setCurrentPosition(null);
// Cancel any pending animation frame
if (animationRef.current) {
cancelAnimationFrame(animationRef.current);
animationRef.current = null;
}
}
};
const handleKebabClick = (id: string, event: React.MouseEvent) => {
event.stopPropagation();
setOpenKebabId((prevId) => (prevId === id ? null : id));
};
const containerHeight = getComputedStyle(
document.documentElement
).getPropertyValue("--realTimeViz-container-height");
const containerWidth = getComputedStyle(
document.documentElement
).getPropertyValue("--realTimeViz-container-width");
const heightMultiplier = parseFloat(containerHeight) * 0.14;
const widthMultiplier = parseFloat(containerWidth) * 0.13;
return (
<div
onPointerMove={handlePointerMove}
onPointerUp={handlePointerUp}
className="floating-wrapper"
>
{zone.objects.map((obj, index) => {
const topPosition =
typeof obj.position.top === "number"
? `calc(${obj.position.top}px + ${
isPlaying && selectedZone.activeSides.includes("top")
? `${heightMultiplier - 55}px`
: "0px"
})`
: "auto";
const leftPosition =
typeof obj.position.left === "number"
? `calc(${obj.position.left}px + ${
isPlaying && selectedZone.activeSides.includes("left")
? `${widthMultiplier - 100}px`
: "0px"
})`
: "auto";
const rightPosition =
typeof obj.position.right === "number"
? `calc(${obj.position.right}px + ${
isPlaying && selectedZone.activeSides.includes("right")
? `${widthMultiplier - 100}px`
: "0px"
})`
: "auto";
const bottomPosition =
typeof obj.position.bottom === "number"
? `calc(${obj.position.bottom}px + ${
isPlaying && selectedZone.activeSides.includes("bottom")
? `${heightMultiplier - 55}px`
: "0px"
})`
: "auto";
return (
<div
key={`${zoneName}-${index}`}
className={`${obj.className} ${
selectedChartId?.id === obj.id && "activeChart"
} `}
ref={chartWidget}
style={{
position: "absolute",
top: topPosition,
left: leftPosition,
right: rightPosition,
bottom: bottomPosition,
pointerEvents: isPlaying ? "none" : "auto",
minHeight: `${
obj.className === "warehouseThroughput" && "150px !important"
} `,
}}
onPointerDown={(event) => {
setSelectedChartId(obj);
handlePointerDown(event, index);
}}
>
{obj.className === "floating total-card" ? (
<TotalCardComponent object={obj} />
) : obj.className === "warehouseThroughput floating" ? (
<WarehouseThroughputComponent object={obj} />
) : obj.className === "fleetEfficiency floating" ? (
<FleetEfficiencyComponent object={obj} />
) : null}
<div
className="icon kebab"
ref={kebabRef}
onClick={(event) => {
event.stopPropagation();
handleKebabClick(obj.id, event);
}}
>
<KebabIcon />
</div>
{openKebabId === obj.id && (
<div className="kebab-options" ref={kebabRef}>
<div
className="dublicate btn"
onClick={(event) => {
event.stopPropagation();
handleDuplicate(zoneName, index); // Call the duplicate handler
}}
>
<div className="icon">
<DublicateIcon />
</div>
<div className="label">Duplicate</div>
</div>
<div
className="edit btn"
onClick={(event) => {
event.stopPropagation();
handleDelete(zoneName, obj.id); // Call the delete handler
}}
>
<div className="icon">
<DeleteIcon />
</div>
<div className="label">Delete</div>
</div>
</div>
)}
</div>
);
})}
{/* Render DistanceLines component during drag */}
{isPlaying === false &&
draggingIndex !== null &&
activeEdges !== null &&
currentPosition !== null && (
<DistanceLines
obj={{
position: {
top:
currentPosition.top !== "auto"
? currentPosition.top
: undefined,
bottom:
currentPosition.bottom !== "auto"
? currentPosition.bottom
: undefined,
left:
currentPosition.left !== "auto"
? currentPosition.left
: undefined,
right:
currentPosition.right !== "auto"
? currentPosition.right
: undefined,
},
}}
activeEdges={activeEdges}
/>
)}
</div>
);
};
export default DroppedObjects;

View File

@@ -0,0 +1,49 @@
const FleetEfficiency = () => {
const progress = 50; // Example progress value (0-100)
// Calculate the rotation angle for the progress bar
const rotationAngle = 45 + progress * 1.8;
const handleDragStart = (event: React.DragEvent<HTMLDivElement>) => {
const rect = event.currentTarget.getBoundingClientRect(); // Get position
const cardData = JSON.stringify({
className: event.currentTarget.className,
position: [rect.top, rect.left], // Store position
value: rotationAngle, // Example value (you can change if dynamic)
per: progress,
});
event.dataTransfer.setData("text/plain", cardData);
};
return (
<div className="fleetEfficiency floating" draggable onDragStart={handleDragStart}>
<h2 className="header">Fleet Efficiency</h2>
<div className="progressContainer">
<div className="progress">
<div className="barOverflow">
{/* Apply dynamic rotation to the bar */}
<div
className="bar"
style={{ transform: `rotate(${rotationAngle}deg)` }}
></div>
</div>
</div>
</div>
<div className="scaleLabels">
<span>0%</span>
<div className="centerText">
<div className="percentage">{progress}%</div>
<div className="status">Optimal</div>
</div>
<span>100%</span>
</div>
</div>
);
};
export default FleetEfficiency;

View File

@@ -0,0 +1,113 @@
import React, { useState, useEffect } from 'react'
import { Line } from 'react-chartjs-2'
import useChartStore from '../../../../../store/useChartStore';
import { useWidgetStore } from '../../../../../store/useWidgetStore';
import axios from 'axios';
import io from "socket.io-client";
const FleetEfficiencyComponent = ({object}: any) => {
const [ progress, setProgress ] = useState<any>(0)
const [measurements, setmeasurements] = useState<any>({});
const [duration, setDuration] = useState("1h")
const [name, setName] = useState(object.header ? object.header : '')
const email = localStorage.getItem("email") || "";
const organization = email?.split("@")[1]?.split(".")[0]
const { header, flotingDuration, flotingMeasurements } = useChartStore();
const { selectedChartId } = useWidgetStore();
const iotApiUrl = process.env.REACT_APP_IOT_SOCKET_SERVER_URL;
// Calculate the rotation angle for the progress bar
const rotationAngle = 45 + progress * 1.8;
useEffect(() => {
if (!iotApiUrl || !measurements || Object.keys(measurements).length === 0) return;
const socket = io(`http://${iotApiUrl}`);
const inputData = {
measurements,
duration,
interval: 1000,
};
const startStream = () => {
socket.emit("lastInput", inputData);
};
socket.on("connect", startStream);
socket.on("lastOutput", (response) => {
const responseData = response.input1;
console.log(responseData);
if (typeof responseData === "number") {
console.log("It's a number!");
setProgress(responseData);
}
});
return () => {
socket.off("lastOutput");
socket.emit("stop_stream"); // Stop streaming when component unmounts
socket.disconnect();
};
}, [measurements, duration, iotApiUrl]);
const fetchSavedInputes = async() => {
if (object?.id !== "") {
try {
const response = await axios.get(`http://${process.env.REACT_APP_SERVER_REST_API_BASE_URL}/api/v2/A_floatWidget/${object?.id}/${organization}`);
if (response.status === 200) {
setmeasurements(response.data.Data.measurements)
setDuration(response.data.Data.duration)
setName(response.data.header)
} else {
console.log("Unexpected response:", response);
}
} catch (error) {
console.error("There was an error!", error);
}
}
}
useEffect(() => {
fetchSavedInputes();
}, []);
useEffect(() => {
if (selectedChartId?.id === object?.id) {
fetchSavedInputes();
}
}
,[header, flotingDuration, flotingMeasurements])
return (
<>
<h2 className="header">{name}</h2>
<div className="progressContainer">
<div className="progress">
<div className="barOverflow">
<div
className="bar"
style={{ transform: `rotate(${rotationAngle}deg)` }}
></div>
</div>
</div>
</div>
<div className="scaleLabels">
<span>0%</span>
<div className="centerText">
<div className="percentage">{progress}%</div>
<div className="status">Optimal</div>
</div>
<span>100%</span>
</div>
</>
)
}
export default FleetEfficiencyComponent

View File

@@ -0,0 +1,86 @@
import React from "react";
interface ProductivityData {
distancePerTask: number;
spaceUtilization: number;
taskCompletionTime: string;
}
const ProductivityDashboard: React.FC = () => {
const data: ProductivityData = {
distancePerTask: 45,
spaceUtilization: 72,
taskCompletionTime: "7:44",
};
// Function to calculate the stroke dash offset for the circular progress
const calculateDashOffset = (percentage: number, circumference: number) => {
return circumference - (percentage / 100) * circumference;
};
// Constants for the circular progress chart
const radius = 60; // Radius of the circle
const strokeWidth = 10; // Thickness of the stroke
const diameter = radius * 2; // Diameter of the circle
const circumference = Math.PI * (radius * 2); // Circumference of the circle
return (
<div className="productivity-dashboard">
<header>
<h2>Productivity</h2>
<div className="options">...</div>
</header>
<main>
<section className="metrics">
<div className="metric">
<p className="label">Distance per Task</p>
<p className="value">{data.distancePerTask} m</p>
</div>
<div className="metric">
<p className="label">Space Utilization</p>
<p className="value">{data.spaceUtilization}%</p>
</div>
</section>
<section className="chart-section">
<svg
className="progress-circle"
width={diameter}
height={diameter}
viewBox={`0 0 ${diameter} ${diameter}`}
>
{/* Background Circle */}
<circle
cx={radius}
cy={radius}
r={radius - strokeWidth / 2}
fill="transparent"
stroke="#6c757d"
strokeWidth={strokeWidth}
/>
{/* Progress Circle */}
<circle
cx={radius}
cy={radius}
r={radius - strokeWidth / 2}
fill="transparent"
stroke="#2ecc71"
strokeWidth={strokeWidth}
strokeDasharray={circumference}
strokeDashoffset={calculateDashOffset(data.spaceUtilization, circumference)}
strokeLinecap="round"
transform={`rotate(-90 ${radius} ${radius})`}
/>
</svg>
<div className="chart-details">
<p className="title">Task Completion Time</p>
<p className="time">{data.taskCompletionTime}</p>
<p className="subtitle">Total Score</p>
</div>
</section>
</main>
</div>
);
};
export default ProductivityDashboard;

View File

@@ -0,0 +1,58 @@
import React from "react";
interface SimpleCardProps {
header: string;
icon: React.ElementType; // React component for SVG icon
iconName?: string;
value: string;
per: string; // Percentage change
position?: [number, number];
}
const SimpleCard: React.FC<SimpleCardProps> = ({
header,
icon: Icon,
iconName,
value,
per,
position = [0, 0],
}) => {
const handleDragStart = (event: React.DragEvent<HTMLDivElement>) => {
const rect = event.currentTarget.getBoundingClientRect(); // Get position
const cardData = JSON.stringify({
header,
value,
per,
iconName: iconName || "UnknownIcon", // Use the custom iconName
className: event.currentTarget.className,
position: [rect.top, rect.left], // ✅ Store position
});
event.dataTransfer.setData("text/plain", cardData);
console.log("cardData: ", cardData);
};
return (
<div
className="floating total-card"
draggable
onDragStart={handleDragStart}
style={{ top: position[0], left: position[1] }} // No need for ?? 0 if position is guaranteed
>
<div className="header-wrapper">
<div className="header">{header}</div>
<div className="data-values">
<div className="value">{value}</div>
<div className="per">{per}</div>
</div>
</div>
<div className="icon">
<Icon />
</div>
</div>
);
};
export default SimpleCard;

View File

@@ -0,0 +1,113 @@
import React, { useState, useEffect } from "react";
import { Line } from "react-chartjs-2";
import useChartStore from "../../../../../store/useChartStore";
import { useWidgetStore } from "../../../../../store/useWidgetStore";
import axios from "axios";
import io from "socket.io-client";
import {
CartIcon,
DocumentIcon,
GlobeIcon,
WalletIcon,
} from "../../../../../components/icons/3dChartIcons";
const TotalCardComponent = ({ object }: any) => {
const [progress, setProgress] = useState<any>(0);
const [measurements, setmeasurements] = useState<any>({});
const [duration, setDuration] = useState("1h");
const [name, setName] = useState(object.header ? object.header : "");
const email = localStorage.getItem("email") || "";
const organization = email?.split("@")[1]?.split(".")[0];
const { header, flotingDuration, flotingMeasurements } = useChartStore();
const { selectedChartId } = useWidgetStore();
const iotApiUrl = process.env.REACT_APP_IOT_SOCKET_SERVER_URL;
useEffect(() => {
if (!iotApiUrl || !measurements || Object.keys(measurements).length === 0)
return;
const socket = io(`http://${iotApiUrl}`);
const inputData = {
measurements,
duration,
interval: 1000,
};
const startStream = () => {
socket.emit("lastInput", inputData);
};
socket.on("connect", startStream);
socket.on("lastOutput", (response) => {
const responseData = response.input1;
if (typeof responseData === "number") {
setProgress(responseData);
}
});
return () => {
socket.off("lastOutput");
socket.emit("stop_stream"); // Stop streaming when component unmounts
socket.disconnect();
};
}, [measurements, duration, iotApiUrl]);
const fetchSavedInputes = async () => {
if (object?.id !== "") {
try {
const response = await axios.get(
`http://${process.env.REACT_APP_SERVER_REST_API_BASE_URL}/api/v2/A_floatWidget/${object?.id}/${organization}`
);
if (response.status === 200) {
setmeasurements(response.data.Data.measurements);
setDuration(response.data.Data.duration);
setName(response.data.header);
} else {
}
} catch (error) {}
}
};
useEffect(() => {
fetchSavedInputes();
}, []);
useEffect(() => {
if (selectedChartId?.id === object?.id) {
fetchSavedInputes();
}
}, [header, flotingDuration, flotingMeasurements]);
const mapIcon = (iconName: string) => {
switch (iconName) {
case "WalletIcon":
return <WalletIcon />;
case "GlobeIcon":
return <GlobeIcon />;
case "DocumentIcon":
return <DocumentIcon />;
case "CartIcon":
return <CartIcon />;
default:
return <WalletIcon />;
}
};
return (
<>
<div className="header-wrapper">
<div className="header">{name}</div>
<div className="data-values">
<div className="value">{progress}</div>
<div className="per">{object.per}</div>
</div>
</div>
<div className="icon">{mapIcon(object.iconName)}</div>
</>
);
};
export default TotalCardComponent;

View File

@@ -0,0 +1,149 @@
import React from "react";
import { Line } from "react-chartjs-2";
import {
Chart as ChartJS,
CategoryScale,
LinearScale,
PointElement,
LineElement,
Title,
Tooltip,
Legend,
Filler, // Import Filler for area fill
} from "chart.js";
// Register ChartJS components
ChartJS.register(
CategoryScale,
LinearScale,
PointElement,
LineElement,
Title,
Tooltip,
Legend,
Filler
);
const WarehouseThroughput = () => {
// Line graph data for a year (monthly throughput)
const lineGraphData = {
labels: [
"Jan",
"Feb",
"Mar",
"Apr",
"May",
"Jun",
"Jul",
"Aug",
"Sep",
"Oct",
"Nov",
"Dec",
], // Months of the year
datasets: [
{
label: "Throughput (units/month)",
data: [500, 400, 300, 450, 350, 250, 200, 300, 250, 150, 100, 150], // Example monthly data
borderColor: "#6f42c1", // Use the desired color for the line (purple)
backgroundColor: "rgba(111, 66, 193, 0.2)", // Use a semi-transparent purple for the fill
borderWidth: 2, // Line thickness
fill: true, // Enable fill for this dataset
pointRadius: 0, // Remove dots at each data point
tension: 0.5, // Smooth interpolation for the line
},
],
};
// Line graph options
const lineGraphOptions = {
responsive: true,
maintainAspectRatio: false, // Allow custom height/width adjustments
plugins: {
legend: {
display: false, // Hide legend
},
title: {
display: false, // No chart title needed
},
tooltip: {
callbacks: {
label: (context: any) => {
const value = context.parsed.y;
return `${value} units`; // Customize tooltip to display "units"
},
},
},
},
scales: {
x: {
grid: {
display: false, // Hide x-axis grid lines
},
ticks: {
maxRotation: 0, // Prevent label rotation
autoSkip: false, // Display all months
font: {
size: 8, // Adjust font size for readability
color: "#ffffff", // Light text color for labels
},
},
},
y: {
display: true, // Show y-axis
grid: {
drawBorder: false, // Remove border line
color: "rgba(255, 255, 255, 0.2)", // Light gray color for grid lines
borderDash: [5, 5], // Dotted line style (array defines dash and gap lengths)
},
ticks: {
font: {
size: 8, // Adjust font size for readability
color: "#ffffff", // Light text color for ticks
},
},
},
},
elements: {
line: {
tension: 0.5, // Smooth interpolation for the line
},
},
};
const handleDragStart = (event: React.DragEvent<HTMLDivElement>) => {
const rect = event.currentTarget.getBoundingClientRect(); // Get element position
const cardData = JSON.stringify({
header: "Warehouse Throughput", // Static header
value: "+5", // Example value (you can change if dynamic)
per: "2025", // Example percentage or date
icon: "📊", // Placeholder for an icon (if needed)
className: event.currentTarget.className,
position: [rect.top, rect.left], // ✅ Store initial position
lineGraphData, // ✅ Include chart data
lineGraphOptions, // ✅ Include chart options
});
event.dataTransfer.setData("text/plain", cardData);
// event.dataTransfer.effectAllowed = "move"; // Improve drag effect
};
return (
<div className="warehouseThroughput floating" style={{ minHeight: "160px !important" }} draggable onDragStart={handleDragStart}>
<div className="header">
<h2>Warehouse Throughput</h2>
<p>
<span>(+5) more</span> in 2025
</p>
</div>
<div className="lineGraph" style={{ height: "100%" }}>
{/* Line Graph */}
<Line data={lineGraphData} options={lineGraphOptions} />
</div>
</div>
);
};
export default WarehouseThroughput;

View File

@@ -0,0 +1,205 @@
import React, { useState, useEffect } from 'react'
import { Line } from 'react-chartjs-2'
import useChartStore from '../../../../../store/useChartStore';
import { useWidgetStore } from '../../../../../store/useWidgetStore';
import axios from 'axios';
import io from "socket.io-client";
const WarehouseThroughputComponent = ({
object
}: any) => {
const [measurements, setmeasurements] = useState<any>({});
const [duration, setDuration] = useState("1h")
const [name, setName] = useState(object.header ? object.header : '')
const [chartData, setChartData] = useState<{ labels: string[]; datasets: any[] }>({
labels: [],
datasets: [],
});
const email = localStorage.getItem("email") || "";
const organization = email?.split("@")[1]?.split(".")[0]
const { header, flotingDuration, flotingMeasurements } = useChartStore();
const { selectedChartId } = useWidgetStore();
const iotApiUrl = process.env.REACT_APP_IOT_SOCKET_SERVER_URL;
const lineGraphData = {
labels: [
"Jan",
"Feb",
"Mar",
"Apr",
"May",
"Jun",
"Jul",
"Aug",
"Sep",
"Oct",
"Nov",
"Dec",
], // Months of the year
datasets: [
{
label: "Throughput (units/month)",
data: [500, 400, 300, 450, 350, 250, 200, 300, 250, 150, 100, 150], // Example monthly data
borderColor: "#6f42c1", // Use the desired color for the line (purple)
backgroundColor: "rgba(111, 66, 193, 0.2)", // Use a semi-transparent purple for the fill
borderWidth: 2, // Line thickness
fill: true, // Enable fill for this dataset
pointRadius: 0, // Remove dots at each data point
tension: 0.5, // Smooth interpolation for the line
},
],
};
// Line graph options
const lineGraphOptions = {
responsive: true,
maintainAspectRatio: false, // Allow custom height/width adjustments
plugins: {
legend: {
display: false, // Hide legend
},
title: {
display: false, // No chart title needed
},
tooltip: {
callbacks: {
label: (context: any) => {
const value = context.parsed.y;
return `${value} units`; // Customize tooltip to display "units"
},
},
},
},
scales: {
x: {
grid: {
display: false, // Hide x-axis grid lines
},
ticks: {
maxRotation: 0, // Prevent label rotation
autoSkip: false, // Display all months
font: {
size: 8, // Adjust font size for readability
color: "#ffffff", // Light text color for labels
},
},
},
y: {
display: true, // Show y-axis
grid: {
drawBorder: false, // Remove border line
color: "rgba(255, 255, 255, 0.2)", // Light gray color for grid lines
borderDash: [5, 5], // Dotted line style (array defines dash and gap lengths)
},
ticks: {
font: {
size: 8, // Adjust font size for readability
color: "#ffffff", // Light text color for ticks
},
},
},
},
elements: {
line: {
tension: 0.5, // Smooth interpolation for the line
},
},
};
useEffect(() => {
if (!iotApiUrl || !measurements || Object.keys(measurements).length === 0) return;
const socket = io(`http://${iotApiUrl}`);
const inputData = {
measurements,
duration,
interval: 1000,
};
const startStream = () => {
socket.emit("lineInput", inputData);
};
socket.on("connect", startStream);
socket.on("lineOutput", (response) => {
const responseData = response.data;
// Extract timestamps and values
const labels = responseData.time;
const datasets = Object.keys(measurements).map((key) => {
const measurement = measurements[key];
const datasetKey = `${measurement.name}.${measurement.fields}`;
return {
label: datasetKey,
data: responseData[datasetKey]?.values ?? [],
borderColor: "#6f42c1", // Use the desired color for the line (purple)
backgroundColor: "rgba(111, 66, 193, 0.2)", // Use a semi-transparent purple for the fill
borderWidth: 2, // Line thickness
fill: true, // Enable fill for this dataset
pointRadius: 0, // Remove dots at each data point
tension: 0.5, // Smooth interpolation for the line
};
});
setChartData({ labels, datasets });
});
return () => {
socket.off("lineOutput");
socket.emit("stop_stream"); // Stop streaming when component unmounts
socket.disconnect();
};
}, [measurements, duration, iotApiUrl]);
const fetchSavedInputes = async() => {
if (object?.id !== "") {
try {
const response = await axios.get(`http://${process.env.REACT_APP_SERVER_REST_API_BASE_URL}/api/v2/A_floatWidget/${object?.id}/${organization}`);
if (response.status === 200) {
setmeasurements(response.data.Data.measurements)
setDuration(response.data.Data.duration)
setName(response.data.header)
} else {
console.log("Unexpected response:", response);
}
} catch (error) {
console.error("There was an error!", error);
}
}
}
useEffect(() => {
fetchSavedInputes();
}, []);
useEffect(() => {
if (selectedChartId?.id === object?.id) {
fetchSavedInputes();
}
}
,[header, flotingDuration, flotingMeasurements])
return (
<>
<div className="header">
<h2>{name}</h2>
{/* <p>
<span>(+5) more</span> in 2025
</p> */}
</div>
<div className="lineGraph" style={{ height: "100%" }}>
<Line data={ Object.keys(measurements).length > 0 ? chartData : lineGraphData} options={lineGraphOptions} />
</div>
</>
)
}
export default WarehouseThroughputComponent

View File

@@ -0,0 +1,345 @@
import React from "react";
import {
CleanPannel,
EyeIcon,
LockIcon,
} from "../../../../components/icons/RealTimeVisulationIcons";
import { AddIcon } from "../../../../components/icons/ExportCommonIcons";
import { useSocketStore } from "../../../../store/store";
import { clearPanel } from "../../../../services/realTimeVisulization/zoneData/clearPanel";
import { lockPanel } from "../../../../services/realTimeVisulization/zoneData/lockPanel";
// Define the type for `Side`
type Side = "top" | "bottom" | "left" | "right";
// Define the type for HiddenPanels, where keys are zone IDs and values are arrays of hidden sides
interface HiddenPanels {
[zoneId: string]: Side[];
}
// Define the type for the props passed to the Buttons component
interface ButtonsProps {
selectedZone: {
zoneName: string;
activeSides: Side[];
panelOrder: Side[];
lockedPanels: Side[];
points: [];
zoneId: string;
zoneViewPortTarget: number[];
zoneViewPortPosition: number[];
widgets: {
id: string;
type: string;
title: string;
panel: Side;
data: any;
}[];
};
setSelectedZone: React.Dispatch<
React.SetStateAction<{
zoneName: string;
activeSides: Side[];
panelOrder: Side[];
lockedPanels: Side[];
points: [];
zoneId: string;
zoneViewPortTarget: number[];
zoneViewPortPosition: number[];
widgets: {
id: string;
type: string;
title: string;
panel: Side;
data: any;
}[];
}>
>;
hiddenPanels: HiddenPanels; // Updated prop type
setHiddenPanels: React.Dispatch<React.SetStateAction<HiddenPanels>>; // Updated prop type
}
const AddButtons: React.FC<ButtonsProps> = ({
selectedZone,
setSelectedZone,
setHiddenPanels,
hiddenPanels,
}) => {
const { visualizationSocket } = useSocketStore();
// Function to toggle visibility of a panel
const toggleVisibility = (side: Side) => {
const isHidden = hiddenPanels[selectedZone.zoneId]?.includes(side) ?? false;
if (isHidden) {
// If the panel is already hidden, remove it from the hiddenPanels array for this zone
setHiddenPanels((prevHiddenPanels) => ({
...prevHiddenPanels,
[selectedZone.zoneId]: prevHiddenPanels[selectedZone.zoneId].filter(
(panel) => panel !== side
),
}));
} else {
// If the panel is visible, add it to the hiddenPanels array for this zone
setHiddenPanels((prevHiddenPanels) => ({
...prevHiddenPanels,
[selectedZone.zoneId]: [
...(prevHiddenPanels[selectedZone.zoneId] || []),
side,
],
}));
}
};
// Function to toggle lock/unlock a panel
const toggleLockPanel = async (side: Side) => {
// console.log('side: ', side);
const email = localStorage.getItem("email") || "";
const organization = email?.split("@")[1]?.split(".")[0]; // Fallback value
//add api
const newLockedPanels = selectedZone.lockedPanels.includes(side)
? selectedZone.lockedPanels.filter((panel) => panel !== side)
: [...selectedZone.lockedPanels, side];
const updatedZone = {
...selectedZone,
lockedPanels: newLockedPanels,
};
let lockedPanel = {
organization: organization,
lockedPanel: newLockedPanels,
zoneId: selectedZone.zoneId,
};
if (visualizationSocket) {
visualizationSocket.emit("v2:viz-panel:locked", lockedPanel);
}
setSelectedZone(updatedZone);
// let response = await lockPanel(selectedZone.zoneId, organization, newLockedPanels)
// console.log('response: ', response);
// if (response.message === 'locked panel updated successfully') {
// // Update the selectedZone state
// setSelectedZone(updatedZone);
// }
};
// Function to clean all widgets from a panel
const cleanPanel = async (side: Side) => {
//add api
// console.log('side: ', side);
const email = localStorage.getItem("email") || "";
const organization = email?.split("@")[1]?.split(".")[0]; // Fallback value
let clearPanel = {
organization: organization,
panelName: side,
zoneId: selectedZone.zoneId,
};
if (visualizationSocket) {
visualizationSocket.emit("v2:viz-panel:clear", clearPanel);
}
const cleanedWidgets = selectedZone.widgets.filter(
(widget) => widget.panel !== side
);
const updatedZone = {
...selectedZone,
widgets: cleanedWidgets,
};
// Update the selectedZone state
// console.log('updatedZone: ', updatedZone);
setSelectedZone(updatedZone);
// let response = await clearPanel(selectedZone.zoneId, organization, side)
// console.log('response: ', response);
// if (response.message === 'PanelWidgets cleared successfully') {
// const cleanedWidgets = selectedZone.widgets.filter(
// (widget) => widget.panel !== side
// );
// const updatedZone = {
// ...selectedZone,
// widgets: cleanedWidgets,
// };
// // Update the selectedZone state
// setSelectedZone(updatedZone);
// }
};
// Function to handle "+" button click
const handlePlusButtonClick = async (side: Side) => {
if (selectedZone.activeSides.includes(side)) {
console.log("open");
// Panel already exists: Remove widgets from that side and update activeSides
const email = localStorage.getItem("email") || "";
const organization = email?.split("@")[1]?.split(".")[0]; // Fallback value
// Remove all widgets associated with the side and update active sides
const cleanedWidgets = selectedZone.widgets.filter(
(widget) => widget.panel !== side
);
const newActiveSides = selectedZone.activeSides.filter((s) => s !== side);
const updatedZone = {
...selectedZone,
widgets: cleanedWidgets,
activeSides: newActiveSides,
panelOrder: newActiveSides,
};
let deletePanel = {
organization: organization,
panelName: side,
zoneId: selectedZone.zoneId,
};
if (visualizationSocket) {
visualizationSocket.emit("v2:viz-panel:delete", deletePanel);
}
setSelectedZone(updatedZone);
if (hiddenPanels[selectedZone.zoneId]?.includes(side)) {
setHiddenPanels(prev => ({
...prev,
[selectedZone.zoneId]: prev[selectedZone.zoneId].filter(s => s !== side)
}));
}
// if(hiddenPanels[selectedZone.zoneId].includes(side))
// API call to delete the panel
// try {
// const response = await deletePanelApi(selectedZone.zoneId, side, organization);
//
// if (response.message === "Panel deleted successfully") {
// } else {
//
// }
// } catch (error) {
//
// }
} else {
// Panel does not exist: Create panel
try {
// Get email and organization safely with a default fallback
const email = localStorage.getItem("email") || "";
const organization = email?.split("@")[1]?.split(".")[0];
// Prevent duplicate side entries
const newActiveSides = selectedZone.activeSides.includes(side)
? [...selectedZone.activeSides]
: [...selectedZone.activeSides, side];
const updatedZone = {
...selectedZone,
activeSides: newActiveSides,
panelOrder: newActiveSides,
};
let addPanel = {
organization: organization,
zoneId: selectedZone.zoneId,
panelOrder: newActiveSides,
};
if (visualizationSocket) {
visualizationSocket.emit("v2:viz-panel:add", addPanel);
}
setSelectedZone(updatedZone);
// API call to create panels
// const response = await panelData(organization, selectedZone.zoneId, newActiveSides);
//
// if (response.message === "Panels created successfully") {
// } else {
//
// }
} catch (error) {}
}
};
return (
<>
<div>
{(["top", "right", "bottom", "left"] as Side[]).map((side) => (
<div key={side} className={`side-button-container ${side}`}>
{/* "+" Button */}
<button
className={`side-button ${side}${
selectedZone.activeSides.includes(side) ? " active" : ""
}`}
onClick={() => handlePlusButtonClick(side)}
title={
selectedZone.activeSides.includes(side)
? `Remove all items and close ${side} panel`
: `Activate ${side} panel`
}
>
<div className="add-icon">
<AddIcon />
</div>
</button>
{/* Extra Buttons */}
{selectedZone.activeSides.includes(side) && (
<div className="extra-Bs">
{/* Hide Panel */}
<div
className={`icon ${hiddenPanels[selectedZone.zoneId]?.includes(side)
? "active"
: ""
}`}
title={
hiddenPanels[selectedZone.zoneId]?.includes(side)
? "Show Panel"
: "Hide Panel"
}
onClick={() => toggleVisibility(side)}
>
<EyeIcon
fill={
hiddenPanels[selectedZone.zoneId]?.includes(side)
? "var(--primary-color)"
: "var(--text-color)"
}
/>
</div>
{/* Clean Panel */}
<div
className="icon"
title="Clean Panel"
onClick={() => cleanPanel(side)}
>
<CleanPannel />
</div>
{/* Lock/Unlock Panel */}
<div
className={`icon ${
selectedZone.lockedPanels.includes(side) ? "active" : ""
}`}
title={
selectedZone.lockedPanels.includes(side)
? "Unlock Panel"
: "Lock Panel"
}
onClick={() => toggleLockPanel(side)}
>
<LockIcon
fill={
selectedZone.lockedPanels.includes(side)
? "var(--primary-color)"
: "var(--text-color)"
}
/>
</div>
</div>
)}
</div>
))}
</div>
</>
);
};
export default AddButtons;

View File

@@ -0,0 +1,336 @@
import React, { useEffect, useMemo, useRef, useState } from "react";
import { arrayMove } from "@dnd-kit/sortable";
import { useAsset3dWidget, useSocketStore } from "../../../../store/store";
import { usePlayButtonStore } from "../../../../store/usePlayButtonStore";
import { useWidgetStore } from "../../../../store/useWidgetStore";
import { DraggableWidget } from "../2d/DraggableWidget";
type Side = "top" | "bottom" | "left" | "right";
interface Widget {
id: string;
type: string;
title: string;
panel: Side;
data: any;
}
interface PanelProps {
selectedZone: {
zoneName: string;
activeSides: Side[];
panelOrder: Side[];
lockedPanels: Side[];
points: [];
zoneId: string;
zoneViewPortTarget: number[];
zoneViewPortPosition: number[];
widgets: Widget[];
};
setSelectedZone: React.Dispatch<
React.SetStateAction<{
zoneName: string;
activeSides: Side[];
panelOrder: Side[];
lockedPanels: Side[];
points: [];
zoneId: string;
zoneViewPortTarget: number[];
zoneViewPortPosition: number[];
widgets: Widget[];
}>
>;
hiddenPanels: any;
setZonesData: React.Dispatch<React.SetStateAction<any>>;
}
const generateUniqueId = () =>
`${Date.now()}-${Math.random().toString(36).substr(2, 9)}`;
const Panel: React.FC<PanelProps> = ({
selectedZone,
setSelectedZone,
hiddenPanels,
setZonesData,
}) => {
const { widgetSelect, setWidgetSelect } = useAsset3dWidget();
const panelRefs = useRef<{ [side in Side]?: HTMLDivElement }>({});
const [panelDimensions, setPanelDimensions] = useState<{
[side in Side]?: { width: number; height: number };
}>({});
const [openKebabId, setOpenKebabId] = useState<string | null>(null);
const { isPlaying } = usePlayButtonStore();
const { visualizationSocket } = useSocketStore();
const [canvasDimensions, setCanvasDimensions] = useState({
width: 0,
height: 0,
});
// Track canvas dimensions
useEffect(() => {
const canvas = document.getElementById("real-time-vis-canvas");
if (!canvas) return;
const updateCanvasDimensions = () => {
const rect = canvas.getBoundingClientRect();
setCanvasDimensions({
width: rect.width,
height: rect.height,
});
};
updateCanvasDimensions();
const resizeObserver = new ResizeObserver(updateCanvasDimensions);
resizeObserver.observe(canvas);
return () => resizeObserver.unobserve(canvas);
}, []);
// Calculate panel size
const panelSize = Math.max(
Math.min(canvasDimensions.width * 0.25, canvasDimensions.height * 0.25),
170 // Min 170px
);
// Define getPanelStyle
const getPanelStyle = useMemo(
() => (side: Side) => {
const currentIndex = selectedZone.panelOrder.indexOf(side);
const previousPanels = selectedZone.panelOrder.slice(0, currentIndex);
const leftActive = previousPanels.includes("left");
const rightActive = previousPanels.includes("right");
const topActive = previousPanels.includes("top");
const bottomActive = previousPanels.includes("bottom");
switch (side) {
case "top":
case "bottom":
return {
minWidth: "170px",
width: `calc(100% - ${
(leftActive ? panelSize : 0) + (rightActive ? panelSize : 0)
}px)`,
minHeight: "170px",
height: `${panelSize}px`,
left: leftActive ? `${panelSize}px` : "0",
right: rightActive ? `${panelSize}px` : "0",
[side]: "0",
};
case "left":
case "right":
return {
minWidth: "170px",
width: `${panelSize}px`,
minHeight: "170px",
height: `calc(100% - ${
(topActive ? panelSize : 0) + (bottomActive ? panelSize : 0)
}px)`,
top: topActive ? `${panelSize}px` : "0",
bottom: bottomActive ? `${panelSize}px` : "0",
[side]: "0",
};
default:
return {};
}
},
[selectedZone.panelOrder, panelSize]
);
// Handle drop event
const handleDrop = (e: React.DragEvent, panel: Side) => {
e.preventDefault();
const { draggedAsset } = useWidgetStore.getState();
if (
!draggedAsset ||
isPanelLocked(panel) ||
hiddenPanels[selectedZone.zoneId]?.includes(panel)
)
return;
const currentWidgetsCount = getCurrentWidgetCount(panel);
const maxCapacity = calculatePanelCapacity(panel);
if (currentWidgetsCount < maxCapacity) {
addWidgetToPanel(draggedAsset, panel);
}
};
// Check if panel is locked
const isPanelLocked = (panel: Side) =>
selectedZone.lockedPanels.includes(panel);
// Get current widget count in a panel
const getCurrentWidgetCount = (panel: Side) =>
selectedZone.widgets.filter((w) => w.panel === panel).length;
// Calculate panel capacity
const calculatePanelCapacity = (panel: Side) => {
const CHART_WIDTH = panelSize - 10;
const CHART_HEIGHT = panelSize - 10;
const dimensions = panelDimensions[panel];
if (!dimensions) {
return panel === "top" || panel === "bottom" ? 5 : 3; // Fallback capacities
}
return panel === "top" || panel === "bottom"
? Math.max(1, Math.floor(dimensions.width / CHART_WIDTH))
: Math.max(1, Math.floor(dimensions.height / CHART_HEIGHT));
};
// Add widget to panel
const addWidgetToPanel = async (asset: any, panel: Side) => {
const email = localStorage.getItem("email") || "";
const organization = email?.split("@")[1]?.split(".")[0];
const newWidget = {
...asset,
id: generateUniqueId(),
panel,
};
let addWidget = {
organization: organization,
zoneId: selectedZone.zoneId,
widget: newWidget,
};
if (visualizationSocket) {
visualizationSocket.emit("v2:viz-widget:add", addWidget);
}
setSelectedZone((prev) => ({
...prev,
widgets: [...prev.widgets, newWidget],
}));
};
// Observe panel dimensions
useEffect(() => {
const observers: ResizeObserver[] = [];
const currentPanelRefs = panelRefs.current;
selectedZone.activeSides.forEach((side) => {
const element = currentPanelRefs[side];
if (element) {
const observer = new ResizeObserver((entries) => {
for (const entry of entries) {
const { width, height } = entry.contentRect;
setPanelDimensions((prev) => ({
...prev,
[side]: { width, height },
}));
}
});
observer.observe(element);
observers.push(observer);
}
});
return () => {
observers.forEach((observer) => observer.disconnect());
};
}, [selectedZone.activeSides]);
// Handle widget reordering
const handleReorder = (fromIndex: number, toIndex: number, panel: Side) => {
setSelectedZone((prev) => {
const widgetsInPanel = prev.widgets.filter((w) => w.panel === panel);
const reorderedWidgets = arrayMove(widgetsInPanel, fromIndex, toIndex);
const updatedWidgets = prev.widgets
.filter((widget) => widget.panel !== panel)
.concat(reorderedWidgets);
return {
...prev,
widgets: updatedWidgets,
};
});
};
// Calculate capacities and dimensions
const topWidth = getPanelStyle("top").width;
const bottomWidth = getPanelStyle("bottom").height;
const leftHeight = getPanelStyle("left").height;
const rightHeight = getPanelStyle("right").height;
const topCapacity = calculatePanelCapacity("top");
const bottomCapacity = calculatePanelCapacity("bottom");
const leftCapacity = calculatePanelCapacity("left");
const rightCapacity = calculatePanelCapacity("right");
return (
<>
<style>
{`
:root {
--topWidth: ${topWidth};
--bottomWidth: ${bottomWidth} ;
--leftHeight: ${leftHeight};
--rightHeight: ${rightHeight};
--topCapacity: ${topCapacity};
--bottomCapacity: ${bottomCapacity};
--leftCapacity: ${leftCapacity};
--rightCapacity: ${rightCapacity};
}
`}
</style>
{selectedZone.activeSides.map((side) => (
<div
key={side}
id="panel-wrapper"
className={`panel ${side}-panel absolute ${
hiddenPanels[selectedZone.zoneId]?.includes(side) ? "hidePanel" : ""
}`}
style={getPanelStyle(side)}
onDrop={(e) => handleDrop(e, side)}
onDragOver={(e) => e.preventDefault()}
ref={(el) => {
if (el) {
panelRefs.current[side] = el;
} else {
delete panelRefs.current[side];
}
}}
>
<div
className={`panel-content ${isPlaying && "fullScreen"}`}
style={{
pointerEvents:
selectedZone.lockedPanels.includes(side) ||
hiddenPanels[selectedZone.zoneId]?.includes(side)
? "none"
: "auto",
opacity: selectedZone.lockedPanels.includes(side) ? "0.8" : "1",
}}
>
{selectedZone.widgets
.filter((w) => w.panel === side)
.map((widget, index) => (
<DraggableWidget
hiddenPanels={hiddenPanels}
widget={widget}
key={widget.id}
index={index}
onReorder={(fromIndex, toIndex) =>
handleReorder(fromIndex, toIndex, side)
}
openKebabId={openKebabId}
setOpenKebabId={setOpenKebabId}
selectedZone={selectedZone}
setSelectedZone={setSelectedZone}
/>
))}
</div>
</div>
))}
</>
);
};
export default Panel;

View File

@@ -0,0 +1,83 @@
import React, { useEffect, useRef } from 'react'
import { useSelectedFloorItem, useZoneAssetId } from '../../store/store';
import * as THREE from "three";
import { useThree } from '@react-three/fiber';
import * as Types from "../../types/world/worldTypes";
export default function ZoneAssets() {
const { zoneAssetId, setZoneAssetId } = useZoneAssetId();
const { setSelectedFloorItem } = useSelectedFloorItem();
const { raycaster, controls, scene }: any = useThree();
useEffect(() => {
// console.log('zoneAssetId: ', zoneAssetId);
if (!zoneAssetId) return
console.log('zoneAssetId: ', zoneAssetId);
let AssetMesh = scene.getObjectByProperty("uuid", zoneAssetId.id);
if (AssetMesh) {
const bbox = new THREE.Box3().setFromObject(AssetMesh);
const size = bbox.getSize(new THREE.Vector3());
const center = bbox.getCenter(new THREE.Vector3());
const front = new THREE.Vector3(0, 0, 1);
AssetMesh.localToWorld(front);
front.sub(AssetMesh.position).normalize();
const distance = Math.max(size.x, size.y, size.z) * 2;
const newPosition = center.clone().addScaledVector(front, distance);
controls.setPosition(newPosition.x, newPosition.y, newPosition.z, true);
controls.setTarget(center.x, center.y, center.z, true);
controls.fitToBox(AssetMesh, true, { cover: true, paddingTop: 5, paddingLeft: 5, paddingBottom: 5, paddingRight: 5, });
setSelectedFloorItem(AssetMesh);
} else {
console.log('zoneAssetId: ', zoneAssetId)
if (Array.isArray(zoneAssetId.position) && zoneAssetId.position.length >= 3) {
let selectedAssetPosition = [
zoneAssetId.position[0],
10,
zoneAssetId.position[2]
];
console.log('selectedAssetPosition: ', selectedAssetPosition);
let selectedAssetTarget = [
zoneAssetId.position[0],
zoneAssetId.position[1],
zoneAssetId.position[2]
];
console.log('selectedAssetTarget: ', selectedAssetTarget);
const setCam = async () => {
await controls?.setLookAt(...selectedAssetPosition, ...selectedAssetTarget, true);
setTimeout(() => {
let AssetMesh = scene.getObjectByProperty("uuid", zoneAssetId.id);
if (AssetMesh) {
const bbox = new THREE.Box3().setFromObject(AssetMesh);
const size = bbox.getSize(new THREE.Vector3());
const center = bbox.getCenter(new THREE.Vector3());
const front = new THREE.Vector3(0, 0, 1);
AssetMesh.localToWorld(front);
front.sub(AssetMesh.position).normalize();
const distance = Math.max(size.x, size.y, size.z) * 2;
const newPosition = center.clone().addScaledVector(front, distance);
controls.setPosition(newPosition.x, newPosition.y, newPosition.z, true);
controls.setTarget(center.x, center.y, center.z, true);
controls.fitToBox(AssetMesh, true, { cover: true, paddingTop: 5, paddingLeft: 5, paddingBottom: 5, paddingRight: 5, });
setSelectedFloorItem(AssetMesh);
}
}, 500)
};
setCam();
}
}
}, [zoneAssetId, scene, controls])
return (
<>
</>
)
}