diff --git a/app/src/app.tsx b/app/src/app.tsx index bbd5984..2b2a25d 100644 --- a/app/src/app.tsx +++ b/app/src/app.tsx @@ -10,25 +10,24 @@ import ForgotPassword from "./pages/ForgotPassword"; import PageNotFound from "./pages/PageNotFound"; const App: React.FC = () => { + useEffect(() => { + Cache.clear(); + Cache.enabled = true; + }, []); - useEffect(() => { - Cache.clear(); - Cache.enabled = true; - }, []); - - return ( - - - - } /> - } /> - } /> - } /> - } /> - - - - ); + return ( + + + + } /> + } /> + } /> + } /> + } /> + + + + ); }; export default App; diff --git a/app/src/components/footer/Footer.tsx b/app/src/components/footer/Footer.tsx index daa4741..eb1a430 100644 --- a/app/src/components/footer/Footer.tsx +++ b/app/src/components/footer/Footer.tsx @@ -5,11 +5,11 @@ import { GetLogIcon } from "./getLogIcons"; import { CurserLeftIcon, CurserMiddleIcon, CurserRightIcon } from "../icons/LogIcons"; import ShortcutHelper from "./shortcutHelper"; import useVersionHistoryVisibleStore, { useShortcutStore } from "../../store/builder/store"; -import { usePlayButtonStore } from "../../store/usePlayButtonStore"; -import useModuleStore, { useSubModuleStore } from "../../store/useModuleStore"; -import { useVersionContext } from "../../modules/builder/version/versionContext"; +import { usePlayButtonStore } from "../../store/ui/usePlayButtonStore"; +import useModuleStore, { useSubModuleStore } from "../../store/ui/useModuleStore"; import { mouseActionHelper } from "../../utils/mouseUtils/mouseHelper"; -import { useMouseNoteStore } from "../../store/useUIToggleStore"; +import { useMouseNoteStore } from "../../store/ui/useUIToggleStore"; +import { useSceneContext } from "../../modules/scene/sceneContext"; const Footer: React.FC = () => { const { logs, setIsLogListVisible } = useLogger(); @@ -20,8 +20,8 @@ const Footer: React.FC = () => { const { setVersionHistoryVisible } = useVersionHistoryVisibleStore(); const { isPlaying } = usePlayButtonStore(); const { showShortcuts, setShowShortcuts } = useShortcutStore(); - const { selectedVersionStore } = useVersionContext(); - const { selectedVersion } = selectedVersionStore(); + const { versionStore } = useSceneContext(); + const { selectedVersion } = versionStore(); const { Leftnote, Middlenote, Rightnote } = useMouseNoteStore(); const [isOnline, setIsOnline] = useState(navigator.onLine); diff --git a/app/src/components/heatMapGenerator/baked/bakedHeatMap.tsx b/app/src/components/heatMapGenerator/baked/bakedHeatMap.tsx new file mode 100644 index 0000000..c774943 --- /dev/null +++ b/app/src/components/heatMapGenerator/baked/bakedHeatMap.tsx @@ -0,0 +1,129 @@ +import * as THREE from "three"; +import { useEffect, useMemo, useRef, useCallback } from "react"; +import { useThree } from "@react-three/fiber"; +import { useHeatMapStore } from "../../../store/simulation/useHeatMapStore"; +import * as CONSTANTS from "../../../types/world/worldConstants"; +import { exportHeatmapAsPNG } from "../functions/exportHeatmapAsPNG"; + +// Constants +const RADIUS = 0.0025; +const OPACITY = 0.8; +const GROWTH_RATE = 20.0; + +// 🔹 React Component +const BakedHeatMap = () => { + const { bakedPoints } = useHeatMapStore(); + const materialRef = useRef(null); + const meshRef = useRef(null); + const { gl } = useThree(); + + const height = CONSTANTS.gridConfig.size; + const width = CONSTANTS.gridConfig.size; + + const pointTexture = useMemo(() => { + if (bakedPoints.length === 0) return null; + const data = new Float32Array(bakedPoints.length * 4); + bakedPoints.forEach((p, i) => { + const index = i * 4; + data[index] = (p.points.x + width / 2) / width; + data[index + 1] = (p.points.y + height / 2) / height; + data[index + 2] = 0.3; + data[index + 3] = 0.0; + }); + const texture = new THREE.DataTexture(data, bakedPoints.length, 1, THREE.RGBAFormat, THREE.FloatType); + texture.needsUpdate = true; + return texture; + }, [bakedPoints, width, height]); + + const uniformsRef = useRef({ + u_points: { value: pointTexture }, + u_count: { value: bakedPoints.length }, + u_radius: { value: RADIUS }, + u_opacity: { value: OPACITY }, + u_growthRate: { value: GROWTH_RATE }, + }); + + useEffect(() => { + uniformsRef.current.u_points.value = pointTexture; + uniformsRef.current.u_count.value = bakedPoints.length; + }, [pointTexture, bakedPoints.length]); + + useEffect(() => { + if (meshRef.current) { + exportHeatmapAsPNG({ + bakedPoints, + gl, + width: width, + height: height, + mesh: meshRef.current, + }); + } + }, []); + + return ( + <> + // + // + // = u_count) break; + // float fi = float(i) + 0.5; + // float u = fi / float(u_count); + + // vec4 point = texture2D(u_points, vec2(u, 0.5)); + // vec2 pos = point.rg; + // float strength = point.b; + + // float d = distance(vUv, pos); + // intensity += strength * gauss(d, u_radius); + // } + + // float normalized = clamp(intensity / max(u_growthRate, 0.0001), 0.0, 1.0); + + // vec3 color = vec3(0.0); + // if (normalized < 0.33) { + // color = mix(vec3(0.0, 0.0, 1.0), vec3(0.0, 1.0, 0.0), normalized / 0.33); + // } else if (normalized < 0.66) { + // color = mix(vec3(0.0, 1.0, 0.0), vec3(1.0, 1.0, 0.0), (normalized - 0.33) / 0.33); + // } else { + // color = mix(vec3(1.0, 1.0, 0.0), vec3(1.0, 0.0, 0.0), (normalized - 0.66) / 0.34); + // } + + // gl_FragColor = vec4(color, normalized * u_opacity); + // } + // `} + // /> + // + ); +}; + +export default BakedHeatMap; diff --git a/app/src/components/heatMapGenerator/functions/exportHeatmapAsPNG.ts b/app/src/components/heatMapGenerator/functions/exportHeatmapAsPNG.ts new file mode 100644 index 0000000..1084f10 --- /dev/null +++ b/app/src/components/heatMapGenerator/functions/exportHeatmapAsPNG.ts @@ -0,0 +1,94 @@ +import * as THREE from "three"; + +const RADIUS = 0.0025; +const OPACITY = 0.8; +const GROWTH_RATE = 20.0; + +export function exportHeatmapAsPNG({ bakedPoints, gl, width, height, mesh }: { bakedPoints: any[]; gl: THREE.WebGLRenderer; width: number; height: number; mesh: THREE.Mesh }) { + const createPointTexture = (filteredPoints: typeof bakedPoints) => { + if (filteredPoints.length === 0) return null; + + const data = new Float32Array(filteredPoints.length * 4); + filteredPoints.forEach((p, i) => { + const index = i * 4; + data[index] = (p.points.x + width / 2) / width; + data[index + 1] = (p.points.y + height / 2) / height; + data[index + 2] = 0.3; + data[index + 3] = 0.0; + }); + + const texture = new THREE.DataTexture(data, filteredPoints.length, 1, THREE.RGBAFormat, THREE.FloatType); + texture.needsUpdate = true; + return texture; + }; + + const downloadImage = (base64: string, filename: string) => { + const link = document.createElement("a"); + link.href = base64; + link.download = filename; + document.body.appendChild(link); + link.click(); + document.body.removeChild(link); + }; + + const renderHeatmapToImage = (type: string) => { + const filteredPoints = bakedPoints.filter((p) => p.type === type); + if (filteredPoints.length === 0) return null; + + const pointTexture = createPointTexture(filteredPoints); + if (!pointTexture) return null; + + const uniforms = { + u_points: { value: pointTexture }, + u_count: { value: filteredPoints.length }, + u_radius: { value: RADIUS }, + u_opacity: { value: OPACITY }, + u_growthRate: { value: GROWTH_RATE }, + }; + + const exportCamera = new THREE.OrthographicCamera(width / -2, width / 2, height / 2, height / -2, 0.1, 10); + exportCamera.position.set(0, 1, 0); + exportCamera.lookAt(0, 0, 0); + + const renderTarget = new THREE.WebGLRenderTarget(1024, 1024, { + format: THREE.RGBAFormat, + type: THREE.UnsignedByteType, + }); + + const tempScene = new THREE.Scene(); + tempScene.add(mesh); + + gl.setRenderTarget(renderTarget); + gl.render(tempScene, exportCamera); + gl.setRenderTarget(null); + + const pixels = new Uint8Array(1024 * 1024 * 4); + gl.readRenderTargetPixels(renderTarget, 0, 0, 1024, 1024, pixels); + + const canvas = document.createElement("canvas"); + canvas.width = 1024; + canvas.height = 1024; + const ctx = canvas.getContext("2d"); + + if (ctx) { + const imageData = ctx.createImageData(1024, 1024); + imageData.data.set(pixels); + ctx.putImageData(imageData, 0, 0); + return canvas.toDataURL("image/png"); + } + + return null; + }; + + const types = ["human", "vehicle"]; + const result = types.map((type) => { + const image = renderHeatmapToImage(type); + if (image) { + downloadImage(image, `${type}-heatmap.png`); + } + return { type, image }; + }); + + console.log("Exported Heatmaps:", result); + return result; +} diff --git a/app/src/components/heatMapGenerator/heatMap.tsx b/app/src/components/heatMapGenerator/heatMap.tsx new file mode 100644 index 0000000..bda354a --- /dev/null +++ b/app/src/components/heatMapGenerator/heatMap.tsx @@ -0,0 +1,22 @@ +import RealTimeHeatMap from "./realTime/realTimeHeatMap"; +import BakedHeatMap from "./baked/bakedHeatMap"; +import { useEffect } from "react"; +import { useHeatMapStore } from "../../store/simulation/useHeatMapStore"; + +function HeatMap() { + const { bakedPoints, setBakedPoints } = useHeatMapStore(); + + useEffect(() => { + // console.log("bakedPoints: ", bakedPoints); + }, [bakedPoints]); + + return ( + <> + + + + + ); +} + +export default HeatMap; diff --git a/app/src/components/heatMapGenerator/realTime/realTimeHeatMap.tsx b/app/src/components/heatMapGenerator/realTime/realTimeHeatMap.tsx new file mode 100644 index 0000000..760dcde --- /dev/null +++ b/app/src/components/heatMapGenerator/realTime/realTimeHeatMap.tsx @@ -0,0 +1,248 @@ +import * as THREE from "three"; +import { useEffect, useMemo, useRef, useState } from "react"; +import { useFrame, useThree } from "@react-three/fiber"; +import { useSceneContext } from "../../../modules/scene/sceneContext"; +import * as CONSTANTS from "../../../types/world/worldConstants"; +import { determineExecutionMachineSequences } from "../../../modules/simulation/simulator/functions/determineExecutionMachineSequences"; +import { useAnimationPlaySpeed, usePauseButtonStore, usePlayButtonStore, useResetButtonStore } from "../../../store/ui/usePlayButtonStore"; +import { useHeatMapStore } from "../../../store/simulation/useHeatMapStore"; + +const DECAY_RATE = 0.01; +const GROWTH_TIME_MULTIPLIER = 20; +const RADIUS = 0.005; +const OPACITY = 0.8; +const UPDATE_INTERVAL = 1; + +interface HeatPoint { + x: number; + y: number; + strength: number; + lastUpdated: number; +} + +const RealTimeHeatMap = () => { + const isUsingBBOX = false; + const height = CONSTANTS.gridConfig.size; + const width = CONSTANTS.gridConfig.size; + const debugMode: "solid" | "grayscale" | "normal" = "normal"; + const debugModeMap = { solid: 0, grayscale: 1, normal: 2 } as const; + const { productStore } = useSceneContext(); + const { getProductById, products, selectedProduct } = productStore(); + const { hasHuman, hasVehicle, monitoringHuman, monitoringVehicle, addMonitoringHuman, addMonitoringVehicle, addBakedPoint } = useHeatMapStore(); + const { isPlaying } = usePlayButtonStore(); + const { isReset } = useResetButtonStore(); + const { isPaused } = usePauseButtonStore(); + const { speed } = useAnimationPlaySpeed(); + const { scene } = useThree(); + + const [events, setEvents] = useState([]); + const [points, setPoints] = useState([]); + const materialRef = useRef(null); + + const lastFrameTime = useRef(null); + const lastUpdateTime = useRef(0); + + const uniformsRef = useRef({ + u_points: { value: null as THREE.DataTexture | null }, + u_count: { value: 0 }, + u_radius: { value: RADIUS }, + u_opacity: { value: OPACITY }, + u_debugMode: { value: debugModeMap[debugMode] }, + u_growthRate: { value: GROWTH_TIME_MULTIPLIER }, + }); + + useEffect(() => { + if (isReset || !isPlaying) { + setPoints([]); + lastFrameTime.current = null; + lastUpdateTime.current = 0; + } + }, [isReset, isPlaying]); + + useEffect(() => { + addMonitoringVehicle("26770368-55e8-4d40-87f7-8eacb48dc236"); + addMonitoringHuman("264a51e7-d8b9-4093-95ac-fa7e2dc49cfa"); + }, []); + + useEffect(() => { + const selectedProductData = getProductById(selectedProduct.productUuid); + const newEvents: EventsSchema[] = []; + + if (selectedProductData) { + determineExecutionMachineSequences([selectedProductData]).then((sequences) => { + sequences.forEach((sequence) => { + sequence.forEach((event) => { + if (event.type === "human") { + if (hasHuman(event.modelUuid)) { + newEvents.push(event); + } + } else if (event.type === "vehicle") { + if (hasVehicle(event.modelUuid)) { + newEvents.push(event); + } + } + }); + }); + setEvents(newEvents); + }); + } + }, [selectedProduct, products, monitoringHuman, monitoringVehicle]); + + useFrame((state) => { + if (!scene || !isPlaying || isReset) return; + + const now = state.clock.elapsedTime; + if (isPaused || speed === 0) { + lastFrameTime.current = now; + return; + } + + let delta = 0; + if (lastFrameTime.current !== null) { + delta = now - lastFrameTime.current; + } + lastFrameTime.current = now; + + if (delta <= 0) return; + const updateInterval = UPDATE_INTERVAL / Math.max(speed, 0.1); + + if (now - lastUpdateTime.current < updateInterval) return; + lastUpdateTime.current = now; + const scaledDelta = delta * speed; + let updatedPoints = [...points]; + + events.forEach((event) => { + const model = scene.getObjectByProperty("uuid", event.modelUuid) as THREE.Object3D; + if (!model) return; + + const pos = isUsingBBOX + ? (() => { + const box = new THREE.Box3().setFromObject(model); + const { min, max } = box; + return new THREE.Vector3((min.x + max.x) / 2, 0, (min.z + max.z) / 2); + })() + : model.position; + + addBakedPoint({ + type: event.type, + points: { x: pos.x, y: pos.z }, + }); + + updatedPoints.push({ x: pos.x, y: pos.z, strength: 0.3, lastUpdated: now }); + }); + + updatedPoints = updatedPoints.map((p) => ({ ...p, strength: Math.max(0, p.strength - DECAY_RATE * scaledDelta) })).filter((p) => p.strength > 0.01); + + setPoints(updatedPoints); + }); + + const pointTexture = useMemo(() => { + if (points.length === 0) return null; + const data = new Float32Array(points.length * 4); + points.forEach((p, i) => { + const index = i * 4; + data[index] = (p.x + width / 2) / width; + data[index + 1] = (p.y + height / 2) / height; + data[index + 2] = p.strength; + data[index + 3] = 0.0; + }); + + const texture = new THREE.DataTexture(data, points.length, 1, THREE.RGBAFormat, THREE.FloatType); + texture.needsUpdate = true; + return texture; + }, [points, width, height]); + + useEffect(() => { + uniformsRef.current.u_radius.value = RADIUS; + uniformsRef.current.u_opacity.value = OPACITY; + uniformsRef.current.u_debugMode.value = debugModeMap[debugMode]; + uniformsRef.current.u_growthRate.value = GROWTH_TIME_MULTIPLIER; + }, [RADIUS, OPACITY, debugMode, GROWTH_TIME_MULTIPLIER]); + + useEffect(() => { + uniformsRef.current.u_points.value = pointTexture; + uniformsRef.current.u_count.value = points.length; + }, [pointTexture, points.length]); + + return ( + + + = u_count) break; + float fi = float(i) + 0.5; + float u = fi / float(u_count); + + vec4 point = texture2D(u_points, vec2(u, 0.5)); + vec2 pos = point.rg; + float strength = point.b; + + float d = distance(vUv, pos); + intensity += strength * gauss(d, u_radius); + } + + if (u_debugMode == 1) { + gl_FragColor = vec4(vec3(intensity), 1.0); + return; + } + + // Apply growth rate BEFORE normalization + float adjustedIntensity = intensity * u_growthRate; + + // Normalize intensity between 0-1 + float normalized = clamp(intensity / max(u_growthRate, 0.0001), 0.0, 1.0); + + vec3 color = vec3(0.0); + if (normalized < 0.33) { + color = mix(vec3(0.0, 0.0, 1.0), vec3(0.0, 1.0, 0.0), normalized / 0.33); + } else if (normalized < 0.66) { + color = mix(vec3(0.0, 1.0, 0.0), vec3(1.0, 1.0, 0.0), (normalized - 0.33) / 0.33); + } else { + color = mix(vec3(1.0, 1.0, 0.0), vec3(1.0, 0.0, 0.0), (normalized - 0.66) / 0.34); + } + + gl_FragColor = vec4(color, normalized * u_opacity); + } + + `} + /> + + ); +}; + +export default RealTimeHeatMap; diff --git a/app/src/components/layout/controls/ControlsPlayer.tsx b/app/src/components/layout/controls/ControlsPlayer.tsx index 484cd35..0a8d42b 100644 --- a/app/src/components/layout/controls/ControlsPlayer.tsx +++ b/app/src/components/layout/controls/ControlsPlayer.tsx @@ -1,14 +1,14 @@ import React, { useEffect } from "react"; import useCameraModeStore, { usePlayButtonStore, -} from "../../../store/usePlayButtonStore"; -import useModuleStore from "../../../store/useModuleStore"; +} from "../../../store/ui/usePlayButtonStore"; +import useModuleStore from "../../../store/ui/useModuleStore"; import { PlayIcon } from "../../icons/ShortcutIcons"; import InputToggle from "../../ui/inputs/InputToggle"; import { EyeCloseIcon, WalkIcon } from "../../icons/ExportCommonIcons"; import { ExitIcon } from "../../icons/SimulationIcons"; import { useCamMode } from "../../../store/builder/store"; -import { usePlayerStore } from "../../../store/useUIToggleStore"; +import { usePlayerStore } from "../../../store/ui/useUIToggleStore"; const ControlsPlayer: React.FC = () => { const { setIsPlaying } = usePlayButtonStore(); diff --git a/app/src/components/layout/scenes/ComparisonScene.tsx b/app/src/components/layout/scenes/ComparisonScene.tsx index 38d65cb..00b757d 100644 --- a/app/src/components/layout/scenes/ComparisonScene.tsx +++ b/app/src/components/layout/scenes/ComparisonScene.tsx @@ -1,127 +1,25 @@ -import { useProductContext } from "../../../modules/simulation/products/productContext"; -import RegularDropDown from "../../ui/inputs/RegularDropDown"; -import { useCompareProductDataStore, useLoadingProgress, useSaveVersion } from "../../../store/builder/store"; -import useModuleStore from "../../../store/useModuleStore"; +import { useCompareProductDataStore, useLoadingProgress, useIsComparing } from "../../../store/builder/store"; +import { useComparisonProduct, useMainProduct } from "../../../store/simulation/useSimulationStore"; +import { usePlayButtonStore } from "../../../store/ui/usePlayButtonStore"; +import { useEffect, useState } from "react"; +import { useSceneContext } from "../../../modules/scene/sceneContext"; +import useModuleStore from "../../../store/ui/useModuleStore"; import CompareLayOut from "../../ui/compareVersion/CompareLayOut"; import ComparisonResult from "../../ui/compareVersion/ComparisonResult"; -import { useComparisonProduct, useMainProduct } from "../../../store/simulation/useSimulationStore"; -import { usePlayButtonStore } from "../../../store/usePlayButtonStore"; -import { useEffect, useState } from "react"; -import { useVersionHistoryStore } from "../../../store/builder/useVersionHistoryStore"; -import { useVersionContext } from "../../../modules/builder/version/versionContext"; -import { useSceneContext } from "../../../modules/scene/sceneContext"; -import { useSimulationManager } from "../../../store/rough/useSimulationManagerStore"; -import { useParams } from "react-router-dom"; - -export interface CompareProduct { - productUuid: string; - productName: string; - simulationData: { - roiPercentage: number; - netProfit: number; - productionCapacity: number; - paybackPeriod: number; - machineIdleTime: number; - machineActiveTime: number; - throughputData: number; - simulationTime?: number; - simulationCost?: number; - efficiencyScore?: number; - energyUsage?: number; - }; -} - -type AssetData = { - activeTime: number; - idleTime: number; - type: string; - assetId: string; -}; - -const calculateSimulationData = (assets: AssetData[]) => { - let totalActiveTime = 0; - let totalIdleTime = 0; - let throughput = 0; - let productionCapacity = 0; - let simulationCost = 0; - - // Cost weight per type (example values, adjust as needed) - const costWeight: Record = { - roboticArm: 50, - machine: 100, - human: 30, - transfer: 20, - storageUnit: 10, - }; - const energyUsage = assets.filter((a) => a.type === "human").reduce((sum, a) => sum + a.activeTime * 1, 0); - - assets.forEach((asset) => { - totalActiveTime += asset.activeTime; - totalIdleTime += asset.idleTime; - - if (asset.activeTime > 0) throughput += 1; - - productionCapacity += asset.activeTime; - simulationCost += asset.activeTime * (costWeight[asset.type] || 10); - }); - - const machineActiveTime = assets.filter((a) => a.type === "machine").reduce((acc, a) => acc + a.activeTime, 0); - - const machineIdleTime = assets.filter((a) => a.type === "machine").reduce((acc, a) => acc + a.idleTime, 0); - - const simulationTime = totalActiveTime + totalIdleTime; - - // --- Efficiency Score --- - // Weighted formula: lower cost + lower time => higher score - // Example formula (normalize to 0–100): - const efficiencyScore = Math.max( - 0, - 100 - - (simulationTime / 1000) * 0.5 - // weight 0.5 for time - (simulationCost / 1000) * 0.5 // weight 0.5 for cost - ); - - return { - throughputData: throughput, - machineActiveTime, - machineIdleTime, - productionCapacity, - netProfit: 0, // placeholder - roiPercentage: 0, // placeholder - paybackPeriod: 0, // placeholder - simulationTime, - simulationCost, - efficiencyScore, - energyUsage, - }; -}; - -export const createCompareProduct = (productUuid: string, productName: string, assets: AssetData[]): CompareProduct => ({ - productUuid, - productName, - simulationData: calculateSimulationData(assets), -}); +import RegularDropDown from "../../ui/inputs/RegularDropDown"; function ComparisonScene() { const { isPlaying } = usePlayButtonStore(); - const { productStore } = useSceneContext(); - const { products, getProductById } = productStore(); - const { isVersionSaved } = useSaveVersion(); - + const { productStore, versionStore } = useSceneContext(); + const { versionHistory, selectedVersion, setSelectedVersion } = versionStore(); + const { products, selectedProduct } = productStore(); + const { isComparing } = useIsComparing(); const { activeModule } = useModuleStore(); - const { selectedProductStore } = useProductContext(); - const { selectedProduct } = selectedProductStore(); - const { comparisonProduct, setComparisonProduct } = useComparisonProduct(); const { mainProduct } = useMainProduct(); const { loadingProgress } = useLoadingProgress(); - const { compareProductsData, setCompareProductsData } = useCompareProductDataStore(); + const { compareProductsData } = useCompareProductDataStore(); const [shouldShowComparisonResult, setShouldShowComparisonResult] = useState(false); - const { versionHistory } = useVersionHistoryStore(); - const { selectedVersionStore } = useVersionContext(); - const { selectedVersion, setSelectedVersion } = selectedVersionStore(); - const { simulationRecords } = useSimulationManager(); - const { projectId } = useParams(); const handleSelectVersion = (option: string) => { const version = versionHistory.find((version) => version.versionName === option); @@ -137,88 +35,23 @@ function ComparisonScene() { } }; - // useEffect(() => { - // if (versionHistory.length > 0) { - // setSelectedVersion(versionHistory[0]) - // } - // }, [versionHistory]) - - // useEffect(() => { - // setCompareProductsData([ - // { - // "productUuid": "15193386-ec58-4ec6-8a92-e665a39eebf1", - // "productName": "Product 1", - // "simulationData": { - // "roiPercentage": 273.9428571428571, - // "paybackPeriod": 1.8251981643721318, - // "netProfit": 9588000, - // "productionCapacity": 4508.5, - // "machineIdleTime": 1450, - // "machineActiveTime": 430, - // "throughputData": 180.34 - // } - // }, - // { - // "productUuid": "f614bf50-f61d-41c5-acc0-3783fb4da6b8", - // "productName": "Product 2", - // "simulationData": { - // "roiPercentage": 281.7214285714286, - // "paybackPeriod": 1.7748028701097842, - // "netProfit": 9860250, - // "productionCapacity": 4599.25, - // "machineIdleTime": 1885, - // "machineActiveTime": 646, - // "throughputData": 183.97 - // } - // } - // ]) - // }, []); - - // useEffect(() => { - - // - // - // if (mainProduct && comparisonProduct) { - // // if (mainProduct && comparisonProduct && compareProductsData.length > 1) { - // // - // const hasMain = compareProductsData.some(val => val.productUuid === mainProduct.productUuid); - // const hasComparison = compareProductsData.some(val => val.productUuid === comparisonProduct.productUuid); - // - // - // if (hasMain && hasComparison) { - // setShouldShowComparisonResult(true); - // } else { - // setShouldShowComparisonResult(false); - // } - // } - // }, [compareProductsData, mainProduct, comparisonProduct]); - useEffect(() => { - const selectedProductData = getProductById(selectedProduct.productUuid); - if (mainProduct && comparisonProduct && selectedVersion) { - const product1 = useSimulationManager.getState().getProductById(projectId, selectedVersion?.versionId, mainProduct.productUuid); - - const product2 = useSimulationManager.getState().getProductById(projectId, selectedVersion?.versionId, comparisonProduct.productUuid); - - const compareProduct1 = createCompareProduct(product1?.productId ?? "", mainProduct.productName, product1?.simulateData || []); - const compareProduct2 = createCompareProduct(product2?.productId ?? "", comparisonProduct.productName, product2?.simulateData || []); - - const comparedArray = [compareProduct1, compareProduct2]; - - if (product1 == undefined || product2 === undefined) { - setShouldShowComparisonResult(false); - } else if (comparedArray.length === 2) { - setCompareProductsData(comparedArray); + if (mainProduct && comparisonProduct && compareProductsData.length > 1) { + const hasMain = compareProductsData.some((val) => val.productUuid === mainProduct.productUuid); + const hasComparison = compareProductsData.some((val) => val.productUuid === comparisonProduct.productUuid); + if (hasMain && hasComparison && mainProduct.productUuid !== comparisonProduct.productUuid) { setShouldShowComparisonResult(true); + } else { + setShouldShowComparisonResult(false); } } else { setShouldShowComparisonResult(false); } - }, [mainProduct, comparisonProduct, simulationRecords]); + }, [compareProductsData, mainProduct, comparisonProduct]); return ( <> - {isVersionSaved && activeModule === "simulation" && selectedProduct && ( + {isComparing && activeModule === "simulation" && selectedProduct && ( <> {selectedVersion && !isPlaying && (
@@ -238,7 +71,8 @@ function ComparisonScene() {
)} - {shouldShowComparisonResult && !loadingProgress && compareProductsData && } + + {shouldShowComparisonResult && !loadingProgress && } )} diff --git a/app/src/components/layout/scenes/ComparisonSceneProvider.tsx b/app/src/components/layout/scenes/ComparisonSceneProvider.tsx deleted file mode 100644 index 46749b7..0000000 --- a/app/src/components/layout/scenes/ComparisonSceneProvider.tsx +++ /dev/null @@ -1,21 +0,0 @@ -import { useEffect } from 'react'; -import { ProductProvider } from '../../../modules/simulation/products/productContext' -import ComparisonScene from './ComparisonScene'; -import { useSceneContext } from '../../../modules/scene/sceneContext'; - -function ComparisonSceneProvider() { - const { assetStore } = useSceneContext(); - const { clearAssets } = assetStore(); - - useEffect(() => { - clearAssets(); - }, []) - - return ( - - - - ) -} - -export default ComparisonSceneProvider \ No newline at end of file diff --git a/app/src/components/layout/scenes/MainScene.tsx b/app/src/components/layout/scenes/MainScene.tsx index 79e1958..82b237f 100644 --- a/app/src/components/layout/scenes/MainScene.tsx +++ b/app/src/components/layout/scenes/MainScene.tsx @@ -1,5 +1,16 @@ import { useEffect } from "react"; -import { useLoadingProgress, useRenameModeStore, useSaveVersion, useSelectedComment, useSocketStore, useWidgetSubOption } from "../../../store/builder/store"; +import { useParams } from "react-router-dom"; +import { useLoadingProgress, useRenameModeStore, useIsComparing, useSelectedComment, useSocketStore, useWidgetSubOption } from "../../../store/builder/store"; +import useModuleStore, { useThreeDStore } from "../../../store/ui/useModuleStore"; +import { usePlayButtonStore } from "../../../store/ui/usePlayButtonStore"; +import { useSelectedZoneStore } from "../../../store/visualization/useZoneStore"; +import { useFloatingWidget } from "../../../store/visualization/useDroppedObjectsStore"; +import { useSelectedUserStore } from "../../../store/collaboration/useCollabStore"; +import { createHandleDrop } from "../../../modules/visualization/functions/handleUiDrop"; +import { useComparisonProduct, useMainProduct } from "../../../store/simulation/useSimulationStore"; +import { useSceneContext } from "../../../modules/scene/sceneContext"; +import { useBuilderStore } from "../../../store/builder/useBuilderStore"; +import useRestStates from "../../../hooks/useResetStates"; import KeyPressListener from "../../../utils/shortcutkeys/handleShortcutKeys"; import LoadingPage from "../../templates/LoadingPage"; import ModuleToggle from "../../ui/ModuleToggle"; @@ -17,29 +28,15 @@ import VersionSaved from "../sidebarRight/versionHisory/VersionSaved"; import Footer from "../../footer/Footer"; import ThreadChat from "../../ui/collaboration/ThreadChat"; import Scene from "../../../modules/scene/scene"; -import useModuleStore, { useThreeDStore } from "../../../store/useModuleStore"; -import { usePlayButtonStore } from "../../../store/usePlayButtonStore"; -import { useSelectedZoneStore } from "../../../store/visualization/useZoneStore"; -import { useFloatingWidget } from "../../../store/visualization/useDroppedObjectsStore"; -import { useSelectedUserStore } from "../../../store/collaboration/useCollabStore"; -import { createHandleDrop } from "../../../modules/visualization/functions/handleUiDrop"; -import { useComparisonProduct, useMainProduct } from "../../../store/simulation/useSimulationStore"; -import { useProductContext } from "../../../modules/simulation/products/productContext"; -import { setAssetsApi } from "../../../services/factoryBuilder/asset/floorAsset/setAssetsApi"; -import { useParams } from "react-router-dom"; -import { useSceneContext } from "../../../modules/scene/sceneContext"; -import { useVersionHistoryStore } from "../../../store/builder/useVersionHistoryStore"; -import { useVersionContext } from "../../../modules/builder/version/versionContext"; -import { useBuilderStore } from "../../../store/builder/useBuilderStore"; -import { recentlyViewed } from "../../../services/dashboard/recentlyViewed"; + import { getUserData } from "../../../functions/getUserData"; -import useRestStates from "../../../hooks/useResetStates"; +import { recentlyViewed } from "../../../services/dashboard/recentlyViewed"; +import { setAssetsApi } from "../../../services/factoryBuilder/asset/floorAsset/setAssetsApi"; +import { getVersionHistoryApi } from "../../../services/factoryBuilder/versionControl/getVersionHistoryApi"; function MainScene() { const { setMainProduct } = useMainProduct(); - const { selectedProductStore } = useProductContext(); - const { selectedProduct } = selectedProductStore(); - const { isVersionSaved, setIsVersionSaved } = useSaveVersion(); + const { isComparing, setIsComparing } = useIsComparing(); const { activeModule } = useModuleStore(); const { selectedUser } = useSelectedUserStore(); const { loadingProgress } = useLoadingProgress(); @@ -51,15 +48,13 @@ function MainScene() { const { setFloatingWidget } = useFloatingWidget(); const { clearComparisonProduct } = useComparisonProduct(); const { selectedFloorAsset, setSelectedFloorAsset } = useBuilderStore(); - const { assetStore, productStore } = useSceneContext(); - const { products } = productStore(); + const { assetStore, productStore, versionStore } = useSceneContext(); + const { products, selectedProduct } = productStore(); + const { versionHistory, setVersions, selectedVersion, setSelectedVersion } = versionStore(); const { setName, selectedAssets, setSelectedAssets } = assetStore(); const { projectId } = useParams(); const { organization, userId } = getUserData(); const { isRenameMode, setIsRenameMode } = useRenameModeStore(); - const { versionHistory } = useVersionHistoryStore(); - const { selectedVersionStore } = useVersionContext(); - const { selectedVersion, setSelectedVersion } = selectedVersionStore(); const { selectedComment, commentPositionState } = useSelectedComment(); const { resetStates } = useRestStates(); @@ -72,9 +67,33 @@ function MainScene() { useEffect(() => { if (activeModule !== "simulation") { clearComparisonProduct(); - setIsVersionSaved(false); + setIsComparing(false); } - }, [activeModule, clearComparisonProduct, setIsVersionSaved]); + }, [activeModule, clearComparisonProduct, setIsComparing]); + + useEffect(() => { + if (!projectId) return; + + getVersionHistoryApi(projectId) + .then((data) => { + const versions: VersionHistory = []; + data.versions.forEach((version: any) => { + versions.push({ + version: version.version, + versionId: version.versionId, + versionName: version.versionName, + versionDescription: version.description, + timeStamp: version.createdAt, + createdBy: version.createdBy.userName, + }); + }); + setVersions(versions); + }) + .catch(() => { + console.error("Error fetching version history"); + }); + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [projectId]); useEffect(() => { if (versionHistory.length > 0 && organization && userId) { @@ -143,14 +162,14 @@ function MainScene() { {loadingProgress > 0 && } {!isPlaying && ( <> - {toggleThreeD && !isVersionSaved && } + {toggleThreeD && !isComparing && } )} {activeModule === "market" && } - {activeModule !== "market" && !isPlaying && !isVersionSaved && } + {activeModule !== "market" && !isPlaying && !isComparing && } {isPlaying && activeModule === "simulation" && loadingProgress === 0 && } {isPlaying && activeModule !== "simulation" && } @@ -185,7 +204,7 @@ function MainScene() { - {selectedProduct && selectedVersion && isVersionSaved && !isPlaying && activeModule === "simulation" && ( + {selectedProduct && selectedVersion && isComparing && !isPlaying && activeModule === "simulation" && (
{ - clearAssets(); - }, []) - - return ( - - - - ) -} - -export default MainSceneProvider \ No newline at end of file diff --git a/app/src/components/layout/sidebarLeft/Header.tsx b/app/src/components/layout/sidebarLeft/Header.tsx index edcd2e8..5180240 100644 --- a/app/src/components/layout/sidebarLeft/Header.tsx +++ b/app/src/components/layout/sidebarLeft/Header.tsx @@ -2,8 +2,8 @@ import React from "react"; import { ToggleSidebarIcon } from "../../icons/HeaderIcons"; import { LogoIcon } from "../../icons/Logo"; import FileMenu from "../../ui/FileMenu"; -import { useToggleStore } from "../../../store/useUIToggleStore"; -import useModuleStore from "../../../store/useModuleStore"; +import { useToggleStore } from "../../../store/ui/useUIToggleStore"; +import useModuleStore from "../../../store/ui/useModuleStore"; import { useNavigate } from "react-router-dom"; import useRestStates from "../../../hooks/useResetStates"; diff --git a/app/src/components/layout/sidebarLeft/SideBarLeft.tsx b/app/src/components/layout/sidebarLeft/SideBarLeft.tsx index ad26627..f50be07 100644 --- a/app/src/components/layout/sidebarLeft/SideBarLeft.tsx +++ b/app/src/components/layout/sidebarLeft/SideBarLeft.tsx @@ -2,13 +2,13 @@ import React, { useEffect, useState } from "react"; import ToggleHeader from "../../ui/inputs/ToggleHeader"; import Outline from "./Outline"; import Header from "./Header"; -import { useToggleStore } from "../../../store/useUIToggleStore"; +import { useToggleStore } from "../../../store/ui/useUIToggleStore"; import Assets from "./assetList/Assets"; -import useModuleStore from "../../../store/useModuleStore"; +import useModuleStore from "../../../store/ui/useModuleStore"; import Widgets from "./visualization/widgets/Widgets"; import Templates from "../../../modules/visualization/template/Templates"; import Search from "../../ui/inputs/Search"; -import { useSaveVersion } from "../../../store/builder/store"; +import { useIsComparing } from "../../../store/builder/store"; const SideBarLeft: React.FC = () => { const [activeOption, setActiveOption] = useState("Widgets"); @@ -16,7 +16,7 @@ const SideBarLeft: React.FC = () => { const { toggleUILeft } = useToggleStore(); const { activeModule } = useModuleStore(); - const { isVersionSaved } = useSaveVersion(); + const { isComparing } = useIsComparing(); // Reset activeOption whenever activeModule changes useEffect(() => { @@ -35,7 +35,7 @@ const SideBarLeft: React.FC = () => { return (
@@ -74,7 +74,7 @@ const SideBarLeft: React.FC = () => { } else { return ( <> - {!isVersionSaved && ( + {!isComparing && ( <> { diff --git a/app/src/components/layout/sidebarRight/SideBarRight.tsx b/app/src/components/layout/sidebarRight/SideBarRight.tsx index 2d88241..ef9f1a2 100644 --- a/app/src/components/layout/sidebarRight/SideBarRight.tsx +++ b/app/src/components/layout/sidebarRight/SideBarRight.tsx @@ -1,12 +1,12 @@ import React, { useEffect, useState } from "react"; import Header from "./Header"; -import useModuleStore, { useSubModuleStore } from "../../../store/useModuleStore"; +import useModuleStore, { useSubModuleStore } from "../../../store/ui/useModuleStore"; import { AnalysisIcon, FilePackageIcon, MechanicsIcon, PropertiesIcon, SimulationIcon, } from "../../icons/SimulationIcons"; -import { useToggleStore } from "../../../store/useUIToggleStore"; +import { useToggleStore } from "../../../store/ui/useUIToggleStore"; import Visualization from "./visualization/Visualization"; import Analysis from "./analysis/Analysis"; import Simulations from "./simulation/Simulations"; -import useVersionHistoryVisibleStore, { useSaveVersion, useToolMode } from "../../../store/builder/store"; +import useVersionHistoryVisibleStore, { useIsComparing, useToolMode } from "../../../store/builder/store"; import { useSelectedEventData, useSelectedEventSphere, } from "../../../store/simulation/useSimulationStore"; import { useBuilderStore } from "../../../store/builder/useBuilderStore"; import GlobalProperties from "./properties/GlobalProperties"; @@ -52,7 +52,7 @@ const SideBarRight: React.FC = () => { const { selectedEventData } = useSelectedEventData(); const { selectedEventSphere } = useSelectedEventSphere(); const { viewVersionHistory, setVersionHistoryVisible } = useVersionHistoryVisibleStore(); - const { isVersionSaved } = useSaveVersion(); + const { isComparing } = useIsComparing(); const [displayComponent, setDisplayComponent] = useState("none"); @@ -80,7 +80,7 @@ const SideBarRight: React.FC = () => { return; } - if (!isVersionSaved && activeModule === "simulation") { + if (!isComparing && activeModule === "simulation") { if (subModule === "simulations") { setDisplayComponent("simulations"); return; @@ -155,7 +155,7 @@ const SideBarRight: React.FC = () => { } setDisplayComponent("none"); - }, [viewVersionHistory, activeModule, subModule, isVersionSaved, selectedFloorAsset, selectedWall, selectedFloor, selectedAisle, toolMode, selectedDecal]); + }, [viewVersionHistory, activeModule, subModule, isComparing, selectedFloorAsset, selectedWall, selectedFloor, selectedAisle, toolMode, selectedDecal]); const renderComponent = () => { switch (displayComponent) { @@ -197,11 +197,11 @@ const SideBarRight: React.FC = () => { }; return ( -
e.stopPropagation()}> +
e.stopPropagation()}>
{toggleUIRight && ( <> - {(!isVersionSaved || activeModule !== "simulation") && ( + {(!isComparing || activeModule !== "simulation") && (
{activeModule !== "simulation" && ( <> diff --git a/app/src/components/layout/sidebarRight/properties/SelectedAisleProperties.tsx b/app/src/components/layout/sidebarRight/properties/SelectedAisleProperties.tsx index e4e993f..40da752 100644 --- a/app/src/components/layout/sidebarRight/properties/SelectedAisleProperties.tsx +++ b/app/src/components/layout/sidebarRight/properties/SelectedAisleProperties.tsx @@ -15,7 +15,6 @@ import Solid from "../../../../assets/image/aisleTypes/Solid.png"; import InputToggle from "../../../ui/inputs/InputToggle"; import { useBuilderStore } from "../../../../store/builder/useBuilderStore"; import { useSceneContext } from "../../../../modules/scene/sceneContext"; -import { useVersionContext } from "../../../../modules/builder/version/versionContext"; import { useSocketStore } from "../../../../store/builder/store"; import { getUserData } from "../../../../functions/getUserData"; import { aisleTextureList } from "./AisleProperties"; @@ -25,10 +24,9 @@ import { upsertAisleApi } from "../../../../services/factoryBuilder/aisle/upsert const SelectedAisleProperties: React.FC = () => { const [collapsePresets, setCollapsePresets] = useState(false); const [collapseTexture, setCollapseTexture] = useState(true); - const { aisleStore } = useSceneContext(); + const { aisleStore, versionStore } = useSceneContext(); const { getAisleById, updateAisle, setDashedAisleProperties, setDottedAisleProperties, setArrowsAisleProperties, setArcAisleWidth, setColor } = aisleStore(); - const { selectedVersionStore } = useVersionContext(); - const { selectedVersion } = selectedVersionStore(); + const { selectedVersion } = versionStore(); const { socket } = useSocketStore(); const { userId, organization } = getUserData(); const { projectId } = useParams(); diff --git a/app/src/components/layout/sidebarRight/properties/SelectedDecalProperties.tsx b/app/src/components/layout/sidebarRight/properties/SelectedDecalProperties.tsx index 196b793..1e2d3f2 100644 --- a/app/src/components/layout/sidebarRight/properties/SelectedDecalProperties.tsx +++ b/app/src/components/layout/sidebarRight/properties/SelectedDecalProperties.tsx @@ -1,5 +1,4 @@ import { useParams } from "react-router-dom"; -import { useVersionContext } from "../../../../modules/builder/version/versionContext"; import { useSceneContext } from "../../../../modules/scene/sceneContext"; import { useBuilderStore } from "../../../../store/builder/useBuilderStore"; import { LayeringBottomIcon, LayeringTopIcon } from "../../../icons/ExportCommonIcons"; @@ -12,12 +11,11 @@ import { upsertFloorApi } from "../../../../services/factoryBuilder/floor/upsert const SelectedDecalProperties = () => { const { selectedDecal, setSelectedDecal } = useBuilderStore(); - const { wallStore, floorStore } = useSceneContext(); + const { wallStore, floorStore, versionStore } = useSceneContext(); const { updateDecal: updateDecalInWall } = wallStore(); const { updateDecal: updateDecalInFloor } = floorStore(); const { userId, organization } = getUserData(); - const { selectedVersionStore } = useVersionContext(); - const { selectedVersion } = selectedVersionStore(); + const { selectedVersion } = versionStore(); const { projectId } = useParams(); const { socket } = useSocketStore(); diff --git a/app/src/components/layout/sidebarRight/properties/SelectedFloorProperties.tsx b/app/src/components/layout/sidebarRight/properties/SelectedFloorProperties.tsx index bcb51a1..93432ff 100644 --- a/app/src/components/layout/sidebarRight/properties/SelectedFloorProperties.tsx +++ b/app/src/components/layout/sidebarRight/properties/SelectedFloorProperties.tsx @@ -4,7 +4,6 @@ import InputToggle from "../../../ui/inputs/InputToggle"; import { useBuilderStore } from "../../../../store/builder/useBuilderStore"; import { useSceneContext } from "../../../../modules/scene/sceneContext"; -import { useVersionContext } from "../../../../modules/builder/version/versionContext"; import { useParams } from "react-router-dom"; import { getUserData } from "../../../../functions/getUserData"; import { useSocketStore } from "../../../../store/builder/store"; @@ -17,9 +16,8 @@ const SelectedFloorProperties = () => { const [isBeveled, setIsBeveled] = useState(false); const [bevelStrength, setBevelStrength] = useState(""); const { selectedFloor } = useBuilderStore(); - const { floorStore } = useSceneContext(); - const { selectedVersionStore } = useVersionContext(); - const { selectedVersion } = selectedVersionStore(); + const { floorStore, versionStore } = useSceneContext(); + const { selectedVersion } = versionStore(); const { socket } = useSocketStore(); const { userId, organization } = getUserData(); const { projectId } = useParams(); diff --git a/app/src/components/layout/sidebarRight/properties/SelectedWallProperties.tsx b/app/src/components/layout/sidebarRight/properties/SelectedWallProperties.tsx index c26265a..cd8c7c1 100644 --- a/app/src/components/layout/sidebarRight/properties/SelectedWallProperties.tsx +++ b/app/src/components/layout/sidebarRight/properties/SelectedWallProperties.tsx @@ -6,7 +6,6 @@ import wallTexture1 from '../../../../assets/textures/floor/factory wall texture import { useBuilderStore } from "../../../../store/builder/useBuilderStore"; import { useSceneContext } from "../../../../modules/scene/sceneContext"; -import { useVersionContext } from "../../../../modules/builder/version/versionContext"; import { useParams } from "react-router-dom"; import { getUserData } from "../../../../functions/getUserData"; import { useSocketStore } from "../../../../store/builder/store"; @@ -17,9 +16,8 @@ const SelectedWallProperties = () => { const [height, setHeight] = useState(""); const [thickness, setThickness] = useState(""); const { selectedWall } = useBuilderStore(); - const { wallStore } = useSceneContext(); - const { selectedVersionStore } = useVersionContext(); - const { selectedVersion } = selectedVersionStore(); + const { wallStore, versionStore } = useSceneContext(); + const { selectedVersion } = versionStore(); const { socket } = useSocketStore(); const { userId, organization } = getUserData(); const { projectId } = useParams(); diff --git a/app/src/components/layout/sidebarRight/properties/ZoneProperties.tsx b/app/src/components/layout/sidebarRight/properties/ZoneProperties.tsx index 32bec03..6a0f2e1 100644 --- a/app/src/components/layout/sidebarRight/properties/ZoneProperties.tsx +++ b/app/src/components/layout/sidebarRight/properties/ZoneProperties.tsx @@ -10,7 +10,6 @@ import { import { zoneCameraUpdate } from "../../../../services/visulization/zone/zoneCameraUpdation"; import { useParams } from "react-router-dom"; import { getUserData } from "../../../../functions/getUserData"; -import { useVersionContext } from "../../../../modules/builder/version/versionContext"; import { useSceneContext } from "../../../../modules/scene/sceneContext"; const ZoneProperties: React.FC = () => { @@ -18,13 +17,12 @@ const ZoneProperties: React.FC = () => { const { selectedZone, setSelectedZone } = useSelectedZoneStore(); const { zonePosition, setZonePosition } = usezonePosition(); const { zoneTarget, setZoneTarget } = usezoneTarget(); - const { zoneStore } = useSceneContext(); + const { zoneStore, versionStore } = useSceneContext(); + const { selectedVersion } = versionStore(); const { zones, setZoneName } = zoneStore() const { projectId } = useParams(); const { organization } = getUserData(); - const { selectedVersionStore } = useVersionContext(); - const { selectedVersion } = selectedVersionStore(); useEffect(() => { setZonePosition(selectedZone.zoneViewPortPosition); @@ -85,7 +83,7 @@ const ZoneProperties: React.FC = () => { setSelectedZone((prev) => ({ ...prev, [key]: newValue })); } const checkZoneNameDuplicate = (name: string) => { - + return zones.some( (zone: any) => zone.zoneName?.trim().toLowerCase() === name?.trim().toLowerCase() && diff --git a/app/src/components/layout/sidebarRight/properties/eventProperties/EventProperties.tsx b/app/src/components/layout/sidebarRight/properties/eventProperties/EventProperties.tsx index a6332db..402c2a0 100644 --- a/app/src/components/layout/sidebarRight/properties/eventProperties/EventProperties.tsx +++ b/app/src/components/layout/sidebarRight/properties/eventProperties/EventProperties.tsx @@ -1,8 +1,5 @@ import React, { useEffect, useState } from "react"; -import { - useSelectedEventData, - useSelectedEventSphere, -} from "../../../../../store/simulation/useSimulationStore"; +import { useSelectedEventData, useSelectedEventSphere } from "../../../../../store/simulation/useSimulationStore"; import ConveyorMechanics from "./mechanics/conveyorMechanics"; import VehicleMechanics from "./mechanics/vehicleMechanics"; import RoboticArmMechanics from "./mechanics/roboticArmMechanics"; @@ -11,135 +8,117 @@ import StorageMechanics from "./mechanics/storageMechanics"; import HumanMechanics from "./mechanics/humanMechanics"; import { AddIcon } from "../../../../icons/ExportCommonIcons"; import { handleAddEventToProduct } from "../../../../../modules/simulation/events/points/functions/handleAddEventToProduct"; -import { useProductContext } from "../../../../../modules/simulation/products/productContext"; import { useParams } from "react-router-dom"; -import { useVersionContext } from "../../../../../modules/builder/version/versionContext"; import { useSceneContext } from "../../../../../modules/scene/sceneContext"; import CraneMechanics from "./mechanics/craneMechanics"; const EventProperties: React.FC = () => { - const { selectedEventData } = useSelectedEventData(); - const { selectedProductStore } = useProductContext(); - const { eventStore, productStore } = useSceneContext(); - const { selectedProduct } = selectedProductStore(); - const [currentEventData, setCurrentEventData] = useState(null); - const [assetType, setAssetType] = useState(null); - const { products, addEvent, getEventByModelUuid } = productStore(); - const { selectedEventSphere } = useSelectedEventSphere(); - const { selectedVersionStore } = useVersionContext(); - const { selectedVersion } = selectedVersionStore(); - const { projectId } = useParams(); - useEffect(() => { - const event = getCurrentEventData(); - setCurrentEventData(event); + const { selectedEventData } = useSelectedEventData(); + const { eventStore, productStore, versionStore } = useSceneContext(); + const [currentEventData, setCurrentEventData] = useState(null); + const [assetType, setAssetType] = useState(null); + const { products, addEvent, getEventByModelUuid, selectedProduct } = productStore(); + const { selectedEventSphere } = useSelectedEventSphere(); + const { selectedVersion } = versionStore(); + const { projectId } = useParams(); - const type = determineAssetType(event); - setAssetType(type); - // eslint-disable-next-line react-hooks/exhaustive-deps - }, [selectedEventData, selectedProduct]); + useEffect(() => { + const event = getCurrentEventData(); + setCurrentEventData(event); + + const type = determineAssetType(event); + setAssetType(type); + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [selectedEventData, selectedProduct]); + + const getCurrentEventData = () => { + if (!selectedEventData?.data || !selectedProduct) return null; + return getEventByModelUuid(selectedProduct.productUuid, selectedEventData.data.modelUuid) ?? null; + }; + + const determineAssetType = (event: EventsSchema | null) => { + if (!event) return null; + + switch (event.type) { + case "transfer": + return "conveyor"; + case "vehicle": + return "vehicle"; + case "roboticArm": + return "roboticArm"; + case "machine": + return "machine"; + case "storageUnit": + return "storageUnit"; + case "human": + return "human"; + case "crane": + return "crane"; + default: + return null; + } + }; - const getCurrentEventData = () => { - if (!selectedEventData?.data || !selectedProduct) return null; return ( - getEventByModelUuid( - selectedProduct.productUuid, - selectedEventData.data.modelUuid - ) ?? null +
+ {currentEventData && ( + <> +
+
{selectedEventData?.data.modelName}
+
+ {assetType === "conveyor" && } + {assetType === "vehicle" && } + {assetType === "roboticArm" && } + {assetType === "machine" && } + {assetType === "storageUnit" && } + {assetType === "human" && } + {assetType === "crane" && } + + )} + {!currentEventData && selectedEventSphere && ( +
+

+ Oops! It looks like this object doesn't have an event assigned yet. To continue, please link it to one of the products below. +

+ +
+

+ Here are some products you can add it to: +

+
+ {products.map((product) => ( + + ))} +
+
+
+ )} + {!selectedEventSphere && ( +
+

+ Oops! It looks like you haven't selected an event point yet. Please select an event to view its properties. +

+
+ )} +
); - }; - - const determineAssetType = (event: EventsSchema | null) => { - if (!event) return null; - - switch (event.type) { - case "transfer": - return "conveyor"; - case "vehicle": - return "vehicle"; - case "roboticArm": - return "roboticArm"; - case "machine": - return "machine"; - case "storageUnit": - return "storageUnit"; - case "human": - return "human"; - case "crane": - return "crane"; - default: - return null; - } - }; - - return ( -
- {currentEventData && ( - <> -
-
- {selectedEventData?.data.modelName} -
-
- {assetType === "conveyor" && } - {assetType === "vehicle" && } - {assetType === "roboticArm" && } - {assetType === "machine" && } - {assetType === "storageUnit" && } - {assetType === "human" && } - {assetType === "crane" && } - - )} - {!currentEventData && selectedEventSphere && ( -
-

- Oops! It looks like this object doesn't have an - event assigned yet. To continue, please link it to one of the - products below. -

- -
-

- Here are some products you can add it to: -

-
- {products.map((product) => ( - - ))} -
-
-
- )} - {!selectedEventSphere && ( -
-

- Oops! It looks like you haven't selected an event - point yet. Please select an event to view its properties. -

-
- )} -
- ); }; export default EventProperties; diff --git a/app/src/components/layout/sidebarRight/properties/eventProperties/components/ActionsList.tsx b/app/src/components/layout/sidebarRight/properties/eventProperties/components/ActionsList.tsx index 4656357..f71eb9a 100644 --- a/app/src/components/layout/sidebarRight/properties/eventProperties/components/ActionsList.tsx +++ b/app/src/components/layout/sidebarRight/properties/eventProperties/components/ActionsList.tsx @@ -1,166 +1,108 @@ import React, { useRef } from "react"; -import { - AddIcon, - RemoveIcon, - ResizeHeightIcon, -} from "../../../../../icons/ExportCommonIcons"; +import { AddIcon, RemoveIcon, ResizeHeightIcon } from "../../../../../icons/ExportCommonIcons"; import RenameInput from "../../../../../ui/inputs/RenameInput"; import { handleResize } from "../../../../../../functions/handleResizePannel"; -import { - useSelectedAction, -} from "../../../../../../store/simulation/useSimulationStore"; +import { useSelectedAction } from "../../../../../../store/simulation/useSimulationStore"; import { upsertProductOrEventApi } from "../../../../../../services/simulation/products/UpsertProductOrEventApi"; -import { useProductContext } from "../../../../../../modules/simulation/products/productContext"; import { useParams } from "react-router-dom"; -import { useVersionContext } from "../../../../../../modules/builder/version/versionContext"; import { useSceneContext } from "../../../../../../modules/scene/sceneContext"; interface ActionsListProps { - selectedPointData: any; - multipleAction?: boolean; - handleAddAction?: () => void; - handleDeleteAction?: (actionUuid: string) => void; + selectedPointData: any; + multipleAction?: boolean; + handleAddAction?: () => void; + handleDeleteAction?: (actionUuid: string) => void; } -const ActionsList: React.FC = ({ - selectedPointData, - multipleAction = false, - handleAddAction, - handleDeleteAction, -}) => { - const actionsContainerRef = useRef(null); +const ActionsList: React.FC = ({ selectedPointData, multipleAction = false, handleAddAction, handleDeleteAction }) => { + const actionsContainerRef = useRef(null); - // store + // store - const { productStore } = useSceneContext(); - const { renameAction } = productStore(); - const { selectedProductStore } = useProductContext(); - const { selectedProduct } = selectedProductStore(); - const { selectedAction, setSelectedAction } = useSelectedAction(); - const { selectedVersionStore } = useVersionContext(); - const { selectedVersion } = selectedVersionStore(); - const { projectId } = useParams(); + const { productStore, versionStore } = useSceneContext(); + const { renameAction, selectedProduct } = productStore(); + const { selectedAction, setSelectedAction } = useSelectedAction(); + const { selectedVersion } = versionStore(); + const { projectId } = useParams(); - const handleRenameAction = (newName: string) => { - if (!selectedAction.actionId) return; - const event = renameAction( - selectedProduct.productUuid, - selectedAction.actionId, - newName - ); - setSelectedAction(selectedAction.actionId, newName); - if (event) { - upsertProductOrEventApi({ - productName: selectedProduct.productName, - productUuid: selectedProduct.productUuid, - projectId, - eventDatas: event, - versionId: selectedVersion?.versionId || '', - }); - } - }; + const handleRenameAction = (newName: string) => { + if (!selectedAction.actionId) return; + const event = renameAction(selectedProduct.productUuid, selectedAction.actionId, newName); + setSelectedAction(selectedAction.actionId, newName); + if (event) { + upsertProductOrEventApi({ + productName: selectedProduct.productName, + productUuid: selectedProduct.productUuid, + projectId, + eventDatas: event, + versionId: selectedVersion?.versionId || "", + }); + } + }; - const handleActionSelect = (actionUuid: string, actionName: string) => { - setSelectedAction(actionUuid, actionName); - }; + const handleActionSelect = (actionUuid: string, actionName: string) => { + setSelectedAction(actionUuid, actionName); + }; - return ( -
-
-
-
Actions
+ return ( +
+
+
+
Actions
- -
-
-
- {multipleAction && - selectedPointData?.actions?.map((action: any) => ( -
- - {selectedPointData?.actions?.length > 1 && ( - )}
- ))} - {!multipleAction && selectedPointData?.action && ( -
- -
- )} -
- {multipleAction && ( - - )} +
+
+ {multipleAction && + selectedPointData?.actions?.map((action: any) => ( +
+ + {selectedPointData?.actions?.length > 1 && ( + + )} +
+ ))} + {!multipleAction && selectedPointData?.action && ( +
+ +
+ )} +
+ {multipleAction && ( + + )} +
+
-
-
- ); + ); }; export default ActionsList; diff --git a/app/src/components/layout/sidebarRight/properties/eventProperties/mechanics/conveyorMechanics.tsx b/app/src/components/layout/sidebarRight/properties/eventProperties/mechanics/conveyorMechanics.tsx index 20ce08a..5a492fd 100644 --- a/app/src/components/layout/sidebarRight/properties/eventProperties/mechanics/conveyorMechanics.tsx +++ b/app/src/components/layout/sidebarRight/properties/eventProperties/mechanics/conveyorMechanics.tsx @@ -11,9 +11,7 @@ import Trigger from "../trigger/Trigger"; import { useSelectedAction, useSelectedEventData } from "../../../../../../store/simulation/useSimulationStore"; import ActionsList from "../components/ActionsList"; import { upsertProductOrEventApi } from "../../../../../../services/simulation/products/UpsertProductOrEventApi"; -import { useProductContext } from "../../../../../../modules/simulation/products/productContext"; import { useParams } from "react-router-dom"; -import { useVersionContext } from "../../../../../../modules/builder/version/versionContext"; import { useSceneContext } from "../../../../../../modules/scene/sceneContext"; function ConveyorMechanics() { @@ -27,27 +25,17 @@ function ConveyorMechanics() { const [selectedPointData, setSelectedPointData] = useState(); const { selectedEventData } = useSelectedEventData(); - const { productStore } = useSceneContext(); - const { getPointByUuid, updateEvent, updateAction, getEventByModelUuid } = productStore(); - const { selectedProductStore } = useProductContext(); - const { selectedProduct } = selectedProductStore(); + const { productStore, versionStore } = useSceneContext(); + const { getPointByUuid, updateEvent, updateAction, getEventByModelUuid, selectedProduct } = productStore(); const { setSelectedAction, clearSelectedAction } = useSelectedAction(); + const { selectedVersion } = versionStore(); const { projectId } = useParams(); - const { selectedVersionStore } = useVersionContext(); - const { selectedVersion } = selectedVersionStore(); useEffect(() => { if (selectedEventData) { - const point = getPointByUuid( - selectedProduct.productUuid, - selectedEventData?.data.modelUuid, - selectedEventData?.selectedPoint - ) as ConveyorPointSchema | undefined; + const point = getPointByUuid(selectedProduct.productUuid, selectedEventData?.data.modelUuid, selectedEventData?.selectedPoint) as ConveyorPointSchema | undefined; - const event = getEventByModelUuid( - selectedProduct.productUuid, - selectedEventData?.data.modelUuid - ) as ConveyorEventSchema | undefined; + const event = getEventByModelUuid(selectedProduct.productUuid, selectedEventData?.data.modelUuid) as ConveyorEventSchema | undefined; if (point && "action" in point && event) { setSelectedPointData(point); @@ -65,12 +53,7 @@ function ConveyorMechanics() { } }, [selectedProduct, selectedEventData]); - const updateBackend = ( - productName: string, - productUuid: string, - projectId: string, - eventData: EventsSchema - ) => { + const updateBackend = (productName: string, productUuid: string, projectId: string, eventData: EventsSchema) => { upsertProductOrEventApi({ productName, productUuid, @@ -86,19 +69,10 @@ function ConveyorMechanics() { const numericValue = parseFloat(value); if (isNaN(numericValue)) return; - const event = updateEvent( - selectedProduct.productUuid, - selectedEventData.data.modelUuid, - { speed: numericValue } - ); + const event = updateEvent(selectedProduct.productUuid, selectedEventData.data.modelUuid, { speed: numericValue }); if (event) { - updateBackend( - selectedProduct.productName, - selectedProduct.productUuid, - projectId || '', - event - ); + updateBackend(selectedProduct.productName, selectedProduct.productUuid, projectId || "", event); } setSpeed(value); }; @@ -109,19 +83,10 @@ function ConveyorMechanics() { const validOption = option as "default" | "spawn" | "swap" | "delay" | "despawn"; setActiveOption(validOption); - const event = updateAction( - selectedProduct.productUuid, - selectedPointData.action.actionUuid, - { actionType: validOption } - ); + const event = updateAction(selectedProduct.productUuid, selectedPointData.action.actionUuid, { actionType: validOption }); if (event) { - updateBackend( - selectedProduct.productName, - selectedProduct.productUuid, - projectId || '', - event - ); + updateBackend(selectedProduct.productName, selectedProduct.productUuid, projectId || "", event); } }; @@ -132,19 +97,10 @@ function ConveyorMechanics() { if (isNaN(numericValue)) return; setSpawnCount(value); - const event = updateAction( - selectedProduct.productUuid, - selectedPointData.action.actionUuid, - { spawnCount: numericValue } - ); + const event = updateAction(selectedProduct.productUuid, selectedPointData.action.actionUuid, { spawnCount: numericValue }); if (event) { - updateBackend( - selectedProduct.productName, - selectedProduct.productUuid, - projectId || '', - event - ); + updateBackend(selectedProduct.productName, selectedProduct.productUuid, projectId || "", event); } }; @@ -155,19 +111,10 @@ function ConveyorMechanics() { if (isNaN(numericValue)) return; setSpawnInterval(value); - const event = updateAction( - selectedProduct.productUuid, - selectedPointData.action.actionUuid, - { spawnInterval: numericValue } - ); + const event = updateAction(selectedProduct.productUuid, selectedPointData.action.actionUuid, { spawnInterval: numericValue }); if (event) { - updateBackend( - selectedProduct.productName, - selectedProduct.productUuid, - projectId || '', - event - ); + updateBackend(selectedProduct.productName, selectedProduct.productUuid, projectId || "", event); } }; @@ -175,19 +122,10 @@ function ConveyorMechanics() { if (!selectedPointData) return; setMaterial(selectedMaterial); - const event = updateAction( - selectedProduct.productUuid, - selectedPointData.action.actionUuid, - { material: selectedMaterial } - ); + const event = updateAction(selectedProduct.productUuid, selectedPointData.action.actionUuid, { material: selectedMaterial }); if (event) { - updateBackend( - selectedProduct.productName, - selectedProduct.productUuid, - projectId || '', - event - ); + updateBackend(selectedProduct.productName, selectedProduct.productUuid, projectId || "", event); } }; @@ -198,19 +136,10 @@ function ConveyorMechanics() { if (isNaN(numericValue)) return; setDelay(value); - const event = updateAction( - selectedProduct.productUuid, - selectedPointData.action.actionUuid, - { delay: numericValue } - ); + const event = updateAction(selectedProduct.productUuid, selectedPointData.action.actionUuid, { delay: numericValue }); if (event) { - updateBackend( - selectedProduct.productName, - selectedProduct.productUuid, - projectId || '', - event - ); + updateBackend(selectedProduct.productName, selectedProduct.productUuid, projectId || "", event); } }; @@ -224,17 +153,7 @@ function ConveyorMechanics() {
- { }} - onChange={handleSpeedChange} - /> + {}} onChange={handleSpeedChange} />
@@ -243,60 +162,23 @@ function ConveyorMechanics() {
- +
- + {activeOption === "default" && } - {activeOption === "spawn" && ( - - )} - {activeOption === "swap" && ( - - )} + {activeOption === "spawn" && } + {activeOption === "swap" && } {activeOption === "despawn" && } - {activeOption === "delay" && ( - - )} + {activeOption === "delay" && }
- +
); } -export default ConveyorMechanics; \ No newline at end of file +export default ConveyorMechanics; diff --git a/app/src/components/layout/sidebarRight/properties/eventProperties/mechanics/craneMechanics.tsx b/app/src/components/layout/sidebarRight/properties/eventProperties/mechanics/craneMechanics.tsx index 3df0401..b594256 100644 --- a/app/src/components/layout/sidebarRight/properties/eventProperties/mechanics/craneMechanics.tsx +++ b/app/src/components/layout/sidebarRight/properties/eventProperties/mechanics/craneMechanics.tsx @@ -6,9 +6,7 @@ import Trigger from "../trigger/Trigger"; import { useSelectedEventData, useSelectedAction } from "../../../../../../store/simulation/useSimulationStore"; import ActionsList from "../components/ActionsList"; import { upsertProductOrEventApi } from "../../../../../../services/simulation/products/UpsertProductOrEventApi"; -import { useProductContext } from "../../../../../../modules/simulation/products/productContext"; import { useParams } from "react-router-dom"; -import { useVersionContext } from "../../../../../../modules/builder/version/versionContext"; import { useSceneContext } from "../../../../../../modules/scene/sceneContext"; function CraneMechanics() { @@ -16,22 +14,15 @@ function CraneMechanics() { const [selectedPointData, setSelectedPointData] = useState(); const { selectedEventData } = useSelectedEventData(); - const { productStore } = useSceneContext(); - const { getPointByUuid, addAction, removeAction } = productStore(); - const { selectedProductStore } = useProductContext(); - const { selectedProduct } = selectedProductStore(); + const { productStore, versionStore } = useSceneContext(); + const { getPointByUuid, addAction, removeAction, selectedProduct } = productStore(); const { selectedAction, setSelectedAction, clearSelectedAction } = useSelectedAction(); - const { selectedVersionStore } = useVersionContext(); - const { selectedVersion } = selectedVersionStore(); + const { selectedVersion } = versionStore(); const { projectId } = useParams(); useEffect(() => { if (selectedEventData) { - const point = getPointByUuid( - selectedProduct.productUuid, - selectedEventData.data.modelUuid, - selectedEventData.selectedPoint - ) as CranePointSchema | undefined; + const point = getPointByUuid(selectedProduct.productUuid, selectedEventData.data.modelUuid, selectedEventData.selectedPoint) as CranePointSchema | undefined; if (point?.actions) { setSelectedPointData(point); @@ -47,12 +38,7 @@ function CraneMechanics() { } }, [selectedEventData, selectedProduct]); - const updateBackend = ( - productName: string, - productUuid: string, - projectId: string, - eventData: EventsSchema - ) => { + const updateBackend = (productName: string, productUuid: string, projectId: string, eventData: EventsSchema) => { upsertProductOrEventApi({ productName, productUuid, @@ -73,20 +59,10 @@ function CraneMechanics() { triggers: [] as TriggerSchema[], }; - const event = addAction( - selectedProduct.productUuid, - selectedEventData.data.modelUuid, - selectedEventData.selectedPoint, - newAction - ); + const event = addAction(selectedProduct.productUuid, selectedEventData.data.modelUuid, selectedEventData.selectedPoint, newAction); if (event) { - updateBackend( - selectedProduct.productName, - selectedProduct.productUuid, - projectId || '', - event - ); + updateBackend(selectedProduct.productName, selectedProduct.productUuid, projectId || "", event); } setSelectedPointData({ @@ -99,22 +75,14 @@ function CraneMechanics() { const handleDeleteAction = (actionUuid: string) => { if (!selectedPointData) return; - const event = removeAction( - selectedProduct.productUuid, - actionUuid - ); + const event = removeAction(selectedProduct.productUuid, actionUuid); if (event) { - updateBackend( - selectedProduct.productName, - selectedProduct.productUuid, - projectId || '', - event - ); + updateBackend(selectedProduct.productName, selectedProduct.productUuid, projectId || "", event); } - const index = selectedPointData.actions.findIndex(a => a.actionUuid === actionUuid); - const newActions = selectedPointData.actions.filter(a => a.actionUuid !== actionUuid); + const index = selectedPointData.actions.findIndex((a) => a.actionUuid === actionUuid); + const newActions = selectedPointData.actions.filter((a) => a.actionUuid !== actionUuid); setSelectedPointData({ ...selectedPointData, @@ -136,39 +104,23 @@ function CraneMechanics() { options: ["pickAndDrop"], }; - const currentAction = selectedPointData?.actions.find(a => a.actionUuid === selectedAction.actionId); + const currentAction = selectedPointData?.actions.find((a) => a.actionUuid === selectedAction.actionId); return ( <>
- + {selectedAction.actionId && currentAction && (
- +
- { }} - disabled={true} - /> + {}} disabled={true} />
- +
)} @@ -177,4 +129,4 @@ function CraneMechanics() { ); } -export default CraneMechanics \ No newline at end of file +export default CraneMechanics; diff --git a/app/src/components/layout/sidebarRight/properties/eventProperties/mechanics/humanMechanics.tsx b/app/src/components/layout/sidebarRight/properties/eventProperties/mechanics/humanMechanics.tsx index 99c1a0c..d69f72d 100644 --- a/app/src/components/layout/sidebarRight/properties/eventProperties/mechanics/humanMechanics.tsx +++ b/app/src/components/layout/sidebarRight/properties/eventProperties/mechanics/humanMechanics.tsx @@ -11,8 +11,6 @@ import ManufactureAction from "../actions/ManufactureAction"; import { useSelectedEventData, useSelectedAction } from "../../../../../../store/simulation/useSimulationStore"; import { upsertProductOrEventApi } from "../../../../../../services/simulation/products/UpsertProductOrEventApi"; -import { useProductContext } from "../../../../../../modules/simulation/products/productContext"; -import { useVersionContext } from "../../../../../../modules/builder/version/versionContext"; import { useSceneContext } from "../../../../../../modules/scene/sceneContext"; import { useParams } from "react-router-dom"; @@ -27,34 +25,22 @@ function HumanMechanics() { const [currentAction, setCurrentAction] = useState(); const [selectedPointData, setSelectedPointData] = useState(); const { selectedEventData } = useSelectedEventData(); - const { productStore } = useSceneContext(); - const { getPointByUuid, updateEvent, updateAction, addAction, removeAction, getEventByModelUuid, getActionByUuid } = productStore(); - const { selectedProductStore } = useProductContext(); - const { selectedProduct } = selectedProductStore(); + const { productStore, versionStore } = useSceneContext(); + const { getPointByUuid, updateEvent, updateAction, addAction, removeAction, getEventByModelUuid, getActionByUuid, selectedProduct } = productStore(); const { selectedAction, setSelectedAction, clearSelectedAction } = useSelectedAction(); - const { selectedVersionStore } = useVersionContext(); - const { selectedVersion } = selectedVersionStore(); + const { selectedVersion } = versionStore(); const { projectId } = useParams(); useEffect(() => { if (selectedEventData && selectedEventData.data.type === "human") { - const point = getPointByUuid( - selectedProduct.productUuid, - selectedEventData.data.modelUuid, - selectedEventData.selectedPoint - ) as HumanPointSchema | undefined; + const point = getPointByUuid(selectedProduct.productUuid, selectedEventData.data.modelUuid, selectedEventData.selectedPoint) as HumanPointSchema | undefined; if (point?.actions?.length) { setSelectedPointData(point); const firstAction = point.actions[0]; setSelectedAction(firstAction.actionUuid, firstAction.actionName); setCurrentAction(firstAction); - setSpeed(( - getEventByModelUuid( - selectedProduct.productUuid, - selectedEventData?.data.modelUuid || "" - ) as HumanEventSchema | undefined - )?.speed?.toString() || "1"); + setSpeed((getEventByModelUuid(selectedProduct.productUuid, selectedEventData?.data.modelUuid || "") as HumanEventSchema | undefined)?.speed?.toString() || "1"); setLoadCapacity(firstAction.loadCapacity.toString()); setActiveOption(firstAction.actionType); setLoadCount(firstAction.loadCount || 0); @@ -69,17 +55,13 @@ function HumanMechanics() { useEffect(() => { if (selectedEventData && selectedEventData.data.type === "human") { - const point = getPointByUuid( - selectedProduct.productUuid, - selectedEventData.data.modelUuid, - selectedEventData.selectedPoint - ) as HumanPointSchema | undefined; + const point = getPointByUuid(selectedProduct.productUuid, selectedEventData.data.modelUuid, selectedEventData.selectedPoint) as HumanPointSchema | undefined; - const actionUuid = selectedAction.actionId || point?.actions[0].actionUuid || ''; + const actionUuid = selectedAction.actionId || point?.actions[0].actionUuid || ""; const newCurrentAction = getActionByUuid(selectedProduct.productUuid, actionUuid); - if (newCurrentAction && (newCurrentAction.actionType === 'manufacturer' || newCurrentAction?.actionType === 'worker' || newCurrentAction?.actionType === "operator")) { + if (newCurrentAction && (newCurrentAction.actionType === "manufacturer" || newCurrentAction?.actionType === "worker" || newCurrentAction?.actionType === "operator")) { if (!selectedAction.actionId) { setSelectedAction(newCurrentAction.actionUuid, newCurrentAction.actionName); } @@ -89,7 +71,7 @@ function HumanMechanics() { setLoadCount(newCurrentAction.loadCount || 0); setManufactureCount(newCurrentAction.manufactureCount || 0); - if (newCurrentAction.actionType === 'manufacturer') { + if (newCurrentAction.actionType === "manufacturer") { setProcessTime(newCurrentAction.processTime || 10); setSwappedMaterial(newCurrentAction.swapMaterial || "Default material"); } @@ -100,12 +82,7 @@ function HumanMechanics() { } }, [selectedAction, selectedProduct, selectedEventData]); - const updateBackend = ( - productName: string, - productUuid: string, - projectId: string, - eventData: EventsSchema - ) => { + const updateBackend = (productName: string, productUuid: string, projectId: string, eventData: EventsSchema) => { upsertProductOrEventApi({ productName, productUuid, @@ -119,17 +96,13 @@ function HumanMechanics() { if (!selectedAction.actionId || !currentAction || !selectedPointData) return; const updatedAction = { ...currentAction, actionType: actionType as "worker" | "manufacturer" | "operator" | "assembler" }; - const updatedActions = selectedPointData.actions.map(action => action.actionUuid === updatedAction.actionUuid ? updatedAction : action); + const updatedActions = selectedPointData.actions.map((action) => (action.actionUuid === updatedAction.actionUuid ? updatedAction : action)); const updatedPoint = { ...selectedPointData, actions: updatedActions }; - const event = updateAction( - selectedProduct.productUuid, - selectedAction.actionId, - updatedAction - ); + const event = updateAction(selectedProduct.productUuid, selectedAction.actionId, updatedAction); if (event) { - updateBackend(selectedProduct.productName, selectedProduct.productUuid, projectId || '', event); + updateBackend(selectedProduct.productName, selectedProduct.productUuid, projectId || "", event); } setCurrentAction(updatedAction); @@ -143,17 +116,13 @@ function HumanMechanics() { if (isNaN(numericValue)) return; const updatedEvent = { - speed: numericValue + speed: numericValue, } as HumanEventSchema; - const event = updateEvent( - selectedProduct.productUuid, - selectedEventData.data.modelUuid, - updatedEvent - ); + const event = updateEvent(selectedProduct.productUuid, selectedEventData.data.modelUuid, updatedEvent); if (event) { - updateBackend(selectedProduct.productName, selectedProduct.productUuid, projectId || '', event); + updateBackend(selectedProduct.productName, selectedProduct.productUuid, projectId || "", event); } setSpeed(value); @@ -163,17 +132,13 @@ function HumanMechanics() { if (!currentAction || !selectedPointData || !selectedAction.actionId) return; const updatedAction = { ...currentAction, loadCapacity: parseInt(value) }; - const updatedActions = selectedPointData.actions.map(action => action.actionUuid === updatedAction.actionUuid ? updatedAction : action); + const updatedActions = selectedPointData.actions.map((action) => (action.actionUuid === updatedAction.actionUuid ? updatedAction : action)); const updatedPoint = { ...selectedPointData, actions: updatedActions }; - const event = updateAction( - selectedProduct.productUuid, - selectedAction.actionId, - updatedAction - ); + const event = updateAction(selectedProduct.productUuid, selectedAction.actionId, updatedAction); if (event) { - updateBackend(selectedProduct.productName, selectedProduct.productUuid, projectId || '', event); + updateBackend(selectedProduct.productName, selectedProduct.productUuid, projectId || "", event); } setCurrentAction(updatedAction); @@ -185,17 +150,13 @@ function HumanMechanics() { if (!currentAction || !selectedPointData || !selectedAction.actionId) return; const updatedAction = { ...currentAction, loadCount: value }; - const updatedActions = selectedPointData.actions.map(action => action.actionUuid === updatedAction.actionUuid ? updatedAction : action); + const updatedActions = selectedPointData.actions.map((action) => (action.actionUuid === updatedAction.actionUuid ? updatedAction : action)); const updatedPoint = { ...selectedPointData, actions: updatedActions }; - const event = updateAction( - selectedProduct.productUuid, - selectedAction.actionId, - updatedAction - ); + const event = updateAction(selectedProduct.productUuid, selectedAction.actionId, updatedAction); if (event) { - updateBackend(selectedProduct.productName, selectedProduct.productUuid, projectId || '', event); + updateBackend(selectedProduct.productName, selectedProduct.productUuid, projectId || "", event); } setCurrentAction(updatedAction); @@ -207,17 +168,13 @@ function HumanMechanics() { if (!currentAction || !selectedPointData || !selectedAction.actionId) return; const updatedAction = { ...currentAction, manufactureCount: value }; - const updatedActions = selectedPointData.actions.map(action => action.actionUuid === updatedAction.actionUuid ? updatedAction : action); + const updatedActions = selectedPointData.actions.map((action) => (action.actionUuid === updatedAction.actionUuid ? updatedAction : action)); const updatedPoint = { ...selectedPointData, actions: updatedActions }; - const event = updateAction( - selectedProduct.productUuid, - selectedAction.actionId, - updatedAction - ); + const event = updateAction(selectedProduct.productUuid, selectedAction.actionId, updatedAction); if (event) { - updateBackend(selectedProduct.productName, selectedProduct.productUuid, projectId || '', event); + updateBackend(selectedProduct.productName, selectedProduct.productUuid, projectId || "", event); } setCurrentAction(updatedAction); @@ -229,17 +186,13 @@ function HumanMechanics() { if (!currentAction || !selectedPointData || !selectedAction.actionId) return; const updatedAction = { ...currentAction, processTime: value }; - const updatedActions = selectedPointData.actions.map(action => action.actionUuid === updatedAction.actionUuid ? updatedAction : action); + const updatedActions = selectedPointData.actions.map((action) => (action.actionUuid === updatedAction.actionUuid ? updatedAction : action)); const updatedPoint = { ...selectedPointData, actions: updatedActions }; - const event = updateAction( - selectedProduct.productUuid, - selectedAction.actionId, - updatedAction - ); + const event = updateAction(selectedProduct.productUuid, selectedAction.actionId, updatedAction); if (event) { - updateBackend(selectedProduct.productName, selectedProduct.productUuid, projectId || '', event); + updateBackend(selectedProduct.productName, selectedProduct.productUuid, projectId || "", event); } setCurrentAction(updatedAction); @@ -251,17 +204,13 @@ function HumanMechanics() { if (!currentAction || !selectedPointData || !selectedAction.actionId) return; const updatedAction = { ...currentAction, swapMaterial: value }; - const updatedActions = selectedPointData.actions.map(action => action.actionUuid === updatedAction.actionUuid ? updatedAction : action); + const updatedActions = selectedPointData.actions.map((action) => (action.actionUuid === updatedAction.actionUuid ? updatedAction : action)); const updatedPoint = { ...selectedPointData, actions: updatedActions }; - const event = updateAction( - selectedProduct.productUuid, - selectedAction.actionId, - updatedAction - ); + const event = updateAction(selectedProduct.productUuid, selectedAction.actionId, updatedAction); if (event) { - updateBackend(selectedProduct.productName, selectedProduct.productUuid, projectId || '', event); + updateBackend(selectedProduct.productName, selectedProduct.productUuid, projectId || "", event); } setCurrentAction(updatedAction); @@ -274,24 +223,20 @@ function HumanMechanics() { const updatedAction: HumanAction = JSON.parse(JSON.stringify(currentAction)); - if (updatedAction.actionType === 'manufacturer') { - updatedAction.manufacturePoint = { position: null, rotation: null, } + if (updatedAction.actionType === "manufacturer") { + updatedAction.manufacturePoint = { position: null, rotation: null }; } else { - updatedAction.pickUpPoint = { position: null, rotation: null, }; - updatedAction.dropPoint = { position: null, rotation: null, } + updatedAction.pickUpPoint = { position: null, rotation: null }; + updatedAction.dropPoint = { position: null, rotation: null }; } - const updatedActions = selectedPointData.actions.map(action => action.actionUuid === updatedAction.actionUuid ? updatedAction : action); + const updatedActions = selectedPointData.actions.map((action) => (action.actionUuid === updatedAction.actionUuid ? updatedAction : action)); const updatedPoint = { ...selectedPointData, actions: updatedActions }; - const event = updateAction( - selectedProduct.productUuid, - selectedAction.actionId, - updatedAction - ); + const event = updateAction(selectedProduct.productUuid, selectedAction.actionId, updatedAction); if (event) { - updateBackend(selectedProduct.productName, selectedProduct.productUuid, projectId || '', event); + updateBackend(selectedProduct.productName, selectedProduct.productUuid, projectId || "", event); } setCurrentAction(updatedAction); @@ -308,8 +253,8 @@ function HumanMechanics() { loadCount: 1, assemblyCount: 1, assemblyCondition: { - conditionType: 'material', - materialType: "Default material" + conditionType: "material", + materialType: "Default material", }, manufactureCount: 1, loadCapacity: 1, @@ -320,15 +265,10 @@ function HumanMechanics() { const updatedActions = [...(selectedPointData.actions || []), newAction]; const updatedPoint = { ...selectedPointData, actions: updatedActions }; - const event = addAction( - selectedProduct.productUuid, - selectedEventData.data.modelUuid, - selectedEventData.selectedPoint, - newAction - ); + const event = addAction(selectedProduct.productUuid, selectedEventData.data.modelUuid, selectedEventData.selectedPoint, newAction); if (event) { - updateBackend(selectedProduct.productName, selectedProduct.productUuid, projectId || '', event); + updateBackend(selectedProduct.productName, selectedProduct.productUuid, projectId || "", event); } setSelectedPointData(updatedPoint); @@ -338,16 +278,13 @@ function HumanMechanics() { const handleDeleteAction = (actionUuid: string) => { if (!selectedPointData || !actionUuid) return; - const updatedActions = selectedPointData.actions.filter(action => action.actionUuid !== actionUuid); + const updatedActions = selectedPointData.actions.filter((action) => action.actionUuid !== actionUuid); const updatedPoint = { ...selectedPointData, actions: updatedActions }; - const event = removeAction( - selectedProduct.productUuid, - actionUuid - ); + const event = removeAction(selectedProduct.productUuid, actionUuid); if (event) { - updateBackend(selectedProduct.productName, selectedProduct.productUuid, projectId || '', event); + updateBackend(selectedProduct.productName, selectedProduct.productUuid, projectId || "", event); } setSelectedPointData(updatedPoint); @@ -371,27 +308,12 @@ function HumanMechanics() {
- { }} - onChange={handleSpeedChange} - /> + {}} onChange={handleSpeedChange} />
- + {selectedAction.actionId && currentAction && (
@@ -399,15 +321,9 @@ function HumanMechanics() {
- +
- {(currentAction.actionType === 'worker' || currentAction.actionType === "operator") && + {(currentAction.actionType === "worker" || currentAction.actionType === "operator") && ( - } - {currentAction.actionType === 'manufacturer' && + )} + {currentAction.actionType === "manufacturer" && ( - } + )}
@@ -463,4 +379,4 @@ function HumanMechanics() { ); } -export default HumanMechanics; \ No newline at end of file +export default HumanMechanics; diff --git a/app/src/components/layout/sidebarRight/properties/eventProperties/mechanics/machineMechanics.tsx b/app/src/components/layout/sidebarRight/properties/eventProperties/mechanics/machineMechanics.tsx index 22b3277..43c4f6f 100644 --- a/app/src/components/layout/sidebarRight/properties/eventProperties/mechanics/machineMechanics.tsx +++ b/app/src/components/layout/sidebarRight/properties/eventProperties/mechanics/machineMechanics.tsx @@ -6,9 +6,7 @@ import { useSelectedAction, useSelectedEventData } from "../../../../../../store import ProcessAction from "../actions/ProcessAction"; import ActionsList from "../components/ActionsList"; import { upsertProductOrEventApi } from "../../../../../../services/simulation/products/UpsertProductOrEventApi"; -import { useProductContext } from "../../../../../../modules/simulation/products/productContext"; import { useParams } from "react-router-dom"; -import { useVersionContext } from "../../../../../../modules/builder/version/versionContext"; import { useSceneContext } from "../../../../../../modules/scene/sceneContext"; function MachineMechanics() { @@ -19,22 +17,15 @@ function MachineMechanics() { const [selectedPointData, setSelectedPointData] = useState(); const { selectedEventData } = useSelectedEventData(); - const { productStore } = useSceneContext(); - const { getPointByUuid, updateAction } = productStore(); - const { selectedProductStore } = useProductContext(); - const { selectedProduct } = selectedProductStore(); + const { productStore, versionStore } = useSceneContext(); + const { getPointByUuid, updateAction, selectedProduct } = productStore(); const { setSelectedAction, clearSelectedAction } = useSelectedAction(); - const { selectedVersionStore } = useVersionContext(); - const { selectedVersion } = selectedVersionStore(); + const { selectedVersion } = versionStore(); const { projectId } = useParams(); useEffect(() => { if (selectedEventData) { - const point = getPointByUuid( - selectedProduct.productUuid, - selectedEventData?.data.modelUuid, - selectedEventData?.selectedPoint - ) as MachinePointSchema | undefined; + const point = getPointByUuid(selectedProduct.productUuid, selectedEventData?.data.modelUuid, selectedEventData?.selectedPoint) as MachinePointSchema | undefined; if (point && "action" in point) { setSelectedPointData(point); @@ -49,12 +40,7 @@ function MachineMechanics() { } }, [selectedProduct, selectedEventData]); - const updateBackend = ( - productName: string, - productUuid: string, - projectId: string, - eventData: EventsSchema - ) => { + const updateBackend = (productName: string, productUuid: string, projectId: string, eventData: EventsSchema) => { upsertProductOrEventApi({ productName, productUuid, @@ -70,19 +56,10 @@ function MachineMechanics() { const validOption = option as "process"; setActiveOption(validOption); - const event = updateAction( - selectedProduct.productUuid, - selectedPointData.action.actionUuid, - { actionType: validOption } - ); + const event = updateAction(selectedProduct.productUuid, selectedPointData.action.actionUuid, { actionType: validOption }); if (event) { - updateBackend( - selectedProduct.productName, - selectedProduct.productUuid, - projectId || '', - event - ); + updateBackend(selectedProduct.productName, selectedProduct.productUuid, projectId || "", event); } }; @@ -90,19 +67,10 @@ function MachineMechanics() { if (!selectedPointData) return; setActionName(newName); - const event = updateAction( - selectedProduct.productUuid, - selectedPointData.action.actionUuid, - { actionName: newName } - ); + const event = updateAction(selectedProduct.productUuid, selectedPointData.action.actionUuid, { actionName: newName }); if (event) { - updateBackend( - selectedProduct.productName, - selectedProduct.productUuid, - projectId || '', - event - ); + updateBackend(selectedProduct.productName, selectedProduct.productUuid, projectId || "", event); } }; @@ -113,19 +81,10 @@ function MachineMechanics() { if (isNaN(numericValue)) return; setProcessTime(value); - const event = updateAction( - selectedProduct.productUuid, - selectedPointData.action.actionUuid, - { processTime: numericValue } - ); + const event = updateAction(selectedProduct.productUuid, selectedPointData.action.actionUuid, { processTime: numericValue }); if (event) { - updateBackend( - selectedProduct.productName, - selectedProduct.productUuid, - projectId || '', - event - ); + updateBackend(selectedProduct.productName, selectedProduct.productUuid, projectId || "", event); } }; @@ -133,19 +92,10 @@ function MachineMechanics() { if (!selectedPointData) return; setMaterial(selectedMaterial); - const event = updateAction( - selectedProduct.productUuid, - selectedPointData.action.actionUuid, - { swapMaterial: selectedMaterial } - ); + const event = updateAction(selectedProduct.productUuid, selectedPointData.action.actionUuid, { swapMaterial: selectedMaterial }); if (event) { - updateBackend( - selectedProduct.productName, - selectedProduct.productUuid, - projectId || '', - event - ); + updateBackend(selectedProduct.productName, selectedProduct.productUuid, projectId || "", event); } }; @@ -160,34 +110,16 @@ function MachineMechanics() {
- +
- - {activeOption === "process" && ( - - )} + + {activeOption === "process" && }
- +
)} @@ -195,4 +127,4 @@ function MachineMechanics() { ); } -export default MachineMechanics; \ No newline at end of file +export default MachineMechanics; diff --git a/app/src/components/layout/sidebarRight/properties/eventProperties/mechanics/roboticArmMechanics.tsx b/app/src/components/layout/sidebarRight/properties/eventProperties/mechanics/roboticArmMechanics.tsx index dea6ef5..24fd497 100644 --- a/app/src/components/layout/sidebarRight/properties/eventProperties/mechanics/roboticArmMechanics.tsx +++ b/app/src/components/layout/sidebarRight/properties/eventProperties/mechanics/roboticArmMechanics.tsx @@ -8,9 +8,7 @@ import { useSelectedEventData, useSelectedAction } from "../../../../../../store import PickAndPlaceAction from "../actions/PickAndPlaceAction"; import ActionsList from "../components/ActionsList"; import { upsertProductOrEventApi } from "../../../../../../services/simulation/products/UpsertProductOrEventApi"; -import { useProductContext } from "../../../../../../modules/simulation/products/productContext"; import { useParams } from "react-router-dom"; -import { useVersionContext } from "../../../../../../modules/builder/version/versionContext"; import { useSceneContext } from "../../../../../../modules/scene/sceneContext"; function RoboticArmMechanics() { @@ -19,31 +17,19 @@ function RoboticArmMechanics() { const [selectedPointData, setSelectedPointData] = useState(); const { selectedEventData } = useSelectedEventData(); - const { productStore } = useSceneContext(); - const { getPointByUuid, getEventByModelUuid, updateEvent, updateAction, addAction, removeAction } = productStore(); - const { selectedProductStore } = useProductContext(); - const { selectedProduct } = selectedProductStore(); + const { productStore, versionStore } = useSceneContext(); + const { getPointByUuid, getEventByModelUuid, updateEvent, updateAction, addAction, removeAction, selectedProduct } = productStore(); const { selectedAction, setSelectedAction, clearSelectedAction } = useSelectedAction(); - const { selectedVersionStore } = useVersionContext(); - const { selectedVersion } = selectedVersionStore(); + const { selectedVersion } = versionStore(); const { projectId } = useParams(); useEffect(() => { - if (selectedEventData && selectedEventData.data.type === 'roboticArm') { - const point = getPointByUuid( - selectedProduct.productUuid, - selectedEventData.data.modelUuid, - selectedEventData.selectedPoint - ) as RoboticArmPointSchema | undefined; + if (selectedEventData && selectedEventData.data.type === "roboticArm") { + const point = getPointByUuid(selectedProduct.productUuid, selectedEventData.data.modelUuid, selectedEventData.selectedPoint) as RoboticArmPointSchema | undefined; if (point?.actions) { setSelectedPointData(point); - setSpeed( - (getEventByModelUuid( - selectedProduct.productUuid, - selectedEventData.data.modelUuid - ) as RoboticArmEventSchema | undefined)?.speed?.toString() || "0.5" - ); + setSpeed((getEventByModelUuid(selectedProduct.productUuid, selectedEventData.data.modelUuid) as RoboticArmEventSchema | undefined)?.speed?.toString() || "0.5"); if (point.actions.length > 0) { const firstAction = point.actions[0]; @@ -56,12 +42,7 @@ function RoboticArmMechanics() { } }, [selectedEventData, selectedProduct]); - const updateBackend = ( - productName: string, - productUuid: string, - projectId: string, - eventData: EventsSchema - ) => { + const updateBackend = (productName: string, productUuid: string, projectId: string, eventData: EventsSchema) => { upsertProductOrEventApi({ productName, productUuid, @@ -78,43 +59,25 @@ function RoboticArmMechanics() { if (isNaN(numericValue)) return; setSpeed(value); - const event = updateEvent( - selectedProduct.productUuid, - selectedEventData.data.modelUuid, - { speed: numericValue } - ); + const event = updateEvent(selectedProduct.productUuid, selectedEventData.data.modelUuid, { speed: numericValue }); if (event) { - updateBackend( - selectedProduct.productName, - selectedProduct.productUuid, - projectId || '', - event - ); + updateBackend(selectedProduct.productName, selectedProduct.productUuid, projectId || "", event); } }; const handleClearPoints = () => { if (!selectedAction.actionId || !selectedPointData) return; - const event = updateAction( - selectedProduct.productUuid, - selectedAction.actionId, - { - process: { - startPoint: null, - endPoint: null, - }, - } - ); + const event = updateAction(selectedProduct.productUuid, selectedAction.actionId, { + process: { + startPoint: null, + endPoint: null, + }, + }); if (event) { - updateBackend( - selectedProduct.productName, - selectedProduct.productUuid, - projectId || '', - event - ); + updateBackend(selectedProduct.productName, selectedProduct.productUuid, projectId || "", event); } }; @@ -132,20 +95,10 @@ function RoboticArmMechanics() { triggers: [] as TriggerSchema[], }; - const event = addAction( - selectedProduct.productUuid, - selectedEventData.data.modelUuid, - selectedEventData.selectedPoint, - newAction - ); + const event = addAction(selectedProduct.productUuid, selectedEventData.data.modelUuid, selectedEventData.selectedPoint, newAction); if (event) { - updateBackend( - selectedProduct.productName, - selectedProduct.productUuid, - projectId || '', - event - ); + updateBackend(selectedProduct.productName, selectedProduct.productUuid, projectId || "", event); } setSelectedPointData({ @@ -158,22 +111,14 @@ function RoboticArmMechanics() { const handleDeleteAction = (actionUuid: string) => { if (!selectedPointData) return; - const event = removeAction( - selectedProduct.productUuid, - actionUuid - ); + const event = removeAction(selectedProduct.productUuid, actionUuid); if (event) { - updateBackend( - selectedProduct.productName, - selectedProduct.productUuid, - projectId || '', - event - ); + updateBackend(selectedProduct.productName, selectedProduct.productUuid, projectId || "", event); } - const index = selectedPointData.actions.findIndex(a => a.actionUuid === actionUuid); - const newActions = selectedPointData.actions.filter(a => a.actionUuid !== actionUuid); + const index = selectedPointData.actions.findIndex((a) => a.actionUuid === actionUuid); + const newActions = selectedPointData.actions.filter((a) => a.actionUuid !== actionUuid); setSelectedPointData({ ...selectedPointData, @@ -195,57 +140,31 @@ function RoboticArmMechanics() { options: ["pickAndPlace"], }; - const currentAction = selectedPointData?.actions.find(a => a.actionUuid === selectedAction.actionId); + const currentAction = selectedPointData?.actions.find((a) => a.actionUuid === selectedAction.actionId); return ( <>
- { }} - onChange={handleSpeedChange} - /> + {}} onChange={handleSpeedChange} />
- + {selectedAction.actionId && currentAction && (
- +
- { }} - disabled={true} - /> + {}} disabled={true} />
- +
)} @@ -254,4 +173,4 @@ function RoboticArmMechanics() { ); } -export default RoboticArmMechanics; \ No newline at end of file +export default RoboticArmMechanics; diff --git a/app/src/components/layout/sidebarRight/properties/eventProperties/mechanics/storageMechanics.tsx b/app/src/components/layout/sidebarRight/properties/eventProperties/mechanics/storageMechanics.tsx index bf264fb..460438a 100644 --- a/app/src/components/layout/sidebarRight/properties/eventProperties/mechanics/storageMechanics.tsx +++ b/app/src/components/layout/sidebarRight/properties/eventProperties/mechanics/storageMechanics.tsx @@ -7,9 +7,7 @@ import StorageAction from "../actions/StorageAction"; import ActionsList from "../components/ActionsList"; import { upsertProductOrEventApi } from "../../../../../../services/simulation/products/UpsertProductOrEventApi"; import { useSelectedAction, useSelectedEventData } from "../../../../../../store/simulation/useSimulationStore"; -import { useProductContext } from "../../../../../../modules/simulation/products/productContext"; import { useParams } from "react-router-dom"; -import { useVersionContext } from "../../../../../../modules/builder/version/versionContext"; import { useSceneContext } from "../../../../../../modules/scene/sceneContext"; function StorageMechanics() { @@ -19,31 +17,21 @@ function StorageMechanics() { const [spawnedMaterial, setSpawnedMaterial] = useState("Default material"); const [selectedPointData, setSelectedPointData] = useState(); const { selectedEventData } = useSelectedEventData(); - const { productStore } = useSceneContext(); - const { getPointByUuid, updateAction, updateEvent, getEventByModelUuid, getActionByUuid, addAction, removeAction } = productStore(); - const { selectedProductStore } = useProductContext(); - const { selectedProduct } = selectedProductStore(); + const { productStore, versionStore } = useSceneContext(); + const { getPointByUuid, updateAction, updateEvent, getEventByModelUuid, getActionByUuid, addAction, removeAction, selectedProduct } = productStore(); const { selectedAction, setSelectedAction, clearSelectedAction } = useSelectedAction(); - const { selectedVersionStore } = useVersionContext(); - const { selectedVersion } = selectedVersionStore(); + const { selectedVersion } = versionStore(); const { projectId } = useParams(); useEffect(() => { if (selectedEventData && selectedEventData.data.type === "storageUnit") { - const point = getPointByUuid( - selectedProduct.productUuid, - selectedEventData.data.modelUuid, - selectedEventData.selectedPoint - ) as StoragePointSchema | undefined; + const point = getPointByUuid(selectedProduct.productUuid, selectedEventData.data.modelUuid, selectedEventData.selectedPoint) as StoragePointSchema | undefined; if (point?.actions?.length) { setSelectedPointData(point); const firstAction = point.actions[0]; - const eventData = getEventByModelUuid( - selectedProduct.productUuid, - selectedEventData.data.modelUuid - ) as StorageEventSchema | undefined; + const eventData = getEventByModelUuid(selectedProduct.productUuid, selectedEventData.data.modelUuid) as StorageEventSchema | undefined; setCurrentCapacity(eventData?.storageCapacity?.toString() || "1"); setSpawnedCount(eventData?.storageCount?.toString() || "0"); @@ -58,17 +46,13 @@ function StorageMechanics() { useEffect(() => { if (selectedEventData && selectedEventData.data.type === "storageUnit" && selectedAction.actionId) { - const point = getPointByUuid( - selectedProduct.productUuid, - selectedEventData.data.modelUuid, - selectedEventData.selectedPoint - ) as StoragePointSchema | undefined; + const point = getPointByUuid(selectedProduct.productUuid, selectedEventData.data.modelUuid, selectedEventData.selectedPoint) as StoragePointSchema | undefined; - const actionUuid = selectedAction.actionId || point?.actions[0].actionUuid || ''; + const actionUuid = selectedAction.actionId || point?.actions[0].actionUuid || ""; const newCurrentAction = getActionByUuid(selectedProduct.productUuid, actionUuid); - if (newCurrentAction && (newCurrentAction.actionType === 'store' || newCurrentAction.actionType === 'retrieve')) { + if (newCurrentAction && (newCurrentAction.actionType === "store" || newCurrentAction.actionType === "retrieve")) { if (!selectedAction.actionId) { setSelectedAction(newCurrentAction.actionUuid, newCurrentAction.actionName); } @@ -80,20 +64,15 @@ function StorageMechanics() { } }, [selectedAction, selectedProduct, selectedEventData]); - const updateBackend = ( - productName: string, - productUuid: string, - projectId: string, - eventData: EventsSchema - ) => { + const updateBackend = (productName: string, productUuid: string, projectId: string, eventData: EventsSchema) => { upsertProductOrEventApi({ productName: productName, productUuid: productUuid, projectId: projectId, eventDatas: eventData, - versionId: selectedVersion?.versionId || '', - }) - } + versionId: selectedVersion?.versionId || "", + }); + }; const handleActionTypeChange = (option: string) => { if (!selectedAction.actionId || !selectedPointData) return; @@ -101,31 +80,24 @@ function StorageMechanics() { const internalOption = option === "spawn" ? "retrieve" : "store"; const updatedAction = { - actionType: internalOption as "store" | "retrieve" + actionType: internalOption as "store" | "retrieve", }; - const updatedActions = selectedPointData.actions.map(action => - action.actionUuid === selectedAction.actionId ? { - ...action, - actionType: updatedAction.actionType - } : action + const updatedActions = selectedPointData.actions.map((action) => + action.actionUuid === selectedAction.actionId + ? { + ...action, + actionType: updatedAction.actionType, + } + : action ); const updatedPoint = { ...selectedPointData, actions: updatedActions }; - const event = updateAction( - selectedProduct.productUuid, - selectedAction.actionId, - updatedAction - ); + const event = updateAction(selectedProduct.productUuid, selectedAction.actionId, updatedAction); if (event) { - updateBackend( - selectedProduct.productName, - selectedProduct.productUuid, - projectId || '', - event - ); + updateBackend(selectedProduct.productName, selectedProduct.productUuid, projectId || "", event); } setSelectedPointData(updatedPoint); @@ -139,7 +111,7 @@ function StorageMechanics() { if (isNaN(numericValue)) return; const updatedEvent = { - storageCapacity: numericValue + storageCapacity: numericValue, } as StorageEventSchema; const currentCount = parseInt(spawnedCount); @@ -148,19 +120,10 @@ function StorageMechanics() { setSpawnedCount(numericValue.toString()); } - const event = updateEvent( - selectedProduct.productUuid, - selectedEventData.data.modelUuid, - updatedEvent - ); + const event = updateEvent(selectedProduct.productUuid, selectedEventData.data.modelUuid, updatedEvent); if (event) { - updateBackend( - selectedProduct.productName, - selectedProduct.productUuid, - projectId || '', - event - ); + updateBackend(selectedProduct.productName, selectedProduct.productUuid, projectId || "", event); } setCurrentCapacity(value); @@ -176,22 +139,13 @@ function StorageMechanics() { if (numericValue > maxCapacity) return; const updatedEvent = { - storageCount: numericValue + storageCount: numericValue, } as StorageEventSchema; - const event = updateEvent( - selectedProduct.productUuid, - selectedEventData.data.modelUuid, - updatedEvent - ); + const event = updateEvent(selectedProduct.productUuid, selectedEventData.data.modelUuid, updatedEvent); if (event) { - updateBackend( - selectedProduct.productName, - selectedProduct.productUuid, - projectId || '', - event - ); + updateBackend(selectedProduct.productName, selectedProduct.productUuid, projectId || "", event); } setSpawnedCount(value); @@ -201,22 +155,13 @@ function StorageMechanics() { if (!selectedEventData) return; const updatedEvent = { - materialType: value + materialType: value, } as StorageEventSchema; - const event = updateEvent( - selectedProduct.productUuid, - selectedEventData.data.modelUuid, - updatedEvent - ); + const event = updateEvent(selectedProduct.productUuid, selectedEventData.data.modelUuid, updatedEvent); if (event) { - updateBackend( - selectedProduct.productName, - selectedProduct.productUuid, - projectId || '', - event - ); + updateBackend(selectedProduct.productName, selectedProduct.productUuid, projectId || "", event); } setSpawnedMaterial(value); @@ -235,15 +180,10 @@ function StorageMechanics() { const updatedActions = [...(selectedPointData.actions || []), newAction]; const updatedPoint = { ...selectedPointData, actions: updatedActions }; - const event = addAction( - selectedProduct.productUuid, - selectedEventData.data.modelUuid, - selectedEventData.selectedPoint, - newAction - ); + const event = addAction(selectedProduct.productUuid, selectedEventData.data.modelUuid, selectedEventData.selectedPoint, newAction); if (event) { - updateBackend(selectedProduct.productName, selectedProduct.productUuid, projectId || '', event); + updateBackend(selectedProduct.productName, selectedProduct.productUuid, projectId || "", event); } setSelectedPointData(updatedPoint); @@ -253,16 +193,13 @@ function StorageMechanics() { const handleDeleteAction = (actionUuid: string) => { if (!selectedPointData || !actionUuid) return; - const updatedActions = selectedPointData.actions.filter(action => action.actionUuid !== actionUuid); + const updatedActions = selectedPointData.actions.filter((action) => action.actionUuid !== actionUuid); const updatedPoint = { ...selectedPointData, actions: updatedActions }; - const event = removeAction( - selectedProduct.productUuid, - actionUuid - ); + const event = removeAction(selectedProduct.productUuid, actionUuid); if (event) { - updateBackend(selectedProduct.productName, selectedProduct.productUuid, projectId || '', event); + updateBackend(selectedProduct.productName, selectedProduct.productUuid, projectId || "", event); } setSelectedPointData(updatedPoint); @@ -281,45 +218,21 @@ function StorageMechanics() { {selectedEventData && selectedEventData.data.type === "storageUnit" && ( <>
- +
- + {selectedAction.actionId && (
- +
- +
- +
)} @@ -330,4 +243,4 @@ function StorageMechanics() { ); } -export default StorageMechanics; \ No newline at end of file +export default StorageMechanics; diff --git a/app/src/components/layout/sidebarRight/properties/eventProperties/mechanics/vehicleMechanics.tsx b/app/src/components/layout/sidebarRight/properties/eventProperties/mechanics/vehicleMechanics.tsx index 181252b..732f8e7 100644 --- a/app/src/components/layout/sidebarRight/properties/eventProperties/mechanics/vehicleMechanics.tsx +++ b/app/src/components/layout/sidebarRight/properties/eventProperties/mechanics/vehicleMechanics.tsx @@ -7,9 +7,7 @@ import { useSelectedAction, useSelectedEventData } from "../../../../../../store import TravelAction from "../actions/TravelAction"; import ActionsList from "../components/ActionsList"; import { upsertProductOrEventApi } from "../../../../../../services/simulation/products/UpsertProductOrEventApi"; -import { useProductContext } from "../../../../../../modules/simulation/products/productContext"; import { useParams } from "react-router-dom"; -import { useVersionContext } from "../../../../../../modules/builder/version/versionContext"; import { useSceneContext } from "../../../../../../modules/scene/sceneContext"; import { useSelectedPath } from "../../../../../../store/builder/store"; @@ -22,34 +20,22 @@ function VehicleMechanics() { const [selectedPointData, setSelectedPointData] = useState(); const { selectedEventData } = useSelectedEventData(); - const { productStore } = useSceneContext(); - const { getPointByUuid, updateEvent, updateAction, getEventByModelUuid } = productStore(); - const { selectedProductStore } = useProductContext(); - const { selectedProduct } = selectedProductStore(); + const { productStore, versionStore } = useSceneContext(); + const { getPointByUuid, updateEvent, updateAction, getEventByModelUuid, selectedProduct } = productStore(); const { setSelectedAction, clearSelectedAction } = useSelectedAction(); - const { selectedVersionStore } = useVersionContext(); - const { selectedVersion } = selectedVersionStore(); + const { selectedVersion } = versionStore(); const { projectId } = useParams(); const { setSelectedPath } = useSelectedPath(); useEffect(() => { if (selectedEventData && selectedEventData.data.type === "vehicle") { - const point = getPointByUuid( - selectedProduct.productUuid, - selectedEventData.data.modelUuid, - selectedEventData.selectedPoint - ) as VehiclePointSchema | undefined; + const point = getPointByUuid(selectedProduct.productUuid, selectedEventData.data.modelUuid, selectedEventData.selectedPoint) as VehiclePointSchema | undefined; if (point) { setSelectedPointData(point); setActiveOption(point.action.actionType as "travel"); setActionName(point.action.actionName); - setSpeed( - (getEventByModelUuid( - selectedProduct.productUuid, - selectedEventData.data.modelUuid - ) as VehicleEventSchema | undefined)?.speed?.toString() || "0.5" - ); + setSpeed((getEventByModelUuid(selectedProduct.productUuid, selectedEventData.data.modelUuid) as VehicleEventSchema | undefined)?.speed?.toString() || "0.5"); setLoadCapacity(point.action.loadCapacity?.toString() || "1"); setUnloadDuration(point.action.unLoadDuration?.toString() || "1"); setSelectedAction(point.action.actionUuid, point.action.actionName); @@ -59,12 +45,7 @@ function VehicleMechanics() { } }, [selectedProduct, selectedEventData]); - const updateBackend = ( - productName: string, - productUuid: string, - projectId: string, - eventData: EventsSchema - ) => { + const updateBackend = (productName: string, productUuid: string, projectId: string, eventData: EventsSchema) => { upsertProductOrEventApi({ productName, productUuid, @@ -81,19 +62,10 @@ function VehicleMechanics() { if (isNaN(numericValue)) return; setSpeed(value); - const event = updateEvent( - selectedProduct.productUuid, - selectedEventData.data.modelUuid, - { speed: numericValue } - ); + const event = updateEvent(selectedProduct.productUuid, selectedEventData.data.modelUuid, { speed: numericValue }); if (event) { - updateBackend( - selectedProduct.productName, - selectedProduct.productUuid, - projectId || '', - event - ); + updateBackend(selectedProduct.productName, selectedProduct.productUuid, projectId || "", event); } }; @@ -103,19 +75,10 @@ function VehicleMechanics() { const validOption = option as "travel"; setActiveOption(validOption); - const event = updateAction( - selectedProduct.productUuid, - selectedPointData.action.actionUuid, - { actionType: validOption } - ); + const event = updateAction(selectedProduct.productUuid, selectedPointData.action.actionUuid, { actionType: validOption }); if (event) { - updateBackend( - selectedProduct.productName, - selectedProduct.productUuid, - projectId || '', - event - ); + updateBackend(selectedProduct.productName, selectedProduct.productUuid, projectId || "", event); } }; @@ -126,19 +89,10 @@ function VehicleMechanics() { if (isNaN(numericValue)) return; setLoadCapacity(value); - const event = updateAction( - selectedProduct.productUuid, - selectedPointData.action.actionUuid, - { loadCapacity: numericValue } - ); + const event = updateAction(selectedProduct.productUuid, selectedPointData.action.actionUuid, { loadCapacity: numericValue }); if (event) { - updateBackend( - selectedProduct.productName, - selectedProduct.productUuid, - projectId || '', - event - ); + updateBackend(selectedProduct.productName, selectedProduct.productUuid, projectId || "", event); } }; @@ -149,42 +103,24 @@ function VehicleMechanics() { if (isNaN(numericValue)) return; setUnloadDuration(value); - const event = updateAction( - selectedProduct.productUuid, - selectedPointData.action.actionUuid, - { unLoadDuration: numericValue } - ); + const event = updateAction(selectedProduct.productUuid, selectedPointData.action.actionUuid, { unLoadDuration: numericValue }); if (event) { - updateBackend( - selectedProduct.productName, - selectedProduct.productUuid, - projectId || '', - event - ); + updateBackend(selectedProduct.productName, selectedProduct.productUuid, projectId || "", event); } }; const handleClearPoints = () => { if (!selectedPointData) return; - const event = updateAction( - selectedProduct.productUuid, - selectedPointData.action.actionUuid, - { - pickUpPoint: null, - unLoadPoint: null, - steeringAngle: 0, - } - ); + const event = updateAction(selectedProduct.productUuid, selectedPointData.action.actionUuid, { + pickUpPoint: null, + unLoadPoint: null, + steeringAngle: 0, + }); if (event) { - updateBackend( - selectedProduct.productName, - selectedProduct.productUuid, - projectId || '', - event - ); + updateBackend(selectedProduct.productName, selectedProduct.productUuid, projectId || "", event); } }; @@ -200,17 +136,7 @@ function VehicleMechanics() {
- { }} - onChange={handleSpeedChange} - /> + {}} onChange={handleSpeedChange} />
@@ -218,17 +144,10 @@ function VehicleMechanics() {
- +
- + {activeOption === "travel" && (
- +
-
+
-
+
{triggers.map((trigger) => ( -
setSelectedTrigger(trigger)} - > +
setSelectedTrigger(trigger)}>
))}
-
@@ -412,16 +307,8 @@ const Trigger = ({ selectedPointData, type }: TriggerProps) => { /> `Point ${option.uuid.slice(0, 4)}` - ), - ]} + defaultOption={triggeredPoint?.uuid ? `Point ${triggeredPoint?.uuid.slice(0, 4)}` : ""} + options={[...pointOptions.map((option) => `Point ${option.uuid.slice(0, 4)}`)]} onSelect={(option) => { handlePointSelect(option, selectedTrigger.triggerUuid); }} @@ -429,9 +316,7 @@ const Trigger = ({ selectedPointData, type }: TriggerProps) => { option.actionName), - ]} + options={[...actionOptions.map((option: any) => option.actionName)]} onSelect={(option) => { handleActionSelect(option, selectedTrigger.triggerUuid); }} diff --git a/app/src/components/layout/sidebarRight/simulation/Simulations.tsx b/app/src/components/layout/sidebarRight/simulation/Simulations.tsx index fa09ed1..55869be 100644 --- a/app/src/components/layout/sidebarRight/simulation/Simulations.tsx +++ b/app/src/components/layout/sidebarRight/simulation/Simulations.tsx @@ -13,11 +13,9 @@ import { deleteProductApi } from "../../../../services/simulation/products/delet import { renameProductApi } from "../../../../services/simulation/products/renameProductApi"; import { determineExecutionMachineSequences } from "../../../../modules/simulation/simulator/functions/determineExecutionMachineSequences"; import ComparePopUp from "../../../ui/compareVersion/Compare"; -import { useCompareStore, useSaveVersion, useSimulateId } from "../../../../store/builder/store"; -import { useToggleStore } from "../../../../store/useUIToggleStore"; -import { useProductContext } from "../../../../modules/simulation/products/productContext"; +import { useCompareStore, useIsComparing } from "../../../../store/builder/store"; +import { useToggleStore } from "../../../../store/ui/useUIToggleStore"; import { useParams } from "react-router-dom"; -import { useVersionContext } from "../../../../modules/builder/version/versionContext"; import { useSceneContext } from "../../../../modules/scene/sceneContext"; import { getSimulationData, updateSimulateData } from "../../scenes/functions/simulationStorage"; @@ -26,24 +24,10 @@ interface Event { modelId: string; } -interface ListProps { - val: Event; -} - -const List: React.FC = ({ val }) => { - return ( -
-
{val.modelName}
-
- ); -}; - const Simulations: React.FC = () => { const productsContainerRef = useRef(null); - const { eventStore, productStore } = useSceneContext(); - const { products, addProduct, removeProduct, renameProduct, addEvent, removeEvent, getProductById } = productStore(); - const { selectedProductStore } = useProductContext(); - const { selectedProduct, setSelectedProduct } = selectedProductStore(); + const { eventStore, productStore, versionStore } = useSceneContext(); + const { products, addProduct, removeProduct, renameProduct, addEvent, removeEvent, getProductById, selectedProduct, setSelectedProduct } = productStore(); const { getEventByModelUuid } = eventStore(); const { selectedAsset, clearSelectedAsset } = useSelectedAsset(); const [openObjects, setOpenObjects] = useState(true); @@ -51,14 +35,12 @@ const Simulations: React.FC = () => { const { setToggleUI } = useToggleStore(); const { projectId } = useParams(); const { setMainProduct } = useMainProduct(); - const { selectedVersionStore } = useVersionContext(); - const { selectedVersion } = selectedVersionStore(); + const { selectedVersion } = versionStore(); const { comparePopUp, setComparePopUp } = useCompareStore(); - const { setIsVersionSaved } = useSaveVersion(); - const { simulateId } = useSimulateId(); + const { setIsComparing } = useIsComparing(); const handleSaveVersion = () => { - setIsVersionSaved(true); + setIsComparing(true); setComparePopUp(false); setToggleUI(false, false); }; @@ -131,7 +113,6 @@ const Simulations: React.FC = () => { if (selectedProductData) { determineExecutionMachineSequences([selectedProductData]).then((sequences) => { - console.log("selectedProductData: ", selectedProductData); sequences.forEach((sequence) => { const events: Event[] = sequence.map((event) => ({ @@ -213,7 +194,9 @@ const Simulations: React.FC = () => { processes?.map((process, index) => (
{process.map((event, index) => ( - +
+
{event.modelName}
+
))}
))} diff --git a/app/src/components/layout/sidebarRight/versionHisory/VersionHistory.tsx b/app/src/components/layout/sidebarRight/versionHisory/VersionHistory.tsx index 8cc35e1..14e862f 100644 --- a/app/src/components/layout/sidebarRight/versionHisory/VersionHistory.tsx +++ b/app/src/components/layout/sidebarRight/versionHisory/VersionHistory.tsx @@ -1,18 +1,17 @@ -import { AddIcon, ArrowIcon, CloseIcon, KebabIcon, LocationIcon } from "../../../icons/ExportCommonIcons"; -import RenameInput from "../../../ui/inputs/RenameInput"; -import { useVersionHistoryStore } from "../../../../store/builder/useVersionHistoryStore"; -import { useSubModuleStore } from "../../../../store/useModuleStore"; -import useVersionHistoryVisibleStore from "../../../../store/builder/store"; import { useParams } from "react-router-dom"; +import { AddIcon, ArrowIcon, CloseIcon, KebabIcon, LocationIcon } from "../../../icons/ExportCommonIcons"; +import { useSubModuleStore } from "../../../../store/ui/useModuleStore"; +import { useSceneContext } from "../../../../modules/scene/sceneContext"; +import useVersionHistoryVisibleStore from "../../../../store/builder/store"; +import RenameInput from "../../../ui/inputs/RenameInput"; + import { getVersionDataApi } from "../../../../services/factoryBuilder/versionControl/getVersionDataApi"; -import { useVersionContext } from "../../../../modules/builder/version/versionContext"; const VersionHistory = () => { const { setSubModule } = useSubModuleStore(); + const { versionStore } = useSceneContext(); const { setVersionHistoryVisible } = useVersionHistoryVisibleStore(); - const { versionHistory, setCreateNewVersion } = useVersionHistoryStore(); - const { selectedVersionStore } = useVersionContext(); - const { selectedVersion, setSelectedVersion } = selectedVersionStore(); + const { versionHistory, setCreateNewVersion, selectedVersion, setSelectedVersion } = versionStore(); const { projectId } = useParams(); const addNewVersion = () => { diff --git a/app/src/components/layout/sidebarRight/versionHisory/VersionSaved.tsx b/app/src/components/layout/sidebarRight/versionHisory/VersionSaved.tsx index d099b6f..a662bf4 100644 --- a/app/src/components/layout/sidebarRight/versionHisory/VersionSaved.tsx +++ b/app/src/components/layout/sidebarRight/versionHisory/VersionSaved.tsx @@ -1,16 +1,15 @@ +import { useParams } from "react-router-dom"; import { useEffect, useState } from "react"; import { FinishEditIcon, RenameVersionIcon } from "../../../icons/ExportCommonIcons"; -import RenderOverlay from "../../../templates/Overlay"; -import { useVersionHistoryStore } from "../../../../store/builder/useVersionHistoryStore"; import { createVersionApi } from "../../../../services/factoryBuilder/versionControl/addVersionApi"; -import { useParams } from "react-router-dom"; +import { useSceneContext } from "../../../../modules/scene/sceneContext"; +import RenderOverlay from "../../../templates/Overlay"; + import { getUserData } from "../../../../functions/getUserData"; -import { useVersionContext } from "../../../../modules/builder/version/versionContext"; const VersionSaved = () => { - const { addVersion, createNewVersion, setCreateNewVersion } = useVersionHistoryStore(); - const { selectedVersionStore } = useVersionContext(); - const { selectedVersion, setSelectedVersion } = selectedVersionStore(); + const { versionStore } = useSceneContext(); + const { addVersion, createNewVersion, setCreateNewVersion, selectedVersion, setSelectedVersion } = versionStore(); const [newName, setNewName] = useState(new Date().toLocaleString("en-US", { month: "short", day: "numeric", diff --git a/app/src/components/layout/sidebarRight/visualization/IotInputCards/BarChartInput.tsx b/app/src/components/layout/sidebarRight/visualization/IotInputCards/BarChartInput.tsx index 09da02b..e413f42 100644 --- a/app/src/components/layout/sidebarRight/visualization/IotInputCards/BarChartInput.tsx +++ b/app/src/components/layout/sidebarRight/visualization/IotInputCards/BarChartInput.tsx @@ -1,194 +1,174 @@ -import React, { useEffect, useState } from "react"; +import { useEffect, useState } from "react"; import MultiLevelDropdown from "../../../../ui/inputs/MultiLevelDropDown"; import { AddIcon } from "../../../../icons/ExportCommonIcons"; import RegularDropDown from "../../../../ui/inputs/RegularDropDown"; import useChartStore from "../../../../../store/visualization/useChartStore"; import { useSelectedZoneStore } from "../../../../../store/visualization/useZoneStore"; -import { useWidgetStore } from "../../../../../store/useWidgetStore"; +import { useWidgetStore } from "../../../../../store/ui/useWidgetStore"; import axios from "axios"; import RenameInput from "../../../../ui/inputs/RenameInput"; import { useParams } from "react-router-dom"; -import { useSocketStore } from "../../../../../store/builder/store"; import { getUserData } from "../../../../../functions/getUserData"; import { addingWidgets } from "../../../../../services/visulization/zone/addWidgets"; -import { useVersionContext } from "../../../../../modules/builder/version/versionContext"; import { getWidgetInputData } from "../../../../../services/visulization/zone/getWidgetInputData"; +import { useSceneContext } from "../../../../../modules/scene/sceneContext"; type Props = {}; const BarChartInput = (props: Props) => { - const [widgetName, setWidgetName] = useState("Widget"); - const { setMeasurements, updateDuration, updateName } = useChartStore(); - const [duration, setDuration] = useState("1h"); - const [dropDowndata, setDropDownData] = useState({}); - const [selections, setSelections] = useState< - Record - >({}); - const { selectedZone } = useSelectedZoneStore(); - const { selectedChartId } = useWidgetStore(); - const iotApiUrl = process.env.REACT_APP_IOT_SOCKET_SERVER_URL; - const { userName, userId, organization, email } = getUserData(); - const [isLoading, setLoading] = useState(true); - const { projectId } = useParams(); - const { visualizationSocket } = useSocketStore(); - const { selectedVersionStore } = useVersionContext(); - const { selectedVersion } = selectedVersionStore(); + const [widgetName, setWidgetName] = useState("Widget"); + const { setMeasurements, updateDuration, updateName } = useChartStore(); + const [duration, setDuration] = useState("1h"); + const [dropDownData, setDropDownData] = useState({}); + const [selections, setSelections] = useState>({}); + const { selectedZone } = useSelectedZoneStore(); + const { selectedChartId } = useWidgetStore(); + const iotApiUrl = process.env.REACT_APP_IOT_SOCKET_SERVER_URL; + const { organization } = getUserData(); + const [isLoading, setIsLoading] = useState(true); + const { projectId } = useParams(); + const { versionStore } = useSceneContext(); + const { selectedVersion } = versionStore(); - useEffect(() => { - const fetchZoneData = async () => { - try { - setLoading(true); - const response = await axios.get(`http://${iotApiUrl}/floatinput`); - if (response.status === 200) { - // - setDropDownData(response.data); - setLoading(false); + useEffect(() => { + const fetchZoneData = async () => { + try { + setIsLoading(true); + const response = await axios.get(`http://${iotApiUrl}/floatinput`); + if (response.status === 200) { + setDropDownData(response.data); + setIsLoading(false); + } + } catch { + echo.log("Failed to fetch zone data"); + } + }; + fetchZoneData(); + }, []); + + useEffect(() => { + const fetchSavedInputes = async () => { + if (selectedChartId.id !== "") { + let response = await getWidgetInputData(selectedChartId.id, selectedZone.zoneUuid, projectId, selectedVersion?.versionId || "") + + if (response) { + setSelections(response.Datastructure.measurements); + setDuration(response.Datastructure.duration); + setWidgetName(response.widgetName); + } + } + }; + fetchSavedInputes(); + }, [selectedChartId]); + + useEffect(() => { + setMeasurements(selections); + updateDuration(duration); + updateName(widgetName); + }, [selections, duration, widgetName]); + + const sendInputes = async ( + inputMeasurement: any, + inputDuration: any, + inputName: any + ) => { + let newWidget = { + id: selectedChartId.id, + panel: selectedChartId.panel, + widgetName: inputName, + Data: { + measurements: inputMeasurement, + duration: inputDuration, + } + } + + let response = await addingWidgets(selectedZone.zoneUuid, organization, newWidget, projectId, selectedVersion?.versionId || ""); + + + if (response.message === "Widget updated successfully") { + return true; } else { + return false; + }; + }; + + const handleSelect = async ( + inputKey: string, + selectedData: { name: string; fields: string } | null + ) => { + const newSelections = { ...selections }; + if (selectedData === null) { + delete newSelections[inputKey]; + } else { + newSelections[inputKey] = selectedData; } - } catch (error) { - echo.log("Failed to fetch zone data"); - - } - }; - fetchZoneData(); - }, []); - - useEffect(() => { - const fetchSavedInputes = async () => { - if (selectedChartId.id !== "") { - let response = await getWidgetInputData(selectedChartId.id, selectedZone.zoneUuid, projectId, selectedVersion?.versionId || "") - - if (response) { - setSelections(response.Datastructure.measurements); - setDuration(response.Datastructure.duration); - setWidgetName(response.widgetName); + if (await sendInputes(newSelections, duration, widgetName)) { + setSelections(newSelections); } - } - }; - fetchSavedInputes(); - }, [selectedChartId]); - - // Sync Zustand state when component mounts - useEffect(() => { - setMeasurements(selections); - updateDuration(duration); - updateName(widgetName); - }, [selections, duration, widgetName]); - - const sendInputes = async ( - inputMeasurement: any, - inputDuration: any, - inputName: any - ) => { - // const userId = localStorage.getItem("userId"); - let newWidget = { - id: selectedChartId.id, - panel: selectedChartId.panel, - widgetName: inputName, - Data: { - measurements: inputMeasurement, - duration: inputDuration, - } - } - - let response = await addingWidgets(selectedZone.zoneUuid, organization, newWidget, projectId, selectedVersion?.versionId || ""); - - - if (response.message === "Widget updated successfully") { - return true; - } else { - - return false; }; - }; + const handleSelectDuration = async (option: string) => { + if (await sendInputes(selections, option, widgetName)) { + setDuration(option); + } + }; - const handleSelect = async ( - inputKey: string, - selectedData: { name: string; fields: string } | null - ) => { - // async() => { - const newSelections = { ...selections }; - if (selectedData === null) { - delete newSelections[inputKey]; - } else { - newSelections[inputKey] = selectedData; - } - // setMeasurements(newSelections); // Update Zustand store - // - if (await sendInputes(newSelections, duration, widgetName)) { - setSelections(newSelections); - } - // sendInputes(newSelections, duration); // Send data to server - // return newSelections; - // }; - }; + const handleNameChange = async (name: any) => { + if (await sendInputes(selections, duration, name)) { + setWidgetName(name); + } + }; - const handleSelectDuration = async (option: string) => { - if (await sendInputes(selections, option, widgetName)) { - setDuration(option); - } - // setDuration(option); - }; - - const handleNameChange = async (name: any) => { - - - if (await sendInputes(selections, duration, name)) { - setWidgetName(name); - } - }; - - return ( - <> -
-
-
Title
- -
- {[...Array(3)].map((_, index) => { - const inputKey = `input${index + 1}`; - return ( -
-
Input {index + 1}
-
- - handleSelect(inputKey, selectedData) - } - onUnselect={() => handleSelect(inputKey, null)} - selectedValue={selections[inputKey]} // Load from Zustand - isLoading={isLoading} - allSelections={selections} - /> -
- + return ( + <> +
+
+
Title
+
-
+ {[...Array(3)].map((_, index) => { + const inputKey = `input${index + 1}`; + return ( +
+
Input {index + 1}
+
+ + handleSelect(inputKey, selectedData) + } + onUnselect={() => handleSelect(inputKey, null)} + selectedValue={selections[inputKey]} // Load from Zustand + isLoading={isLoading} + allSelections={selections} + /> +
+ +
+
+
+ ); + })}
- ); - })} -
-
-
-
Duration
-
- -
-
-
- - ); +
+
+
Duration
+
+ +
+
+
+ + ); }; export default BarChartInput; diff --git a/app/src/components/layout/sidebarRight/visualization/IotInputCards/FleetEfficiencyInputComponent.tsx b/app/src/components/layout/sidebarRight/visualization/IotInputCards/FleetEfficiencyInputComponent.tsx index fa6ef5c..49cb1bc 100644 --- a/app/src/components/layout/sidebarRight/visualization/IotInputCards/FleetEfficiencyInputComponent.tsx +++ b/app/src/components/layout/sidebarRight/visualization/IotInputCards/FleetEfficiencyInputComponent.tsx @@ -1,183 +1,159 @@ -import React, { useEffect, useState } from "react"; +import { useEffect, useState } from "react"; import MultiLevelDropdown from "../../../../ui/inputs/MultiLevelDropDown"; import { AddIcon } from "../../../../icons/ExportCommonIcons"; -import RegularDropDown from "../../../../ui/inputs/RegularDropDown"; import useChartStore from "../../../../../store/visualization/useChartStore"; import { useSelectedZoneStore } from "../../../../../store/visualization/useZoneStore"; -import { useWidgetStore } from "../../../../../store/useWidgetStore"; +import { useWidgetStore } from "../../../../../store/ui/useWidgetStore"; import axios from "axios"; import RenameInput from "../../../../ui/inputs/RenameInput"; import { getUserData } from "../../../../../functions/getUserData"; import { addingFloatingWidgets } from "../../../../../services/visulization/zone/addFloatingWidgets"; import { useParams } from "react-router-dom"; -import { useVersionContext } from "../../../../../modules/builder/version/versionContext"; import { getFloatingWidgetInput } from "../../../../../services/visulization/zone/getFloatingWidgetInput"; +import { useSceneContext } from "../../../../../modules/scene/sceneContext"; type Props = {}; const FleetEfficiencyInputComponent = (props: Props) => { - const [widgetName, setWidgetName] = useState("Widget"); - const { setFlotingMeasurements, updateFlotingDuration, updateHeader } = - useChartStore(); - const [duration, setDuration] = useState("1h"); - const [dropDowndata, setDropDownData] = useState({}); - const [selections, setSelections] = useState< - Record - >({}); - const { selectedZone } = useSelectedZoneStore(); - const { selectedChartId } = useWidgetStore(); - const iotApiUrl = process.env.REACT_APP_IOT_SOCKET_SERVER_URL; - const { userName, userId, organization, email } = getUserData(); - const [isLoading, setLoading] = useState(true); - const { selectedVersionStore } = useVersionContext(); - const { selectedVersion } = selectedVersionStore(); - const { projectId } = useParams() + const [widgetName, setWidgetName] = useState("Widget"); + const { setFlotingMeasurements, updateFlotingDuration, updateHeader } = useChartStore(); + const [duration, setDuration] = useState("1h"); + const [dropDownData, setDropDownData] = useState({}); + const [selections, setSelections] = useState>({}); + const { selectedZone } = useSelectedZoneStore(); + const { selectedChartId } = useWidgetStore(); + const iotApiUrl = process.env.REACT_APP_IOT_SOCKET_SERVER_URL; + const { organization } = getUserData(); + const [isLoading, setIsLoading] = useState(true); + const { versionStore } = useSceneContext(); + const { selectedVersion } = versionStore(); + const { projectId } = useParams() - const isSelected = () => { }; + useEffect(() => { + const fetchZoneData = async () => { + try { + const response = await axios.get(`http://${iotApiUrl}/floatinput`); + setIsLoading(true); + if (response.status === 200) { + setDropDownData(response.data); + setIsLoading(false); + } + } catch { + echo.error("Failed to fetch zone data"); + } + }; + fetchZoneData(); + }, []); - useEffect(() => { - const fetchZoneData = async () => { - try { - const response = await axios.get(`http://${iotApiUrl}/floatinput`); - setLoading(true); - if (response.status === 200) { - // - setDropDownData(response.data); - setLoading(false); + useEffect(() => { + const fetchSavedInputes = async () => { + if (selectedChartId.id !== "") { + let response = await getFloatingWidgetInput(selectedChartId.id, organization, projectId, selectedVersion?.versionId || "") + + if (response) { + setSelections(response.Data.Datastructure.measurements); + setDuration(response.Data.Datastructure.duration); + setWidgetName(response.Data.header); + } + } + }; + + fetchSavedInputes(); + }, [selectedChartId.id]); + + useEffect(() => { + setFlotingMeasurements(selections); + updateFlotingDuration(duration); + updateHeader(widgetName); + }, [selections, duration, widgetName]); + + const sendInputes = async ( + inputMeasurement: any, + inputDuration: any, + inputName: any + ) => { + let newWidget = { + id: selectedChartId.id, + header: inputName, + Data: { + measurements: inputMeasurement, + duration: inputDuration, + }, + } + + const response = await addingFloatingWidgets(selectedZone.zoneUuid, organization, newWidget, projectId, selectedVersion?.versionId || "") + + if (response.message === "Widget updated successfully") { + return true; } else { - // + return false; } - } catch (error) { - echo.error("Failed to fetch zone data"); - - } - }; - fetchZoneData(); - }, []); - useEffect(() => { - const fetchSavedInputes = async () => { - if (selectedChartId.id !== "") { - let response = await getFloatingWidgetInput(selectedChartId.id, organization,projectId,selectedVersion?.versionId||"") - - if (response) { - - setSelections(response.Data.Datastructure.measurements); - setDuration(response.Data.Datastructure.duration); - setWidgetName(response.Data.header); - } - - } }; - fetchSavedInputes(); - }, [selectedChartId.id]); + const handleSelect = async ( + inputKey: string, + selectedData: { name: string; fields: string } | null + ) => { + const newSelections = { ...selections }; + if (selectedData === null) { + delete newSelections[inputKey]; + } else { + newSelections[inputKey] = selectedData; + } + if (await sendInputes(newSelections, duration, widgetName)) { + setSelections(newSelections); + } + }; - // Sync Zustand state when component mounts - useEffect(() => { - setFlotingMeasurements(selections); - updateFlotingDuration(duration); - updateHeader(widgetName); - }, [selections, duration, widgetName]); + const handleSelectDuration = async (option: string) => { + if (await sendInputes(selections, option, widgetName)) { + setDuration(option); + } + }; - const sendInputes = async ( - inputMeasurement: any, - inputDuration: any, - inputName: any - ) => { - let newWidget = { - id: selectedChartId.id, - header: inputName, - Data: { - measurements: inputMeasurement, - duration: inputDuration, - }, - } + const handleNameChange = async (name: any) => { + if (await sendInputes(selections, duration, name)) { + setWidgetName(name); + } + }; - - const response = await addingFloatingWidgets(selectedZone.zoneUuid, organization, newWidget, projectId, selectedVersion?.versionId || "") - - if (response.message === "Widget updated successfully") { - return true; - } else { - - return false; - } - - }; - - const handleSelect = async ( - inputKey: string, - selectedData: { name: string; fields: string } | null - ) => { - // async() => { - const newSelections = { ...selections }; - if (selectedData === null) { - delete newSelections[inputKey]; - } else { - newSelections[inputKey] = selectedData; - } - // setMeasurements(newSelections); // Update Zustand store - // - if (await sendInputes(newSelections, duration, widgetName)) { - setSelections(newSelections); - } - // sendInputes(newSelections, duration); // Send data to server - // return newSelections; - // }; - }; - - const handleSelectDuration = async (option: string) => { - if (await sendInputes(selections, option, widgetName)) { - setDuration(option); - } - // setDuration(option); - }; - - const handleNameChange = async (name: any) => { - - - if (await sendInputes(selections, duration, name)) { - setWidgetName(name); - } - }; - - return ( - <> -
-
-
Title
- -
- {[...Array(1)].map((_, index) => { - const inputKey = `input${index + 1}`; - return ( -
-
Input {index + 1}
-
- - handleSelect(inputKey, selectedData) - } - onUnselect={() => handleSelect(inputKey, null)} - selectedValue={selections[inputKey]} // Load from Zustand - isLoading={isLoading} - allSelections={selections} - /> -
- + return ( + <> +
+
+
Title
+
-
+ {[...Array(1)].map((_, index) => { + const inputKey = `input${index + 1}`; + return ( +
+
Input {index + 1}
+
+ + handleSelect(inputKey, selectedData) + } + onUnselect={() => handleSelect(inputKey, null)} + selectedValue={selections[inputKey]} // Load from Zustand + isLoading={isLoading} + allSelections={selections} + /> +
+ +
+
+
+ ); + })}
- ); - })} -
-
- {/*
+
+ {/*
Duration
{ />
*/} -
- - ); +
+ + ); }; export default FleetEfficiencyInputComponent; diff --git a/app/src/components/layout/sidebarRight/visualization/IotInputCards/FlotingWidgetInput.tsx b/app/src/components/layout/sidebarRight/visualization/IotInputCards/FlotingWidgetInput.tsx index c8247b6..faafc1c 100644 --- a/app/src/components/layout/sidebarRight/visualization/IotInputCards/FlotingWidgetInput.tsx +++ b/app/src/components/layout/sidebarRight/visualization/IotInputCards/FlotingWidgetInput.tsx @@ -1,194 +1,157 @@ -import React, { useEffect, useState } from "react"; +import { useEffect, useState } from "react"; import MultiLevelDropdown from "../../../../ui/inputs/MultiLevelDropDown"; import { AddIcon } from "../../../../icons/ExportCommonIcons"; import RegularDropDown from "../../../../ui/inputs/RegularDropDown"; import useChartStore from "../../../../../store/visualization/useChartStore"; import { useSelectedZoneStore } from "../../../../../store/visualization/useZoneStore"; -import { useWidgetStore } from "../../../../../store/useWidgetStore"; +import { useWidgetStore } from "../../../../../store/ui/useWidgetStore"; import axios from "axios"; import RenameInput from "../../../../ui/inputs/RenameInput"; import { getUserData } from "../../../../../functions/getUserData"; import { addingFloatingWidgets } from "../../../../../services/visulization/zone/addFloatingWidgets"; import { useParams } from "react-router-dom"; -import { useVersionContext } from "../../../../../modules/builder/version/versionContext"; import { getFloatingWidgetInput } from "../../../../../services/visulization/zone/getFloatingWidgetInput"; +import { useSceneContext } from "../../../../../modules/scene/sceneContext"; type Props = {}; const FlotingWidgetInput = (props: Props) => { - const [widgetName, setWidgetName] = useState("Widget"); - const { setFlotingMeasurements, updateFlotingDuration, updateHeader } = - useChartStore(); - const [duration, setDuration] = useState("1h"); - const [dropDowndata, setDropDownData] = useState({}); - const [selections, setSelections] = useState< - Record - >({}); - const { selectedZone } = useSelectedZoneStore(); - const { selectedChartId } = useWidgetStore(); - const iotApiUrl = process.env.REACT_APP_IOT_SOCKET_SERVER_URL; - const { userName, userId, organization, email } = getUserData(); - const [isLoading, setLoading] = useState(true); - const { projectId } = useParams() - const { selectedVersionStore } = useVersionContext(); - const { selectedVersion } = selectedVersionStore(); + const [widgetName, setWidgetName] = useState("Widget"); + const { setFlotingMeasurements, updateFlotingDuration, updateHeader } = useChartStore(); + const [duration, setDuration] = useState("1h"); + const [dropDownData, setDropDownData] = useState({}); + const [selections, setSelections] = useState>({}); + const { selectedZone } = useSelectedZoneStore(); + const { selectedChartId } = useWidgetStore(); + const iotApiUrl = process.env.REACT_APP_IOT_SOCKET_SERVER_URL; + const { organization } = getUserData(); + const [isLoading, setIsLoading] = useState(true); + const { projectId } = useParams(); + const { versionStore } = useSceneContext(); + const { selectedVersion } = versionStore(); - useEffect(() => { - const fetchZoneData = async () => { - try { - setLoading(true); - const response = await axios.get(`http://${iotApiUrl}/floatinput`); - if (response.status === 200) { - // - setDropDownData(response.data); - setLoading(false); + useEffect(() => { + const fetchZoneData = async () => { + try { + setIsLoading(true); + const response = await axios.get(`http://${iotApiUrl}/floatinput`); + if (response.status === 200) { + // + setDropDownData(response.data); + setIsLoading(false); + } + } catch { + echo.error("Failed to fetch zone data"); + } + }; + fetchZoneData(); + }, []); + + useEffect(() => { + const fetchSavedInputes = async () => { + if (selectedChartId.id !== "") { + let response = await getFloatingWidgetInput(selectedChartId.id, organization, projectId, selectedVersion?.versionId || ""); + + if (response) { + setSelections(response.Data.Datastructure.measurements); + setDuration(response.Data.Datastructure.duration); + setWidgetName(response.Data.header); + } + } + }; + + fetchSavedInputes(); + }, [selectedChartId.id]); + + useEffect(() => { + setFlotingMeasurements(selections); + updateFlotingDuration(duration); + updateHeader(widgetName); + }, [selections, duration, widgetName]); + + const sendInputes = async (inputMeasurement: any, inputDuration: any, inputName: any) => { + let newWidget = { + id: selectedChartId.id, + header: inputName, + Data: { + measurements: inputMeasurement, + duration: inputDuration, + }, + }; + + const response = await addingFloatingWidgets(selectedZone.zoneUuid, organization, newWidget, projectId, selectedVersion?.versionId || ""); + + if (response.message === "Widget updated successfully") { + return true; } else { - // + // + return false; } - } catch (error) { - echo.error("Failed to fetch zone data"); - - - } - }; - fetchZoneData(); - }, []); - - useEffect(() => { - const fetchSavedInputes = async () => { - if (selectedChartId.id !== "") { - let response = await getFloatingWidgetInput(selectedChartId.id, organization, projectId, selectedVersion?.versionId || "") - - if (response) { - setSelections(response.Data.Datastructure.measurements); - setDuration(response.Data.Datastructure.duration); - setWidgetName(response.Data.header); - } - - } }; - fetchSavedInputes(); - }, [selectedChartId.id]); + const handleSelect = async (inputKey: string, selectedData: { name: string; fields: string } | null) => { + const newSelections = { ...selections }; + if (selectedData === null) { + delete newSelections[inputKey]; + } else { + newSelections[inputKey] = selectedData; + } + if (await sendInputes(newSelections, duration, widgetName)) { + setSelections(newSelections); + } + }; - // Sync Zustand state when component mounts - useEffect(() => { - setFlotingMeasurements(selections); - updateFlotingDuration(duration); - updateHeader(widgetName); - }, [selections, duration, widgetName]); + const handleSelectDuration = async (option: string) => { + if (await sendInputes(selections, option, widgetName)) { + setDuration(option); + } + }; - const sendInputes = async ( - inputMeasurement: any, - inputDuration: any, - inputName: any - ) => { - let newWidget = { - id: selectedChartId.id, - header: inputName, - Data: { - measurements: inputMeasurement, - duration: inputDuration, - }, - } + const handleNameChange = async (name: any) => { + if (await sendInputes(selections, duration, name)) { + setWidgetName(name); + } + }; - - const response = await addingFloatingWidgets(selectedZone.zoneUuid, organization, newWidget, projectId, selectedVersion?.versionId || "") - - if (response.message === "Widget updated successfully") { - return true; - } else { - // - return false; - } - - }; - - const handleSelect = async ( - inputKey: string, - selectedData: { name: string; fields: string } | null - ) => { - // async() => { - const newSelections = { ...selections }; - if (selectedData === null) { - delete newSelections[inputKey]; - } else { - newSelections[inputKey] = selectedData; - } - // setMeasurements(newSelections); // Update Zustand store - // - if (await sendInputes(newSelections, duration, widgetName)) { - setSelections(newSelections); - } - // sendInputes(newSelections, duration); // Send data to server - // return newSelections; - // }; - }; - - const handleSelectDuration = async (option: string) => { - if (await sendInputes(selections, option, widgetName)) { - setDuration(option); - } - // setDuration(option); - }; - - const handleNameChange = async (name: any) => { - - - if (await sendInputes(selections, duration, name)) { - setWidgetName(name); - } - }; - - return ( - <> -
-
-
Title
- -
- {[...Array(6)].map((_, index) => { - const inputKey = `input${index + 1}`; - return ( -
-
Input {index + 1}
-
- - handleSelect(inputKey, selectedData) - } - onUnselect={() => handleSelect(inputKey, null)} - selectedValue={selections[inputKey]} // Load from Zustand - isLoading={isLoading} - allSelections={selections} - /> -
- + return ( + <> +
+
+
Title
+
-
+ {[...Array(6)].map((_, index) => { + const inputKey = `input${index + 1}`; + return ( +
+
Input {index + 1}
+
+ handleSelect(inputKey, selectedData)} + onUnselect={() => handleSelect(inputKey, null)} + selectedValue={selections[inputKey]} // Load from Zustand + isLoading={isLoading} + allSelections={selections} + /> +
+ +
+
+
+ ); + })}
- ); - })} -
-
-
-
Duration
-
- -
-
-
- - ); +
+
+
Duration
+
+ +
+
+
+ + ); }; export default FlotingWidgetInput; diff --git a/app/src/components/layout/sidebarRight/visualization/IotInputCards/InputSelecterComponent.tsx b/app/src/components/layout/sidebarRight/visualization/IotInputCards/InputSelecterComponent.tsx index 210e2b4..e55ee08 100644 --- a/app/src/components/layout/sidebarRight/visualization/IotInputCards/InputSelecterComponent.tsx +++ b/app/src/components/layout/sidebarRight/visualization/IotInputCards/InputSelecterComponent.tsx @@ -10,7 +10,7 @@ import Widget2InputCard3D from './Widget2InputCard3D' import Widget3InputCard3D from './Widget3InputCard3D' import Widget4InputCard3D from './Widget4InputCard3D' import WarehouseThroughputInputComponent from './WarehouseThroughputInputComponent' -import { useWidgetStore } from '../../../../../store/useWidgetStore' +import { useWidgetStore } from '../../../../../store/ui/useWidgetStore' // const InputSelecterComponent = () => { // const { selectedChartId } = useWidgetStore(); diff --git a/app/src/components/layout/sidebarRight/visualization/IotInputCards/LineGrapInput.tsx b/app/src/components/layout/sidebarRight/visualization/IotInputCards/LineGrapInput.tsx index 29263fe..1ba3abb 100644 --- a/app/src/components/layout/sidebarRight/visualization/IotInputCards/LineGrapInput.tsx +++ b/app/src/components/layout/sidebarRight/visualization/IotInputCards/LineGrapInput.tsx @@ -1,313 +1,175 @@ -// import React, { useEffect, useState } from 'react' -// import MultiLevelDropdown from '../../../../ui/inputs/MultiLevelDropDown' -// import { AddIcon } from '../../../../icons/ExportCommonIcons' -// import RegularDropDown from '../../../../ui/inputs/RegularDropDown' -// import useChartStore from '../../../../../store/useChartStore' -// import axios from 'axios' - -// type Props = {} - -// const LineGrapInput = (props: Props) => { -// const [dropDowndata, setDropDownData] = useState({}) -// const [selections, setSelections] = useState>({}) -// const [selectedOption, setSelectedOption] = useState('1h') -// const { measurements, setMeasurements, updateDuration, duration } = useChartStore(); -// const iotApiUrl = process.env.REACT_APP_IOT_SOCKET_SERVER_URL; - -// const handleSelectDuration = (option: string) => { -// updateDuration(option); // Normalize for key matching -// }; - -// useEffect(() => { -// const fetchZoneData = async () => { -// try { -// const response = await axios.get(`http://${iotApiUrl}/getinput`); -// if (response.status === 200) { -// -// setDropDownData(response.data) -// } else { -// -// } -// } catch (error) { -// -// } -// }; -// fetchZoneData(); -// }, []); - -// useEffect(() => { -// -// }, [selections]) - -// const handleSelect = (inputKey: string, selectedData: { name: string, fields: string } | null) => { -// setSelections(prev => { -// if (selectedData === null) { -// const newSelections = { ...prev }; -// delete newSelections[inputKey]; -// return newSelections; -// } else { -// return { -// ...prev, -// [inputKey]: selectedData -// }; -// } -// }); -// }; - -// interface Measurement { -// name: string; -// fields: string; -// } - -// interface InputData { -// [key: string]: Measurement; -// } - -// const extractMeasurements = (input: InputData): Measurement[] => { -// return Object.values(input); -// }; - -// useEffect(() => { -// const measurementsData = extractMeasurements(selections); -// setMeasurements(measurementsData); -// }, [selections]); - -// return ( -// <> -//
-// {[...Array(6)].map((_, index) => { -// const inputKey = `input${index + 1}`; -// return ( -//
-//
Input {index + 1}
-//
-// handleSelect(inputKey, selectedData)} -// onUnselect={() => handleSelect(inputKey, null)} -// selectedValue={selections[inputKey]} -// /> -//
-// -//
-//
-//
-// ); -// })} -//
-//
-//
-//
duration
-//
-// -//
-//
-//
-// -// ) -// } - -// export default LineGrapInput - -import React, { useEffect, useState } from "react"; +import { useEffect, useState } from "react"; import MultiLevelDropdown from "../../../../ui/inputs/MultiLevelDropDown"; import { AddIcon } from "../../../../icons/ExportCommonIcons"; import RegularDropDown from "../../../../ui/inputs/RegularDropDown"; import useChartStore from "../../../../../store/visualization/useChartStore"; import { useSelectedZoneStore } from "../../../../../store/visualization/useZoneStore"; -import { useWidgetStore } from "../../../../../store/useWidgetStore"; +import { useWidgetStore } from "../../../../../store/ui/useWidgetStore"; import axios from "axios"; import RenameInput from "../../../../ui/inputs/RenameInput"; import { useParams } from "react-router-dom"; -import { useSocketStore } from "../../../../../store/builder/store"; import { getUserData } from "../../../../../functions/getUserData"; import { addingWidgets } from "../../../../../services/visulization/zone/addWidgets"; -import { useVersionContext } from "../../../../../modules/builder/version/versionContext"; import { getWidgetInputData } from "../../../../../services/visulization/zone/getWidgetInputData"; +import { useSceneContext } from "../../../../../modules/scene/sceneContext"; type Props = {}; const LineGrapInput = (props: Props) => { - const [widgetName, setWidgetName] = useState("Widget"); - const { setMeasurements, updateDuration, updateName } = useChartStore(); - const [duration, setDuration] = useState("1h"); - const [dropDowndata, setDropDownData] = useState({}); - const [selections, setSelections] = useState< - Record - >({}); - const { selectedZone } = useSelectedZoneStore(); - const { selectedChartId } = useWidgetStore(); - const iotApiUrl = process.env.REACT_APP_IOT_SOCKET_SERVER_URL; - const { userName, userId, organization, email } = getUserData(); - const [isLoading, setLoading] = useState(true); - const { projectId } = useParams(); - const { visualizationSocket } = useSocketStore(); - const { selectedVersionStore } = useVersionContext(); - const { selectedVersion } = selectedVersionStore(); + const [widgetName, setWidgetName] = useState("Widget"); + const { setMeasurements, updateDuration, updateName } = useChartStore(); + const [duration, setDuration] = useState("1h"); + const [dropDownData, setDropDownData] = useState({}); + const [selections, setSelections] = useState>({}); + const { selectedZone } = useSelectedZoneStore(); + const { selectedChartId } = useWidgetStore(); + const iotApiUrl = process.env.REACT_APP_IOT_SOCKET_SERVER_URL; + const { organization } = getUserData(); + const [isLoading, setIsLoading] = useState(true); + const { projectId } = useParams(); + const { versionStore } = useSceneContext(); + const { selectedVersion } = versionStore(); - useEffect(() => { - const fetchZoneData = async () => { - try { - setLoading(true); - const response = await axios.get(`http://${iotApiUrl}/floatinput`); - if (response.status === 200) { - // - setDropDownData(response.data); - setLoading(false); + useEffect(() => { + const fetchZoneData = async () => { + try { + setIsLoading(true); + const response = await axios.get(`http://${iotApiUrl}/floatinput`); + if (response.status === 200) { + setDropDownData(response.data); + setIsLoading(false); + } + } catch { + echo.error("Failed to fetch zone data"); + } + }; + fetchZoneData(); + }, []); + + useEffect(() => { + const fetchSavedInputes = async () => { + if (selectedChartId.id !== "") { + let response = await getWidgetInputData(selectedChartId.id, selectedZone.zoneUuid, projectId, selectedVersion?.versionId || "") + + if (response) { + setSelections(response.Datastructure.measurements); + setDuration(response.Datastructure.duration); + setWidgetName(response.widgetName); + } + } + }; + + fetchSavedInputes(); + }, [selectedChartId.id]); + + useEffect(() => { + setMeasurements(selections); + updateDuration(duration); + updateName(widgetName); + }, [selections, duration, widgetName]); + + const sendInputes = async ( + inputMeasurement: any, + inputDuration: any, + inputName: any + ) => { + let newWidget = { + id: selectedChartId.id, + panel: selectedChartId.panel, + widgetName: inputName, + Data: { + measurements: inputMeasurement, + duration: inputDuration, + } + } + + let response = await addingWidgets(selectedZone.zoneUuid, organization, newWidget, projectId, selectedVersion?.versionId || ""); + + if (response.message === "Widget updated successfully") { + + return true; } else { + return false; } - } catch (error) { - echo.error("Failed to fetch zone data"); - - } - }; - fetchZoneData(); - }, []); - - useEffect(() => { - const fetchSavedInputes = async () => { - if (selectedChartId.id !== "") { - let response = await getWidgetInputData(selectedChartId.id, selectedZone.zoneUuid, projectId, selectedVersion?.versionId || "") - - if (response) { - setSelections(response.Datastructure.measurements); - setDuration(response.Datastructure.duration); - setWidgetName(response.widgetName); - } - - } }; - fetchSavedInputes(); - }, [selectedChartId.id]); + const handleSelect = async ( + inputKey: string, + selectedData: { name: string; fields: string } | null + ) => { + const newSelections = { ...selections }; + if (selectedData === null) { + delete newSelections[inputKey]; + } else { + newSelections[inputKey] = selectedData; + } + if (await sendInputes(newSelections, duration, widgetName)) { + setSelections(newSelections); + } + }; - // Sync Zustand state when component mounts - useEffect(() => { - setMeasurements(selections); - updateDuration(duration); - updateName(widgetName); - }, [selections, duration, widgetName]); + const handleSelectDuration = async (option: string) => { + if (await sendInputes(selections, option, widgetName)) { + setDuration(option); + } + }; - const sendInputes = async ( - inputMeasurement: any, - inputDuration: any, - inputName: any - ) => { - // const userId = localStorage.getItem("userId"); - let newWidget = { - id: selectedChartId.id, - panel: selectedChartId.panel, - widgetName: inputName, - Data: { - measurements: inputMeasurement, - duration: inputDuration, - } - } + const handleNameChange = async (name: any) => { + if (await sendInputes(selections, duration, name)) { + setWidgetName(name); + } + }; - - let response = await addingWidgets(selectedZone.zoneUuid, organization, newWidget, projectId, selectedVersion?.versionId || ""); - - if (response.message === "Widget updated successfully") { - - return true; - } else { - - return false; - } - - }; - - const handleSelect = async ( - inputKey: string, - selectedData: { name: string; fields: string } | null - ) => { - // async() => { - const newSelections = { ...selections }; - if (selectedData === null) { - delete newSelections[inputKey]; - } else { - newSelections[inputKey] = selectedData; - } - // setMeasurements(newSelections); // Update Zustand store - // - if (await sendInputes(newSelections, duration, widgetName)) { - setSelections(newSelections); - } - // sendInputes(newSelections, duration); // Send data to server - // return newSelections; - // }; - }; - - const handleSelectDuration = async (option: string) => { - if (await sendInputes(selections, option, widgetName)) { - setDuration(option); - } - // setDuration(option); - }; - - const handleNameChange = async (name: any) => { - - - if (await sendInputes(selections, duration, name)) { - setWidgetName(name); - } - }; - - return ( - <> -
-
-
Title
- -
- {[...Array(4)].map((_, index) => { - const inputKey = `input${index + 1}`; - return ( -
-
Input {index + 1}
-
- - handleSelect(inputKey, selectedData) - } - onUnselect={() => handleSelect(inputKey, null)} - selectedValue={selections[inputKey]} // Load from Zustand - isLoading={isLoading} - allSelections={selections} - /> -
- + return ( + <> +
+
+
Title
+
-
+ {[...Array(4)].map((_, index) => { + const inputKey = `input${index + 1}`; + return ( +
+
Input {index + 1}
+
+ + handleSelect(inputKey, selectedData) + } + onUnselect={() => handleSelect(inputKey, null)} + selectedValue={selections[inputKey]} // Load from Zustand + isLoading={isLoading} + allSelections={selections} + /> +
+ +
+
+
+ ); + })}
- ); - })} -
-
-
-
Duration
-
- -
-
-
- - ); +
+
+
Duration
+
+ +
+
+
+ + ); }; export default LineGrapInput; diff --git a/app/src/components/layout/sidebarRight/visualization/IotInputCards/PieChartInput.tsx b/app/src/components/layout/sidebarRight/visualization/IotInputCards/PieChartInput.tsx index 26988aa..1e9c0de 100644 --- a/app/src/components/layout/sidebarRight/visualization/IotInputCards/PieChartInput.tsx +++ b/app/src/components/layout/sidebarRight/visualization/IotInputCards/PieChartInput.tsx @@ -1,199 +1,173 @@ -import React, { useEffect, useState } from "react"; +import { useEffect, useState } from "react"; import MultiLevelDropdown from "../../../../ui/inputs/MultiLevelDropDown"; import { AddIcon } from "../../../../icons/ExportCommonIcons"; import RegularDropDown from "../../../../ui/inputs/RegularDropDown"; import useChartStore from "../../../../../store/visualization/useChartStore"; import { useSelectedZoneStore } from "../../../../../store/visualization/useZoneStore"; -import { useWidgetStore } from "../../../../../store/useWidgetStore"; +import { useWidgetStore } from "../../../../../store/ui/useWidgetStore"; import axios from "axios"; import RenameInput from "../../../../ui/inputs/RenameInput"; import { useParams } from "react-router-dom"; -import { useSocketStore } from "../../../../../store/builder/store"; import { getUserData } from "../../../../../functions/getUserData"; import { addingWidgets } from "../../../../../services/visulization/zone/addWidgets"; -import { useVersionContext } from "../../../../../modules/builder/version/versionContext"; import { getWidgetInputData } from "../../../../../services/visulization/zone/getWidgetInputData"; +import { useSceneContext } from "../../../../../modules/scene/sceneContext"; type Props = {}; const PieChartInput = (props: Props) => { - const [widgetName, setWidgetName] = useState("Widget"); - const { setMeasurements, updateDuration, updateName } = useChartStore(); - const [duration, setDuration] = useState("1h"); - const [dropDowndata, setDropDownData] = useState({}); - const [selections, setSelections] = useState< - Record - >({}); - const { selectedZone } = useSelectedZoneStore(); - const { selectedChartId } = useWidgetStore(); - const iotApiUrl = process.env.REACT_APP_IOT_SOCKET_SERVER_URL; - const { userName, userId, organization, email } = getUserData(); - const [isLoading, setLoading] = useState(true); - const { projectId } = useParams(); - const { visualizationSocket } = useSocketStore(); - const { selectedVersionStore } = useVersionContext(); - const { selectedVersion } = selectedVersionStore(); + const [widgetName, setWidgetName] = useState("Widget"); + const { setMeasurements, updateDuration, updateName } = useChartStore(); + const [duration, setDuration] = useState("1h"); + const [dropDownData, setDropDownData] = useState({}); + const [selections, setSelections] = useState>({}); + const { selectedZone } = useSelectedZoneStore(); + const { selectedChartId } = useWidgetStore(); + const iotApiUrl = process.env.REACT_APP_IOT_SOCKET_SERVER_URL; + const { organization } = getUserData(); + const [isLoading, setIsLoading] = useState(true); + const { projectId } = useParams(); + const { versionStore } = useSceneContext(); + const { selectedVersion } = versionStore(); - useEffect(() => { - const fetchZoneData = async () => { - try { - setLoading(true); - const response = await axios.get(`http://${iotApiUrl}/floatinput`); - if (response.status === 200) { - // - setDropDownData(response.data); - setLoading(false); + useEffect(() => { + const fetchZoneData = async () => { + try { + setIsLoading(true); + const response = await axios.get(`http://${iotApiUrl}/floatinput`); + if (response.status === 200) { + setDropDownData(response.data); + setIsLoading(false); + } + } catch { + echo.error("Failed to fetch zone data"); + } + }; + fetchZoneData(); + }, []); + + useEffect(() => { + const fetchSavedInputes = async () => { + if (selectedChartId.id !== "") { + let response = await getWidgetInputData(selectedChartId.id, selectedZone.zoneUuid, projectId, selectedVersion?.versionId || "") + + if (response) { + setSelections(response.Datastructure.measurements); + setDuration(response.Datastructure.duration); + setWidgetName(response.widgetName); + } + } + }; + + fetchSavedInputes(); + }, [selectedChartId.id]); + + useEffect(() => { + setMeasurements(selections); + updateDuration(duration); + updateName(widgetName); + }, [selections, duration, widgetName]); + + const sendInputes = async ( + inputMeasurement: any, + inputDuration: any, + inputName: any + ) => { + let newWidget = { + id: selectedChartId.id, + panel: selectedChartId.panel, + widgetName: inputName, + Data: { + measurements: inputMeasurement, + duration: inputDuration, + }, + } + + let response = await addingWidgets(selectedZone.zoneUuid, organization, newWidget, projectId, selectedVersion?.versionId || ""); + + if (response.message === "Widget updated successfully") { + return true; } else { - + return false; } - } catch (error) { - echo.error("Failed to fetch zone data"); - - } - }; - fetchZoneData(); - }, []); - - useEffect(() => { - const fetchSavedInputes = async () => { - if (selectedChartId.id !== "") { - let response = await getWidgetInputData(selectedChartId.id, selectedZone.zoneUuid, projectId, selectedVersion?.versionId || "") - - if (response) { - setSelections(response.Datastructure.measurements); - setDuration(response.Datastructure.duration); - setWidgetName(response.widgetName); - } - - } }; - fetchSavedInputes(); - }, [selectedChartId.id]); + const handleSelect = async ( + inputKey: string, + selectedData: { name: string; fields: string } | null + ) => { + const newSelections = { ...selections }; + if (selectedData === null) { + delete newSelections[inputKey]; + } else { + newSelections[inputKey] = selectedData; + } + if (await sendInputes(newSelections, duration, widgetName)) { + setSelections(newSelections); + } + }; - // Sync Zustand state when component mounts - useEffect(() => { - setMeasurements(selections); - updateDuration(duration); - updateName(widgetName); - }, [selections, duration, widgetName]); + const handleSelectDuration = async (option: string) => { + if (await sendInputes(selections, option, widgetName)) { + setDuration(option); + } + }; - const sendInputes = async ( - inputMeasurement: any, - inputDuration: any, - inputName: any - ) => { + const handleNameChange = async (name: any) => { + if (await sendInputes(selections, duration, name)) { + setWidgetName(name); + } + }; - // const userId = localStorage.getItem("userId"); - let newWidget = { - id: selectedChartId.id, - panel: selectedChartId.panel, - widgetName: inputName, - Data: { - measurements: inputMeasurement, - duration: inputDuration, - }, - } - - - let response = await addingWidgets(selectedZone.zoneUuid, organization, newWidget, projectId, selectedVersion?.versionId || ""); - - if (response.message === "Widget updated successfully") { - - return true; - } else { - - - return false; - } - - }; - - const handleSelect = async ( - inputKey: string, - selectedData: { name: string; fields: string } | null - ) => { - // async() => { - const newSelections = { ...selections }; - if (selectedData === null) { - delete newSelections[inputKey]; - } else { - newSelections[inputKey] = selectedData; - } - // setMeasurements(newSelections); // Update Zustand store - // - if (await sendInputes(newSelections, duration, widgetName)) { - setSelections(newSelections); - } - // sendInputes(newSelections, duration); // Send data to server - // return newSelections; - // }; - }; - - const handleSelectDuration = async (option: string) => { - if (await sendInputes(selections, option, widgetName)) { - setDuration(option); - } - // setDuration(option); - }; - - const handleNameChange = async (name: any) => { - - - if (await sendInputes(selections, duration, name)) { - setWidgetName(name); - } - }; - - return ( - <> -
-
-
Title
- -
- {[...Array(2)].map((_, index) => { - const inputKey = `input${index + 1}`; - return ( -
-
Input {index + 1}
-
- - handleSelect(inputKey, selectedData) - } - onUnselect={() => handleSelect(inputKey, null)} - selectedValue={selections[inputKey]} // Load from Zustand - isLoading={isLoading} - allSelections={selections} - /> -
- + return ( + <> +
+
+
Title
+
-
+ {[...Array(2)].map((_, index) => { + const inputKey = `input${index + 1}`; + return ( +
+
Input {index + 1}
+
+ + handleSelect(inputKey, selectedData) + } + onUnselect={() => handleSelect(inputKey, null)} + selectedValue={selections[inputKey]} // Load from Zustand + isLoading={isLoading} + allSelections={selections} + /> +
+ +
+
+
+ ); + })}
- ); - })} -
-
-
-
Duration
-
- -
-
-
- - ); +
+
+
Duration
+
+ +
+
+
+ + ); }; export default PieChartInput; diff --git a/app/src/components/layout/sidebarRight/visualization/IotInputCards/Progress1Input.tsx b/app/src/components/layout/sidebarRight/visualization/IotInputCards/Progress1Input.tsx index 6854848..b6c6fba 100644 --- a/app/src/components/layout/sidebarRight/visualization/IotInputCards/Progress1Input.tsx +++ b/app/src/components/layout/sidebarRight/visualization/IotInputCards/Progress1Input.tsx @@ -1,177 +1,157 @@ -import React, { useEffect, useState } from "react"; +import { useEffect, useState } from "react"; import MultiLevelDropdown from "../../../../ui/inputs/MultiLevelDropDown"; import { AddIcon } from "../../../../icons/ExportCommonIcons"; -import RegularDropDown from "../../../../ui/inputs/RegularDropDown"; import useChartStore from "../../../../../store/visualization/useChartStore"; import { useSelectedZoneStore } from "../../../../../store/visualization/useZoneStore"; -import { useWidgetStore } from "../../../../../store/useWidgetStore"; +import { useWidgetStore } from "../../../../../store/ui/useWidgetStore"; import axios from "axios"; import RenameInput from "../../../../ui/inputs/RenameInput"; import { useParams } from "react-router-dom"; -import { useSocketStore } from "../../../../../store/builder/store"; import { getUserData } from "../../../../../functions/getUserData"; import { addingWidgets } from "../../../../../services/visulization/zone/addWidgets"; -import { useVersionContext } from "../../../../../modules/builder/version/versionContext"; import { getWidgetInputData } from "../../../../../services/visulization/zone/getWidgetInputData"; +import { useSceneContext } from "../../../../../modules/scene/sceneContext"; type Props = {}; const Progress1Input = (props: Props) => { - const [widgetName, setWidgetName] = useState("Widget"); - const { setMeasurements, updateDuration, updateName } = useChartStore(); - const [duration, setDuration] = useState("1h"); - const [dropDowndata, setDropDownData] = useState({}); - const [selections, setSelections] = useState< - Record - >({}); - const { selectedZone } = useSelectedZoneStore(); - const { selectedChartId } = useWidgetStore(); - const iotApiUrl = process.env.REACT_APP_IOT_SOCKET_SERVER_URL; - const { userName, userId, organization, email } = getUserData(); - const [isLoading, setLoading] = useState(true); - const { projectId } = useParams(); - const { visualizationSocket } = useSocketStore(); - const { selectedVersionStore } = useVersionContext(); - const { selectedVersion } = selectedVersionStore(); + const [widgetName, setWidgetName] = useState("Widget"); + const { setMeasurements, updateDuration, updateName } = useChartStore(); + const [duration, setDuration] = useState("1h"); + const [dropDownData, setDropDownData] = useState({}); + const [selections, setSelections] = useState>({}); + const { selectedZone } = useSelectedZoneStore(); + const { selectedChartId } = useWidgetStore(); + const iotApiUrl = process.env.REACT_APP_IOT_SOCKET_SERVER_URL; + const { organization } = getUserData(); + const [isLoading, setIsLoading] = useState(true); + const { projectId } = useParams(); + const { versionStore } = useSceneContext(); + const { selectedVersion } = versionStore(); - useEffect(() => { - const fetchZoneData = async () => { - try { - setLoading(true); - const response = await axios.get(`http://${iotApiUrl}/floatinput`); - if (response.status === 200) { - // - setDropDownData(response.data); - setLoading(false); + useEffect(() => { + const fetchZoneData = async () => { + try { + setIsLoading(true); + const response = await axios.get(`http://${iotApiUrl}/floatinput`); + if (response.status === 200) { + setDropDownData(response.data); + setIsLoading(false); + } + } catch { + echo.error("Failed to fetch zone data"); + } + }; + fetchZoneData(); + }, []); + + useEffect(() => { + const fetchSavedInputes = async () => { + if (selectedChartId.id !== "") { + let response = await getWidgetInputData(selectedChartId.id, selectedZone.zoneUuid, projectId, selectedVersion?.versionId || "") + if (response) { + setSelections(response.Datastructure.measurements); + setDuration(response.Datastructure.duration); + setWidgetName(response.widgetName); + } + } + }; + + fetchSavedInputes(); + }, [selectedChartId.id]); + + useEffect(() => { + setMeasurements(selections); + updateDuration(duration); + updateName(widgetName); + }, [selections, duration, widgetName]); + + const sendInputes = async ( + inputMeasurement: any, + inputDuration: any, + inputName: any + ) => { + let newWidget = { + id: selectedChartId.id, + panel: selectedChartId.panel, + widgetName: inputName, + Data: { + measurements: inputMeasurement, + duration: inputDuration, + }, + } + + let response = await addingWidgets(selectedZone.zoneUuid, organization, newWidget, projectId, selectedVersion?.versionId || ""); + + if (response.message === "Widget updated successfully") { + return true; } else { - + return false; } - } catch (error) { - echo.error("Failed to fetch zone data"); - - } - }; - fetchZoneData(); - }, []); - - useEffect(() => { - const fetchSavedInputes = async () => { - if (selectedChartId.id !== "") { - let response = await getWidgetInputData(selectedChartId.id, selectedZone.zoneUuid, projectId, selectedVersion?.versionId || "") - - if (response) { - setSelections(response.Datastructure.measurements); - setDuration(response.Datastructure.duration); - setWidgetName(response.widgetName); - } - - } }; - fetchSavedInputes(); - }, [selectedChartId.id]); + const handleSelect = async ( + inputKey: string, + selectedData: { name: string; fields: string } | null + ) => { + const newSelections = { ...selections }; + if (selectedData === null) { + delete newSelections[inputKey]; + } else { + newSelections[inputKey] = selectedData; + } + if (await sendInputes(newSelections, duration, widgetName)) { + setSelections(newSelections); + } + }; - // Sync Zustand state when component mounts - useEffect(() => { - setMeasurements(selections); - updateDuration(duration); - updateName(widgetName); - }, [selections, duration, widgetName]); + const handleSelectDuration = async (option: string) => { + if (await sendInputes(selections, option, widgetName)) { + setDuration(option); + } + }; - const sendInputes = async ( - inputMeasurement: any, - inputDuration: any, - inputName: any - ) => { - // const userId = localStorage.getItem("userId"); - let newWidget = { - id: selectedChartId.id, - panel: selectedChartId.panel, - widgetName: inputName, - Data: { - measurements: inputMeasurement, - duration: inputDuration, - }, - } + const handleNameChange = async (name: any) => { + if (await sendInputes(selections, duration, name)) { + setWidgetName(name); + } + }; - let response = await addingWidgets(selectedZone.zoneUuid, organization, newWidget, projectId, selectedVersion?.versionId || ""); - - if (response.message === "Widget updated successfully") { - - return true; - } else { - - - return false; - } - - }; - - const handleSelect = async ( - inputKey: string, - selectedData: { name: string; fields: string } | null - ) => { - // async() => { - const newSelections = { ...selections }; - if (selectedData === null) { - delete newSelections[inputKey]; - } else { - newSelections[inputKey] = selectedData; - } - // setMeasurements(newSelections); // Update Zustand store - // - if (await sendInputes(newSelections, duration, widgetName)) { - setSelections(newSelections); - } - }; - - const handleSelectDuration = async (option: string) => { - if (await sendInputes(selections, option, widgetName)) { - setDuration(option); - } - }; - - const handleNameChange = async (name: any) => { - if (await sendInputes(selections, duration, name)) { - setWidgetName(name); - } - }; - - return ( - <> -
-
-
Title
- -
- {[...Array(1)].map((_, index) => { - const inputKey = `input${index + 1}`; - return ( -
-
Input {index + 1}
-
- - handleSelect(inputKey, selectedData) - } - onUnselect={() => handleSelect(inputKey, null)} - selectedValue={selections[inputKey]} // Load from Zustand - isLoading={isLoading} - allSelections={selections} - /> -
- + return ( + <> +
+
+
Title
+
-
+ {[...Array(1)].map((_, index) => { + const inputKey = `input${index + 1}`; + return ( +
+
Input {index + 1}
+
+ + handleSelect(inputKey, selectedData) + } + onUnselect={() => handleSelect(inputKey, null)} + selectedValue={selections[inputKey]} // Load from Zustand + isLoading={isLoading} + allSelections={selections} + /> +
+ +
+
+
+ ); + })}
- ); - })} -
- {/*
+ {/*
Duration
@@ -184,8 +164,8 @@ const Progress1Input = (props: Props) => {
*/} - - ); + + ); }; export default Progress1Input; diff --git a/app/src/components/layout/sidebarRight/visualization/IotInputCards/Progress2Input.tsx b/app/src/components/layout/sidebarRight/visualization/IotInputCards/Progress2Input.tsx index 2482346..24576fd 100644 --- a/app/src/components/layout/sidebarRight/visualization/IotInputCards/Progress2Input.tsx +++ b/app/src/components/layout/sidebarRight/visualization/IotInputCards/Progress2Input.tsx @@ -1,177 +1,157 @@ -import React, { useEffect, useState } from "react"; +import { useEffect, useState } from "react"; import MultiLevelDropdown from "../../../../ui/inputs/MultiLevelDropDown"; import { AddIcon } from "../../../../icons/ExportCommonIcons"; -import RegularDropDown from "../../../../ui/inputs/RegularDropDown"; import useChartStore from "../../../../../store/visualization/useChartStore"; import { useSelectedZoneStore } from "../../../../../store/visualization/useZoneStore"; -import { useWidgetStore } from "../../../../../store/useWidgetStore"; +import { useWidgetStore } from "../../../../../store/ui/useWidgetStore"; import axios from "axios"; import RenameInput from "../../../../ui/inputs/RenameInput"; import { useParams } from "react-router-dom"; -import { useSocketStore } from "../../../../../store/builder/store"; import { getUserData } from "../../../../../functions/getUserData"; import { addingWidgets } from "../../../../../services/visulization/zone/addWidgets"; -import { useVersionContext } from "../../../../../modules/builder/version/versionContext"; import { getWidgetInputData } from "../../../../../services/visulization/zone/getWidgetInputData"; +import { useSceneContext } from "../../../../../modules/scene/sceneContext"; type Props = {}; const Progress2Input = (props: Props) => { - const [widgetName, setWidgetName] = useState("Widget"); - const { setMeasurements, updateDuration, updateName } = useChartStore(); - const [duration, setDuration] = useState("1h"); - const [dropDowndata, setDropDownData] = useState({}); - const [selections, setSelections] = useState< - Record - >({}); - const { selectedZone } = useSelectedZoneStore(); - const { selectedChartId } = useWidgetStore(); - const iotApiUrl = process.env.REACT_APP_IOT_SOCKET_SERVER_URL; - const { userName, userId, organization, email } = getUserData(); - const [isLoading, setLoading] = useState(true); - const { projectId } = useParams(); - const { visualizationSocket } = useSocketStore(); - const { selectedVersionStore } = useVersionContext(); - const { selectedVersion } = selectedVersionStore(); + const [widgetName, setWidgetName] = useState("Widget"); + const { setMeasurements, updateDuration, updateName } = useChartStore(); + const [duration, setDuration] = useState("1h"); + const [dropDownData, setDropDownData] = useState({}); + const [selections, setSelections] = useState>({}); + const { selectedZone } = useSelectedZoneStore(); + const { selectedChartId } = useWidgetStore(); + const iotApiUrl = process.env.REACT_APP_IOT_SOCKET_SERVER_URL; + const { organization } = getUserData(); + const [isLoading, setIsLoading] = useState(true); + const { projectId } = useParams(); + const { versionStore } = useSceneContext(); + const { selectedVersion } = versionStore(); - useEffect(() => { - const fetchZoneData = async () => { - try { - setLoading(true); - const response = await axios.get(`http://${iotApiUrl}/floatinput`); - if (response.status === 200) { - // - setDropDownData(response.data); - setLoading(false); + useEffect(() => { + const fetchZoneData = async () => { + try { + setIsLoading(true); + const response = await axios.get(`http://${iotApiUrl}/floatinput`); + if (response.status === 200) { + setDropDownData(response.data); + setIsLoading(false); + } + } catch { + echo.error("Failed to fetch zone data"); + } + }; + fetchZoneData(); + }, []); + + useEffect(() => { + const fetchSavedInputes = async () => { + if (selectedChartId.id !== "") { + let response = await getWidgetInputData(selectedChartId.id, selectedZone.zoneUuid, projectId, selectedVersion?.versionId || "") + if (response) { + setSelections(response.Datastructure.measurements); + setDuration(response.Datastructure.duration); + setWidgetName(response.widgetName); + } + } + }; + + fetchSavedInputes(); + }, [selectedChartId.id]); + + useEffect(() => { + setMeasurements(selections); + updateDuration(duration); + updateName(widgetName); + }, [selections, duration, widgetName]); + + const sendInputes = async ( + inputMeasurement: any, + inputDuration: any, + inputName: any + ) => { + let newWidget = { + id: selectedChartId.id, + panel: selectedChartId.panel, + widgetName: inputName, + Data: { + measurements: inputMeasurement, + duration: inputDuration, + } + } + + let response = await addingWidgets(selectedZone.zoneUuid, organization, newWidget, projectId, selectedVersion?.versionId || ""); + + if (response.message === "Widget updated successfully") { + return true; } else { - + return false; } - } catch (error) { - echo.error("Failed to fetch zone data"); - - } - }; - fetchZoneData(); - }, []); - - useEffect(() => { - const fetchSavedInputes = async () => { - if (selectedChartId.id !== "") { - let response = await getWidgetInputData(selectedChartId.id, selectedZone.zoneUuid, projectId, selectedVersion?.versionId || "") - - if (response) { - setSelections(response.Datastructure.measurements); - setDuration(response.Datastructure.duration); - setWidgetName(response.widgetName); - } - - } }; - fetchSavedInputes(); - }, [selectedChartId.id]); + const handleSelect = async ( + inputKey: string, + selectedData: { name: string; fields: string } | null + ) => { + const newSelections = { ...selections }; + if (selectedData === null) { + delete newSelections[inputKey]; + } else { + newSelections[inputKey] = selectedData; + } + if (await sendInputes(newSelections, duration, widgetName)) { + setSelections(newSelections); + } + }; - // Sync Zustand state when component mounts - useEffect(() => { - setMeasurements(selections); - updateDuration(duration); - updateName(widgetName); - }, [selections, duration, widgetName]); + const handleSelectDuration = async (option: string) => { + if (await sendInputes(selections, option, widgetName)) { + setDuration(option); + } + }; - const sendInputes = async ( - inputMeasurement: any, - inputDuration: any, - inputName: any - ) => { - // const userId = localStorage.getItem("userId"); - let newWidget = { - id: selectedChartId.id, - panel: selectedChartId.panel, - widgetName: inputName, - Data: { - measurements: inputMeasurement, - duration: inputDuration, - } - } + const handleNameChange = async (name: any) => { + if (await sendInputes(selections, duration, name)) { + setWidgetName(name); + } + }; - let response = await addingWidgets(selectedZone.zoneUuid, organization, newWidget, projectId, selectedVersion?.versionId || ""); - - if (response.message === "Widget updated successfully") { - - return true; - } else { - - - return false; - } - - }; - - const handleSelect = async ( - inputKey: string, - selectedData: { name: string; fields: string } | null - ) => { - // async() => { - const newSelections = { ...selections }; - if (selectedData === null) { - delete newSelections[inputKey]; - } else { - newSelections[inputKey] = selectedData; - } - // setMeasurements(newSelections); // Update Zustand store - // - if (await sendInputes(newSelections, duration, widgetName)) { - setSelections(newSelections); - } - }; - - const handleSelectDuration = async (option: string) => { - if (await sendInputes(selections, option, widgetName)) { - setDuration(option); - } - }; - - const handleNameChange = async (name: any) => { - if (await sendInputes(selections, duration, name)) { - setWidgetName(name); - } - }; - - return ( - <> -
-
-
Title
- -
- {[...Array(2)].map((_, index) => { - const inputKey = `input${index + 1}`; - return ( -
-
Input {index + 1}
-
- - handleSelect(inputKey, selectedData) - } - onUnselect={() => handleSelect(inputKey, null)} - selectedValue={selections[inputKey]} // Load from Zustand - isLoading={isLoading} - allSelections={selections} - /> -
- + return ( + <> +
+
+
Title
+
-
+ {[...Array(2)].map((_, index) => { + const inputKey = `input${index + 1}`; + return ( +
+
Input {index + 1}
+
+ + handleSelect(inputKey, selectedData) + } + onUnselect={() => handleSelect(inputKey, null)} + selectedValue={selections[inputKey]} // Load from Zustand + isLoading={isLoading} + allSelections={selections} + /> +
+ +
+
+
+ ); + })}
- ); - })} -
- {/*
+ {/*
Duration
@@ -184,8 +164,8 @@ const Progress2Input = (props: Props) => {
*/} - - ); + + ); }; export default Progress2Input; diff --git a/app/src/components/layout/sidebarRight/visualization/IotInputCards/WarehouseThroughputInputComponent.tsx b/app/src/components/layout/sidebarRight/visualization/IotInputCards/WarehouseThroughputInputComponent.tsx index e82aa58..d360d04 100644 --- a/app/src/components/layout/sidebarRight/visualization/IotInputCards/WarehouseThroughputInputComponent.tsx +++ b/app/src/components/layout/sidebarRight/visualization/IotInputCards/WarehouseThroughputInputComponent.tsx @@ -1,193 +1,174 @@ -import React, { useEffect, useState } from "react"; +import { useEffect, useState } from "react"; import MultiLevelDropdown from "../../../../ui/inputs/MultiLevelDropDown"; import { AddIcon } from "../../../../icons/ExportCommonIcons"; import RegularDropDown from "../../../../ui/inputs/RegularDropDown"; import useChartStore from "../../../../../store/visualization/useChartStore"; import { useSelectedZoneStore } from "../../../../../store/visualization/useZoneStore"; -import { useWidgetStore } from "../../../../../store/useWidgetStore"; +import { useWidgetStore } from "../../../../../store/ui/useWidgetStore"; import axios from "axios"; import RenameInput from "../../../../ui/inputs/RenameInput"; import { getUserData } from "../../../../../functions/getUserData"; import { addingFloatingWidgets } from "../../../../../services/visulization/zone/addFloatingWidgets"; import { useParams } from "react-router-dom"; -import { useVersionContext } from "../../../../../modules/builder/version/versionContext"; import { getFloatingWidgetInput } from "../../../../../services/visulization/zone/getFloatingWidgetInput"; +import { useSceneContext } from "../../../../../modules/scene/sceneContext"; type Props = {}; const WarehouseThroughputInputComponent = (props: Props) => { - const [widgetName, setWidgetName] = useState("Widget"); - const { setFlotingMeasurements, updateFlotingDuration, updateHeader } = - useChartStore(); - const [duration, setDuration] = useState("1h"); - const [dropDowndata, setDropDownData] = useState({}); - const [selections, setSelections] = useState< - Record - >({}); - const { selectedZone } = useSelectedZoneStore(); - const { selectedChartId } = useWidgetStore(); - const iotApiUrl = process.env.REACT_APP_IOT_SOCKET_SERVER_URL; - const { userName, userId, organization, email } = getUserData(); - const [isLoading, setLoading] = useState(true); - const { projectId } = useParams(); - const { selectedVersionStore } = useVersionContext(); - const { selectedVersion } = selectedVersionStore(); + const [widgetName, setWidgetName] = useState("Widget"); + const { setFlotingMeasurements, updateFlotingDuration, updateHeader } = useChartStore(); + const [duration, setDuration] = useState("1h"); + const [dropDownData, setDropDownData] = useState({}); + const [selections, setSelections] = useState>({}); + const { selectedZone } = useSelectedZoneStore(); + const { selectedChartId } = useWidgetStore(); + const iotApiUrl = process.env.REACT_APP_IOT_SOCKET_SERVER_URL; + const { organization } = getUserData(); + const [isLoading, setIsLoading] = useState(true); + const { projectId } = useParams(); + const { versionStore } = useSceneContext(); + const { selectedVersion } = versionStore(); - useEffect(() => { - const fetchZoneData = async () => { - try { - setLoading(true); - const response = await axios.get(`http://${iotApiUrl}/floatinput`); - if (response.status === 200) { - // - setDropDownData(response.data); - setLoading(false); + useEffect(() => { + const fetchZoneData = async () => { + try { + setIsLoading(true); + const response = await axios.get(`http://${iotApiUrl}/floatinput`); + if (response.status === 200) { + setDropDownData(response.data); + setIsLoading(false); + } + } catch { + echo.error("Failed to fetch zone data"); + } + }; + fetchZoneData(); + }, []); + + useEffect(() => { + const fetchSavedInputes = async () => { + if (selectedChartId.id !== "") { + let response = await getFloatingWidgetInput(selectedChartId.id, organization, projectId, selectedVersion?.versionId || "") + + if (response) { + setSelections(response.Data.Datastructure.measurements); + setDuration(response.Data.Datastructure.duration); + setWidgetName(response.Data.header); + } + } + }; + + fetchSavedInputes(); + }, [selectedChartId.id]); + + useEffect(() => { + setFlotingMeasurements(selections); + updateFlotingDuration(duration); + updateHeader(widgetName); + }, [selections, duration, widgetName]); + + const sendInputes = async ( + inputMeasurement: any, + inputDuration: any, + inputName: any + ) => { + + let newWidget = { + id: selectedChartId.id, + header: inputName, + Data: { + measurements: inputMeasurement, + duration: inputDuration, + }, + } + + const response = await addingFloatingWidgets(selectedZone.zoneUuid, organization, newWidget, projectId, selectedVersion?.versionId || "") + + if (response.message === "Widget updated successfully") { + return true; } else { - // + return false; } - } catch (error) { - echo.error("Failed to fetch zone data"); - - } - }; - fetchZoneData(); - }, []); - useEffect(() => { - const fetchSavedInputes = async () => { - if (selectedChartId.id !== "") { - let response = await getFloatingWidgetInput(selectedChartId.id, organization,projectId,selectedVersion?.versionId||"") - - if (response) { - setSelections(response.Data.Datastructure.measurements); - setDuration(response.Data.Datastructure.duration); - setWidgetName(response.Data.header); - } - - } }; - fetchSavedInputes(); - }, [selectedChartId.id]); + const handleSelect = async ( + inputKey: string, + selectedData: { name: string; fields: string } | null + ) => { + const newSelections = { ...selections }; + if (selectedData === null) { + delete newSelections[inputKey]; + } else { + newSelections[inputKey] = selectedData; + } + if (await sendInputes(newSelections, duration, widgetName)) { + setSelections(newSelections); + } + }; - // Sync Zustand state when component mounts - useEffect(() => { - setFlotingMeasurements(selections); - updateFlotingDuration(duration); - updateHeader(widgetName); - }, [selections, duration, widgetName]); + const handleSelectDuration = async (option: string) => { + if (await sendInputes(selections, option, widgetName)) { + setDuration(option); + } + }; - const sendInputes = async ( - inputMeasurement: any, - inputDuration: any, - inputName: any - ) => { + const handleNameChange = async (name: any) => { + if (await sendInputes(selections, duration, name)) { + setWidgetName(name); + } + }; - let newWidget = { - id: selectedChartId.id, - header: inputName, - Data: { - measurements: inputMeasurement, - duration: inputDuration, - }, - } - - const response = await addingFloatingWidgets(selectedZone.zoneUuid, organization, newWidget, projectId, selectedVersion?.versionId || "") - // - if (response.message === "Widget updated successfully") { - return true; - } else { - // - return false; - } - - }; - - const handleSelect = async ( - inputKey: string, - selectedData: { name: string; fields: string } | null - ) => { - // async() => { - const newSelections = { ...selections }; - if (selectedData === null) { - delete newSelections[inputKey]; - } else { - newSelections[inputKey] = selectedData; - } - // setMeasurements(newSelections); // Update Zustand store - // - if (await sendInputes(newSelections, duration, widgetName)) { - setSelections(newSelections); - } - // sendInputes(newSelections, duration); // Send data to server - // return newSelections; - // }; - }; - - const handleSelectDuration = async (option: string) => { - if (await sendInputes(selections, option, widgetName)) { - setDuration(option); - } - // setDuration(option); - }; - - const handleNameChange = async (name: any) => { - // - - if (await sendInputes(selections, duration, name)) { - setWidgetName(name); - } - }; - - return ( - <> -
-
-
Title
- -
- {[...Array(1)].map((_, index) => { - const inputKey = `input${index + 1}`; - return ( -
-
Input {index + 1}
-
- - handleSelect(inputKey, selectedData) - } - onUnselect={() => handleSelect(inputKey, null)} - selectedValue={selections[inputKey]} // Load from Zustand - isLoading={isLoading} - allSelections={selections} - /> -
- + return ( + <> +
+
+
Title
+
-
+ {[...Array(1)].map((_, index) => { + const inputKey = `input${index + 1}`; + return ( +
+
Input {index + 1}
+
+ + handleSelect(inputKey, selectedData) + } + onUnselect={() => handleSelect(inputKey, null)} + selectedValue={selections[inputKey]} // Load from Zustand + isLoading={isLoading} + allSelections={selections} + /> +
+ +
+
+
+ ); + })}
- ); - })} -
-
-
-
Duration
-
- -
-
-
- - ); +
+
+
Duration
+
+ +
+
+
+ + ); }; export default WarehouseThroughputInputComponent; diff --git a/app/src/components/layout/sidebarRight/visualization/IotInputCards/Widget2InputCard3D.tsx b/app/src/components/layout/sidebarRight/visualization/IotInputCards/Widget2InputCard3D.tsx index 0889809..868df41 100644 --- a/app/src/components/layout/sidebarRight/visualization/IotInputCards/Widget2InputCard3D.tsx +++ b/app/src/components/layout/sidebarRight/visualization/IotInputCards/Widget2InputCard3D.tsx @@ -1,212 +1,144 @@ -import React, { useEffect, useState } from "react"; +import { useEffect, useState } from "react"; import MultiLevelDropdown from "../../../../ui/inputs/MultiLevelDropDown"; import { AddIcon } from "../../../../icons/ExportCommonIcons"; -import RegularDropDown from "../../../../ui/inputs/RegularDropDown"; import useChartStore from "../../../../../store/visualization/useChartStore"; import { useSelectedZoneStore } from "../../../../../store/visualization/useZoneStore"; -import { useWidgetStore } from "../../../../../store/useWidgetStore"; +import { useWidgetStore } from "../../../../../store/ui/useWidgetStore"; import axios from "axios"; import RenameInput from "../../../../ui/inputs/RenameInput"; import { getUserData } from "../../../../../functions/getUserData"; import { get3dWidgetInput } from "../../../../../services/visulization/zone/get3dWidgetInput"; import { adding3dWidgets } from "../../../../../services/visulization/zone/add3dWidget"; -import { useVersionContext } from "../../../../../modules/builder/version/versionContext"; import { useParams } from "react-router-dom"; +import { useSceneContext } from "../../../../../modules/scene/sceneContext"; type Props = {}; const Widget2InputCard3D = (props: Props) => { - const { selectedChartId } = useWidgetStore(); - const [widgetName, setWidgetName] = useState("untited"); - const { setMeasurements, updateDuration, updateName } = useChartStore(); - const [duration, setDuration] = useState("1h"); - const [dropDowndata, setDropDownData] = useState({}); - const [selections, setSelections] = useState< - Record - >({}); - const { selectedZone } = useSelectedZoneStore(); - const iotApiUrl = process.env.REACT_APP_IOT_SOCKET_SERVER_URL; - const { userName, userId, organization, email } = getUserData(); - const [isLoading, setLoading] = useState(true); - const { selectedVersionStore } = useVersionContext(); - const { selectedVersion } = selectedVersionStore(); - const { projectId } = useParams() + const { selectedChartId } = useWidgetStore(); + const [widgetName, setWidgetName] = useState("untited"); + const { setMeasurements, updateDuration, updateName } = useChartStore(); + const [duration, setDuration] = useState("1h"); + const [dropDownData, setDropDownData] = useState({}); + const [selections, setSelections] = useState>({}); + const { selectedZone } = useSelectedZoneStore(); + const iotApiUrl = process.env.REACT_APP_IOT_SOCKET_SERVER_URL; + const { organization } = getUserData(); + const [isLoading, setIsLoading] = useState(true); + const { versionStore } = useSceneContext(); + const { selectedVersion } = versionStore(); + const { projectId } = useParams(); - useEffect(() => { - const fetchZoneData = async () => { - try { - setLoading(true); - const response = await axios.get(`http://${iotApiUrl}/floatinput`); - if (response.status === 200) { - // - setDropDownData(response.data); - setLoading(false); + useEffect(() => { + const fetchZoneData = async () => { + try { + setIsLoading(true); + const response = await axios.get(`http://${iotApiUrl}/floatinput`); + if (response.status === 200) { + setDropDownData(response.data); + setIsLoading(false); + } + } catch { + echo.error("Failed to fetch zone data"); + } + }; + fetchZoneData(); + }, []); + + useEffect(() => { + const fetchSavedInputes = async () => { + if (selectedChartId.id !== "") { + let response = await get3dWidgetInput(selectedChartId.id, organization, projectId, selectedVersion?.versionId || ""); + + if (response) { + setSelections(response.Datastructure.measurements); + setDuration(response.Datastructure.duration); + setWidgetName(response.widgetName); + } + } + }; + + fetchSavedInputes(); + }, [selectedChartId.id]); + + useEffect(() => { + setMeasurements(selections); + updateDuration(duration); + updateName(widgetName); + }, [selections, duration, widgetName]); + + const sendInputes = async (inputMeasurement: any, inputDuration: any, inputName: any) => { + let newWidget = { + id: selectedChartId.id, + widgetName: inputName, + Data: { + measurements: inputMeasurement, + duration: inputDuration, + }, + }; + + let response = await adding3dWidgets(selectedZone.zoneUuid, organization, newWidget, projectId, selectedVersion?.versionId || ""); + + if (response.message === "widget update successfully") { + return true; } else { - // + return false; } - } catch (error) { - echo.error("Failed to fetch zone data"); - - } - }; - fetchZoneData(); - }, []); - - useEffect(() => { - const fetchSavedInputes = async () => { - if (selectedChartId.id !== "") { - let response = await get3dWidgetInput(selectedChartId.id, organization, projectId, selectedVersion?.versionId || "") - - if (response) { - setSelections(response.Datastructure.measurements); - setDuration(response.Datastructure.duration); - setWidgetName(response.widgetName); - } - - } }; - fetchSavedInputes(); - }, [selectedChartId.id]); + const handleSelect = async (inputKey: string, selectedData: { name: string; fields: string } | null) => { + const newSelections = { ...selections }; + if (selectedData === null) { + delete newSelections[inputKey]; + } else { + newSelections[inputKey] = selectedData; + } + if (await sendInputes(newSelections, duration, widgetName)) { + setSelections(newSelections); + } + }; - // Sync Zustand state when component mounts - useEffect(() => { - setMeasurements(selections); - updateDuration(duration); - updateName(widgetName); - }, [selections, duration, widgetName]); + const handleSelectDuration = async (option: string) => { + if (await sendInputes(selections, option, widgetName)) { + setDuration(option); + } + }; - const sendInputes = async ( - inputMeasurement: any, - inputDuration: any, - inputName: any - ) => { - let newWidget = { - id: selectedChartId.id, - widgetName: inputName, - Data: { - measurements: inputMeasurement, - duration: inputDuration, - }, - } + const handleNameChange = async (name: any) => { + if (await sendInputes(selections, duration, name)) { + setWidgetName(name); + } + }; - let response = await adding3dWidgets(selectedZone.zoneUuid, organization, newWidget, projectId, selectedVersion?.versionId || "") - - if (response.message === "widget update successfully") { - return true; - } else { - return false - } - // try { - // const response = await axios.post( - // `http://${process.env.REACT_APP_SERVER_REST_API_BASE_URL}/api/V1/widget3d/save`, - // { - // headers: { - // Authorization: "Bearer ", - // "Content-Type": "application/json", - // token: localStorage.getItem("token") || "", - // refresh_token: localStorage.getItem("refreshToken") || "", - // }, - // }, - // { - // organization, - // zoneUuid: selectedZone.zoneUuid, - // widget: { - // id: selectedChartId.id, - // widgetName: inputName, - // Data: { - // measurements: inputMeasurement, - // duration: inputDuration, - // }, - // }, - // projectId: projectId, - // versionId: selectedVersion?.versionId || "" - // } as any, - - // ); - // - // if (response.status === 200) { - // return true; - // } else { - // // - // return false; - // } - // } catch (error) { - // echo.error("Failed to send input"); - // - // return false; - // } - }; - - const handleSelect = async ( - inputKey: string, - selectedData: { name: string; fields: string } | null - ) => { - // async() => { - const newSelections = { ...selections }; - if (selectedData === null) { - delete newSelections[inputKey]; - } else { - newSelections[inputKey] = selectedData; - } - // setMeasurements(newSelections); // Update Zustand store - // - if (await sendInputes(newSelections, duration, widgetName)) { - setSelections(newSelections); - } - // sendInputes(newSelections, duration); // Send data to server - // return newSelections; - // }; - }; - - const handleSelectDuration = async (option: string) => { - if (await sendInputes(selections, option, widgetName)) { - setDuration(option); - } - // setDuration(option); - }; - - const handleNameChange = async (name: any) => { - // - - if (await sendInputes(selections, duration, name)) { - setWidgetName(name); - } - }; - - return ( - <> -
-
-
Title
- -
- {[...Array(2)].map((_, index) => { - const inputKey = `input${index + 1}`; - return ( -
-
Input {index + 1}
-
- - handleSelect(inputKey, selectedData) - } - onUnselect={() => handleSelect(inputKey, null)} - selectedValue={selections[inputKey]} // Load from Zustand - isLoading={isLoading} - allSelections={selections} - /> -
- -
-
+ return ( +
+
+
Title
+
- ); - })} -
- - ); + {[...Array(2)].map((_, index) => { + const inputKey = `input${index + 1}`; + return ( +
+
Input {index + 1}
+
+ handleSelect(inputKey, selectedData)} + onUnselect={() => handleSelect(inputKey, null)} + selectedValue={selections[inputKey]} // Load from Zustand + isLoading={isLoading} + allSelections={selections} + /> +
+ +
+
+
+ ); + })} +
+ ); }; export default Widget2InputCard3D; diff --git a/app/src/components/layout/sidebarRight/visualization/IotInputCards/Widget3InputCard3D.tsx b/app/src/components/layout/sidebarRight/visualization/IotInputCards/Widget3InputCard3D.tsx index a236d5a..33dac38 100644 --- a/app/src/components/layout/sidebarRight/visualization/IotInputCards/Widget3InputCard3D.tsx +++ b/app/src/components/layout/sidebarRight/visualization/IotInputCards/Widget3InputCard3D.tsx @@ -1,206 +1,142 @@ -import React, { useEffect, useState } from "react"; +import { useEffect, useState } from "react"; import MultiLevelDropdown from "../../../../ui/inputs/MultiLevelDropDown"; import { AddIcon } from "../../../../icons/ExportCommonIcons"; -import RegularDropDown from "../../../../ui/inputs/RegularDropDown"; import useChartStore from "../../../../../store/visualization/useChartStore"; import { useSelectedZoneStore } from "../../../../../store/visualization/useZoneStore"; -import { useWidgetStore } from "../../../../../store/useWidgetStore"; +import { useWidgetStore } from "../../../../../store/ui/useWidgetStore"; import axios from "axios"; import RenameInput from "../../../../ui/inputs/RenameInput"; import { getUserData } from "../../../../../functions/getUserData"; import { get3dWidgetInput } from "../../../../../services/visulization/zone/get3dWidgetInput"; -import { useVersionContext } from "../../../../../modules/builder/version/versionContext"; import { useParams } from "react-router-dom"; import { adding3dWidgets } from "../../../../../services/visulization/zone/add3dWidget"; +import { useSceneContext } from "../../../../../modules/scene/sceneContext"; const Widget3InputCard3D = () => { - const { selectedChartId } = useWidgetStore(); - const [widgetName, setWidgetName] = useState("untited"); - const { setMeasurements, updateDuration, updateName } = useChartStore(); - const [duration, setDuration] = useState("1h"); - const [dropDowndata, setDropDownData] = useState({}); - const [selections, setSelections] = useState< - Record - >({}); - const { selectedZone } = useSelectedZoneStore(); - const iotApiUrl = process.env.REACT_APP_IOT_SOCKET_SERVER_URL; - const { userName, userId, organization, email } = getUserData(); - const [isLoading, setLoading] = useState(true); - const { selectedVersionStore } = useVersionContext(); - const { selectedVersion } = selectedVersionStore(); - const { projectId } = useParams() + const { selectedChartId } = useWidgetStore(); + const [widgetName, setWidgetName] = useState("untited"); + const { setMeasurements, updateDuration, updateName } = useChartStore(); + const [duration, setDuration] = useState("1h"); + const [dropDownData, setDropDownData] = useState({}); + const [selections, setSelections] = useState>({}); + const { selectedZone } = useSelectedZoneStore(); + const iotApiUrl = process.env.REACT_APP_IOT_SOCKET_SERVER_URL; + const { organization } = getUserData(); + const [isLoading, setIsLoading] = useState(true); + const { versionStore } = useSceneContext(); + const { selectedVersion } = versionStore(); + const { projectId } = useParams(); - useEffect(() => { - const fetchZoneData = async () => { - try { - setLoading(true); - const response = await axios.get(`http://${iotApiUrl}/getinput`); - if (response.status === 200) { - // - setDropDownData(response.data); - setLoading(false); + useEffect(() => { + const fetchZoneData = async () => { + try { + setIsLoading(true); + const response = await axios.get(`http://${iotApiUrl}/getinput`); + if (response.status === 200) { + setDropDownData(response.data); + setIsLoading(false); + } + } catch { + echo.error("Failed to fetch zone data"); + } + }; + fetchZoneData(); + }, []); + + useEffect(() => { + const fetchSavedInputes = async () => { + if (selectedChartId.id !== "") { + let response = await get3dWidgetInput(selectedChartId.id, organization, projectId, selectedVersion?.versionId || ""); + + if (response) { + setSelections(response.Datastructure.measurements); + setDuration(response.Datastructure.duration); + setWidgetName(response.widgetName); + } + } + }; + + fetchSavedInputes(); + }, [selectedChartId.id]); + + useEffect(() => { + setMeasurements(selections); + updateDuration(duration); + updateName(widgetName); + }, [selections, duration, widgetName]); + + const sendInputes = async (inputMeasurement: any, inputDuration: any, inputName: any) => { + let newWidget = { + id: selectedChartId.id, + widgetName: inputName, + Data: { + measurements: inputMeasurement, + duration: inputDuration, + }, + }; + + let response = await adding3dWidgets(selectedZone.zoneUuid, organization, newWidget, projectId, selectedVersion?.versionId || ""); + + if (response.message === "widget update successfully") { + return true; } else { - // + return false; } - } catch (error) { - echo.error("Failed to fetch zone data"); - - } - }; - fetchZoneData(); - }, []); - - useEffect(() => { - const fetchSavedInputes = async () => { - if (selectedChartId.id !== "") { - let response = await get3dWidgetInput(selectedChartId.id, organization, projectId, selectedVersion?.versionId || "") - - if (response) { - setSelections(response.Datastructure.measurements); - setDuration(response.Datastructure.duration); - setWidgetName(response.widgetName); - } - - } }; - fetchSavedInputes(); - }, [selectedChartId.id]); + const handleSelect = async (inputKey: string, selectedData: { name: string; fields: string } | null) => { + const newSelections = { ...selections }; + if (selectedData === null) { + delete newSelections[inputKey]; + } else { + newSelections[inputKey] = selectedData; + } + if (await sendInputes(newSelections, duration, widgetName)) { + setSelections(newSelections); + } + }; - useEffect(() => { - setMeasurements(selections); - updateDuration(duration); - updateName(widgetName); - }, [selections, duration, widgetName]); + const handleSelectDuration = async (option: string) => { + if (await sendInputes(selections, option, widgetName)) { + setDuration(option); + } + }; - const sendInputes = async ( - inputMeasurement: any, - inputDuration: any, - inputName: any - ) => { + const handleNameChange = async (name: any) => { + if (await sendInputes(selections, duration, name)) { + setWidgetName(name); + } + }; - let newWidget = { - id: selectedChartId.id, - widgetName: inputName, - Data: { - measurements: inputMeasurement, - duration: inputDuration, - }, - } - - let response = await adding3dWidgets(selectedZone.zoneUuid, organization, newWidget, projectId, selectedVersion?.versionId || "") - - if (response.message === "widget update successfully") { - return true; - } else { - return false - } - - // try { - // const response = await axios.post( - // `http://${process.env.REACT_APP_SERVER_REST_API_BASE_URL}/api/V1/widget3d/save`, - // { - // headers: { - // Authorization: "Bearer ", - // "Content-Type": "application/json", - // token: localStorage.getItem("token") || "", - // refresh_token: localStorage.getItem("refreshToken") || "", - // }, - // }, - // { - // organization, - // zoneUuid: selectedZone.zoneUuid, - // widget: { - // id: selectedChartId.id, - // widgetName: inputName, - // Data: { - // measurements: inputMeasurement, - // duration: inputDuration, - // }, - // }, - // projectId: projectId, - // versionId: selectedVersion?.versionId || "" - // } as any - // ); - // - // if (response.status === 200) { - // return true; - // } else { - // // - // return false; - // } - // } catch (error) { - // echo.error("Failed to send input"); - // - // return false; - // } - }; - - const handleSelect = async ( - inputKey: string, - selectedData: { name: string; fields: string } | null - ) => { - // async() => { - const newSelections = { ...selections }; - if (selectedData === null) { - delete newSelections[inputKey]; - } else { - newSelections[inputKey] = selectedData; - } - // setMeasurements(newSelections); // Update Zustand store - // - if (await sendInputes(newSelections, duration, widgetName)) { - setSelections(newSelections); - } - }; - - const handleSelectDuration = async (option: string) => { - if (await sendInputes(selections, option, widgetName)) { - setDuration(option); - } - }; - - const handleNameChange = async (name: any) => { - // - - if (await sendInputes(selections, duration, name)) { - setWidgetName(name); - } - }; - - return ( - <> -
-
-
Title
- -
- {[...Array(7)].map((_, index) => { - const inputKey = `input${index + 1}`; - return ( -
-
Input {index + 1}
-
- - handleSelect(inputKey, selectedData) - } - onUnselect={() => handleSelect(inputKey, null)} - selectedValue={selections[inputKey]} // Load from Zustand - isLoading={isLoading} - allSelections={selections} - /> -
- -
-
+ return ( +
+
+
Title
+
- ); - })} -
- - ); + {[...Array(7)].map((_, index) => { + const inputKey = `input${index + 1}`; + return ( +
+
Input {index + 1}
+
+ handleSelect(inputKey, selectedData)} + onUnselect={() => handleSelect(inputKey, null)} + selectedValue={selections[inputKey]} // Load from Zustand + isLoading={isLoading} + allSelections={selections} + /> +
+ +
+
+
+ ); + })} +
+ ); }; export default Widget3InputCard3D; diff --git a/app/src/components/layout/sidebarRight/visualization/IotInputCards/Widget4InputCard3D.tsx b/app/src/components/layout/sidebarRight/visualization/IotInputCards/Widget4InputCard3D.tsx index df09e7b..f83aa38 100644 --- a/app/src/components/layout/sidebarRight/visualization/IotInputCards/Widget4InputCard3D.tsx +++ b/app/src/components/layout/sidebarRight/visualization/IotInputCards/Widget4InputCard3D.tsx @@ -1,228 +1,155 @@ -import React, { useEffect, useState } from "react"; +import { useEffect, useState } from "react"; import MultiLevelDropdown from "../../../../ui/inputs/MultiLevelDropDown"; import { AddIcon } from "../../../../icons/ExportCommonIcons"; import RegularDropDown from "../../../../ui/inputs/RegularDropDown"; import useChartStore from "../../../../../store/visualization/useChartStore"; import { useSelectedZoneStore } from "../../../../../store/visualization/useZoneStore"; -import { useWidgetStore } from "../../../../../store/useWidgetStore"; +import { useWidgetStore } from "../../../../../store/ui/useWidgetStore"; import axios from "axios"; import RenameInput from "../../../../ui/inputs/RenameInput"; import { getUserData } from "../../../../../functions/getUserData"; import { get3dWidgetInput } from "../../../../../services/visulization/zone/get3dWidgetInput"; -import { useVersionContext } from "../../../../../modules/builder/version/versionContext"; import { useParams } from "react-router-dom"; import { adding3dWidgets } from "../../../../../services/visulization/zone/add3dWidget"; +import { useSceneContext } from "../../../../../modules/scene/sceneContext"; type Props = {}; const Widget4InputCard3D = (props: Props) => { - const { selectedChartId } = useWidgetStore(); - const [widgetName, setWidgetName] = useState("untited"); - const { setMeasurements, updateDuration, updateName } = useChartStore(); - const [duration, setDuration] = useState("1h"); - const [dropDowndata, setDropDownData] = useState({}); - const [selections, setSelections] = useState< - Record - >({}); - const { selectedZone } = useSelectedZoneStore(); - const iotApiUrl = process.env.REACT_APP_IOT_SOCKET_SERVER_URL; - const { userName, userId, organization, email } = getUserData(); - const [isLoading, setLoading] = useState(true); - const { selectedVersionStore } = useVersionContext(); - const { selectedVersion } = selectedVersionStore(); - const { projectId } = useParams() + const { selectedChartId } = useWidgetStore(); + const [widgetName, setWidgetName] = useState("untited"); + const { setMeasurements, updateDuration, updateName } = useChartStore(); + const [duration, setDuration] = useState("1h"); + const [dropDownSata, setDropDownSata] = useState({}); + const [selections, setSelections] = useState>({}); + const { selectedZone } = useSelectedZoneStore(); + const iotApiUrl = process.env.REACT_APP_IOT_SOCKET_SERVER_URL; + const { organization } = getUserData(); + const [isLoading, setIsLoading] = useState(true); + const { versionStore } = useSceneContext(); + const { selectedVersion } = versionStore(); + const { projectId } = useParams(); - useEffect(() => { - const fetchZoneData = async () => { - try { - setLoading(true); - const response = await axios.get(`http://${iotApiUrl}/floatinput`); - if (response.status === 200) { - // - setDropDownData(response.data); - setLoading(false); + useEffect(() => { + const fetchZoneData = async () => { + try { + setIsLoading(true); + const response = await axios.get(`http://${iotApiUrl}/floatinput`); + if (response.status === 200) { + setDropDownSata(response.data); + setIsLoading(false); + } + } catch { + echo.error("Failed to fetch zone data"); + } + }; + fetchZoneData(); + }, []); + + useEffect(() => { + const fetchSavedInputes = async () => { + if (selectedChartId.id !== "") { + let response = await get3dWidgetInput(selectedChartId.id, organization, projectId, selectedVersion?.versionId || ""); + + if (response) { + setSelections(response.Datastructure.measurements); + setDuration(response.Datastructure.duration); + setWidgetName(response.widgetName); + } + } + }; + + fetchSavedInputes(); + }, [selectedChartId.id]); + + useEffect(() => { + setMeasurements(selections); + updateDuration(duration); + updateName(widgetName); + }, [selections, duration, widgetName]); + + const sendInputes = async (inputMeasurement: any, inputDuration: any, inputName: any) => { + let newWidget = { + id: selectedChartId.id, + widgetName: inputName, + Data: { + measurements: inputMeasurement, + duration: inputDuration, + }, + }; + + let response = await adding3dWidgets(selectedZone.zoneUuid, organization, newWidget, projectId, selectedVersion?.versionId || ""); + + if (response.message === "widget update successfully") { + return true; } else { - // + return false; } - } catch (error) { - echo.error("Failed to fetch zone data"); - - } - }; - fetchZoneData(); - }, []); - - useEffect(() => { - const fetchSavedInputes = async () => { - if (selectedChartId.id !== "") { - - - - let response = await get3dWidgetInput(selectedChartId.id, organization, projectId, selectedVersion?.versionId || "") - - if (response) { - setSelections(response.Datastructure.measurements); - setDuration(response.Datastructure.duration); - setWidgetName(response.widgetName); - } - - } }; - fetchSavedInputes(); - }, [selectedChartId.id]); + const handleSelect = async (inputKey: string, selectedData: { name: string; fields: string } | null) => { + const newSelections = { ...selections }; + if (selectedData === null) { + delete newSelections[inputKey]; + } else { + newSelections[inputKey] = selectedData; + } + if (await sendInputes(newSelections, duration, widgetName)) { + setSelections(newSelections); + } + }; - // Sync Zustand state when component mounts - useEffect(() => { - setMeasurements(selections); - updateDuration(duration); - updateName(widgetName); - }, [selections, duration, widgetName]); + const handleSelectDuration = async (option: string) => { + if (await sendInputes(selections, option, widgetName)) { + setDuration(option); + } + }; - const sendInputes = async ( - inputMeasurement: any, - inputDuration: any, - inputName: any - ) => { - let newWidget = { - id: selectedChartId.id, - widgetName: inputName, - Data: { - measurements: inputMeasurement, - duration: inputDuration, - }, - } + const handleNameChange = async (name: any) => { + if (await sendInputes(selections, duration, name)) { + setWidgetName(name); + } + }; - let response = await adding3dWidgets(selectedZone.zoneUuid, organization, newWidget, projectId, selectedVersion?.versionId || "") - - if (response.message === "widget update successfully") { - return true; - } else { - return false - } - // - // try { - // const response = await axios.post( - // `http://${process.env.REACT_APP_SERVER_REST_API_BASE_URL}/api/V1/widget3d/save`, - // { - // headers: { - // Authorization: "Bearer ", - // "Content-Type": "application/json", - // token: localStorage.getItem("token") || "", - // refresh_token: localStorage.getItem("refreshToken") || "", - // }, - // }, - // { - // organization, - // zoneUuid: selectedZone.zoneUuid, - // widget: { - // id: selectedChartId.id, - // widgetName: inputName, - // Data: { - // measurements: inputMeasurement, - // duration: inputDuration, - // }, - // }, - // projectId: projectId, - // versionId: selectedVersion?.versionId || "" - // } as any - // ); - // - // if (response.status === 200) { - // return true; - // } else { - // // - // return false; - // } - // } catch (error) { - // echo.error("Failed to send input"); - // - // return false; - // } - }; - - const handleSelect = async ( - inputKey: string, - selectedData: { name: string; fields: string } | null - ) => { - // async() => { - const newSelections = { ...selections }; - if (selectedData === null) { - delete newSelections[inputKey]; - } else { - newSelections[inputKey] = selectedData; - } - // setMeasurements(newSelections); // Update Zustand store - // - if (await sendInputes(newSelections, duration, widgetName)) { - setSelections(newSelections); - } - // sendInputes(newSelections, duration); // Send data to server - // return newSelections; - // }; - }; - - const handleSelectDuration = async (option: string) => { - if (await sendInputes(selections, option, widgetName)) { - setDuration(option); - } - // setDuration(option); - }; - - const handleNameChange = async (name: any) => { - - - if (await sendInputes(selections, duration, name)) { - setWidgetName(name); - } - }; - - return ( - <> -
-
-
Title
- -
- {[...Array(1)].map((_, index) => { - const inputKey = `input${index + 1}`; - return ( -
-
Input {index + 1}
-
- - handleSelect(inputKey, selectedData) - } - onUnselect={() => handleSelect(inputKey, null)} - selectedValue={selections[inputKey]} // Load from Zustand - isLoading={isLoading} - allSelections={selections} - /> -
- + return ( + <> +
+
+
Title
+
-
+ {[...Array(1)].map((_, index) => { + const inputKey = `input${index + 1}`; + return ( +
+
Input {index + 1}
+
+ handleSelect(inputKey, selectedData)} + onUnselect={() => handleSelect(inputKey, null)} + selectedValue={selections[inputKey]} // Load from Zustand + isLoading={isLoading} + allSelections={selections} + /> +
+ +
+
+
+ ); + })}
- ); - })} -
-
-
-
Duration
-
- -
-
-
- - ); +
+
+
Duration
+
+ +
+
+
+ + ); }; export default Widget4InputCard3D; diff --git a/app/src/components/layout/sidebarRight/visualization/Visualization.tsx b/app/src/components/layout/sidebarRight/visualization/Visualization.tsx index c24dea2..4460b61 100644 --- a/app/src/components/layout/sidebarRight/visualization/Visualization.tsx +++ b/app/src/components/layout/sidebarRight/visualization/Visualization.tsx @@ -4,24 +4,18 @@ import Data from "./data/Data"; import Design from "./design/Design"; const Visualization = () => { - const [activeOption, setActiveOption] = useState("Data"); + const [activeOption, setActiveOption] = useState("Data"); - const handleToggleClick = (option: string) => { - setActiveOption(option); // Update the active option - }; + const handleToggleClick = (option: string) => { + setActiveOption(option); + }; - return ( -
- -
- {activeOption === "Data" ? : } -
-
- ); + return ( +
+ +
{activeOption === "Data" ? : }
+
+ ); }; export default Visualization; diff --git a/app/src/components/layout/sidebarRight/visualization/data/Data.tsx b/app/src/components/layout/sidebarRight/visualization/data/Data.tsx index d41a38f..01bd169 100644 --- a/app/src/components/layout/sidebarRight/visualization/data/Data.tsx +++ b/app/src/components/layout/sidebarRight/visualization/data/Data.tsx @@ -1,5 +1,5 @@ import { useEffect, useState } from "react"; -import { useWidgetStore } from "../../../../../store/useWidgetStore"; +import { useWidgetStore } from "../../../../../store/ui/useWidgetStore"; import { AddIcon, RemoveIcon } from "../../../../icons/ExportCommonIcons"; import MultiLevelDropDown from "../../../../ui/inputs/MultiLevelDropDown"; import LineGrapInput from "../IotInputCards/LineGrapInput"; diff --git a/app/src/components/layout/sidebarRight/visualization/design/Design.tsx b/app/src/components/layout/sidebarRight/visualization/design/Design.tsx index 53ea8a7..afcfbd0 100644 --- a/app/src/components/layout/sidebarRight/visualization/design/Design.tsx +++ b/app/src/components/layout/sidebarRight/visualization/design/Design.tsx @@ -2,7 +2,7 @@ import React, { useEffect, useState } from "react"; import { ArrowIcon } from "../../../../icons/ExportCommonIcons"; import RegularDropDown from "../../../../ui/inputs/RegularDropDown"; import InputRange from "../../../../ui/inputs/InputRange"; -import { useWidgetStore } from "../../../../../store/useWidgetStore"; +import { useWidgetStore } from "../../../../../store/ui/useWidgetStore"; import ChartComponent from "../../../sidebarLeft/visualization/widgets/ChartComponent"; const defaultStyle = { diff --git a/app/src/components/ui/ModuleToggle.tsx b/app/src/components/ui/ModuleToggle.tsx index dea27c7..0ae1ea7 100644 --- a/app/src/components/ui/ModuleToggle.tsx +++ b/app/src/components/ui/ModuleToggle.tsx @@ -1,18 +1,18 @@ import React from "react"; -import useModuleStore from "../../store/useModuleStore"; +import useModuleStore from "../../store/ui/useModuleStore"; import { BuilderIcon, CartIcon, SimulationIcon, VisualizationIcon, } from "../icons/ExportModuleIcons"; -import {useToggleStore} from "../../store/useUIToggleStore"; -import useVersionHistoryStore from "../../store/builder/store"; +import {useToggleStore} from "../../store/ui/useUIToggleStore"; +import useVersionStore from "../../store/builder/store"; const ModuleToggle: React.FC = () => { const { activeModule, setActiveModule } = useModuleStore(); const { setToggleUI } = useToggleStore(); - const { setVersionHistoryVisible } = useVersionHistoryStore(); + const { setVersionHistoryVisible } = useVersionStore(); return (
diff --git a/app/src/components/ui/Tools.tsx b/app/src/components/ui/Tools.tsx index 6ae7a81..ede444a 100644 --- a/app/src/components/ui/Tools.tsx +++ b/app/src/components/ui/Tools.tsx @@ -1,52 +1,21 @@ import React, { useEffect, useRef, useState } from "react"; -import { - AsileIcon, - CommentIcon, - CursorIcon, - DeleteIcon, - FloorIcon, - FreeMoveIcon, - MeasureToolIcon, - PenIcon, - PlayIcon, - SaveTemplateIcon, - WallIcon, - ZoneIcon, -} from "../icons/ExportToolsIcons"; +import { AsileIcon, CommentIcon, CursorIcon, DeleteIcon, FloorIcon, FreeMoveIcon, MeasureToolIcon, PenIcon, PlayIcon, SaveTemplateIcon, WallIcon, ZoneIcon } from "../icons/ExportToolsIcons"; import { ArrowIcon, TickIcon } from "../icons/ExportCommonIcons"; -import useModuleStore, { useThreeDStore } from "../../store/useModuleStore"; +import useModuleStore, { useThreeDStore } from "../../store/ui/useModuleStore"; import { handleSaveTemplate } from "../../modules/visualization/functions/handleSaveTemplate"; -import { usePlayButtonStore } from "../../store/usePlayButtonStore"; -import useTemplateStore from "../../store/useTemplateStore"; +import { usePlayButtonStore } from "../../store/ui/usePlayButtonStore"; +import useTemplateStore from "../../store/ui/useTemplateStore"; import { useSelectedZoneStore } from "../../store/visualization/useZoneStore"; -import { - useActiveTool, - useAddAction, - useSocketStore, - useToggleView, - useToolMode, - useActiveSubTool, - useShortcutStore, -} from "../../store/builder/store"; -import { useToggleStore } from "../../store/useUIToggleStore"; -import { - use3DWidget, - useFloatingWidget, -} from "../../store/visualization/useDroppedObjectsStore"; +import { useActiveTool, useAddAction, useSocketStore, useToggleView, useToolMode, useActiveSubTool, useShortcutStore } from "../../store/builder/store"; +import { useToggleStore } from "../../store/ui/useUIToggleStore"; +import { use3DWidget, useFloatingWidget } from "../../store/visualization/useDroppedObjectsStore"; import { useParams } from "react-router-dom"; -import { useVersionContext } from "../../modules/builder/version/versionContext"; import { MoveIcon, RotateIcon } from "../icons/ShortcutIcons"; import { useBuilderStore } from "../../store/builder/useBuilderStore"; +import { useSceneContext } from "../../modules/scene/sceneContext"; // Utility component -const ToolButton = ({ - toolKey, - toolId, - icon: Icon, - active, - onClick, - tooltip, -}: any) => ( +const ToolButton = ({ toolKey, toolId, icon: Icon, active, onClick, tooltip }: any) => ( @@ -376,14 +276,7 @@ const Tools: React.FC = () => {
{["move", "rotate"].map((tool) => ( - setActiveTool(tool)} - /> + setActiveTool(tool)} /> ))}
@@ -396,22 +289,8 @@ const Tools: React.FC = () => {
- setActiveTool("comment")} - /> - {toggleThreeD && ( - setIsPlaying(!isPlaying)} - /> - )} + setActiveTool("comment")} /> + {toggleThreeD && setIsPlaying(!isPlaying)} />}
{activeModule === "builder" && ( diff --git a/app/src/components/ui/analysis/ProductionCapacity.tsx b/app/src/components/ui/analysis/ProductionCapacity.tsx index 6ff0b42..d5b0951 100644 --- a/app/src/components/ui/analysis/ProductionCapacity.tsx +++ b/app/src/components/ui/analysis/ProductionCapacity.tsx @@ -1,12 +1,6 @@ import React, { useEffect, useState } from "react"; import { Line } from "react-chartjs-2"; -import { - Chart as ChartJS, - LineElement, - CategoryScale, - LinearScale, - PointElement, -} from "chart.js"; +import { Chart as ChartJS, LineElement, CategoryScale, LinearScale, PointElement } from "chart.js"; import { PowerIcon, ProductionCapacityIcon } from "../../icons/analysis"; import SkeletonUI from "../../templates/SkeletonUI"; import { useInputValues, useMachineUptime, useProductionCapacityData, useThroughPutData } from "../../../store/builder/store"; @@ -14,188 +8,181 @@ import { useInputValues, useMachineUptime, useProductionCapacityData, useThrough ChartJS.register(LineElement, CategoryScale, LinearScale, PointElement); const ThroughputSummary: React.FC = () => { - // Define all data internally within the component - const timeRange = { - startTime: "08:00 AM", - endTime: "06:00 PM", - }; + // Define all data internally within the component + const timeRange = { + startTime: "08:00 AM", + endTime: "06:00 PM", + }; - const { machineActiveTime } = useMachineUptime(); - const energyConsumption = { - energyConsumed: 456, - unit: "KWH", - }; + const { machineActiveTime } = useMachineUptime(); + const energyConsumption = { + energyConsumed: 456, + unit: "KWH", + }; - + // Dynamic shift data + const shiftUtilization = [ + { shift: 1, percentage: 30, color: "#F3C64D" }, + { shift: 2, percentage: 40, color: "#67B3F4" }, + { shift: 3, percentage: 30, color: "#7981F5" }, + ]; - // Dynamic shift data - const shiftUtilization = [ - { shift: 1, percentage: 30, color: "#F3C64D" }, - { shift: 2, percentage: 40, color: "#67B3F4" }, - { shift: 3, percentage: 30, color: "#7981F5" }, - ]; + const { productionCapacityData } = useProductionCapacityData(); + const { throughputData: data } = useThroughPutData(); - const { productionCapacityData } = useProductionCapacityData() - const { throughputData: data } = useThroughPutData() + const chartOptions = { + responsive: true, + scales: { + x: { + display: false, // hide X axis completely + }, + y: { + display: false, // hide Y axis completely + min: 0, // force Y axis to start at 0 + }, + }, + plugins: { + legend: { + display: false, + }, + tooltip: { + enabled: true, + }, + }, + }; + const assetUsage = 85; - const chartOptions = { - responsive: true, - scales: { - x: { - display: false, // hide X axis completely - }, - y: { - display: false, // hide Y axis completely - min: 0, // force Y axis to start at 0 - }, - }, - plugins: { - legend: { - display: false, - }, - tooltip: { - enabled: true, - }, - }, - }; + // machineActiveTime => Throughput + // shiftUtilization.length => Shifts per day + // 8 => Shift length + // assetUsage => Yield rate - const assetUsage = 85; + const throughtputMachineData = machineActiveTime * shiftUtilization.length * 8; - // machineActiveTime => Throughput - // shiftUtilization.length => Shifts per day - // 8 => Shift length - // assetUsage => Yield rate + const throughputData = { + labels: ["08:00", "08:10", "08:20", "08:30", "08:40", "08:50"], + data: [5, 10, 8, 10, 12, 10], + totalThroughput: (throughtputMachineData * assetUsage) / 100, + assetUsage: assetUsage, + }; - const throughtputMachineData = machineActiveTime * shiftUtilization.length * 8 + const { inputValues } = useInputValues(); + // Chart data configuration + const chartData = { + labels: throughputData.labels, + datasets: [ + { + label: "Units/hour", + data: throughputData.data, + borderColor: "#B392F0", + tension: 0.4, + pointRadius: 0, // Hide points + }, + ], + }; - const throughputData = { - labels: ["08:00", "08:10", "08:20", "08:30", "08:40", "08:50"], - data: [5, 10, 8, 10, 12, 10], - totalThroughput: (throughtputMachineData) * assetUsage / 100, - assetUsage: assetUsage, - }; + const [isLoading, setIsLoading] = useState(true); - const { inputValues } = useInputValues(); - // Chart data configuration - const chartData = { - labels: throughputData.labels, - datasets: [ - { - label: "Units/hour", - data: throughputData.data, - borderColor: "#B392F0", - tension: 0.4, - pointRadius: 0, // Hide points - }, - ], - }; + useEffect(() => { + // + if (productionCapacityData > 0) { + setTimeout(() => { + setIsLoading(false); + }, 3000); + } else { + setIsLoading(true); + } + }, [productionCapacityData]); - const [isLoading, setIsLoading] = useState(true); - - useEffect(() => { - // - if (productionCapacityData > 0) { - setTimeout(() => { - - setIsLoading(false); - }, 3000) - - } else { - setIsLoading(true); - } - }, [productionCapacityData]); - - - return ( - <> - {!isLoading &&
-
-
-
-
Production Capacity
-
- {timeRange.startTime} - {timeRange.endTime} -
-
-
- -
-
- - {!isLoading ? ( - <> -
-
- {productionCapacityData}{" "} - Units/Month -
-
-
-
Asset usage
-
{parseFloat(inputValues["Yield rate"])}%
-
- -
-
- -
-
-
Energy Consumption
-
-
- -
-
-
- {energyConsumption.energyConsumed} -
-
{energyConsumption.unit}
-
-
-
-
-
Shift Utilization
-
-
{throughputData.assetUsage}%
- -
- {/* Dynamically create progress bars based on shiftUtilization array */} - {shiftUtilization.map((shift, index) => ( -
- ))} -
- -
- {/* Dynamically create shift indicators with random colors */} - {shiftUtilization.map((shift, index) => ( -
- - + return ( + <> + {!isLoading && ( +
+
+
+
+
Production Capacity
+
+ {timeRange.startTime} - {timeRange.endTime} +
+
+
+ +
- ))} + + {!isLoading ? ( + <> +
+
+ {productionCapacityData} Units/Month +
+
+
+
Asset usage
+
{parseFloat(inputValues["Yield rate"])}%
+
+ +
+
+ +
+
+
Energy Consumption
+
+
+ +
+
+
{energyConsumption.energyConsumed}
+
{energyConsumption.unit}
+
+
+
+
+
Shift Utilization
+
+
{throughputData.assetUsage}%
+ +
+ {/* Dynamically create progress bars based on shiftUtilization array */} + {shiftUtilization.map((shift, index) => ( +
+ ))} +
+ +
+ {/* Dynamically create shift indicators with random colors */} + {shiftUtilization.map((shift, index) => ( +
+ + +
+ ))} +
+
+
+
+ + ) : ( + + )}
-
-
- - ) : ( - - )} -
-
} - - ); + )} + + ); }; export default ThroughputSummary; diff --git a/app/src/components/ui/collaboration/Messages.tsx b/app/src/components/ui/collaboration/Messages.tsx index b02833a..063189a 100644 --- a/app/src/components/ui/collaboration/Messages.tsx +++ b/app/src/components/ui/collaboration/Messages.tsx @@ -4,287 +4,251 @@ import { KebabIcon } from "../../icons/ExportCommonIcons"; import { adjustHeight } from "./function/textAreaHeightAdjust"; import { getUserData } from "../../../functions/getUserData"; import { useParams } from "react-router-dom"; -import { deleteCommentApi } from "../../../services/factoryBuilder/comments/deleteCommentApi"; -import { addCommentsApi } from "../../../services/factoryBuilder/comments/addCommentsApi"; import { useCommentStore } from "../../../store/collaboration/useCommentStore"; import { useSelectedComment, useSocketStore } from "../../../store/builder/store"; import { getRelativeTime } from "./function/getRelativeTime"; import { editThreadTitleApi } from "../../../services/factoryBuilder/comments/editThreadTitleApi"; -import { useVersionContext } from "../../../modules/builder/version/versionContext"; +import { useSceneContext } from "../../../modules/scene/sceneContext"; +// import { deleteCommentApi } from "../../../services/factoryBuilder/comments/deleteCommentApi"; +// import { addCommentsApi } from "../../../services/factoryBuilder/comments/addCommentsApi"; interface MessageProps { - val: Reply | CommentSchema; - // val: Reply | CommentSchema; - i: number; - setMessages?: React.Dispatch> - setIsEditable?: React.Dispatch> - setEditedThread?: React.Dispatch> - setMode?: React.Dispatch> - isEditable?: boolean; - isEditableThread?: boolean - editedThread?: boolean; - mode?: 'create' | 'edit' | null + val: Reply | CommentSchema; + i: number; + setMessages?: React.Dispatch>; + setIsEditable?: React.Dispatch>; + setEditedThread?: React.Dispatch>; + setMode?: React.Dispatch>; + isEditable?: boolean; + isEditableThread?: boolean; + editedThread?: boolean; + mode?: "create" | "edit" | null; } const Messages: React.FC = ({ val, i, setMessages, mode, setIsEditable, setEditedThread, editedThread, isEditableThread, setMode }) => { + const { updateComment, removeReply, updateReply } = useCommentStore(); + const [openOptions, setOpenOptions] = useState(false); + const { projectId } = useParams(); + const { threadSocket } = useSocketStore(); + const { userName, userId, organization } = getUserData(); + const [isEditComment, setIsEditComment] = useState(false); + const { selectedComment, setCommentPositionState } = useSelectedComment(); + const { versionStore } = useSceneContext(); + const { selectedVersion } = versionStore(); - const { comments, updateComment, updateReply, removeReply } = useCommentStore(); - const [openOptions, setOpenOptions] = useState(false); - const { projectId } = useParams(); - const { threadSocket } = useSocketStore(); - const { userName, userId, organization } = getUserData(); - const [isEditComment, setIsEditComment] = useState(false) - const { selectedComment, setCommentPositionState } = useSelectedComment(); - const { selectedVersionStore } = useVersionContext(); - const { selectedVersion } = selectedVersionStore(); + const [value, setValue] = useState("comment" in val ? val.comment : val.threadTitle); - // input - const [value, setValue] = useState( - "comment" in val ? val.comment : val.threadTitle - ); + const textareaRef = useRef(null); - const textareaRef = useRef(null); - const currentUser = "1"; + useEffect(() => { + if (textareaRef.current) adjustHeight(textareaRef.current); + }, [value]); - // const UserName = "username"; + function handleCancelAction() { + setCommentPositionState(null); + if (setIsEditable) setIsEditable(true); + setIsEditComment(false); + } - useEffect(() => { - if (textareaRef.current) adjustHeight(textareaRef.current); - }, [value]); + const handleSaveAction = async () => { + if (!projectId || !selectedVersion) return; - function handleCancelAction() { - setCommentPositionState(null) - setIsEditable && setIsEditable(true); - setIsEditComment(false) - } + if (isEditableThread && editedThread) { + try { + if (!threadSocket?.active) { + const editThreadTitle = await editThreadTitleApi(projectId, (val as CommentSchema).threadId, value, selectedVersion?.versionId || ""); + if (editThreadTitle.message == "ThreadTitle updated Successfully") { + const editedThread: CommentSchema = { + state: "active", + threadId: editThreadTitle.data.replyId, + creatorId: userId, + createdAt: getRelativeTime(editThreadTitle.data.createdAt), + threadTitle: value, + lastUpdatedAt: new Date().toISOString(), + position: editThreadTitle.data.position, + rotation: [0, 0, 0], + comments: [], + }; + updateComment((val as CommentSchema).threadId, editedThread); + } + } else { + const threadEdit = { + projectId, + userId, + threadTitle: value, + organization, + threadId: (val as CommentSchema).threadId || selectedComment.threadId, + versionId: selectedVersion?.versionId || "", + }; - const handleSaveAction = async () => { - - if (!projectId || !selectedVersion) return - - if (isEditableThread && editedThread) { - try { - if (!threadSocket?.active) { - const editThreadTitle = await editThreadTitleApi(projectId, (val as CommentSchema).threadId, value, selectedVersion?.versionId || "") - if (editThreadTitle.message == "ThreadTitle updated Successfully") { - const editedThread: CommentSchema = { - state: 'active', - threadId: editThreadTitle.data.replyId, - creatorId: userId, - createdAt: getRelativeTime(editThreadTitle.data.createdAt), - threadTitle: value, - lastUpdatedAt: new Date().toISOString(), - position: editThreadTitle.data.position, - rotation: [0, 0, 0], - comments: [], - } - updateComment((val as CommentSchema).threadId, editedThread) - } + threadSocket.emit("v1:thread:updateTitle", threadEdit); + } + } catch {} } else { - const threadEdit = { - projectId, - userId, - threadTitle: value, - organization, - threadId: (val as CommentSchema).threadId || selectedComment.threadId, - versionId: selectedVersion?.versionId || "" - } + if (mode === "edit") { + try { + // const editComments = await addCommentsApi(projectId, value, selectedComment?.threadId, (val as Reply).replyId, selectedVersion?.versionId || "") + // + // const commentData = { + // replyId: `${editComments.data?.replyId}`, + // creatorId: `${userId}`, + // createdAt: getRelativeTime(editComments.data?.createdAt), + // lastUpdatedAt: "2 hrs ago", + // comment: value, + // } - threadSocket.emit('v1:thread:updateTitle', threadEdit) - } - } catch { - } - } else { - if (mode === "edit") { - try { - // const editComments = await addCommentsApi(projectId, value, selectedComment?.threadId, (val as Reply).replyId, selectedVersion?.versionId || "") - // - // const commentData = { - // replyId: `${editComments.data?.replyId}`, - // creatorId: `${userId}`, - // createdAt: getRelativeTime(editComments.data?.createdAt), - // lastUpdatedAt: "2 hrs ago", - // comment: value, - // } + // updateReply((val as CommentSchema).threadId, (val as Reply)?.replyId, commentData); - // updateReply((val as CommentSchema).threadId, (val as Reply)?.replyId, commentData); + if (threadSocket) { + // projectId, userId, comment, organization, threadId + const editComment = { + projectId, + userId, + comment: value, + organization, + threadId: selectedComment?.threadId, + commentId: (val as Reply).replyId ?? "", + versionId: selectedVersion?.versionId || "", + }; - if (threadSocket) { - // projectId, userId, comment, organization, threadId - const editComment = { - projectId, - userId, - comment: value, - organization, - threadId: selectedComment?.threadId, - commentId: (val as Reply).replyId ?? "", - versionId: selectedVersion?.versionId || "" + threadSocket.emit("v1-Comment:add", editComment); + setIsEditable && setIsEditable(true); + setEditedThread && setEditedThread(false); + } + } catch {} } - - - threadSocket.emit("v1-Comment:add", editComment); - setIsEditable && setIsEditable(true); - setEditedThread && setEditedThread(false) - } - - } catch { } - } + // setValue(""); + setIsEditComment(false); + }; - } - // setValue(""); - setIsEditComment(false); - } + const handleDeleteAction = async (replyID: any) => { + if (!projectId || !selectedVersion) return; + setOpenOptions(false); + try { + // const deletedComment = await deleteCommentApi(projectId, selectedComment?.threadId, (val as Reply).replyId , selectedVersion?.versionId || "") + // + // if (deletedComment === "'Thread comment deleted Successfully'") { + // setMessages && setMessages(prev => prev.filter(message => message.replyId !== replyID)); + // removeReply(val.creatorId, replyID) + // } + if (threadSocket && setMessages) { + // projectId, userId, commentId, organization, threadId + const deleteComment = { + projectId, + userId, + commentId: (val as Reply).replyId, + organization, + threadId: selectedComment?.threadId, + versionId: selectedVersion?.versionId || "", + }; + setMessages((prev) => { + // 👈 logs the current state + return prev.filter((message) => message.replyId !== (val as Reply).replyId); + }); + removeReply(selectedComment?.threadId, (val as Reply).replyId); // Remove listener after response - const handleDeleteAction = async (replyID: any) => { - if (!projectId || !selectedVersion) return - setOpenOptions(false); - try { - // const deletedComment = await deleteCommentApi(projectId, selectedComment?.threadId, (val as Reply).replyId , selectedVersion?.versionId || "") - // - // if (deletedComment === "'Thread comment deleted Successfully'") { - // setMessages && setMessages(prev => prev.filter(message => message.replyId !== replyID)); - // removeReply(val.creatorId, replyID) - // } - if (threadSocket && setMessages) { + threadSocket.emit("v1-Comment:delete", deleteComment); + } + } catch {} + }; - - // projectId, userId, commentId, organization, threadId - const deleteComment = { - projectId, - userId, - commentId: (val as Reply).replyId, - organization, - threadId: selectedComment?.threadId, - versionId: selectedVersion?.versionId || "" - } - setMessages(prev => { - // 👈 logs the current state - return prev.filter(message => message.replyId !== (val as Reply).replyId); + const handleFocus = (e: React.FocusEvent) => { + requestAnimationFrame(() => { + if (textareaRef.current) { + const length = textareaRef.current.value.length; + textareaRef.current.setSelectionRange(length, length); + } }); - removeReply(selectedComment?.threadId, (val as Reply).replyId); // Remove listener after response + }; + return ( + <> + {isEditComment ? ( +
+
+