mirror of
https://github.com/headporter81/ss-front-react.git
synced 2026-12-06 07:41:11 +09:00
feat : 메뉴 개편 (회사 소개·문의하기 → 방명록·대화실), 방명록·대화실 화면
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
687f8594d5
commit
c296aa5041
9 files changed
+393
-6
No files matched your search
@@ -5,6 +5,8 @@ import { AUTH_KEY, PALETTE_KEY, PALETTES } from "../constants";
|
||||
import { fetchBoards, fetchFeed, fetchMediaCategories, fetchMediaPosts } from "../api";
|
||||
import { apiError, execute, initialState, LOGOUT } from "../lib/command";
|
||||
import type { ListKind, Nav, Palette } from "../types";
|
||||
import Chat from "./Chat";
|
||||
import Guestbook from "./Guestbook";
|
||||
import LoginForm from "./LoginForm";
|
||||
import MainMenu from "./MainMenu";
|
||||
import MediaDetail from "./MediaDetail";
|
||||
@@ -335,6 +337,10 @@ export default function BbsTerminal() {
|
||||
onDeleted={() => dispatch({ screen: "media", rev: state.rev + 1 })}
|
||||
/>
|
||||
)}
|
||||
{state.screen === "guestbook" && (
|
||||
<Guestbook user={state.user} token={state.token} rev={state.rev} onError={onApiError} />
|
||||
)}
|
||||
{state.screen === "chat" && <Chat user={state.user} token={state.token} onError={onApiError} />}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
|
||||
@@ -0,0 +1,155 @@
|
||||
import { useEffect, useRef, useState, type FormEvent } from "react";
|
||||
import { pollChat, sayChat, uuid } from "../api";
|
||||
import { readNick, saveNick, shortTime } from "../lib/nick";
|
||||
import type { ChatMessage } from "../types";
|
||||
import styles from "./bbs.module.css";
|
||||
|
||||
const POLL_MS = 2000; // 새 말을 물어보는 간격
|
||||
const KEEP = 200; // 화면에 남겨 둘 줄 수
|
||||
|
||||
interface Props {
|
||||
user: string | null;
|
||||
token: string | null;
|
||||
onError: (e: unknown) => void;
|
||||
}
|
||||
|
||||
/**
|
||||
* [6] 대화실: 2초마다 서버에 "마지막으로 받은 번호 뒤의 새 말"을 물어봄 (폴링).
|
||||
* 대화는 서버 메모리에만 있어서 매일 밤 서버가 꺼지면 사라짐.
|
||||
*/
|
||||
export default function Chat({ user, token, onError }: Props) {
|
||||
const [nick, setNick] = useState(() => (user ? user : readNick()));
|
||||
const [messages, setMessages] = useState<ChatMessage[]>([]);
|
||||
const [online, setOnline] = useState<string[]>([]);
|
||||
const [offline, setOffline] = useState(false); // 서버에 못 붙는 중
|
||||
const [busy, setBusy] = useState(false);
|
||||
const logRef = useRef<HTMLDivElement>(null);
|
||||
const name = user ?? nick; // 로그인했으면 아이디로
|
||||
|
||||
// 폴링: 화면에 있는 동안만. 응답이 오면 2초 뒤 다음 요청 (요청이 겹치지 않음)
|
||||
useEffect(() => {
|
||||
if (!name) return; // 닉네임부터 정해야 입장
|
||||
const client = uuid(); // 이 화면(접속) 하나를 구분하는 값 → 접속자 목록
|
||||
let after: number | null = null;
|
||||
let timer: ReturnType<typeof setTimeout>;
|
||||
let stopped = false;
|
||||
const tick = async () => {
|
||||
try {
|
||||
const r = await pollChat(token, after, client, name);
|
||||
if (stopped) return;
|
||||
const first = after === null; // 입장(또는 닉네임 변경) 직후 첫 응답 → 목록을 새로 채움
|
||||
if (first || r.messages.length) {
|
||||
if (r.messages.length) after = r.messages.at(-1)!.id;
|
||||
else after = 0;
|
||||
setMessages((prev) => (first ? r.messages : [...prev, ...r.messages]).slice(-KEEP));
|
||||
}
|
||||
setOnline(r.online);
|
||||
setOffline(false);
|
||||
} catch {
|
||||
if (!stopped) setOffline(true); // 알림 팝업 대신 화면에 표시하고 계속 다시 시도
|
||||
}
|
||||
if (!stopped) timer = setTimeout(tick, POLL_MS);
|
||||
};
|
||||
tick();
|
||||
return () => {
|
||||
stopped = true;
|
||||
clearTimeout(timer);
|
||||
};
|
||||
}, [name, token]);
|
||||
|
||||
// 새 말이 오면 맨 아래로
|
||||
useEffect(() => {
|
||||
logRef.current?.scrollTo({ top: logRef.current.scrollHeight });
|
||||
}, [messages]);
|
||||
|
||||
const enter = (e: FormEvent<HTMLFormElement>) => {
|
||||
e.preventDefault();
|
||||
const n = String(new FormData(e.currentTarget).get("nickname")).trim();
|
||||
if (!n) return;
|
||||
saveNick(n);
|
||||
setNick(n);
|
||||
};
|
||||
|
||||
const say = async (e: FormEvent<HTMLFormElement>) => {
|
||||
e.preventDefault();
|
||||
const input = e.currentTarget.elements.namedItem("message") as HTMLInputElement;
|
||||
const text = input.value.trim();
|
||||
if (!text) return;
|
||||
setBusy(true);
|
||||
try {
|
||||
await sayChat(token, name, text);
|
||||
input.value = ""; // 내 말은 다음 폴링 때 다른 사람 말과 같은 순서로 나타남
|
||||
} catch (err) {
|
||||
onError(err);
|
||||
} finally {
|
||||
setBusy(false);
|
||||
input.focus();
|
||||
}
|
||||
};
|
||||
|
||||
if (!name) {
|
||||
return (
|
||||
<section className={`${styles.win} ${styles.full}`}>
|
||||
<span className={styles.cap}>═ [6] 대화실 ═</span>
|
||||
<div className={styles.dim}>대화실에서 쓸 닉네임을 정해 주세요.</div>
|
||||
<hr className={styles.rule} />
|
||||
<form className={styles.loginForm} onSubmit={enter}>
|
||||
<label>
|
||||
<span className={styles.num}>닉네임</span>
|
||||
<input name="nickname" maxLength={20} required autoFocus autoComplete="nickname" />
|
||||
</label>
|
||||
<button type="submit">입장</button>
|
||||
</form>
|
||||
<div className={styles.footer}>
|
||||
<b>M</b>=메인
|
||||
</div>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<section className={`${styles.win} ${styles.full}`}>
|
||||
<span className={styles.cap}>═ [6] 대화실 ═</span>
|
||||
<div className={styles.dim}>
|
||||
접속자 {online.length}명: <span className={styles.accent}>{online.join(", ") || "-"}</span>
|
||||
</div>
|
||||
<hr className={styles.rule} />
|
||||
<div ref={logRef} className={styles.chatLog} aria-live="polite">
|
||||
<div className={styles.dim}>── {name}님이 입장했습니다. 대화는 서버가 쉬는 밤 12시에 지워집니다 ──</div>
|
||||
{messages.map((m) => (
|
||||
<div key={m.id}>
|
||||
<span className={styles.dim}>[{shortTime(m.at).slice(6)}]</span>{" "}
|
||||
<span className={m.nickname === name ? styles.highlight : styles.accent}>
|
||||
{m.nickname}
|
||||
{m.member && "★"}
|
||||
</span>
|
||||
<span className={styles.dim}>> </span>
|
||||
<span className={styles.msg}>{m.message}</span>
|
||||
</div>
|
||||
))}
|
||||
{offline && <div className={styles.error}>※ 서버와 연결이 끊겼습니다. 다시 연결하는 중...</div>}
|
||||
</div>
|
||||
<hr className={styles.rule} />
|
||||
<form className={`${styles.loginForm} ${styles.searchForm}`} onSubmit={say}>
|
||||
<label>
|
||||
<span className={styles.num}>{name}></span>
|
||||
<input name="message" className={styles.wide} placeholder="할 말을 쓰고 엔터" maxLength={200} autoComplete="off" autoFocus />
|
||||
</label>
|
||||
<button type="submit" disabled={busy}>
|
||||
말하기
|
||||
</button>
|
||||
</form>
|
||||
<div className={styles.footer}>
|
||||
★=회원 · <b>M</b>=메인 (나가기)
|
||||
{!user && (
|
||||
<>
|
||||
{" · "}
|
||||
<button type="button" className={styles.linkBtn} onClick={() => setNick("")}>
|
||||
[닉네임 바꾸기]
|
||||
</button>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,136 @@
|
||||
import { useEffect, useState, type FormEvent } from "react";
|
||||
import { deleteGuestbook, fetchGuestbook, writeGuestbook } from "../api";
|
||||
import { readNick, saveNick, shortTime } from "../lib/nick";
|
||||
import type { GuestbookEntry } from "../types";
|
||||
import styles from "./bbs.module.css";
|
||||
|
||||
const PAGE = 30; // 백엔드가 한 번에 주는 개수와 같음
|
||||
|
||||
interface Props {
|
||||
user: string | null;
|
||||
token: string | null;
|
||||
rev: number; // "L"을 누르면 +1 → 다시 불러오기
|
||||
onError: (e: unknown) => void;
|
||||
}
|
||||
|
||||
/** [5] 방명록: 누구나 한 줄 남기기 (손님은 닉네임 입력), 회원은 지우기 가능 */
|
||||
export default function Guestbook({ user, token, rev, onError }: Props) {
|
||||
const [entries, setEntries] = useState<GuestbookEntry[] | null>(null);
|
||||
const [last, setLast] = useState(true); // 더 오래된 글이 없음
|
||||
const [busy, setBusy] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
let stale = false;
|
||||
fetchGuestbook(token)
|
||||
.then((rows) => {
|
||||
if (stale) return;
|
||||
setEntries(rows);
|
||||
setLast(rows.length < PAGE);
|
||||
})
|
||||
.catch((e) => !stale && onError(e));
|
||||
return () => {
|
||||
stale = true;
|
||||
};
|
||||
}, [token, rev, onError]);
|
||||
|
||||
const more = async () => {
|
||||
if (!entries?.length) return;
|
||||
try {
|
||||
const rows = await fetchGuestbook(token, entries.at(-1)!.id);
|
||||
setEntries([...entries, ...rows]);
|
||||
setLast(rows.length < PAGE);
|
||||
} catch (e) {
|
||||
onError(e);
|
||||
}
|
||||
};
|
||||
|
||||
const submit = async (e: FormEvent<HTMLFormElement>) => {
|
||||
e.preventDefault();
|
||||
const form = e.currentTarget;
|
||||
const data = new FormData(form);
|
||||
const nickname = String(data.get("nickname") ?? "").trim();
|
||||
setBusy(true);
|
||||
try {
|
||||
const saved = await writeGuestbook(token, nickname, String(data.get("message")).trim());
|
||||
if (!user) saveNick(nickname);
|
||||
setEntries((prev) => [saved, ...(prev ?? [])]);
|
||||
(form.elements.namedItem("message") as HTMLInputElement).value = "";
|
||||
} catch (err) {
|
||||
onError(err);
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
};
|
||||
|
||||
const remove = async (id: number) => {
|
||||
if (!token) return;
|
||||
try {
|
||||
await deleteGuestbook(token, id);
|
||||
setEntries((prev) => prev?.filter((x) => x.id !== id) ?? null);
|
||||
} catch (e) {
|
||||
onError(e);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<section className={`${styles.win} ${styles.full}`}>
|
||||
<span className={styles.cap}>═ [5] 방명록 ═</span>
|
||||
<div className={styles.dim}>다녀간 흔적을 한 줄 남겨 주세요. (30초에 한 번)</div>
|
||||
<hr className={styles.rule} />
|
||||
<form className={styles.loginForm} onSubmit={submit}>
|
||||
<label>
|
||||
<span className={styles.num}>이름</span>
|
||||
{user ? (
|
||||
<span className={styles.accent}>{user} ★</span>
|
||||
) : (
|
||||
<input name="nickname" defaultValue={readNick()} placeholder="닉네임" maxLength={20} required autoComplete="nickname" />
|
||||
)}
|
||||
</label>
|
||||
<label>
|
||||
<span className={styles.num}>내용</span>
|
||||
<input name="message" className={styles.wide} placeholder="한 줄 남기기" maxLength={300} required autoComplete="off" />
|
||||
</label>
|
||||
<button type="submit" disabled={busy}>
|
||||
{busy ? "남기는 중..." : "남기기"}
|
||||
</button>
|
||||
</form>
|
||||
<hr className={styles.rule} />
|
||||
|
||||
{!entries ? (
|
||||
<div className={styles.dim}>불러오는 중...</div>
|
||||
) : entries.length === 0 ? (
|
||||
<div className={styles.dim}>아직 아무도 다녀가지 않았어요. 첫 번째 손님이 되어 주세요.</div>
|
||||
) : (
|
||||
<ul className={styles.lines}>
|
||||
{entries.map((g) => (
|
||||
<li key={g.id}>
|
||||
<span className={styles.dim}>{shortTime(g.createdAt)}</span>{" "}
|
||||
<span className={styles.accent}>
|
||||
{g.nickname}
|
||||
{g.member && " ★"}
|
||||
</span>
|
||||
<span className={styles.dim}> : </span>
|
||||
<span className={styles.msg}>{g.message}</span>
|
||||
{user && (
|
||||
<>
|
||||
{" "}
|
||||
<button type="button" className={styles.linkBtn} onClick={() => remove(g.id)}>
|
||||
[지우기]
|
||||
</button>
|
||||
</>
|
||||
)}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
{entries && entries.length > 0 && !last && (
|
||||
<button type="button" className={styles.linkBtn} onClick={more}>
|
||||
[더 보기]
|
||||
</button>
|
||||
)}
|
||||
<div className={styles.footer}>
|
||||
★=회원 · <b>L</b>=새로고침 · <b>M</b>=메인
|
||||
</div>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
@@ -56,6 +56,12 @@
|
||||
.dim { color: var(--bbs-dim); }
|
||||
.accent { color: var(--bbs-accent); }
|
||||
.error { color: #ff6b6b; }
|
||||
.highlight { color: var(--bbs-highlight); }
|
||||
/* 방명록·대화실 한 줄: 남이 쓴 글은 줄바꿈만 하고 HTML로 해석하지 않음 (React가 글자로 넣음) */
|
||||
.msg { color: var(--bbs-hi); overflow-wrap: anywhere; }
|
||||
.lines { list-style: none; margin: 0 0 0.6em; padding: 0; display: grid; gap: 0.2em; }
|
||||
/* 대화창: 자기 안에서만 스크롤, 새 말이 오면 맨 아래로 */
|
||||
.chatLog { height: min(50dvh, 24em); overflow-y: auto; overscroll-behavior: contain; }
|
||||
.rule { border: none; border-top: 1px dashed var(--bbs-dim); margin: 0.6em 0; }
|
||||
.footer { color: var(--bbs-dim); margin-top: 0.6em; }
|
||||
.footer b { color: var(--bbs-highlight); }
|
||||
|
||||
Reference in new issue
Block a user