채팅: 가리기 삭제, 100줄이 찬 뒤에도 맨 아래 고정(+새 메시지 수), 이름 줄과 말풍선으로 이름·내용 구분
- 공통 ChatMessage(이름 줄 + 말풍선, 내 말은 오른쪽, 이어 말하면 이름 한 번) — 방 채팅·마피아·라이어 게임, 그림 맞히기 이름 표시 - useStickToBottom: 개수 대신 목록 내용 변화를 보고 맨 아래 유지, 위로 올려 읽는 중엔 그대로, 보내면 다시 맨 아래 - 휴대폰 채팅 버튼의 새 메시지 수도 100줄 뒤에 0이 되던 문제(마지막 본 id 기준으로) - e2e/chat.e2e.ts: PC 대기실·게임 옆 칸·휴대폰 시트 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
46
apps/web/src/lib/useStickToBottom.ts
Normal file
46
apps/web/src/lib/useStickToBottom.ts
Normal file
@@ -0,0 +1,46 @@
|
||||
/**
|
||||
* Keeps a scrolling chat list at its newest (bottom) line. It reacts to what is actually in the list (a DOM
|
||||
* observer), not to a message count: the room chat keeps only the last 100 lines, so once full the count stopped
|
||||
* changing and the list stopped following new messages. If the reader scrolls up to read older lines it stays put
|
||||
* until they come back near the bottom (or `pin()` is called, e.g. after sending a message).
|
||||
*/
|
||||
import { useCallback, useLayoutEffect, useRef } from 'react';
|
||||
|
||||
const NEAR_PX = 48;
|
||||
|
||||
export function useStickToBottom<T extends HTMLElement>() {
|
||||
const ref = useRef<T>(null);
|
||||
const pinned = useRef(true);
|
||||
const toBottom = useCallback(() => {
|
||||
const el = ref.current;
|
||||
if (el) el.scrollTop = el.scrollHeight;
|
||||
}, []);
|
||||
useLayoutEffect(() => {
|
||||
const el = ref.current;
|
||||
if (!el) return;
|
||||
pinned.current = true;
|
||||
toBottom();
|
||||
const onScroll = () => {
|
||||
pinned.current = el.scrollHeight - el.scrollTop - el.clientHeight <= NEAR_PX;
|
||||
};
|
||||
const stick = () => {
|
||||
if (pinned.current) toBottom();
|
||||
};
|
||||
el.addEventListener('scroll', onScroll, { passive: true });
|
||||
const mo = new MutationObserver(stick);
|
||||
mo.observe(el, { childList: true, subtree: true, characterData: true });
|
||||
// The list itself changing size (sheet opening, phone rotating, the input row growing) keeps the bottom too.
|
||||
const ro = typeof ResizeObserver === 'undefined' ? null : new ResizeObserver(stick);
|
||||
ro?.observe(el);
|
||||
return () => {
|
||||
el.removeEventListener('scroll', onScroll);
|
||||
mo.disconnect();
|
||||
ro?.disconnect();
|
||||
};
|
||||
}, [toBottom]);
|
||||
const pin = useCallback(() => {
|
||||
pinned.current = true;
|
||||
toBottom();
|
||||
}, [toBottom]);
|
||||
return { ref, pin };
|
||||
}
|
||||
Reference in New Issue
Block a user