diff --git a/src/features/chat/ChatEntryScreen.tsx b/src/features/chat/ChatEntryScreen.tsx index 1f0f6592..4cda8300 100644 --- a/src/features/chat/ChatEntryScreen.tsx +++ b/src/features/chat/ChatEntryScreen.tsx @@ -1,7 +1,7 @@ import { TopNavigationButton, Typography } from "@wanteddev/wds"; import { IconChevronLeft } from "@wanteddev/wds-icon"; import { useEffect, useRef, useState } from "react"; -import { useNavigate } from "react-router-dom"; +import { useLocation, useNavigate } from "react-router-dom"; import ConfirmModal from "@/components/ui/ConfirmModal"; import ScreenHeader from "@/components/ui/ScreenHeader"; @@ -16,6 +16,11 @@ import SuggestedQuestion from "@/features/chat/components/SuggestedQuestion"; import { CHAT_SEND_FAILURE_MESSAGE } from "@/features/chat/constants/chat"; import { CHAT_SUGGESTED_QUESTIONS } from "@/features/chat/constants/chatSuggestedQuestions"; import { useChatStream } from "@/features/chat/hooks/useChatStream"; +import { + clearChatSnapshot, + readChatSnapshot, + saveChatSnapshot, +} from "@/features/chat/utils/chatSnapshot"; import { useBackNavigation } from "@/hooks/useBackNavigation"; // Figma: 챗봇 진입 화면(nodeId 1887:91534)과 챗봇 대화창(1770:63314) — 메시지를 하나라도 @@ -24,6 +29,9 @@ import { useBackNavigation } from "@/hooks/useBackNavigation"; // 레이아웃이 튀지 않는다. function ChatEntryScreen() { const navigate = useNavigate(); + const location = useLocation(); + // 출처 링크로 공지·행사에 갔다가 뒤로 돌아왔으면 떠날 때의 대화를 이어 간다(utils/chatSnapshot) + const [restored] = useState(() => readChatSnapshot(location.key)); const [inputValue, setInputValue] = useState(""); const [isLeaveOpen, setIsLeaveOpen] = useState(false); const [isFailureToastOpen, setIsFailureToastOpen] = useState(false); @@ -33,13 +41,25 @@ function ChatEntryScreen() { const messageListRef = useRef(null); const inputRef = useRef(null); // 답변을 받지 못하면 보낸 말풍선을 걷고 질문을 입력창에 되살려 둔다 — 그대로 다시 보낼 수 있게 - const { isAnswering, isWaitingForAnswer, messages, send } = useChatStream({ - onFailure: (question) => { - setInputValue(question); - setFailureCount((prev) => prev + 1); - setIsFailureToastOpen(true); - }, - }); + const { conversationId, isAnswering, isWaitingForAnswer, messages, send } = + useChatStream({ + onFailure: (question) => { + setInputValue(question); + setFailureCount((prev) => prev + 1); + setIsFailureToastOpen(true); + }, + restored, + }); + + // 되살린 대화는 화면 상태로 옮겨 왔으니 보관본을 지운다 + useEffect(() => { + clearChatSnapshot(location.key); + }, [location.key]); + + // 답변 속 링크를 누르면 상세 화면으로 떠나며 이 화면이 사라진다 — 뒤로 돌아왔을 때 이어 가도록 대화를 맡겨 둔다 + function keepChatForReturn() { + saveChatSnapshot(location.key, { conversationId, messages }); + } const chatStarted = messages.length > 0; // 메시지가 추가되거나 답변 조각이 붙을 때, 응답 대기 점이 나타날 때마다 최신 대화가 보이도록 맨 아래로 스크롤한다. @@ -158,6 +178,7 @@ function ChatEntryScreen() { ), )} diff --git a/src/features/chat/components/ChatBotMessageBubble.tsx b/src/features/chat/components/ChatBotMessageBubble.tsx index f4c70ee1..9312c6b4 100644 --- a/src/features/chat/components/ChatBotMessageBubble.tsx +++ b/src/features/chat/components/ChatBotMessageBubble.tsx @@ -1,18 +1,29 @@ import { Typography } from "@wanteddev/wds"; -import type { ReactNode } from "react"; +import { Fragment, type ReactNode } from "react"; +import { Link } from "react-router-dom"; import botIcon from "@/assets/icons/chat/bot.svg"; interface ChatBotMessageBubbleProps { // 문단별 답변. 받는 중이면 마지막 말풍선이 계속 자란다 bubbles: string[]; + // 답변 속 링크를 눌러 다른 화면으로 떠나기 직전 — 돌아왔을 때 대화를 되살리도록 화면이 대화를 맡겨 둔다 + onLinkClick?: () => void; } +// AI 서버는 공지·행사를 근거로 답하면 마지막 줄에 `출처: [제목](/notices/11) (게시일)`을 보낸다(stream-ai #82). +// 주소는 `/`로 시작하는 앱 안 경로만 링크로 만든다 — 답변은 모델이 쓴 글이라 `//다른사이트`·`https:`·`javascript:`가 +// 섞여 와도 누르는 링크가 되면 안 된다. 그런 것은 글자 그대로 둔다. +const MARKDOWN_LINK_PATTERN = /\[([^\]\n]+)\]\((\/(?!\/)[^)\s]*)\)/g; + // Figma: 챗봇 대화창의 Bot Response(nodeId 1770:63307) — 아바타(44px, Atomic/Blue/65 // #4F95FF·홈 FAB의 primary #0066FF와는 다른 대화 중 전용 색) + 말풍선(왼쪽 정렬, 좌상단만 // 4px로 꺾임). 답변은 문단마다 말풍선을 나누고 아바타는 첫 말풍선 위에 한 번만 둔다(AI 서버 계약). // 말풍선 폭은 사용자 말풍선처럼 최대 272px로만 막는다 — 짧은 문단이 넓은 빈 상자로 보이지 않게. -function ChatBotMessageBubble({ bubbles }: ChatBotMessageBubbleProps) { +function ChatBotMessageBubble({ + bubbles, + onLinkClick, +}: ChatBotMessageBubbleProps) { return (
@@ -31,7 +42,7 @@ function ChatBotMessageBubble({ bubbles }: ChatBotMessageBubbleProps) { color="semantic.label.normal" variant="body2-reading" > - {renderBold(bubble)} + {renderLinks(bubble, onLinkClick)}
))} @@ -40,6 +51,38 @@ function ChatBotMessageBubble({ bubbles }: ChatBotMessageBubbleProps) { ); } +// 링크 자리를 먼저 나누고, 링크 바깥 글과 링크 글자 각각에 굵게를 입힌다. +// 받는 중이라 아직 `)`가 오지 않은 링크는 패턴에 안 걸려 잠깐 글자 그대로 보이고, 닫히는 조각이 오면 링크로 바뀐다. +function renderLinks(text: string, onLinkClick?: () => void): ReactNode[] { + const nodes: ReactNode[] = []; + let lastIndex = 0; + for (const match of text.matchAll(MARKDOWN_LINK_PATTERN)) { + const [whole, label, path] = match; + nodes.push( + + {renderBold(text.slice(lastIndex, match.index))} + , + // 공지 목록→상세처럼 화면을 쌓는 이동이라 슬라이드 전환을 켠다(coding-style 「라우팅」) + + {renderBold(label)} + , + ); + lastIndex = match.index + whole.length; + } + nodes.push( + + {renderBold(text.slice(lastIndex))} + , + ); + return nodes; +} + // `**굵게**`만 굵은 글씨로 바꾼다 — AI 서버 프롬프트가 제목·표·코드 블록을 쓰지 않아 다른 마크다운은 오지 않는다. // 지금까지 받은 글 전체로 나눠야 조각 경계에서 쪼개진 `**`도 짝이 맞는다. 받는 중이라 아직 닫히지 않은 // `**`는 숨기고 그 뒤를 미리 굵게 그린다 — 닫히는 조각이 오면 그대로 굵게 남는다. diff --git a/src/features/chat/hooks/useChatStream.ts b/src/features/chat/hooks/useChatStream.ts index f8f80763..119be438 100644 --- a/src/features/chat/hooks/useChatStream.ts +++ b/src/features/chat/hooks/useChatStream.ts @@ -1,5 +1,6 @@ import { useEffect, useRef, useState } from "react"; +import type { ChatSnapshot } from "@/features/chat/utils/chatSnapshot"; import { streamChatMessage } from "@/shared/entities/chat/chatStream"; interface ChatUserMessage { @@ -20,17 +21,27 @@ export type ChatMessage = ChatUserMessage | ChatBotMessage; interface UseChatStreamOptions { // 답변을 받지 못했을 때 — 보낸 질문을 돌려주니 화면은 입력창에 되살리고 토스트를 띄운다 onFailure: (question: string) => void; + // 출처 링크로 떠났다가 뒤로 돌아왔을 때 이어 갈 대화(utils/chatSnapshot). 없으면 새 대화로 시작한다 + restored?: ChatSnapshot | null; } // 챗봇 대화 한 번(채팅방 입장 한 번)의 상태. 질문을 보내고 답변 조각을 말풍선에 이어 붙인다. -export function useChatStream({ onFailure }: UseChatStreamOptions) { +export function useChatStream({ onFailure, restored }: UseChatStreamOptions) { // 화면이 처음 그려질 때 한 번 만든다. 나갔다 다시 들어오면 새로 그려져 새 대화가 된다 — - // 화면이 "들어올 때마다 새 대화"인 것과 서버가 이력을 붙이는 범위를 맞춘다 - const [conversationId] = useState(() => crypto.randomUUID()); - const [messages, setMessages] = useState([]); + // 화면이 "들어올 때마다 새 대화"인 것과 서버가 이력을 붙이는 범위를 맞춘다. + // 출처 링크에서 뒤로 돌아온 경우만 떠날 때의 대화를 이어 간다. 서버 이력도 이어지도록 ID까지 되살린다 + const [conversationId] = useState( + () => restored?.conversationId ?? crypto.randomUUID(), + ); + const [messages, setMessages] = useState( + () => restored?.messages ?? [], + ); // 질문을 보낸 뒤 done·error가 올 때까지. 서버도 한 사람당 답변 하나만 받아서 그동안 입력을 막는다 const [isAnswering, setIsAnswering] = useState(false); - const nextMessageIdRef = useRef(0); + // 되살린 말풍선과 번호가 겹치지 않게 그다음 번호부터 쓴다(말풍선 key로 쓰는 값이다) + const nextMessageIdRef = useRef( + Math.max(0, ...(restored?.messages ?? []).map((message) => message.id)), + ); const abortControllerRef = useRef(null); // 답변 중에 화면을 떠나면(종료하기·뒤로가기) 연결을 끊는다 — 서버도 학생이 끊으면 중계를 멈춘다 @@ -120,7 +131,7 @@ export function useChatStream({ onFailure }: UseChatStreamOptions) { // 보낸 뒤 첫 조각이 오기 전까지만 응답 대기 점을 보여준다 — 조각이 오면 말풍선이 그 자리를 잇는다 const isWaitingForAnswer = isAnswering && lastMessage?.sender === "user"; - return { isAnswering, isWaitingForAnswer, messages, send }; + return { conversationId, isAnswering, isWaitingForAnswer, messages, send }; } function appendToLastBubble(bubbles: string[], text: string): string[] { diff --git a/src/features/chat/utils/chatSnapshot.ts b/src/features/chat/utils/chatSnapshot.ts new file mode 100644 index 00000000..69ffe6e3 --- /dev/null +++ b/src/features/chat/utils/chatSnapshot.ts @@ -0,0 +1,76 @@ +import { z } from "zod"; + +import type { ChatMessage } from "@/features/chat/hooks/useChatStream"; + +// 답변 속 출처 링크를 눌러 공지·행사 상세로 갔다가 뒤로 돌아오면 대화를 되살리기 위해 잠깐 맡겨 두는 대화. +// 대화는 화면 상태라 다른 화면으로 가면 사라진다. 링크를 누르기 직전에 sessionStorage에 넣고, 돌아와 화면이 +// 다시 그려질 때 꺼낸 뒤 지운다. +// +// 키에 히스토리 항목의 key(`location.key`)를 붙인다. 뒤로가기로 돌아오면 떠날 때와 같은 key라 대화가 되살아나고, +// 홈에서 챗봇을 새로 열면 새 key라 지금처럼 새 대화로 시작한다("들어올 때마다 새 대화"는 그대로다). +// history.state에 넣지 않는 이유: 링크를 누를 때마다 지금 항목을 replace로 한 번 더 바꿔야 해서 이동이 두 번 +// 일어난다. sessionStorage는 탭(앱이면 웹뷰)을 닫으면 사라져서 대화가 기기에 오래 남지 않는다. +const CHAT_SNAPSHOT_STORAGE_PREFIX = "stream:chat:snapshot:"; + +export interface ChatSnapshot { + // 백엔드가 대화 이력을 이 값으로 묶는다 — 같이 되살려야 돌아와서 이어 묻는 질문도 앞 대화를 기억한다 + conversationId: string; + messages: ChatMessage[]; +} + +// 저장소 값은 다른 버전의 코드가 썼을 수도 있어 모양을 검사한 뒤 쓴다. 안 맞으면 새 대화로 시작한다. +const chatSnapshotSchema = z.object({ + conversationId: z.string(), + messages: z.array( + z.discriminatedUnion("sender", [ + z.object({ id: z.number(), sender: z.literal("user"), text: z.string() }), + z.object({ + bubbles: z.array(z.string()), + id: z.number(), + sender: z.literal("bot"), + }), + ]), + ), +}); + +export function saveChatSnapshot( + historyKey: string, + snapshot: ChatSnapshot, +): void { + try { + window.sessionStorage.setItem( + CHAT_SNAPSHOT_STORAGE_PREFIX + historyKey, + JSON.stringify(snapshot), + ); + } catch (error) { + // 저장소가 막힌 환경(시크릿 모드 등)이면 돌아왔을 때 새 대화가 될 뿐이라 이동은 그대로 한다 + console.warn("챗봇 대화를 보관하지 못했어요.", error); + } +} + +// 읽기와 지우기를 나눈다 — 화면은 첫 렌더의 useState 초기값으로 읽는데, StrictMode(개발 서버)가 초기값 함수를 +// 두 번 부른다. 읽으면서 지우면 두 번째 호출이 빈 값을 받는다. 지우기는 화면이 그려진 뒤(useEffect)에 한다. +export function readChatSnapshot(historyKey: string): ChatSnapshot | null { + try { + const raw = window.sessionStorage.getItem( + CHAT_SNAPSHOT_STORAGE_PREFIX + historyKey, + ); + if (raw === null) { + return null; + } + const parsed = chatSnapshotSchema.safeParse(JSON.parse(raw)); + return parsed.success ? parsed.data : null; + } catch (error) { + console.warn("보관한 챗봇 대화를 읽지 못했어요.", error); + return null; + } +} + +// 되살린 뒤 지운다 — 남겨 두면 대화를 더 이어 간 뒤 새로고침했을 때 이미 지난 시점의 대화가 다시 뜬다. +export function clearChatSnapshot(historyKey: string): void { + try { + window.sessionStorage.removeItem(CHAT_SNAPSHOT_STORAGE_PREFIX + historyKey); + } catch (error) { + console.warn("보관한 챗봇 대화를 지우지 못했어요.", error); + } +}