Skip to content
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 11 additions & 5 deletions src/components/chat/ChatActionSheet.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ export interface ChatActionItem {
icon: ComponentType<SVGProps<SVGSVGElement>>;
onSelect?: () => void;
disabled?: boolean;
hidden?: boolean;
}

const CHAT_ACTIONS_BY_ROLE: Record<ChatParticipantRole, ChatActionItem[]> = {
Expand Down Expand Up @@ -49,14 +50,17 @@ export interface ChatActionSheetProps {
open: boolean;
participantRole: ChatParticipantRole;
onClose: () => void;
actions?: Partial<Record<ChatActionItem["id"], Pick<ChatActionItem, "onSelect" | "disabled">>>;
actions?: Partial<
Record<ChatActionItem["id"], Pick<ChatActionItem, "onSelect" | "disabled" | "hidden">>
>;
}

/**
* 채팅 입력바 아래 액션 메뉴 패널
* // 2026.08.07 김성현 - [추가] 역할별 채팅 액션 메뉴 공통화
* // 2026.08.07 김성현 - [수정] 전역 Modal 대신 채팅 모달 내부 시트로 분리
* // 2026.08.07 김성현 - [수정] 입력바 아래 인라인 패널로 변경 (채팅바와 함께 상승)
* // 2026.08.18 김성현 - [수정] 미배포 기능 액션 숨김 옵션 추가
*/
export default function ChatActionSheet({
open,
Expand All @@ -68,10 +72,12 @@ export default function ChatActionSheet({

if (!isRendered) return null;

const actionItems = CHAT_ACTIONS_BY_ROLE[participantRole].map((item) => ({
...item,
...actions?.[item.id],
}));
const actionItems = CHAT_ACTIONS_BY_ROLE[participantRole]
.map((item) => ({
...item,
...actions?.[item.id],
}))
.filter((item) => !item.hidden);

const handleSelect = (item: ChatActionItem) => {
if (item.disabled) return;
Expand Down
4 changes: 3 additions & 1 deletion src/components/chat/ChatRoomModal.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,9 @@ export interface ChatRoomModalProps {
composerDisabled?: boolean;
onMessageChange?: (value: string) => void;
onSendMessage?: () => void;
actions?: Partial<Record<ChatActionItem["id"], Pick<ChatActionItem, "onSelect" | "disabled">>>;
actions?: Partial<
Record<ChatActionItem["id"], Pick<ChatActionItem, "onSelect" | "disabled" | "hidden">>
>;
/** 기사 견적 수정 시트에 표시할 값·핸들러 */
estimateEdit?: ChatEstimateEditConfig;
}
Expand Down
82 changes: 68 additions & 14 deletions src/components/chat/ChatRoomModalContainer.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
"use client";

import { useEffect, useRef } from "react";
import Image from "next/image";
import { useEffect, useRef, type ChangeEvent } from "react";

import ChatRoomCreateError from "@/components/chat/ChatRoomCreateError";
import ChatRoomModal from "@/components/chat/ChatRoomModal";
Expand All @@ -11,18 +12,23 @@ import {
useConnectedChatRoomModalController,
} from "@/hooks/useChatRoomModalController";
import { cn } from "@/lib/utils/cn";
import { CHAT_IMAGE_CONTENT_TYPES } from "@/types/chat";
import type { ChatActionItem, ChatParticipantRole } from "@/components/chat/ChatActionSheet";
import type { ChatEstimateEditConfig } from "@/components/chat/ChatRoomModal";
import type { ChatMessage, ChatRoom } from "@/types/chat";

const IS_CHAT_IMAGE_UPLOAD_ENABLED = process.env.NEXT_PUBLIC_CHAT_IMAGE_UPLOAD_ENABLED === "true";

export interface ChatRoomModalContainerProps {
open: boolean;
estimateId: number;
participantRole: ChatParticipantRole;
participantName: string;
estimateSummary: string;
onClose: () => void;
actions?: Partial<Record<ChatActionItem["id"], Pick<ChatActionItem, "onSelect" | "disabled">>>;
actions?: Partial<
Record<ChatActionItem["id"], Pick<ChatActionItem, "onSelect" | "disabled" | "hidden">>
>;
estimateEdit?: ChatEstimateEditConfig;
}

Expand Down Expand Up @@ -156,22 +162,33 @@ function ChatMessageList({
) : null}
<div
className={cn(
"rounded-16 max-w-[78%] px-14 py-10",
"rounded-16 max-w-[78%] overflow-hidden",
isMine
? "bg-background-brand text-text-inverse rounded-br-4"
: "bg-background-subtle text-text-primary rounded-bl-4",
)}
>
<Text
as="p"
variant="md-medium"
className={cn(
"wrap-break-word whitespace-pre-wrap",
isMine ? "text-text-inverse" : "text-text-primary",
)}
>
{message.content}
</Text>
{message.type === "IMAGE" && message.imageUrl ? (
<Image
src={message.imageUrl}
alt="첨부 이미지"
width={240}
height={240}
sizes="240px"
className="max-h-240 w-full min-w-160 object-cover"
/>
) : (
<Text
as="p"
variant="md-medium"
className={cn(
"px-14 py-10 wrap-break-word whitespace-pre-wrap",
isMine ? "text-text-inverse" : "text-text-primary",
)}
>
{message.content}
</Text>
)}
</div>
<Text variant="xs-medium" className="text-text-muted">
{formatMessageTime(message.createdAt)}
Expand All @@ -198,9 +215,45 @@ export function ConnectedChatRoomModal({
estimateEdit,
}: ConnectedChatRoomModalProps) {
const chat = useConnectedChatRoomModalController({ open, room });
const fileInputRef = useRef<HTMLInputElement>(null);
const chatImageAccept = CHAT_IMAGE_CONTENT_TYPES.join(",");

const mergedActions: ConnectedChatRoomModalProps["actions"] = {
...actions,
"attach-photo": {
...actions?.["attach-photo"],
hidden: actions?.["attach-photo"]?.hidden || !IS_CHAT_IMAGE_UPLOAD_ENABLED,
disabled: actions?.["attach-photo"]?.disabled || chat.isImageSending || !chat.isConnected,

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

텍스트 전송 버튼은 sendDisabled에서 isSending과 isImageSending을 같이 보는데, 사진 첨부 버튼은 isImageSending만 보고 있어서 텍스트 전송 중에는 계속 활성 상태인 것 같습니다.
이 사이에 사진을 선택하면 handleSendImageMessage 맨 위 가드에 걸려 안내 없이 무시될 수도 있을 것 같은데 체크해보시면 좋을 것 같습니다!

onSelect: () => {
actions?.["attach-photo"]?.onSelect?.();
fileInputRef.current?.click();
},
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
},
};

const handleFileChange = (event: ChangeEvent<HTMLInputElement>) => {
const file = event.target.files?.[0];
event.target.value = "";

if (!file) {
return;
}

void chat.handleSendImageMessage(file);
};

return (
<>
<input
ref={fileInputRef}
type="file"
accept={chatImageAccept}
className="sr-only"
tabIndex={-1}
aria-label="채팅 이미지 첨부"
onChange={handleFileChange}
/>

<ChatRoomModal
open={open}
participantRole={participantRole}
Expand All @@ -211,7 +264,7 @@ export function ConnectedChatRoomModal({
onMessageChange={chat.setMessageValue}
onSendMessage={() => void chat.handleSendMessage()}
onClose={onClose}
actions={actions}
actions={mergedActions}
estimateEdit={estimateEdit}
>
{chat.isMessagesError ? (
Expand Down Expand Up @@ -249,6 +302,7 @@ export function ConnectedChatRoomModal({
/**
* 채팅방 생성/조회, 메시지 목록, 소켓 연결을 묶는 채팅 모달 컨테이너
* // 2026.08.07 김성현 - [추가] 견적 상세 채팅 모달 BE 연동
* // 2026.08.18 김성현 - [수정] 채팅 이미지 첨부 액션 feature flag 적용
*/
export default function ChatRoomModalContainer({
open,
Expand Down
73 changes: 70 additions & 3 deletions src/hooks/useChatRoomModalController.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,16 @@ import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { useChatMessages } from "@/hooks/useChatMessages";
import { useChatRoomSocket } from "@/hooks/useChatRoomSocket";
import { useGetOrCreateChatRoom } from "@/hooks/useChatRoom";
import { getChatImageUploadUrl } from "@/lib/api/chat";
import { getApiErrorMessage } from "@/lib/api/getApiErrorMessage";
import type { ChatMessage, ChatRoom, ChatSocketError } from "@/types/chat";
import { uploadFileToPresignedUrl } from "@/lib/api/profileImage";
import {
CHAT_IMAGE_CONTENT_TYPES,
type ChatImageContentType,
type ChatMessage,
type ChatRoom,
type ChatSocketError,
} from "@/types/chat";

interface UseChatRoomModalControllerOptions {
open: boolean;
Expand Down Expand Up @@ -38,6 +46,18 @@ function mergeMessages(messages: ChatMessage[]): ChatMessage[] {
return sortMessages([...new Map(messages.map((message) => [message.id, message])).values()]);
}

function isChatImageContentType(value: string): value is ChatImageContentType {
return (CHAT_IMAGE_CONTENT_TYPES as readonly string[]).includes(value);
}

function validateChatImageFile(file: File): string | null {
if (!isChatImageContentType(file.type)) {
return "jpg, png, webp 형식의 이미지만 첨부할 수 있습니다.";
}

return null;
}

/**
* 채팅 모달 진입 시 견적 기준 채팅방을 준비하는 훅
* // 2026.08.07 김성현 - [추가] 채팅방 생성/조회 로직 분리
Expand Down Expand Up @@ -100,6 +120,7 @@ export function useChatRoomModalController({
/**
* 준비된 채팅방의 메시지 조회, 소켓 수신, 전송 상태를 관리하는 훅
* // 2026.08.07 김성현 - [추가] 채팅 메시지/소켓 로직 분리
* // 2026.08.18 김성현 - [추가] 채팅 이미지 첨부 업로드/전송 흐름 추가
*/
export function useConnectedChatRoomModalController({
open,
Expand All @@ -109,6 +130,7 @@ export function useConnectedChatRoomModalController({
const [liveMessages, setLiveMessages] = useState<ChatMessage[]>([]);
const [toastMessage, setToastMessage] = useState<string | null>(null);
const [isSending, setIsSending] = useState(false);
const [isImageSending, setIsImageSending] = useState(false);

const messagesQuery = useChatMessages({
roomId: room.id,
Expand All @@ -135,7 +157,7 @@ export function useConnectedChatRoomModalController({
setToastMessage(error.message);
}, []);

const { isConnected, sendMessage } = useChatRoomSocket({
const { isConnected, sendImageMessage, sendMessage } = useChatRoomSocket({
roomId: room.id,
lastMessageId,
onJoined: (response) => {
Expand Down Expand Up @@ -179,6 +201,49 @@ export function useConnectedChatRoomModalController({
}
};

const handleSendImageMessage = async (file: File) => {
if (isSending || isImageSending) {
return;
}

const contentType = file.type;
const validationMessage = validateChatImageFile(file);

if (validationMessage) {
setToastMessage(validationMessage);
return;
}

if (!isChatImageContentType(contentType)) {
return;
}

setToastMessage(null);
setIsImageSending(true);

try {
const uploadResult = await getChatImageUploadUrl(room.id, {
contentType,
});

await uploadFileToPresignedUrl(uploadResult.uploadUrl, file);

const response = await sendImageMessage({
roomId: room.id,
imageKey: uploadResult.key,
clientMessageId: createClientMessageId(),
});

if (!response.ok) {
setToastMessage(response.error.message);
}
} catch (error) {
setToastMessage(getApiErrorMessage(error, "이미지를 첨부하지 못했습니다."));
} finally {
setIsImageSending(false);
}
};

const messagesErrorMessage = messagesQuery.isError
? getApiErrorMessage(messagesQuery.error, "대화 내역을 불러오지 못했습니다.")
: null;
Expand All @@ -195,9 +260,11 @@ export function useConnectedChatRoomModalController({
fetchNextPage: messagesQuery.fetchNextPage,
refetchMessages: messagesQuery.refetch,
isSending,
isImageSending,
isConnected,
sendDisabled: isSending || !isConnected,
sendDisabled: isSending || isImageSending || !isConnected,
handleSendMessage,
handleSendImageMessage,
toastMessage,
clearToastMessage: () => setToastMessage(null),
};
Expand Down
55 changes: 55 additions & 0 deletions src/hooks/useChatRoomSocket.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@ import type {
JoinChatRoomAck,
JoinChatRoomPayload,
LeaveChatRoomPayload,
SendChatImageMessageAck,
SendChatImageMessagePayload,
SendChatMessageAck,
SendChatMessagePayload,
} from "@/types/chat";
Expand Down Expand Up @@ -147,10 +149,63 @@ export function useChatRoomSocket({
[isConnected, socket],
);

const sendImageMessage = useCallback(
(payload: SendChatImageMessagePayload) =>
new Promise<SendChatImageMessageAck>((resolve) => {
if (!socket || !isConnected) {
resolve({
ok: false,
error: {
code: "SOCKET_DISCONNECTED",
message: "채팅 서버에 연결되어 있지 않습니다.",
},
clientMessageId: payload.clientMessageId,
});
return;
}

socket
.timeout(SOCKET_ACK_TIMEOUT_MS)
.emit(
"chat:image:send",
payload,
(error: Error | null, response?: SendChatImageMessageAck) => {
if (error) {
resolve({
ok: false,
error: {
code: "SOCKET_TIMEOUT",
message: "채팅 서버 응답 시간이 초과되었습니다.",
},
clientMessageId: payload.clientMessageId,
});
return;
}

if (!response) {
resolve({
ok: false,
error: {
code: "SOCKET_EMPTY_ACK",
message: "채팅 서버 응답이 올바르지 않습니다.",
},
clientMessageId: payload.clientMessageId,
});
return;
}

resolve(response);
},
);
}),
[isConnected, socket],
);

return {
socket,
isConnected,
canConnect,
sendMessage,
sendImageMessage,
};
}
Loading