threads api refactor

This commit is contained in:
2025-09-10 11:18:47 +05:30
parent aace9be40c
commit 060d7a7d82
16 changed files with 1076 additions and 1059 deletions

View File

@@ -26,7 +26,7 @@ import RegularDropDown from "../../ui/inputs/RegularDropDown";
import RenameTooltip from "../../ui/features/RenameTooltip";
import VersionSaved from "../sidebarRight/versionHisory/VersionSaved";
import Footer from "../../footer/Footer";
import ThreadChat from "../../ui/collaboration/ThreadChat";
import ThreadChat from "../../ui/collaboration/threads/ThreadChat";
import Scene from "../../../modules/scene/scene";
import { getUserData } from "../../../functions/getUserData";
@@ -179,7 +179,9 @@ function MainScene() {
{isPlaying && activeModule === "simulation" && loadingProgress === 0 && <SimulationPlayer />}
{isPlaying && activeModule !== "simulation" && <ControlsPlayer />}
{isRenameMode && (selectedFloorAsset?.userData.modelName || selectedAssets.length === 1) && <RenameTooltip name={selectedFloorAsset?.userData.modelName || selectedAssets[0].userData.modelName} onSubmit={handleObjectRename} />}
{isRenameMode && (selectedFloorAsset?.userData.modelName || selectedAssets.length === 1) && (
<RenameTooltip name={selectedFloorAsset?.userData.modelName || selectedAssets[0].userData.modelName} onSubmit={handleObjectRename} />
)}
{/* remove this later */}
{activeModule === "builder" && !toggleThreeD && <SelectFloorPlan />}
</>

View File

@@ -1,115 +0,0 @@
import React, { useEffect, useState } from "react";
import { getAvatarColor } from "../../../modules/collaboration/functions/getAvatarColor";
import { getUserData } from "../../../functions/getUserData";
import { getAllThreads } from "../../../services/factoryBuilder/comments/getAllThreads";
import { useParams } from "react-router-dom";
import { useCommentStore } from "../../../store/collaboration/useCommentStore";
import { getRelativeTime } from "./function/getRelativeTime";
import { useSelectedComment } from "../../../store/builder/store";
interface CommentThreadsProps {
commentClicked: () => void;
comment?: CommentSchema
}
const CommentThreads: React.FC<CommentThreadsProps> = ({ commentClicked, comment }) => {
const [expand, setExpand] = useState(false);
const commentsedUsers = [{ creatorId: "1" }];
const { userName } = getUserData();
const CommentDetails = {
state: "active",
commentId: "c-1",
creatorId: "12",
createdAt: "2 hours ago",
comment: "Thread check",
lastUpdatedAt: "string",
comments: [
{
replyId: "string",
creatorId: "string",
createdAt: "string",
lastUpdatedAt: "string",
comment: "string",
},
{
replyId: "string",
creatorId: "string",
createdAt: "string",
lastUpdatedAt: "string",
comment: "string",
},
],
};
function getUsername(userId: string) {
const UserName = userName?.charAt(0).toUpperCase() || "user";
return UserName;
}
function getDetails(type?: "clicked") {
if (type === "clicked") {
setExpand(true);
commentClicked();
} else {
setExpand((prev) => !prev);
}
}
return (
<div className="comments-threads-wrapper">
<button
onPointerEnter={() => getDetails()}
onPointerLeave={() => getDetails()}
onClick={() => getDetails("clicked")}
className={`comments-threads-container ${expand ? "open" : "closed"
} unread`}
>
<div className="users-commented">
{commentsedUsers.map((val, i) => (
<div
className="users"
key={val.creatorId}
style={{
background: getAvatarColor(i, getUsername(val.creatorId)),
}}
>
{getUsername(val.creatorId)[0]}
</div>
))}
{/* {commentsedUsers.map((val, i) => (
<div
className="users"
key={val.creatorId}
style={{
background: getAvatarColor(i, getUsername(val.creatorId)),
}}
>
{getUsername(val.creatorId)[0]}
</div>
))} */}
</div>
<div className={`last-comment-details ${expand ? "expand" : ""}`}>
<div className="header">
<div className="user-name">
{userName}
{/* {getUsername(CommentDetails.creatorId)} */}
</div>
<div className="time">{comment?.createdAt && getRelativeTime(comment.createdAt)}</div>
</div>
<div className="message">{comment?.threadTitle}</div>
{comment && comment?.comments.length > 0 && (
<div className="comments">
{comment && comment?.comments.length}{" "}
{comment && comment?.comments.length === 1 ? "comment" : "replies"}
</div>
)}
</div>
</button>
</div>
);
};
export default CommentThreads;

View File

@@ -0,0 +1,68 @@
import React, { useState } from "react";
import { getAvatarColor } from "../../../../modules/collaboration/functions/getAvatarColor";
import { getUserData } from "../../../../functions/getUserData";
import { getRelativeTime } from "../function/getRelativeTime";
interface CommentThreadsProps {
commentClicked: () => void;
comment?: CommentSchema;
}
const CommentThreads: React.FC<CommentThreadsProps> = ({ commentClicked, comment }) => {
const [expand, setExpand] = useState(false);
const commentsedUsers = [{ creatorId: "1" }];
const { userName } = getUserData();
function getUsername(userId: string) {
const UserName = userName?.charAt(0).toUpperCase() || "user";
return UserName;
}
function getDetails(type?: "clicked") {
if (type === "clicked") {
setExpand(true);
commentClicked();
} else {
setExpand((prev) => !prev);
}
}
return (
<div className="comments-threads-wrapper">
<button
onPointerEnter={() => getDetails()}
onPointerLeave={() => getDetails()}
onClick={() => getDetails("clicked")}
className={`comments-threads-container ${expand ? "open" : "closed"} unread`}
>
<div className="users-commented">
{commentsedUsers.map((val, i) => (
<div
className="users"
key={val.creatorId}
style={{
background: getAvatarColor(i, getUsername(val.creatorId)),
}}
>
{getUsername(val.creatorId)[0]}
</div>
))}
</div>
<div className={`last-comment-details ${expand ? "expand" : ""}`}>
<div className="header">
<div className="user-name">{userName}</div>
<div className="time">{comment?.createdAt && getRelativeTime(comment.createdAt)}</div>
</div>
<div className="message">{comment?.threadTitle}</div>
{comment && comment?.comments.length > 0 && (
<div className="comments">
{comment?.comments.length} {comment?.comments.length === 1 ? "comment" : "replies"}
</div>
)}
</div>
</button>
</div>
);
};
export default CommentThreads;

View File

@@ -1,254 +1,259 @@
import React, { useEffect, useRef, useState } from "react";
import { getAvatarColor } from "../../../modules/collaboration/functions/getAvatarColor";
import { KebabIcon } from "../../icons/ExportCommonIcons";
import { adjustHeight } from "./function/textAreaHeightAdjust";
import { getUserData } from "../../../functions/getUserData";
import { useParams } from "react-router-dom";
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 { useSceneContext } from "../../../modules/scene/sceneContext";
// import { deleteCommentApi } from "../../../services/factoryBuilder/comments/deleteCommentApi";
// import { addCommentsApi } from "../../../services/factoryBuilder/comments/addCommentsApi";
interface MessageProps {
val: Reply | CommentSchema;
i: number;
setMessages?: React.Dispatch<React.SetStateAction<Reply[]>>;
setIsEditable?: React.Dispatch<React.SetStateAction<boolean>>;
setEditedThread?: React.Dispatch<React.SetStateAction<boolean>>;
setMode?: React.Dispatch<React.SetStateAction<"create" | "edit" | null>>;
isEditable?: boolean;
isEditableThread?: boolean;
editedThread?: boolean;
mode?: "create" | "edit" | null;
}
const Messages: React.FC<MessageProps> = ({ 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 [value, setValue] = useState<string>("comment" in val ? val.comment : val.threadTitle);
const textareaRef = useRef<HTMLTextAreaElement>(null);
useEffect(() => {
if (textareaRef.current) adjustHeight(textareaRef.current);
}, [value]);
function handleCancelAction() {
setCommentPositionState(null);
if (setIsEditable) setIsEditable(true);
setIsEditComment(false);
}
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);
}
} else {
const threadEdit = {
projectId,
userId,
threadTitle: value,
organization,
threadId: (val as CommentSchema).threadId || selectedComment.threadId,
versionId: selectedVersion?.versionId || "",
};
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);
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 {}
}
}
// 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
threadSocket.emit("v1-Comment:delete", deleteComment);
}
} catch {}
};
const handleFocus = (e: React.FocusEvent<HTMLTextAreaElement>) => {
requestAnimationFrame(() => {
if (textareaRef.current) {
const length = textareaRef.current.value.length;
textareaRef.current.setSelectionRange(length, length);
}
});
};
return (
<>
{isEditComment ? (
<div className="edit-container">
<div className="input-container">
<textarea placeholder="type here" ref={textareaRef} autoFocus value={value} onChange={(e) => setValue(e.target.value)} style={{ resize: "none" }} onFocus={handleFocus} />
</div>
<div className="actions-container">
<div className="options"></div>
<div className="actions">
<button
className="cancel-button"
onClick={() => {
handleCancelAction();
}}
>
Cancel
</button>
<button
className="save-button"
onClick={() => {
handleSaveAction();
}}
>
Save
</button>
</div>
</div>
</div>
) : (
<div className="message-container">
<div className="profile" style={{ background: getAvatarColor(i, userName) }}>
{userName?.charAt(0).toUpperCase() || "user"}
</div>
<div className="content">
<div className="user-details">
<div className="user-name">{userName}</div>
<div className="time">{isEditableThread ? getRelativeTime(val.createdAt) : val.createdAt}</div>
</div>
{(val as Reply).creatorId === userId && (
<div className="more-options" onMouseLeave={() => setOpenOptions(false)}>
<button
className="more-options-button"
onClick={() => {
setOpenOptions(!openOptions);
}}
>
<KebabIcon />
</button>
{openOptions && (
<div className="options-list">
<button
className="option"
onClick={(e) => {
e.preventDefault();
setMode && setMode("edit");
setOpenOptions(false);
setEditedThread && setEditedThread(true);
setIsEditComment(true);
}}
>
Edit
</button>
{!isEditableThread && (
<button
className="option"
onClick={() => {
handleDeleteAction((val as Reply).replyId);
}}
>
Delete
</button>
)}
</div>
)}
</div>
)}
<div className="message">{"comment" in val ? val.comment : val.threadTitle}</div>
</div>
</div>
)}
</>
);
};
export default Messages;
import React, { useEffect, useRef, useState } from "react";
import { getAvatarColor } from "../../../../modules/collaboration/functions/getAvatarColor";
import { KebabIcon } from "../../../icons/ExportCommonIcons";
import { adjustHeight } from "../function/textAreaHeightAdjust";
import { getUserData } from "../../../../functions/getUserData";
import { useParams } from "react-router-dom";
import { useSelectedComment, useSocketStore } from "../../../../store/builder/store";
import { getRelativeTime } from "../function/getRelativeTime";
import { editThreadTitleApi } from "../../../../services/factoryBuilder/comments/editThreadTitleApi";
import { useSceneContext } from "../../../../modules/scene/sceneContext";
import { deleteCommentApi } from "../../../../services/factoryBuilder/comments/deleteCommentApi";
import { addCommentsApi } from "../../../../services/factoryBuilder/comments/addCommentApi";
import { editCommentsApi } from "../../../../services/factoryBuilder/comments/editCommentApi";
interface MessageProps {
val: Reply | CommentSchema;
i: number;
setMessages?: React.Dispatch<React.SetStateAction<Reply[]>>;
setIsEditable?: React.Dispatch<React.SetStateAction<boolean>>;
setEditedThread?: React.Dispatch<React.SetStateAction<boolean>>;
setMode?: React.Dispatch<React.SetStateAction<"create" | "edit" | null>>;
isEditable?: boolean;
isEditableThread?: boolean;
editedThread?: boolean;
mode?: "create" | "edit" | null;
}
const Messages: React.FC<MessageProps> = ({ val, i, setMessages, mode, setIsEditable, setEditedThread, editedThread, isEditableThread, setMode }) => {
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, commentStore } = useSceneContext();
const { updateComment, removeReply, updateReply } = commentStore();
const { selectedVersion } = versionStore();
const [value, setValue] = useState<string>("comment" in val ? val.comment : val.threadTitle);
const textareaRef = useRef<HTMLTextAreaElement>(null);
useEffect(() => {
if (textareaRef.current) adjustHeight(textareaRef.current);
}, [value]);
function handleCancelAction() {
setCommentPositionState(null);
if (setIsEditable) setIsEditable(true);
setIsEditComment(false);
}
const handleSaveAction = async () => {
if (!projectId || !selectedVersion || !setIsEditable || !setEditedThread) return;
if (isEditableThread && editedThread) {
if (!threadSocket?.active) {
// API
editThreadTitleApi(projectId, (val as CommentSchema).threadId, value, selectedVersion?.versionId || "").then((editThreadTitle) => {
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 {
// SOCKET
const threadEdit = {
projectId,
userId,
threadTitle: value,
organization,
threadId: (val as CommentSchema).threadId || selectedComment.threadId,
versionId: selectedVersion?.versionId || "",
};
threadSocket.emit("v1:thread:updateTitle", threadEdit);
}
} else if (mode === "edit") {
if (!threadSocket?.active) {
// API
editCommentsApi(projectId, value, selectedComment?.threadId, (val as Reply).replyId, selectedVersion?.versionId || "").then((editComments) => {
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);
setIsEditable(true);
setEditedThread(false);
});
} else {
// SOCKET
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(true);
setEditedThread(false);
}
}
setIsEditComment(false);
};
const handleDeleteAction = async (replyID: any) => {
if (!projectId || !selectedVersion || !setMessages) return;
setOpenOptions(false);
if (!threadSocket?.active) {
// API
deleteCommentApi(projectId, selectedComment?.threadId, (val as Reply).replyId, selectedVersion?.versionId || "").then((deletedComment) => {
if (deletedComment === "'Thread comment deleted Successfully'") {
setMessages((prev) => prev.filter((message) => message.replyId !== replyID));
removeReply(val.creatorId, replyID);
}
});
} else {
// SOCKET
const deleteComment = {
projectId,
userId,
commentId: (val as Reply).replyId,
organization,
threadId: selectedComment?.threadId,
versionId: selectedVersion?.versionId || "",
};
setMessages((prev) => {
return prev.filter((message) => message.replyId !== (val as Reply).replyId);
});
removeReply(selectedComment?.threadId, (val as Reply).replyId);
threadSocket.emit("v1-Comment:delete", deleteComment);
}
};
const handleFocus = (e: React.FocusEvent<HTMLTextAreaElement>) => {
requestAnimationFrame(() => {
if (textareaRef.current) {
const length = textareaRef.current.value.length;
textareaRef.current.setSelectionRange(length, length);
}
});
};
return (
<>
{isEditComment ? (
<div className="edit-container">
<div className="input-container">
<textarea placeholder="type here" ref={textareaRef} autoFocus value={value} onChange={(e) => setValue(e.target.value)} style={{ resize: "none" }} onFocus={handleFocus} />
</div>
<div className="actions-container">
<div className="options"></div>
<div className="actions">
<button
className="cancel-button"
onClick={() => {
handleCancelAction();
}}
>
Cancel
</button>
<button
className="save-button"
onClick={() => {
handleSaveAction();
}}
>
Save
</button>
</div>
</div>
</div>
) : (
<div className="message-container">
<div className="profile" style={{ background: getAvatarColor(i, userName) }}>
{userName?.charAt(0).toUpperCase() || "user"}
</div>
<div className="content">
<div className="user-details">
<div className="user-name">{userName}</div>
<div className="time">{isEditableThread ? getRelativeTime(val.createdAt) : val.createdAt}</div>
</div>
{(val as Reply).creatorId === userId && (
<div className="more-options" onMouseLeave={() => setOpenOptions(false)}>
<button
className="more-options-button"
onClick={() => {
setOpenOptions(!openOptions);
}}
>
<KebabIcon />
</button>
{openOptions && (
<div className="options-list">
<button
className="option"
onClick={(e) => {
e.preventDefault();
setMode && setMode("edit");
setOpenOptions(false);
setEditedThread && setEditedThread(true);
setIsEditComment(true);
}}
>
Edit
</button>
{!isEditableThread && (
<button
className="option"
onClick={() => {
handleDeleteAction((val as Reply).replyId);
}}
>
Delete
</button>
)}
</div>
)}
</div>
)}
<div className="message">{"comment" in val ? val.comment : val.threadTitle}</div>
</div>
</div>
)}
</>
);
};
export default Messages;

View File

@@ -1,387 +1,382 @@
import React, { useEffect, useRef, useState } from "react";
import { CloseIcon, KebabIcon } from "../../icons/ExportCommonIcons";
import Messages from "./Messages";
import { ExpandIcon } from "../../icons/SimulationIcons";
import { adjustHeight } from "./function/textAreaHeightAdjust";
import { useParams } from "react-router-dom";
import { useSelectedComment, useSocketStore } from "../../../store/builder/store";
import { useCommentStore } from "../../../store/collaboration/useCommentStore";
import { getUserData } from "../../../functions/getUserData";
import ThreadSocketResponsesDev from "../../../modules/collaboration/socket/threadSocketResponses.dev";
import { useSceneContext } from "../../../modules/scene/sceneContext";
// import { addCommentsApi } from "../../../services/factoryBuilder/comments/addCommentsApi";
// import { deleteThreadApi } from "../../../services/factoryBuilder/comments/deleteThreadApi";
// import { createThreadApi } from "../../../services/factoryBuilder/comments/createThreadApi";
// import { getRelativeTime } from "./function/getRelativeTime";
const ThreadChat: React.FC = () => {
const { userId, organization } = getUserData();
const [openThreadOptions, setOpenThreadOptions] = useState(false);
const [inputActive, setInputActive] = useState(false);
const [value, setValue] = useState<string>("");
const { addComment, removeReply, removeComment, addReply, comments } = useCommentStore();
const { selectedComment, setSelectedComment, setCommentPositionState, commentPositionState, position2Dstate } = useSelectedComment();
const [mode, setMode] = useState<"create" | "edit" | null>("create");
const [isEditable, setIsEditable] = useState(false);
const [editedThread, setEditedThread] = useState(false);
const textareaRef = useRef<HTMLTextAreaElement>(null);
const wrapperRef = useRef<HTMLDivElement>(null);
const [messages, setMessages] = useState<Reply[]>([]);
const { projectId } = useParams();
const [dragging, setDragging] = useState(false);
const [dragOffset, setDragOffset] = useState({ x: 0, y: 0 });
const [position, setPosition] = useState({ x: position2Dstate.x, y: position2Dstate.y });
const { threadSocket } = useSocketStore();
const modeRef = useRef<"create" | "edit" | null>(null);
const messagesRef = useRef<HTMLDivElement>(null);
const { versionStore } = useSceneContext();
const { selectedVersion } = versionStore();
useEffect(() => {
modeRef.current = mode;
}, [mode]);
useEffect(() => {
if (comments.length > 0 && selectedComment) {
const allMessages = comments
.flatMap((val: any) => (val?.threadId === selectedComment?.threadId ? val.comments : []))
.map((c) => {
return {
replyId: c._id ?? c.replyId,
creatorId: c.creatorId || c.userId,
createdAt: c.createdAt,
lastUpdatedAt: "1 hr ago",
comment: c.comment,
_id: c._id ?? c.replyId,
};
});
setMessages(allMessages);
}
}, []);
useEffect(() => {
if (textareaRef.current) adjustHeight(textareaRef.current);
}, [value]);
const clamp = (val: number, min: number, max: number) => {
return Math.min(Math.max(val, min), max);
};
const handlePointerDown = (event: React.PointerEvent<HTMLDivElement>) => {
if (event.button !== 0) return;
// Avoid dragging if a button, icon, textarea etc. was clicked
const target = event.target as HTMLElement;
if (
target.closest("button") ||
target.closest(".sent-button") ||
target.closest("textarea") ||
target.closest(".options-button") ||
target.closest(".options-list") ||
target.closest(".send-message-wrapper") ||
target.closest(".options delete")
) {
return;
}
const wrapper = wrapperRef.current;
if (!wrapper) return;
const rect = wrapper.getBoundingClientRect();
const offsetX = event.clientX - rect.left;
const offsetY = event.clientY - rect.top;
setDragging(true);
setDragOffset({ x: offsetX, y: offsetY });
wrapper.setPointerCapture(event.pointerId);
};
const updatePosition = ({ clientX, clientY }: { clientX: number; clientY: number }, allowMove: boolean = true) => {
if (!allowMove || !wrapperRef.current) return;
const container = document.getElementById("work-space-three-d-canvas");
const wrapper = wrapperRef.current;
if (!container || !wrapper) return;
const containerRect = container.getBoundingClientRect();
let newX = clientX - containerRect.left - dragOffset.x;
let newY = clientY - containerRect.top - dragOffset.y;
const maxX = containerRect.width - wrapper.offsetWidth;
const maxY = containerRect.height - wrapper.offsetHeight;
newX = clamp(newX, 0, maxX);
newY = clamp(newY, 0, maxY);
setPosition({ x: newX, y: newY });
};
const handlePointerMove = (e: { clientX: number; clientY: number }) => {
if (dragging) updatePosition(e, true);
};
// Commented this useEffect to prevent offset after user saved the comment
// useEffect(() => {
// updatePosition({ clientX: position.x, clientY: position.y }, true);
// }, [selectedComment]);
const handlePointerUp = (event: React.PointerEvent<HTMLDivElement>) => {
if (!dragging) return;
setDragging(false);
const wrapper = wrapperRef.current;
if (wrapper) wrapper.releasePointerCapture(event.pointerId);
};
const handleCreateComments = async (e: any) => {
// Continue send or create message only there is only value avalibale
// To prevent empty value
if (!value) return;
e.preventDefault();
try {
// const createComments = await addCommentsApi(projectId, value, selectedComment?.threadId, selectedVersion?.versionId || "")/
// if (createComments.message === 'Thread comments add Successfully' && createComments.data) {
// const commentData = {
// replyId: `${createComments.data?._id}`,
// creatorId: `${selectedComment?.threadId}`,
// createdAt: "2 hrs ago",
// lastUpdatedAt: "2 hrs ago",
// comment: value,
// }
// setMessages((prevMessages) => [
// ...prevMessages,
// commentData,
// ]);
// addReply(selectedComment?.threadId, commentData)
// }
if (threadSocket && mode === "create") {
const addComment = {
versionId: selectedVersion?.versionId || "",
projectId,
userId,
comment: value,
organization,
threadId: selectedComment?.threadId,
};
threadSocket.emit("v1-Comment:add", addComment);
}
} catch {}
setInputActive(false);
};
const handleDeleteThread = async () => {
if (!projectId) return;
try {
// const deleteThread = await deleteThreadApi(projectId, selectedComment?.threadId, selectedVersion?.versionId || "")
// if (deleteThread.message === "Thread deleted Successfully") {
// removeComment(selectedComment?.threadId)
// setSelectedComment([])
// }
if (threadSocket) {
// projectId, userId, organization, threadId
const deleteThread = {
projectId,
userId,
organization,
threadId: selectedComment?.threadId,
versionId: selectedVersion?.versionId || "",
};
setSelectedComment(null);
removeComment(selectedComment?.threadId);
threadSocket.emit("v1:thread:delete", deleteThread);
}
} catch {}
};
const handleCreateThread = async (e: any) => {
e.preventDefault();
if (!projectId) return;
try {
// const thread = await createThreadApi(
// projectId,
// "active",
// commentPositionState[0].position,
// [0, 0, 0],
// value,
// selectedVersion?.versionId || ""
// );
//
// if (thread.message === "Thread created Successfully" && thread?.threadData) {
//
// const comment: CommentSchema = {
// state: 'active',
// threadId: thread?.threadData?._id,
// creatorId: userId,
// createdAt: getRelativeTime(thread.threadData?.createdAt),
// threadTitle: value,
// lastUpdatedAt: new Date().toISOString(),
// position: commentPositionState[0].position,
// rotation: [0, 0, 0],
// comments: []
// }
// addComment(comment);
// setCommentPositionState(null);
// setInputActive(false);
// setSelectedComment([])
// }
const createThread = {
projectId,
versionId: selectedVersion?.versionId || "",
userId,
organization,
state: "active",
position: commentPositionState.position,
rotation: [0, 0, 0],
threadTitle: value,
};
if (threadSocket) {
setInputActive(false);
threadSocket.emit("v1:thread:create", createThread);
}
} catch {}
};
const scrollToBottom = () => {
const messagesWrapper = document.querySelector(".messages-wrapper");
if (messagesWrapper) {
messagesWrapper.scrollTop = messagesWrapper.scrollHeight;
}
};
useEffect(() => {
if (messages.length > 0) scrollToBottom();
}, [messages]);
return (
<div
ref={wrapperRef}
className="thread-chat-wrapper"
onPointerDown={handlePointerDown}
onPointerMove={(e) => handlePointerMove({ clientX: e.clientX, clientY: e.clientY })}
onPointerUp={handlePointerUp}
style={{
position: "absolute",
left: position.x,
top: position.y,
cursor: dragging ? "grabbing" : "grab",
userSelect: "none",
zIndex: 9999,
}}
>
<div className="thread-chat-container">
<div className="header-wrapper">
<div className="header">Comment</div>
<div className="header-options">
<div
className="options-button"
style={{ cursor: "pointer" }}
onClick={(e) => {
e.preventDefault();
setOpenThreadOptions((prev) => !prev);
}}
>
<KebabIcon />
</div>
{openThreadOptions && (
<div className="options-list">
<div className="options">Mark as Unread</div>
<div className="options">Mark as Resolved</div>
<div className="options delete" onClick={handleDeleteThread}>
Delete Thread
</div>
</div>
)}
<button
className="close-button"
onClick={() => {
setSelectedComment(null);
setCommentPositionState(null);
}}
>
<CloseIcon />
</button>
</div>
</div>
<div className="messages-wrapper" ref={messagesRef}>
{selectedComment && <Messages val={selectedComment} i={1} key={selectedComment.creatorId} isEditableThread={true} setEditedThread={setEditedThread} editedThread={editedThread} />}
{messages &&
messages.map((val, i) => (
<Messages
val={val as any}
i={i}
key={val.replyId}
setMessages={setMessages}
setIsEditable={setIsEditable}
isEditable={isEditable}
isEditableThread={false}
setMode={setMode}
mode={mode}
/>
))}
</div>
<div className="send-message-wrapper">
<div className={`input-container ${inputActive ? "active" : ""}`}>
<textarea
placeholder={commentPositionState && selectedComment === null ? "Type Thread Title" : "type something"}
ref={textareaRef}
value={value}
onChange={(e) => setValue(e.target.value)}
onKeyDown={(e) => {
if (e.key === "Enter") {
e.preventDefault();
if (commentPositionState && selectedComment === null) {
handleCreateThread(e);
} else {
setMode("create");
handleCreateComments(e);
textareaRef.current?.blur();
}
setValue("");
}
if (e.key === "Escape") {
textareaRef.current?.blur();
}
}}
onClick={() => {
if (!commentPositionState && selectedComment !== null) {
setMode("create");
}
}}
autoFocus={selectedComment === null}
onBlur={() => setInputActive(false)}
onFocus={() => setInputActive(true)}
style={{ resize: "none" }}
/>
<div
className={`sent-button ${value === "" ? "disable-send-btn" : ""}`}
onClick={(e) => {
if (commentPositionState && selectedComment === null) {
handleCreateThread(e);
} else {
setMode("create");
handleCreateComments(e);
}
setValue("");
}}
>
<ExpandIcon />
</div>
</div>
</div>
</div>
<ThreadSocketResponsesDev setMessages={setMessages} modeRef={modeRef} messages={messages} />
</div>
);
};
export default ThreadChat;
import React, { useEffect, useRef, useState } from "react";
import { CloseIcon, KebabIcon } from "../../../icons/ExportCommonIcons";
import Messages from "./Messages";
import { ExpandIcon } from "../../../icons/SimulationIcons";
import { adjustHeight } from "../function/textAreaHeightAdjust";
import { useParams } from "react-router-dom";
import { useSelectedComment, useSocketStore } from "../../../../store/builder/store";
import { getUserData } from "../../../../functions/getUserData";
import ThreadSocketResponsesDev from "../../../../modules/collaboration/socket/threadSocketResponses.dev";
import { useSceneContext } from "../../../../modules/scene/sceneContext";
import { addCommentsApi } from "../../../../services/factoryBuilder/comments/addCommentApi";
import { deleteThreadApi } from "../../../../services/factoryBuilder/comments/deleteThreadApi";
import { createThreadApi } from "../../../../services/factoryBuilder/comments/createThreadApi";
import { getRelativeTime } from "../function/getRelativeTime";
const ThreadChat: React.FC = () => {
const { userId, organization } = getUserData();
const [openThreadOptions, setOpenThreadOptions] = useState(false);
const [inputActive, setInputActive] = useState(false);
const [value, setValue] = useState<string>("");
const { selectedComment, setSelectedComment, setCommentPositionState, commentPositionState, position2Dstate } = useSelectedComment();
const [mode, setMode] = useState<"create" | "edit" | null>("create");
const [isEditable, setIsEditable] = useState(false);
const [editedThread, setEditedThread] = useState(false);
const textareaRef = useRef<HTMLTextAreaElement>(null);
const wrapperRef = useRef<HTMLDivElement>(null);
const [messages, setMessages] = useState<Reply[]>([]);
const { projectId } = useParams();
const [dragging, setDragging] = useState(false);
const [dragOffset, setDragOffset] = useState({ x: 0, y: 0 });
const [position, setPosition] = useState({ x: position2Dstate.x, y: position2Dstate.y });
const { threadSocket } = useSocketStore();
const modeRef = useRef<"create" | "edit" | null>(null);
const messagesRef = useRef<HTMLDivElement>(null);
const { versionStore, commentStore } = useSceneContext();
const { selectedVersion } = versionStore();
const { addComment, removeComment, addReply, comments } = commentStore();
useEffect(() => {
modeRef.current = mode;
}, [mode]);
useEffect(() => {
if (comments.length > 0 && selectedComment) {
const allMessages = comments
.flatMap((val: any) => (val?.threadId === selectedComment?.threadId ? val.comments : []))
.map((c) => {
return {
replyId: c._id ?? c.replyId,
creatorId: c.creatorId || c.userId,
createdAt: c.createdAt,
lastUpdatedAt: "1 hr ago",
comment: c.comment,
_id: c._id ?? c.replyId,
};
});
setMessages(allMessages);
}
}, []);
useEffect(() => {
if (textareaRef.current) adjustHeight(textareaRef.current);
}, [value]);
const clamp = (val: number, min: number, max: number) => {
return Math.min(Math.max(val, min), max);
};
const handlePointerDown = (event: React.PointerEvent<HTMLDivElement>) => {
if (event.button !== 0) return;
const target = event.target as HTMLElement;
if (
target.closest("button") ||
target.closest(".sent-button") ||
target.closest("textarea") ||
target.closest(".options-button") ||
target.closest(".options-list") ||
target.closest(".send-message-wrapper") ||
target.closest(".options delete")
) {
return;
}
const wrapper = wrapperRef.current;
if (!wrapper) return;
const rect = wrapper.getBoundingClientRect();
const offsetX = event.clientX - rect.left;
const offsetY = event.clientY - rect.top;
setDragging(true);
setDragOffset({ x: offsetX, y: offsetY });
wrapper.setPointerCapture(event.pointerId);
};
const updatePosition = ({ clientX, clientY }: { clientX: number; clientY: number }, allowMove: boolean = true) => {
if (!allowMove || !wrapperRef.current) return;
const container = document.getElementById("work-space-three-d-canvas");
const wrapper = wrapperRef.current;
if (!container || !wrapper) return;
const containerRect = container.getBoundingClientRect();
let newX = clientX - containerRect.left - dragOffset.x;
let newY = clientY - containerRect.top - dragOffset.y;
const maxX = containerRect.width - wrapper.offsetWidth;
const maxY = containerRect.height - wrapper.offsetHeight;
newX = clamp(newX, 0, maxX);
newY = clamp(newY, 0, maxY);
setPosition({ x: newX, y: newY });
};
const handlePointerMove = (e: { clientX: number; clientY: number }) => {
if (dragging) updatePosition(e, true);
};
// Commented this useEffect to prevent offset after user saved the comment
// useEffect(() => {
// updatePosition({ clientX: position.x, clientY: position.y }, true);
// }, [selectedComment]);
const handlePointerUp = (event: React.PointerEvent<HTMLDivElement>) => {
if (!dragging) return;
setDragging(false);
const wrapper = wrapperRef.current;
if (wrapper) wrapper.releasePointerCapture(event.pointerId);
};
const handleCreateComments = async (e: any) => {
e.preventDefault();
if (!value) return;
if (!threadSocket?.connected && mode === "create") {
// API
addCommentsApi(projectId, value, selectedComment?.threadId, selectedVersion?.versionId || "").then((createComments) => {
if (createComments.message === "Thread comments add Successfully" && createComments.data) {
const commentData = {
replyId: `${createComments.data?._id}`,
creatorId: `${selectedComment?.threadId}`,
createdAt: "2 hrs ago",
lastUpdatedAt: "2 hrs ago",
comment: value,
};
setMessages((prevMessages) => [...prevMessages, commentData]);
addReply(selectedComment?.threadId, commentData);
}
});
} else if (mode === "create") {
// SOCKET
const addComment = {
versionId: selectedVersion?.versionId || "",
projectId,
userId,
comment: value,
organization,
threadId: selectedComment?.threadId,
};
threadSocket.emit("v1-Comment:add", addComment);
}
setInputActive(false);
};
const handleDeleteThread = async () => {
if (!projectId) return;
if (!threadSocket?.connected) {
// API
deleteThreadApi(projectId, selectedComment?.threadId, selectedVersion?.versionId || "").then((deleteThread) => {
if (deleteThread.message === "Thread deleted Successfully") {
removeComment(selectedComment?.threadId);
setSelectedComment(null);
}
});
} else {
// SOCKET
const deleteThread = {
projectId,
userId,
organization,
threadId: selectedComment?.threadId,
versionId: selectedVersion?.versionId || "",
};
setSelectedComment(null);
removeComment(selectedComment?.threadId);
threadSocket.emit("v1:thread:delete", deleteThread);
}
};
const handleCreateThread = async (e: any) => {
e.preventDefault();
if (!projectId) return;
if (!threadSocket?.connected) {
// API
createThreadApi(projectId, "active", commentPositionState.position, [0, 0, 0], value, selectedVersion?.versionId || "").then((thread) => {
if (thread.message === "Thread created Successfully" && thread?.threadData) {
const comment: CommentSchema = {
state: "active",
threadId: thread?.threadData?._id,
creatorId: userId,
createdAt: getRelativeTime(thread.threadData?.createdAt),
threadTitle: value,
lastUpdatedAt: new Date().toISOString(),
position: commentPositionState.position,
rotation: [0, 0, 0],
comments: [],
};
addComment(comment);
setCommentPositionState(null);
setInputActive(false);
setSelectedComment(null);
}
});
} else {
// SOCKET
const createThread = {
projectId,
versionId: selectedVersion?.versionId || "",
userId,
organization,
state: "active",
position: commentPositionState.position,
rotation: [0, 0, 0],
threadTitle: value,
};
setCommentPositionState(null);
setInputActive(false);
setSelectedComment(null);
threadSocket.emit("v1:thread:create", createThread);
}
};
const scrollToBottom = () => {
const messagesWrapper = document.querySelector(".messages-wrapper");
if (messagesWrapper) {
messagesWrapper.scrollTop = messagesWrapper.scrollHeight;
}
};
useEffect(() => {
if (messages.length > 0) scrollToBottom();
}, [messages]);
return (
<div
ref={wrapperRef}
className="thread-chat-wrapper"
onPointerDown={handlePointerDown}
onPointerMove={(e) => handlePointerMove({ clientX: e.clientX, clientY: e.clientY })}
onPointerUp={handlePointerUp}
style={{
position: "absolute",
left: position.x,
top: position.y,
cursor: dragging ? "grabbing" : "grab",
userSelect: "none",
zIndex: 9999,
}}
>
<div className="thread-chat-container">
<div className="header-wrapper">
<div className="header">Comment</div>
<div className="header-options">
<div
className="options-button"
style={{ cursor: "pointer" }}
onClick={(e) => {
e.preventDefault();
setOpenThreadOptions((prev) => !prev);
}}
>
<KebabIcon />
</div>
{openThreadOptions && (
<div className="options-list">
<div className="options">Mark as Unread</div>
<div className="options">Mark as Resolved</div>
<div className="options delete" onClick={handleDeleteThread}>
Delete Thread
</div>
</div>
)}
<button
className="close-button"
onClick={() => {
setSelectedComment(null);
setCommentPositionState(null);
}}
>
<CloseIcon />
</button>
</div>
</div>
<div className="messages-wrapper" ref={messagesRef}>
{selectedComment && <Messages val={selectedComment} i={1} key={selectedComment.creatorId} isEditableThread={true} setEditedThread={setEditedThread} editedThread={editedThread} />}
{messages.map((val, i) => (
<Messages
val={val as any}
i={i}
key={val.replyId}
setMessages={setMessages}
setIsEditable={setIsEditable}
isEditable={isEditable}
isEditableThread={false}
setMode={setMode}
mode={mode}
/>
))}
</div>
<div className="send-message-wrapper">
<div className={`input-container ${inputActive ? "active" : ""}`}>
<textarea
placeholder={commentPositionState && selectedComment === null ? "Type Thread Title" : "type something"}
ref={textareaRef}
value={value}
onChange={(e) => setValue(e.target.value)}
onKeyDown={(e) => {
if (e.key === "Enter") {
e.preventDefault();
if (commentPositionState && selectedComment === null) {
handleCreateThread(e);
} else {
setMode("create");
handleCreateComments(e);
textareaRef.current?.blur();
}
setValue("");
}
if (e.key === "Escape") {
textareaRef.current?.blur();
}
}}
onClick={() => {
if (!commentPositionState && selectedComment !== null) {
setMode("create");
}
}}
autoFocus={selectedComment === null}
onBlur={() => setInputActive(false)}
onFocus={() => setInputActive(true)}
style={{ resize: "none" }}
/>
<div
className={`sent-button ${value === "" ? "disable-send-btn" : ""}`}
onClick={(e) => {
if (commentPositionState && selectedComment === null) {
handleCreateThread(e);
} else {
setMode("create");
handleCreateComments(e);
}
setValue("");
}}
>
<ExpandIcon />
</div>
</div>
</div>
</div>
<ThreadSocketResponsesDev setMessages={setMessages} modeRef={modeRef} messages={messages} />
</div>
);
};
export default ThreadChat;

View File

@@ -31,6 +31,7 @@ function Model({ asset, isRendered, loader }: Readonly<{ asset: Asset; isRendere
useEffect(() => {
if (!fieldData && asset.eventData) {
getAssetFieldApi(asset.assetId).then((data) => {
if (!data) return;
if (data.type === "ArmBot") {
if (data.data) {
const fieldData: IK[] = data.data;

View File

@@ -1,16 +1,17 @@
import { Html, TransformControls } from '@react-three/drei';
import { useEffect, useRef, useState } from 'react'
import { usePlayButtonStore } from '../../../../../store/ui/usePlayButtonStore';
import CommentThreads from '../../../../../components/ui/collaboration/CommentThreads';
import { useSelectedComment } from '../../../../../store/builder/store';
import { Group, Object3D, Vector2, Vector3 } from 'three';
import { useThree } from '@react-three/fiber';
import { Html, TransformControls } from "@react-three/drei";
import { useEffect, useRef, useState } from "react";
import { usePlayButtonStore } from "../../../../../store/ui/usePlayButtonStore";
import CommentThreads from "../../../../../components/ui/collaboration/threads/CommentThreads";
import { useSelectedComment } from "../../../../../store/builder/store";
import { Group, Object3D, Vector3 } from "three";
import { useThree } from "@react-three/fiber";
import { detectModifierKeys } from "../../../../../utils/shortcutkeys/detectModifierKeys";
function CommentInstance({ comment }: { readonly comment: CommentSchema }) {
function ThreadInstance({ comment }: { readonly comment: CommentSchema }) {
const { isPlaying } = usePlayButtonStore();
const CommentRef = useRef(null);
const [selectedObject, setSelectedObject] = useState<Object3D | null>(null);
const { selectedComment, setSelectedComment, setPosition2Dstate } = useSelectedComment()
const { selectedComment, setSelectedComment, setPosition2Dstate } = useSelectedComment();
const [transformMode, setTransformMode] = useState<"translate" | "rotate" | null>(null);
const groupRef = useRef<Group>(null);
const { size, camera } = useThree();
@@ -33,28 +34,26 @@ function CommentInstance({ comment }: { readonly comment: CommentSchema }) {
const commentClicked = () => {
setSelectedComment(comment);
const position = new Vector3(comment.position[0], comment.position[1], comment.position[2])
const position = new Vector3(comment.position[0], comment.position[1], comment.position[2]);
position.project(camera);
const x = (position.x * 0.5 + 0.5) * size.width;
const y = (-(position.y * 0.5) + 0.2) * size.height;
setPosition2Dstate({ x, y })
setPosition2Dstate({ x, y });
if (groupRef.current) {
setSelectedObject(groupRef.current);
}
}
};
useEffect(() => {
if (!selectedComment || selectedComment.threadId !== comment.threadId) {
setSelectedObject(null)
setSelectedObject(null);
}
}, [selectedComment])
}, [selectedComment]);
if (comment.state === 'inactive' || isPlaying) return null;
if (comment.state === "inactive" || isPlaying) return null;
return (
<>
<group ref={groupRef} position={comment.position} rotation={comment.rotation}>
<Html
@@ -65,7 +64,7 @@ function CommentInstance({ comment }: { readonly comment: CommentSchema }) {
center
// position={comment.position}
// rotation={comment.rotation}
className='comments-main-wrapper'
className="comments-main-wrapper"
>
<CommentThreads commentClicked={commentClicked} comment={comment} />
</Html>
@@ -80,11 +79,7 @@ function CommentInstance({ comment }: { readonly comment: CommentSchema }) {
/>
)} */}
</>
)
);
}
export default CommentInstance;
export default ThreadInstance;

View File

@@ -1,6 +1,5 @@
import React, { useEffect } from "react";
import CommentInstance from "./commentInstance/commentInstance";
import { useCommentStore } from "../../../../store/collaboration/useCommentStore";
import { getAllThreads } from "../../../../services/factoryBuilder/comments/getAllThreads";
import { useParams } from "react-router-dom";
import { getUserData } from "../../../../functions/getUserData";
@@ -8,10 +7,10 @@ import { getRelativeTime } from "../../../../components/ui/collaboration/functio
import { useSceneContext } from "../../../scene/sceneContext";
function CommentInstances() {
const { comments, setComments } = useCommentStore();
const { projectId } = useParams();
const { userId } = getUserData();
const { versionStore } = useSceneContext();
const { versionStore, commentStore } = useSceneContext();
const { comments, setComments } = commentStore();
const { selectedVersion } = versionStore();
useEffect(() => {
@@ -42,7 +41,7 @@ function CommentInstances() {
.catch((err) => {
console.error("Failed to fetch threads:", err);
});
}, []);
}, [projectId, selectedVersion]);
return (
<>

View File

@@ -1,30 +1,30 @@
import React, { useEffect } from 'react';
import { useSelectedComment, useSocketStore } from '../../../store/builder/store';
import { useCommentStore } from '../../../store/collaboration/useCommentStore';
import { getUserData } from '../../../functions/getUserData';
import { getRelativeTime } from '../../../components/ui/collaboration/function/getRelativeTime';
import React, { useEffect } from "react";
import { useSelectedComment, useSocketStore } from "../../../store/builder/store";
import { getUserData } from "../../../functions/getUserData";
import { getRelativeTime } from "../../../components/ui/collaboration/function/getRelativeTime";
import { useSceneContext } from "../../scene/sceneContext";
interface ThreadSocketProps {
setMessages: React.Dispatch<React.SetStateAction<Reply[]>>;
// mode: 'create' | 'edit' | null
modeRef: React.RefObject<'create' | 'edit' | null>;
messages: Reply[]
modeRef: React.RefObject<"create" | "edit" | null>;
messages: Reply[];
}
const ThreadSocketResponsesDev = ({ setMessages, modeRef, messages }: ThreadSocketProps) => {
const { threadSocket } = useSocketStore();
const { selectedComment, setSelectedComment, setCommentPositionState, commentPositionState } = useSelectedComment();
const { comments, removeReply, addComment, addReply, updateComment, updateReply } = useCommentStore();
const { commentStore } = useSceneContext();
const { comments, removeReply, addComment, addReply, updateComment, updateReply } = commentStore();
const { userId } = getUserData();
useEffect(() => {
if (!threadSocket) return;
// --- Add Comment Handler ---
// const handleAddComment = (data: any) => {
//
//
//
//
// const commentData = {
// replyId: data.data?._id,
// creatorId: data.data?.userId,
@@ -32,11 +32,11 @@ const ThreadSocketResponsesDev = ({ setMessages, modeRef, messages }: ThreadSock
// lastUpdatedAt: '2 hrs ago',
// comment: data.data.comment,
// };
// //
//
// //
//
// if (mode == "create") {
// addReply(selectedComment?.threadId, commentData);
//
//
// setMessages(prevMessages => [...prevMessages, commentData]);
// } else if (mode == "edit") {
// updateReply(selectedComment?.threadId, data.data?._id, commentData);
@@ -48,17 +48,14 @@ const ThreadSocketResponsesDev = ({ setMessages, modeRef, messages }: ThreadSock
// : message;
// })
// );
//
//
// } else {
//
//
// }
// threadSocket.off('v1-Comment:response:add', handleAddComment);
// };
// threadSocket.on('v1-Comment:response:add', handleAddComment);
const handleAddComment = (data: any) => {
const commentData = {
replyId: data.data?._id,
creatorId: data.data?.userId,
@@ -75,27 +72,21 @@ const ThreadSocketResponsesDev = ({ setMessages, modeRef, messages }: ThreadSock
setMessages((prev) =>
prev.map((message) => {
// 👈 log each message
return message.replyId === data.data?._id
? { ...message, comment: data.data?.comment }
: message;
return message.replyId === data.data?._id ? { ...message, comment: data.data?.comment } : message;
})
);
}
};
threadSocket.on('v1-Comment:response:add', handleAddComment);
threadSocket.on("v1-Comment:response:add", handleAddComment);
// --- Delete Comment Handler ---
const handleDeleteComment = (data: any) => {
};
threadSocket.on('v1-Comment:response:delete', handleDeleteComment);
const handleDeleteComment = (data: any) => {};
threadSocket.on("v1-Comment:response:delete", handleDeleteComment);
// --- Create Thread Handler ---
const handleCreateThread = (data: any) => {
const comment: CommentSchema = {
state: 'active',
state: "active",
threadId: data.data?._id,
creatorId: userId || data.data?.userId,
createdAt: data.data?.createdAt,
@@ -105,32 +96,26 @@ const ThreadSocketResponsesDev = ({ setMessages, modeRef, messages }: ThreadSock
rotation: [0, 0, 0],
comments: [],
};
setSelectedComment(comment)
setSelectedComment(comment);
addComment(comment);
setCommentPositionState(null);
// setSelectedComment(null);
};
threadSocket.on('v1-thread:response:create', handleCreateThread);
threadSocket.on("v1-thread:response:create", handleCreateThread);
// --- Delete Thread Handler ---
// const handleDeleteThread = (data: any) => {
//
//
// };
// threadSocket.on("v1-thread:response:delete", handleDeleteThread);
const handleDeleteThread = (data: any) => {
};
const handleDeleteThread = (data: any) => {};
threadSocket.on("v1-thread:response:delete", handleDeleteThread);
const handleEditThread = (data: any) => {
const editedThread: CommentSchema = {
state: 'active',
state: "active",
threadId: data.data?._id,
creatorId: userId,
createdAt: data.data?.createdAt,
@@ -141,23 +126,37 @@ const ThreadSocketResponsesDev = ({ setMessages, modeRef, messages }: ThreadSock
comments: data.data?.comments,
};
//
//
updateComment(data.data?._id, editedThread);
setSelectedComment(editedThread)
setSelectedComment(editedThread);
// setSelectedComment(null);
};
threadSocket.on('v1-thread:response:updateTitle', handleEditThread);
threadSocket.on("v1-thread:response:updateTitle", handleEditThread);
// Cleanup on unmount
return () => {
threadSocket.off('v1-Comment:response:add', handleAddComment);
threadSocket.off('v1-Comment:response:delete', handleDeleteComment);
threadSocket.off('v1-thread:response:create', handleCreateThread);
threadSocket.off('v1-thread:response:delete', handleDeleteThread);
threadSocket.off('v1-thread:response:updateTitle', handleEditThread);
threadSocket.off("v1-Comment:response:add", handleAddComment);
threadSocket.off("v1-Comment:response:delete", handleDeleteComment);
threadSocket.off("v1-thread:response:create", handleCreateThread);
threadSocket.off("v1-thread:response:delete", handleDeleteThread);
threadSocket.off("v1-thread:response:updateTitle", handleEditThread);
};
}, [threadSocket, selectedComment, commentPositionState, userId, setMessages, addReply, addComment, setSelectedComment, setCommentPositionState, updateComment, comments, modeRef.current, messages]);
}, [
threadSocket,
selectedComment,
commentPositionState,
userId,
setMessages,
addReply,
addComment,
setSelectedComment,
setCommentPositionState,
updateComment,
comments,
modeRef.current,
messages,
]);
return null;
};

View File

@@ -1,45 +1,46 @@
import { createContext, useContext, useMemo, useRef } from 'react';
import { createContext, useContext, useMemo, useRef } from "react";
import { createVersionStore, VersionStoreType } from '../../store/builder/useVersionStore';
import { createVersionStore, VersionStoreType } from "../../store/builder/useVersionStore";
import { createAssetStore, AssetStoreType } from '../../store/builder/useAssetStore';
import { createWallAssetStore, WallAssetStoreType } from '../../store/builder/useWallAssetStore';
import { createWallStore, WallStoreType } from '../../store/builder/useWallStore';
import { createAisleStore, AisleStoreType } from '../../store/builder/useAisleStore';
import { createZoneStore, ZoneStoreType } from '../../store/builder/useZoneStore';
import { createFloorStore, FloorStoreType } from '../../store/builder/useFloorStore';
import { createAssetStore, AssetStoreType } from "../../store/builder/useAssetStore";
import { createWallAssetStore, WallAssetStoreType } from "../../store/builder/useWallAssetStore";
import { createWallStore, WallStoreType } from "../../store/builder/useWallStore";
import { createAisleStore, AisleStoreType } from "../../store/builder/useAisleStore";
import { createZoneStore, ZoneStoreType } from "../../store/builder/useZoneStore";
import { createFloorStore, FloorStoreType } from "../../store/builder/useFloorStore";
import { createUndoRedo2DStore, UndoRedo2DStoreType } from '../../store/builder/useUndoRedo2DStore';
import { createUndoRedo3DStore, UndoRedo3DStoreType } from '../../store/builder/useUndoRedo3DStore';
import { createUndoRedo2DStore, UndoRedo2DStoreType } from "../../store/builder/useUndoRedo2DStore";
import { createUndoRedo3DStore, UndoRedo3DStoreType } from "../../store/builder/useUndoRedo3DStore";
import { createEventStore, EventStoreType } from '../../store/simulation/useEventsStore';
import { createProductStore, ProductStoreType } from '../../store/simulation/useProductStore';
import { createEventStore, EventStoreType } from "../../store/simulation/useEventsStore";
import { createProductStore, ProductStoreType } from "../../store/simulation/useProductStore";
import { createMaterialStore, MaterialStoreType } from '../../store/simulation/useMaterialStore';
import { createArmBotStore, ArmBotStoreType } from '../../store/simulation/useArmBotStore';
import { createMachineStore, MachineStoreType } from '../../store/simulation/useMachineStore';
import { createConveyorStore, ConveyorStoreType } from '../../store/simulation/useConveyorStore';
import { createVehicleStore, VehicleStoreType } from '../../store/simulation/useVehicleStore';
import { createStorageUnitStore, StorageUnitStoreType } from '../../store/simulation/useStorageUnitStore';
import { createHumanStore, HumanStoreType } from '../../store/simulation/useHumanStore';
import { createCraneStore, CraneStoreType } from '../../store/simulation/useCraneStore';
import { createMaterialStore, MaterialStoreType } from "../../store/simulation/useMaterialStore";
import { createArmBotStore, ArmBotStoreType } from "../../store/simulation/useArmBotStore";
import { createMachineStore, MachineStoreType } from "../../store/simulation/useMachineStore";
import { createConveyorStore, ConveyorStoreType } from "../../store/simulation/useConveyorStore";
import { createVehicleStore, VehicleStoreType } from "../../store/simulation/useVehicleStore";
import { createStorageUnitStore, StorageUnitStoreType } from "../../store/simulation/useStorageUnitStore";
import { createHumanStore, HumanStoreType } from "../../store/simulation/useHumanStore";
import { createCraneStore, CraneStoreType } from "../../store/simulation/useCraneStore";
import { createCommentsStore, CommentStoreType } from "../../store/collaboration/useCommentStore";
type SceneContextValue = {
versionStore: VersionStoreType;
versionStore: VersionStoreType
assetStore: AssetStoreType;
wallAssetStore: WallAssetStoreType;
wallStore: WallStoreType;
aisleStore: AisleStoreType;
zoneStore: ZoneStoreType;
floorStore: FloorStoreType;
assetStore: AssetStoreType,
wallAssetStore: WallAssetStoreType,
wallStore: WallStoreType,
aisleStore: AisleStoreType,
zoneStore: ZoneStoreType,
floorStore: FloorStoreType,
undoRedo2DStore: UndoRedo2DStoreType;
undoRedo3DStore: UndoRedo3DStoreType;
undoRedo2DStore: UndoRedo2DStoreType,
undoRedo3DStore: UndoRedo3DStoreType,
eventStore: EventStoreType,
productStore: ProductStoreType,
eventStore: EventStoreType;
productStore: ProductStoreType;
materialStore: MaterialStoreType;
armBotStore: ArmBotStoreType;
@@ -50,24 +51,19 @@ type SceneContextValue = {
humanStore: HumanStoreType;
craneStore: CraneStoreType;
commentStore: CommentStoreType;
humanEventManagerRef: React.RefObject<HumanEventManagerState>;
craneEventManagerRef: React.RefObject<CraneEventManagerState>;
clearStores: () => void;
layout: 'Main Layout' | 'Comparison Layout';
layout: "Main Layout" | "Comparison Layout";
};
const SceneContext = createContext<SceneContextValue | null>(null);
export function SceneProvider({
children,
layout
}: {
readonly children: React.ReactNode;
readonly layout: 'Main Layout' | 'Comparison Layout';
}) {
export function SceneProvider({ children, layout }: { readonly children: React.ReactNode; readonly layout: "Main Layout" | "Comparison Layout" }) {
const versionStore = useMemo(() => createVersionStore(), []);
const assetStore = useMemo(() => createAssetStore(), []);
@@ -92,35 +88,62 @@ export function SceneProvider({
const humanStore = useMemo(() => createHumanStore(), []);
const craneStore = useMemo(() => createCraneStore(), []);
const commentStore = useMemo(() => createCommentsStore(), []);
const humanEventManagerRef = useRef<HumanEventManagerState>({ humanStates: [] });
const craneEventManagerRef = useRef<CraneEventManagerState>({ craneStates: [] });
const clearStores = useMemo(() => () => {
versionStore.getState().clearVersions();
assetStore.getState().clearAssets();
wallAssetStore.getState().clearWallAssets();
wallStore.getState().clearWalls();
aisleStore.getState().clearAisles();
zoneStore.getState().clearZones();
floorStore.getState().clearFloors();
undoRedo2DStore.getState().clearUndoRedo2D();
undoRedo3DStore.getState().clearUndoRedo3D();
eventStore.getState().clearEvents();
productStore.getState().clearProducts();
materialStore.getState().clearMaterials();
armBotStore.getState().clearArmBots();
machineStore.getState().clearMachines();
conveyorStore.getState().clearConveyors();
vehicleStore.getState().clearVehicles();
storageUnitStore.getState().clearStorageUnits();
humanStore.getState().clearHumans();
craneStore.getState().clearCranes();
humanEventManagerRef.current.humanStates = [];
craneEventManagerRef.current.craneStates = [];
}, [versionStore, assetStore, wallAssetStore, wallStore, aisleStore, zoneStore, undoRedo2DStore, undoRedo3DStore, floorStore, eventStore, productStore, materialStore, armBotStore, machineStore, conveyorStore, vehicleStore, storageUnitStore, humanStore, craneStore]);
const clearStores = useMemo(
() => () => {
versionStore.getState().clearVersions();
assetStore.getState().clearAssets();
wallAssetStore.getState().clearWallAssets();
wallStore.getState().clearWalls();
aisleStore.getState().clearAisles();
zoneStore.getState().clearZones();
floorStore.getState().clearFloors();
undoRedo2DStore.getState().clearUndoRedo2D();
undoRedo3DStore.getState().clearUndoRedo3D();
eventStore.getState().clearEvents();
productStore.getState().clearProducts();
materialStore.getState().clearMaterials();
armBotStore.getState().clearArmBots();
machineStore.getState().clearMachines();
conveyorStore.getState().clearConveyors();
vehicleStore.getState().clearVehicles();
storageUnitStore.getState().clearStorageUnits();
humanStore.getState().clearHumans();
craneStore.getState().clearCranes();
commentStore.getState().clearComments();
humanEventManagerRef.current.humanStates = [];
craneEventManagerRef.current.craneStates = [];
},
[
versionStore,
assetStore,
wallAssetStore,
wallStore,
aisleStore,
zoneStore,
undoRedo2DStore,
undoRedo3DStore,
floorStore,
eventStore,
productStore,
materialStore,
armBotStore,
machineStore,
conveyorStore,
vehicleStore,
storageUnitStore,
humanStore,
craneStore,
commentStore,
]
);
const contextValue = useMemo(() => (
{
const contextValue = useMemo(
() => ({
versionStore,
assetStore,
wallAssetStore,
@@ -140,25 +163,46 @@ export function SceneProvider({
storageUnitStore,
humanStore,
craneStore,
commentStore,
humanEventManagerRef,
craneEventManagerRef,
clearStores,
layout
}
), [versionStore, assetStore, wallAssetStore, wallStore, aisleStore, zoneStore, floorStore, undoRedo2DStore, undoRedo3DStore, eventStore, productStore, materialStore, armBotStore, machineStore, conveyorStore, vehicleStore, storageUnitStore, humanStore, craneStore, clearStores, layout]);
return (
<SceneContext.Provider value={contextValue}>
{children}
</SceneContext.Provider>
layout,
}),
[
versionStore,
assetStore,
wallAssetStore,
wallStore,
aisleStore,
zoneStore,
floorStore,
undoRedo2DStore,
undoRedo3DStore,
eventStore,
productStore,
materialStore,
armBotStore,
machineStore,
conveyorStore,
vehicleStore,
storageUnitStore,
humanStore,
craneStore,
commentStore,
clearStores,
layout,
]
);
return <SceneContext.Provider value={contextValue}>{children}</SceneContext.Provider>;
}
// Base hook to get the context
export function useSceneContext() {
const context = useContext(SceneContext);
if (!context) {
throw new Error('useSceneContext must be used within a SceneProvider');
throw new Error("useSceneContext must be used within a SceneProvider");
}
return context;
}
}

View File

@@ -0,0 +1,31 @@
let url_Backend_dwinzo = `http://${process.env.REACT_APP_SERVER_REST_API_BASE_URL}`;
export const addCommentsApi = async (projectId: any, comment: string, threadId: string, versionId: string) => {
try {
const response = await fetch(`${url_Backend_dwinzo}/api/V1/Thread/addComment`, {
method: "POST",
headers: {
Authorization: "Bearer <access_token>",
"Content-Type": "application/json",
token: localStorage.getItem("token") || "",
refresh_token: localStorage.getItem("refreshToken") || "",
},
body: JSON.stringify({ projectId, comment, threadId, versionId }),
});
const newAccessToken = response.headers.get("x-access-token");
if (newAccessToken) {
localStorage.setItem("token", newAccessToken);
}
if (!response.ok) {
echo.error("Failed to add comment");
}
const result = await response.json();
return result;
} catch {
echo.error("Failed to add comment");
}
};

View File

@@ -1,41 +0,0 @@
let url_Backend_dwinzo = `http://${process.env.REACT_APP_SERVER_REST_API_BASE_URL}`;
export const addCommentsApi = async (
projectId: any,
comment: string,
threadId: string,
commentId: string,
versionId: string
) => {
try {
const response = await fetch(
`${url_Backend_dwinzo}/api/V1/Thread/addComment`,
{
method: "POST",
headers: {
Authorization: "Bearer <access_token>",
"Content-Type": "application/json",
token: localStorage.getItem("token") || "",
refresh_token: localStorage.getItem("refreshToken") || "",
},
body: JSON.stringify({ projectId, comment, threadId, commentId, versionId }),
}
);
const newAccessToken = response.headers.get("x-access-token");
if (newAccessToken) {
localStorage.setItem("token", newAccessToken);
}
if (!response.ok) {
echo.error("Failed to add comment");
}
const result = await response.json();
return result;
} catch {
echo.error("Failed to add comment");
}
};

View File

@@ -0,0 +1,31 @@
let url_Backend_dwinzo = `http://${process.env.REACT_APP_SERVER_REST_API_BASE_URL}`;
export const editCommentsApi = async (projectId: any, comment: string, commentId: string, threadId: string, versionId: string) => {
try {
const response = await fetch(`${url_Backend_dwinzo}/api/V1/Thread/addComment`, {
method: "POST",
headers: {
Authorization: "Bearer <access_token>",
"Content-Type": "application/json",
token: localStorage.getItem("token") || "",
refresh_token: localStorage.getItem("refreshToken") || "",
},
body: JSON.stringify({ projectId, comment, commentId, threadId, versionId }),
});
const newAccessToken = response.headers.get("x-access-token");
if (newAccessToken) {
localStorage.setItem("token", newAccessToken);
}
if (!response.ok) {
echo.error("Failed to edit comment");
}
const result = await response.json();
return result;
} catch {
echo.error("Failed to edit comment");
}
};

View File

@@ -24,10 +24,12 @@ export const useSocketStore = create<any>((set: any, get: any) => ({
reconnection: true,
auth: { token, refreshToken },
});
const projectSocket = io(`http://${process.env.REACT_APP_SERVER_SOCKET_API_BASE_URL}/project`, {
reconnection: true,
auth: { token, refreshToken },
});
const threadSocket = io(`http://${process.env.REACT_APP_SERVER_SOCKET_API_BASE_URL}/thread`, {
reconnection: true,
auth: { token, refreshToken },

View File

@@ -1,6 +1,6 @@
import { Object3D } from 'three';
import { create } from 'zustand';
import { immer } from 'zustand/middleware/immer';
import { Object3D } from "three";
import { create } from "zustand";
import { immer } from "zustand/middleware/immer";
interface AssetsStore {
assets: Assets;
@@ -44,8 +44,8 @@ interface AssetsStore {
removeAnimation: (modelUuid: string, animation: string) => void;
// Event data operations
addEventData: (modelUuid: string, eventData: Asset['eventData']) => void;
updateEventData: (modelUuid: string, updates: Partial<Asset['eventData']>) => void;
addEventData: (modelUuid: string, eventData: Asset["eventData"]) => void;
updateEventData: (modelUuid: string, updates: Partial<Asset["eventData"]>) => void;
removeEventData: (modelUuid: string) => void;
// Helper functions
@@ -68,7 +68,7 @@ export const createAssetStore = () => {
// Asset CRUD operations
addAsset: (asset) => {
set((state) => {
if (!state.assets.some(a => a.modelUuid === asset.modelUuid)) {
if (!state.assets.some((a) => a.modelUuid === asset.modelUuid)) {
state.assets.push(asset);
}
});
@@ -76,13 +76,13 @@ export const createAssetStore = () => {
removeAsset: (modelUuid) => {
set((state) => {
state.assets = state.assets.filter(a => a.modelUuid !== modelUuid);
state.assets = state.assets.filter((a) => a.modelUuid !== modelUuid);
});
},
updateAsset: (modelUuid, updates) => {
set((state) => {
const asset = state.assets.find(a => a.modelUuid === modelUuid);
const asset = state.assets.find((a) => a.modelUuid === modelUuid);
if (asset) {
Object.assign(asset, updates);
}
@@ -96,7 +96,7 @@ export const createAssetStore = () => {
},
resetAsset: (modelUuid) => {
const asset = get().assets.find(a => a.modelUuid === modelUuid);
const asset = get().assets.find((a) => a.modelUuid === modelUuid);
if (asset) {
const clonedAsset = JSON.parse(JSON.stringify(asset));
setTimeout(() => {
@@ -158,7 +158,7 @@ export const createAssetStore = () => {
// Asset properties
setName: (modelUuid, newName) => {
set((state) => {
const asset = state.assets.find(a => a.modelUuid === modelUuid);
const asset = state.assets.find((a) => a.modelUuid === modelUuid);
if (asset) {
asset.modelName = newName;
}
@@ -167,7 +167,7 @@ export const createAssetStore = () => {
setPosition: (modelUuid, position) => {
set((state) => {
const asset = state.assets.find(a => a.modelUuid === modelUuid);
const asset = state.assets.find((a) => a.modelUuid === modelUuid);
if (asset) {
asset.position = position;
}
@@ -176,7 +176,7 @@ export const createAssetStore = () => {
setRotation: (modelUuid, rotation) => {
set((state) => {
const asset = state.assets.find(a => a.modelUuid === modelUuid);
const asset = state.assets.find((a) => a.modelUuid === modelUuid);
if (asset) {
asset.rotation = rotation;
}
@@ -185,7 +185,7 @@ export const createAssetStore = () => {
setLock: (modelUuid, isLocked) => {
set((state) => {
const asset = state.assets.find(a => a.modelUuid === modelUuid);
const asset = state.assets.find((a) => a.modelUuid === modelUuid);
if (asset) {
asset.isLocked = isLocked;
}
@@ -194,7 +194,7 @@ export const createAssetStore = () => {
setCollision: (modelUuid, isCollidable) => {
set((state) => {
const asset = state.assets.find(a => a.modelUuid === modelUuid);
const asset = state.assets.find((a) => a.modelUuid === modelUuid);
if (asset) {
asset.isCollidable = isCollidable;
}
@@ -203,7 +203,7 @@ export const createAssetStore = () => {
setVisibility: (modelUuid, isVisible) => {
set((state) => {
const asset = state.assets.find(a => a.modelUuid === modelUuid);
const asset = state.assets.find((a) => a.modelUuid === modelUuid);
if (asset) {
asset.isVisible = isVisible;
}
@@ -212,7 +212,7 @@ export const createAssetStore = () => {
setOpacity: (modelUuid, opacity) => {
set((state) => {
const asset = state.assets.find(a => a.modelUuid === modelUuid);
const asset = state.assets.find((a) => a.modelUuid === modelUuid);
if (asset) {
asset.opacity = opacity;
}
@@ -222,11 +222,11 @@ export const createAssetStore = () => {
// Animation controls
setAnimations: (modelUuid, animations) => {
set((state) => {
const asset = state.assets.find(a => a.modelUuid === modelUuid);
const asset = state.assets.find((a) => a.modelUuid === modelUuid);
if (asset) {
asset.animations = animations;
if (!asset.animationState) {
asset.animationState = { current: '', isPlaying: false, loopAnimation: true, isCompleted: true };
asset.animationState = { current: "", isPlaying: false, loopAnimation: true, isCompleted: true };
}
}
});
@@ -234,7 +234,7 @@ export const createAssetStore = () => {
setCurrentAnimation: (modelUuid, current, isPlaying, loopAnimation, isCompleted) => {
set((state) => {
const asset = state.assets.find(a => a.modelUuid === modelUuid);
const asset = state.assets.find((a) => a.modelUuid === modelUuid);
if (asset?.animationState) {
asset.animationState.current = current;
asset.animationState.isPlaying = isPlaying;
@@ -246,7 +246,7 @@ export const createAssetStore = () => {
setAnimationComplete: (modelUuid, isCompleted) => {
set((state) => {
const asset = state.assets.find(a => a.modelUuid === modelUuid);
const asset = state.assets.find((a) => a.modelUuid === modelUuid);
if (asset?.animationState) {
asset.animationState.isCompleted = isCompleted;
}
@@ -255,9 +255,9 @@ export const createAssetStore = () => {
resetAnimation: (modelUuid) => {
set((state) => {
const asset = state.assets.find(a => a.modelUuid === modelUuid);
const asset = state.assets.find((a) => a.modelUuid === modelUuid);
if (asset?.animationState) {
asset.animationState.current = '';
asset.animationState.current = "";
asset.animationState.isPlaying = true;
asset.animationState.loopAnimation = true;
asset.animationState.isCompleted = true;
@@ -267,7 +267,7 @@ export const createAssetStore = () => {
addAnimation: (modelUuid, animation) => {
set((state) => {
const asset = state.assets.find(a => a.modelUuid === modelUuid);
const asset = state.assets.find((a) => a.modelUuid === modelUuid);
if (asset) {
if (!asset.animations) {
asset.animations = [animation];
@@ -280,12 +280,12 @@ export const createAssetStore = () => {
removeAnimation: (modelUuid, animation) => {
set((state) => {
const asset = state.assets.find(a => a.modelUuid === modelUuid);
const asset = state.assets.find((a) => a.modelUuid === modelUuid);
if (asset?.animations) {
asset.animations = asset.animations.filter(a => a !== animation);
asset.animations = asset.animations.filter((a) => a !== animation);
if (asset.animationState?.current === animation) {
asset.animationState.isPlaying = false;
asset.animationState.current = '';
asset.animationState.current = "";
}
}
});
@@ -294,7 +294,7 @@ export const createAssetStore = () => {
// Event data operations
addEventData: (modelUuid, eventData) => {
set((state) => {
const asset = state.assets.find(a => a.modelUuid === modelUuid);
const asset = state.assets.find((a) => a.modelUuid === modelUuid);
if (asset) {
asset.eventData = eventData;
}
@@ -303,7 +303,7 @@ export const createAssetStore = () => {
updateEventData: (modelUuid, updates) => {
set((state) => {
const asset = state.assets.find(a => a.modelUuid === modelUuid);
const asset = state.assets.find((a) => a.modelUuid === modelUuid);
if (asset?.eventData) {
asset.eventData = { ...asset.eventData, ...updates };
}
@@ -312,7 +312,7 @@ export const createAssetStore = () => {
removeEventData: (modelUuid) => {
set((state) => {
const asset = state.assets.find(a => a.modelUuid === modelUuid);
const asset = state.assets.find((a) => a.modelUuid === modelUuid);
if (asset) {
delete asset.eventData;
}
@@ -321,21 +321,18 @@ export const createAssetStore = () => {
// Helper functions
getAssetById: (modelUuid) => {
return get().assets.find(a => a.modelUuid === modelUuid);
return get().assets.find((a) => a.modelUuid === modelUuid);
},
getAssetByPointUuid: (pointUuid) => {
return get().assets.find(asset =>
asset.eventData?.point?.uuid === pointUuid ||
asset.eventData?.points?.some(p => p.uuid === pointUuid)
);
return get().assets.find((asset) => asset.eventData?.point?.uuid === pointUuid || asset.eventData?.points?.some((p) => p.uuid === pointUuid));
},
hasAsset: (modelUuid) => {
return get().assets.some(a => a.modelUuid === modelUuid);
}
return get().assets.some((a) => a.modelUuid === modelUuid);
},
}))
)
}
);
};
export type AssetStoreType = ReturnType<typeof createAssetStore>;
export type AssetStoreType = ReturnType<typeof createAssetStore>;

View File

@@ -4,90 +4,94 @@ import { immer } from "zustand/middleware/immer";
interface CommentStore {
comments: CommentsSchema;
// Comment operations
addComment: (comment: CommentSchema) => void;
setComments: (comments: CommentsSchema) => void;
updateComment: (threadId: string, updates: Partial<CommentSchema>) => void;
removeComment: (threadId: string) => void;
clearComments: () => void;
// Reply operations
addReply: (threadId: string, reply: Reply) => void;
updateReply: (threadId: string, replyId: string, updates: Partial<Reply>) => void;
removeReply: (threadId: string, _id: string) => void;
// Getters
getCommentById: (threadId: string) => CommentSchema | undefined;
}
export const useCommentStore = create<CommentStore>()(
immer((set, get) => ({
comments: [],
export const createCommentsStore = () => {
return create<CommentStore>()(
immer((set, get) => ({
comments: [],
// Comment operations
addComment: (comment) => {
set((state) => {
if (!state.comments.find((c) => c.threadId === comment.threadId)) {
state.comments.push(JSON.parse(JSON.stringify(comment)));
}
});
},
addComment: (comment) => {
set((state) => {
if (!state.comments.find((c) => c.threadId === comment.threadId)) {
state.comments.push(JSON.parse(JSON.stringify(comment)));
}
});
},
setComments: (comments) => {
set((state) => {
state.comments = comments;
});
},
setComments: (comments) => {
set((state) => {
state.comments = comments;
});
},
updateComment: (threadId, updates) => {
console.log("threadId:updater ", threadId);
set((state) => {
const comment = state.comments.find((c) => c.threadId === threadId);
if (comment) {
Object.assign(comment, updates);
}
});
},
removeComment: (threadId) => {
set((state) => {
state.comments = state.comments.filter((c) => c.threadId !== threadId);
});
},
// Reply operations
addReply: (threadId, comment) => {
set((state) => {
const reply = state.comments.find((c) => c.threadId === threadId);
if (reply) {
reply.comments.push(comment);
}
});
},
updateReply: (threadId, replyId, updates) => {
set((state) => {
const reply = state.comments.find((c) => c.threadId === threadId);
if (reply) {
const comment = reply.comments.find((r) => r.replyId === replyId);
updateComment: (threadId, updates) => {
set((state) => {
const comment = state.comments.find((c) => c.threadId === threadId);
if (comment) {
Object.assign(comment, updates);
}
}
});
},
});
},
removeReply: (threadId, _id) => {
set((state) => {
const comment = state.comments.find((c) => c.threadId === threadId);
if (comment) {
comment.comments = comment.comments.filter((r) => r.replyId !== _id);
}
});
},
removeComment: (threadId) => {
set((state) => {
state.comments = state.comments.filter((c) => c.threadId !== threadId);
});
},
// Getter
getCommentById: (threadId) => {
return get().comments.find((c) => c.threadId === threadId);
},
}))
);
clearComments: () => {
set((state) => {
state.comments = [];
});
},
addReply: (threadId, comment) => {
set((state) => {
const reply = state.comments.find((c) => c.threadId === threadId);
if (reply) {
reply.comments.push(comment);
}
});
},
updateReply: (threadId, replyId, updates) => {
set((state) => {
const reply = state.comments.find((c) => c.threadId === threadId);
if (reply) {
const comment = reply.comments.find((r) => r.replyId === replyId);
if (comment) {
Object.assign(comment, updates);
}
}
});
},
removeReply: (threadId, _id) => {
set((state) => {
const comment = state.comments.find((c) => c.threadId === threadId);
if (comment) {
comment.comments = comment.comments.filter((r) => r.replyId !== _id);
}
});
},
getCommentById: (threadId) => {
return get().comments.find((c) => c.threadId === threadId);
},
}))
);
};
export type CommentStoreType = ReturnType<typeof createCommentsStore>;