Skip to content

Commit

Permalink
Merge pull request #24 from dtg-lucifer/code-fix
Browse files Browse the repository at this point in the history
code-fix: working on the glitch of sending the attachments
  • Loading branch information
dtg-lucifer authored Mar 8, 2024
2 parents d1d4d72 + ddd1499 commit e895553
Show file tree
Hide file tree
Showing 5 changed files with 75 additions and 37 deletions.
2 changes: 1 addition & 1 deletion client/public/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@
work correctly both with client-side routing and a non-root public URL.
Learn how to configure a non-root public URL by running `npm run build`.
-->
<title>React App</title>
<title>Chat O Cord</title>
</head>

<body>
Expand Down
95 changes: 68 additions & 27 deletions client/src/components/conversation/chat/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -21,26 +21,31 @@ import { ActiveChatContext } from "../../../utils/context/activeChatContext";
import AuthContext from "../../../utils/context/authContext";
import { Message } from "../../../types/conversation";
import {
addMessages,
getMessagesAsync,
} from "../../../utils/store/slices/messages.slice";
import { AppDispatch, RootState } from "../../../utils/store";
import { useDispatch, useSelector } from "react-redux";
import { formatDistance, formatRelative } from "date-fns";
import { formatDistance } from "date-fns";
import { createMessage, createMessageWithAsset } from "../../../lib/api";
import { updateLastMessage } from "../../../utils/store/slices/conversation.slice";
import classNames from "classnames";
import { useBufferToImageSrc } from "../../../utils/hooks/useBufferToImageSrc";
import { toast } from "sonner";
import { useSocket } from "../../../utils/hooks/useSocket";
import { setLocalMsgStateHelper, showTimeStampAndAvatar } from "../../../lib/conversationsUtils";
import {
setLocalMsgStateHelper,
showTimeStampAndAvatar,
} from "../../../lib/conversationsUtils";

export default function ChatSection() {
const emojiPanelRef = useRef<HTMLDivElement>(null);
const fileInputRef = useRef<HTMLInputElement>(null);
const dispatch = useDispatch<AppDispatch>();
const [message, setMessage] = useState<string>("");
const [localMsgState, setLocalMsgState] = useState<{ convId: string; messages: Message[]; }[]>([]);
const [messages, setMessages] = useState<Message[]>([]);
const [localMsgState, setLocalMsgState] = useState<
{ convId: string; messages: Message[] }[]
>([]);
const [file, setFile] = useState<File | null>(null);
const [imagePreviewSrc, setImagePreviewSrc] = useState<string>("");
const [activeAssetToView, setActiveAssetToView] = useState<string>("");
Expand All @@ -67,7 +72,6 @@ export default function ChatSection() {
? activeChat?.creator
: activeChat?.recipient;


/**
*! ---- NOTE ----
*! MAKE THIS FUNCTION WITH REACT-QUERY
Expand All @@ -93,7 +97,29 @@ export default function ChatSection() {
formData.append("id", activeChat!.id);
const { data: messageFromApi } = await createMessageWithAsset(formData);

setLocalMsgState((prev) => setLocalMsgStateHelper(messageFromApi, prev));
setLocalMsgState((prev) => {
const foundIndex = prev.findIndex(
(state) => state.convId === messageFromApi.conversationId
);
if (foundIndex !== -1) {
const updatedState = [...prev];
updatedState[foundIndex] = {
convId: updatedState[foundIndex].convId,
messages: [messageFromApi, ...updatedState[foundIndex].messages],
};
console.log("added the asset");
return updatedState;
} else {
console.log("added the asset");
return [
...prev,
{
convId: messageFromApi.conversationId,
messages: [messageFromApi],
},
];
}
});

setFile(null);
setImagePreviewSrc("");
Expand All @@ -116,7 +142,6 @@ export default function ChatSection() {
id: activeChat!.id,
});


//* Update local message state for text messages
setLocalMsgState((prev) => setLocalMsgStateHelper(messageFromApi, prev));

Expand All @@ -137,7 +162,7 @@ export default function ChatSection() {
});

return () => {
window.removeEventListener("keydown", () => { });
window.removeEventListener("keydown", () => {});
};
}, []);

Expand All @@ -146,20 +171,17 @@ export default function ChatSection() {
dispatch(getMessagesAsync({ id: activeChat.id, limit: 100, page: 1 }))
.unwrap()
.then((data) => {
setLocalMsgState([{ convId: data.data.id, messages: data.data.messages }])
setLocalMsgState([
{ convId: data.data.id, messages: data.data.messages },
]);
});
}
}, [activeChat, dispatch]);

useEffect(() => {
socket?.on(
"message:received",
(data: {
convId: string;
message: Message;
authorId: string;
attachmentSrc: string;
}) => {
(data: { convId: string; message: Message; authorId: string }) => {
if (data.authorId === user?.id) {
dispatch(
updateLastMessage({
Expand All @@ -181,9 +203,19 @@ export default function ChatSection() {
convId: string;
secureUrl: string;
message: Message;
attachmentSrc: string;
}) => {
// TODO: IMPLEMENT
if (data.convId === activeChat?.id) {
dispatch(
updateLastMessage({
id: data.convId,
lastMessageContent: data.message.content,
})
);
return;
}

//* Update localMsgState
setLocalMsgState((prev) => setLocalMsgStateHelper(data.message, prev));
}
);

Expand All @@ -196,10 +228,10 @@ export default function ChatSection() {
});

return () => {
socket?.off("attachment:received", () => { });
socket?.off("message:received", () => { });
socket?.off("typing:started", () => { });
socket?.off("typing:stopped", () => { });
socket?.off("attachment:received", () => {});
socket?.off("message:received", () => {});
socket?.off("typing:started", () => {});
socket?.off("typing:stopped", () => {});
};
}, [socket]);

Expand All @@ -226,7 +258,7 @@ export default function ChatSection() {
<img
src={activeAssetToView}
alt="attachment"
className={classNames("w-full h-full", {
className={classNames("w-full min-h-full", "", {
hidden: !activeImage,
block: activeImage,
})}
Expand Down Expand Up @@ -263,18 +295,21 @@ export default function ChatSection() {
</span>
</ChatMessagesStatus>
) : (
localMsgState.map(state => {
localMsgState.map((state) => {
if (state.convId === activeChat!.id) {
return state.messages.map((msg, i, msgs) => {
return (
<MessageCVA
variant={currentChatUser?.profilePic ? "withImg" : "withoutImg"}
variant={
currentChatUser?.profilePic ? "withImg" : "withoutImg"
}
key={msg?.id}
style={{
marginBlockStart: !showTimeStampAndAvatar(msg, i, msgs)
? ""
: "0.8rem",
}}
ref={null}
>
{msg.author.profilePic ? (
<img
Expand Down Expand Up @@ -315,7 +350,7 @@ export default function ChatSection() {
<img
src={msg.attachmentSrc}
alt="attachment"
className="max-w-[450px] max-h-[400px] rounded-md lazyload cursor-pointer"
className="max-w-[450px] max-h-[400px] rounded-md lazyload cursor-pointer my-1"
loading="lazy"
onClick={() => {
setActiveAssetToView(msg.attachmentSrc!);
Expand All @@ -341,7 +376,11 @@ export default function ChatSection() {
)}
<p
style={{
marginInlineStart: showTimeStampAndAvatar(msg, i, msgs)
marginInlineStart: showTimeStampAndAvatar(
msg,
i,
msgs
)
? ""
: "3rem",
wordWrap: "break-word",
Expand All @@ -356,7 +395,9 @@ export default function ChatSection() {
</div>
<p
style={{
display: showTimeStampAndAvatar(msg, i, msgs) ? "" : "none",
display: showTimeStampAndAvatar(msg, i, msgs)
? ""
: "none",
}}
className="text-xs text-[#555555] self-start mt-[5px] ml-[3rem]"
>
Expand Down
5 changes: 3 additions & 2 deletions client/src/components/conversation/index.components.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -94,6 +94,7 @@ interface MessageProps
extends AllHTMLAttributes<HTMLDivElement>,
VariantProps<typeof messageCVA> {
children: React.ReactNode[];
ref: React.RefObject<HTMLDivElement> | null;
}

export const TextField = ({ variant, size, ...props }: TextFieldProps) => {
Expand All @@ -108,9 +109,9 @@ export const Button = ({ variant, children, ...props }: ButtonProps) => {
);
};

export const Message = ({ variant, children, ...props }: MessageProps) => {
export const Message = ({ variant, children, ref, ...props }: MessageProps) => {
return (
<div className={messageCVA({ variant })} {...props}>
<div className={messageCVA({ variant })} ref={ref} {...props}>
{children.map((child, index) => (
<React.Fragment key={index}>{child}</React.Fragment>
))}
Expand Down
8 changes: 2 additions & 6 deletions server/src/message/message.service.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { getConversationById } from "../conversations/conversation.service";
import { v2 as cloudinary } from "cloudinary";
import { bufferToSrc, getDataUri } from "../lib/utils";
import { getDataUri } from "../lib/utils";
import { CreateMessageDTO } from "./dto/message.dto";

export const getMessages = async (id: string, limit: number) => {
Expand Down Expand Up @@ -109,7 +109,6 @@ export const createMessageWithAsset = async (
resource_type: "auto",
use_asset_folder_as_public_id_prefix: true,
});
const attachmentSrc = bufferToSrc()(file.buffer, file.mimetype);

const attachment = await __db?.attachment.create({
data: {
Expand All @@ -123,9 +122,6 @@ export const createMessageWithAsset = async (
},
},
},
include: {
message: true,
},
});

await __db?.message.update({
Expand All @@ -137,5 +133,5 @@ export const createMessageWithAsset = async (
},
});

return { message, attachment, secureUrl: secure_url, attachmentSrc };
return { message, attachment, secureUrl: secure_url };
};
2 changes: 1 addition & 1 deletion server/src/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ import {
sessionMiddleware,
wrapper,
} from "./lib/session.server";
import { Conversation, User, Message, Attachment } from "@prisma/client";
import { User, Message } from "@prisma/client";

import { AuthGuard } from "./middleware/middleware.server";
import { authRouter } from "./auth/auth.router";
Expand Down

0 comments on commit e895553

Please sign in to comment.