v7.0.0-beta.2 release
This commit is contained in:
1 parent
fa8eba7a0d
commit
5d4890d6fb
30 files changed
+1508
-136
No files matched your search
@@ -1,4 +1,4 @@
|
||||
import React, { useState, useRef, useEffect, useCallback } from 'react';
|
||||
import React, { useState, useRef, useEffect, useCallback, useLayoutEffect } from 'react';
|
||||
import { Div } from '../basic/Div';
|
||||
import { Button } from '../basic/Button';
|
||||
import { Span } from '../basic/Span';
|
||||
@@ -105,28 +105,55 @@ export const NotificationCenter: React.FC<NotificationCenterProps> = ({
|
||||
}) => {
|
||||
const [showNotifications, setShowNotifications] = useState(false);
|
||||
const notificationRef = useRef<HTMLDivElement>(null);
|
||||
const dropdownRef = useRef<HTMLDivElement>(null);
|
||||
const scrollRef = useRef<HTMLDivElement>(null);
|
||||
const sentinelRef = useRef<HTMLDivElement>(null);
|
||||
const visibleUnreadIdsRef = useRef<Set<string | number>>(new Set());
|
||||
|
||||
// 무한스크롤 관련 최신 값 참조 (observer 재등록 없이 최신 prop 접근)
|
||||
const onLoadMoreRef = useRef(onLoadMore);
|
||||
const hasMoreRef = useRef(hasMore);
|
||||
const loadingRef = useRef(loading);
|
||||
const notificationsCountRef = useRef(notifications.length);
|
||||
// 마지막 onLoadMore 발행 시점의 notifications.length — 동일 길이에서 중복 발행 가드
|
||||
const lastRequestedCountRef = useRef<number>(-1);
|
||||
|
||||
useEffect(() => {
|
||||
onLoadMoreRef.current = onLoadMore;
|
||||
hasMoreRef.current = hasMore;
|
||||
loadingRef.current = loading;
|
||||
notificationsCountRef.current = notifications.length;
|
||||
});
|
||||
|
||||
/**
|
||||
* 무한스크롤 — IntersectionObserver
|
||||
*
|
||||
* observer는 드롭다운 열림/닫힘 전환 시에만 재등록한다.
|
||||
* 목록이 append되거나 loading/hasMore가 바뀌어도 observer를 새로 만들지 않으므로,
|
||||
* sentinel이 이미 뷰포트에 있는 상태에서 재등록 시 즉시 intersecting callback이
|
||||
* 중복 발행되던 문제를 방지한다.
|
||||
*/
|
||||
useEffect(() => {
|
||||
if (!sentinelRef.current || !scrollRef.current || !hasMore || loading || !showNotifications) return;
|
||||
if (!sentinelRef.current || !scrollRef.current || !showNotifications) return;
|
||||
|
||||
// 드롭다운이 새로 열릴 때마다 중복 가드 초기화
|
||||
lastRequestedCountRef.current = -1;
|
||||
|
||||
const observer = new IntersectionObserver(
|
||||
([entry]) => {
|
||||
if (entry.isIntersecting) {
|
||||
onLoadMore?.();
|
||||
}
|
||||
if (!entry.isIntersecting) return;
|
||||
if (loadingRef.current || !hasMoreRef.current) return;
|
||||
// B안 가드: 같은 length에서 이미 한 번 발행했다면 skip
|
||||
if (lastRequestedCountRef.current === notificationsCountRef.current) return;
|
||||
lastRequestedCountRef.current = notificationsCountRef.current;
|
||||
onLoadMoreRef.current?.();
|
||||
},
|
||||
{ root: scrollRef.current, threshold: 0.1 }
|
||||
);
|
||||
|
||||
observer.observe(sentinelRef.current);
|
||||
return () => observer.disconnect();
|
||||
}, [hasMore, loading, showNotifications, onLoadMore, notifications.length]);
|
||||
}, [showNotifications]);
|
||||
|
||||
/**
|
||||
* 뷰포트 내 미읽음 알림 추적 — IntersectionObserver
|
||||
@@ -156,19 +183,34 @@ export const NotificationCenter: React.FC<NotificationCenterProps> = ({
|
||||
return () => observer.disconnect();
|
||||
}, [showNotifications, notifications]);
|
||||
|
||||
/**
|
||||
* 뱃지에 표시할 카운트 (handleClose 보다 먼저 선언 — deps 참조 순서)
|
||||
*/
|
||||
const displayCount = unreadCount > 0 ? unreadCount : notifications.filter((n) => !n.read).length;
|
||||
|
||||
/**
|
||||
* 드롭다운 닫기 — 뷰포트에 들어온 미읽음 알림 ID 전달
|
||||
*
|
||||
* 불필요한 read-batch 호출 방지:
|
||||
* 1) displayCount 가 0 이면 이미 모두 읽음/삭제 처리된 상태 → 전체 skip
|
||||
* 2) 뷰포트에 나타났던 ID 중 현재 notifications 기준 여전히 unread 인 것만 전달
|
||||
* ("모두 읽음" onSuccess 로 notifications 가 갱신되면 필터 결과가 빈 배열이 됨)
|
||||
*/
|
||||
const handleClose = useCallback(() => {
|
||||
if (showNotifications) {
|
||||
const ids = Array.from(visibleUnreadIdsRef.current);
|
||||
if (ids.length > 0) {
|
||||
onClose?.(ids);
|
||||
if (displayCount > 0) {
|
||||
const unreadIds = Array.from(visibleUnreadIdsRef.current).filter((id) => {
|
||||
const n = notifications.find((item) => String(item.id) === String(id));
|
||||
return n && !n.read;
|
||||
});
|
||||
if (unreadIds.length > 0) {
|
||||
onClose?.(unreadIds);
|
||||
}
|
||||
}
|
||||
visibleUnreadIdsRef.current.clear();
|
||||
setShowNotifications(false);
|
||||
}
|
||||
}, [showNotifications, onClose]);
|
||||
}, [showNotifications, onClose, displayCount, notifications]);
|
||||
|
||||
/**
|
||||
* 외부 클릭 감지 — 드롭다운이 열려 있을 때만 리스너 등록
|
||||
@@ -203,9 +245,36 @@ export const NotificationCenter: React.FC<NotificationCenterProps> = ({
|
||||
}, [showNotifications, handleClose]);
|
||||
|
||||
/**
|
||||
* 뱃지에 표시할 카운트
|
||||
* 드롭다운 열릴 때 뷰포트 경계 검사 후 이탈량만큼 translateX 로 보정
|
||||
*
|
||||
* class 기반 left-0/right-0 전환은 부모 컨테이너 기준이라 부모가 뷰포트 가장자리에 있을 때
|
||||
* 여전히 이탈할 수 있다. 따라서 초기 렌더 후 드롭다운의 실제 뷰포트 좌표를 측정하여
|
||||
* 이탈한 픽셀만큼 반대 방향으로 이동시키는 방식을 사용한다.
|
||||
*/
|
||||
const displayCount = unreadCount > 0 ? unreadCount : notifications.filter((n) => !n.read).length;
|
||||
useLayoutEffect(() => {
|
||||
const dropdown = dropdownRef.current;
|
||||
if (!showNotifications || !dropdown) return;
|
||||
|
||||
// 측정 전 기존 transform 초기화 (재측정 시 누적 방지)
|
||||
dropdown.style.transform = '';
|
||||
const rect = dropdown.getBoundingClientRect();
|
||||
const vw = typeof window !== 'undefined' ? window.innerWidth : 0;
|
||||
|
||||
// layout 미측정(jsdom 등)에서 rect 가 0 으로 반환되는 경우 보정 스킵
|
||||
if (rect.width === 0 && rect.height === 0) return;
|
||||
|
||||
const margin = 8;
|
||||
let shift = 0;
|
||||
if (rect.right > vw - margin) {
|
||||
shift = -(rect.right - (vw - margin));
|
||||
} else if (rect.left < margin) {
|
||||
shift = margin - rect.left;
|
||||
}
|
||||
|
||||
if (shift !== 0) {
|
||||
dropdown.style.transform = `translateX(${shift}px)`;
|
||||
}
|
||||
}, [showNotifications, dropdownAlign, notifications.length]);
|
||||
|
||||
return (
|
||||
<Div ref={notificationRef} className={`relative ${className}`}>
|
||||
@@ -224,7 +293,7 @@ export const NotificationCenter: React.FC<NotificationCenterProps> = ({
|
||||
|
||||
{/* 알림 드롭다운 */}
|
||||
{showNotifications && (
|
||||
<Div className={`absolute ${dropdownAlign === 'left' ? 'left-0' : 'right-0'} mt-2 w-80 bg-white dark:bg-gray-800 border border-gray-200 dark:border-gray-700 rounded-lg shadow-lg z-50`}>
|
||||
<Div ref={dropdownRef} className={`absolute ${dropdownAlign === 'left' ? 'left-0' : 'right-0'} mt-2 w-80 max-w-[calc(100vw-1rem)] bg-white dark:bg-gray-800 border border-gray-200 dark:border-gray-700 rounded-lg shadow-lg z-50`}>
|
||||
<Div className="px-4 py-3 border-b border-gray-200 dark:border-gray-700 flex items-center justify-between gap-2">
|
||||
<Div className="flex items-center gap-3 min-w-0">
|
||||
<Span className="font-semibold text-gray-900 dark:text-white">{titleText}</Span>
|
||||
|
||||
+275
@@ -237,4 +237,279 @@ describe('NotificationCenter (sirsoft-basic)', () => {
|
||||
expect(read?.className).toMatch(/opacity-70/);
|
||||
});
|
||||
});
|
||||
|
||||
describe('[회귀] 무한스크롤 중복 호출 방지 (gnuboard/g7#14 관련)', () => {
|
||||
// 첫 번째로 생성되는 observer 만 무한스크롤용으로 취급. 미읽음 추적 observer 의
|
||||
// disconnect 가 무한스크롤 callback 을 교란하지 않도록 인스턴스 메서드로 격리한다.
|
||||
let infiniteScrollInstance: any = null;
|
||||
|
||||
beforeEach(() => {
|
||||
infiniteScrollInstance = null;
|
||||
(window as any).IntersectionObserver = class MockIO {
|
||||
root: Element | null = null;
|
||||
rootMargin = '';
|
||||
thresholds: number[] = [];
|
||||
callback: IntersectionObserverCallback | null;
|
||||
target: Element | null = null;
|
||||
constructor(cb: IntersectionObserverCallback) {
|
||||
this.callback = cb;
|
||||
if (!infiniteScrollInstance) infiniteScrollInstance = this;
|
||||
}
|
||||
observe(target: Element) {
|
||||
if (!this.target) this.target = target;
|
||||
}
|
||||
disconnect() {
|
||||
this.callback = null;
|
||||
this.target = null;
|
||||
if (infiniteScrollInstance === this) infiniteScrollInstance = null;
|
||||
}
|
||||
unobserve() {}
|
||||
takeRecords() { return []; }
|
||||
};
|
||||
});
|
||||
|
||||
const fireIntersection = () => {
|
||||
infiniteScrollInstance?.callback?.(
|
||||
[{ isIntersecting: true, target: infiniteScrollInstance.target } as unknown as IntersectionObserverEntry],
|
||||
{} as IntersectionObserver,
|
||||
);
|
||||
};
|
||||
|
||||
const makeNotifications = (count: number): NotificationItem[] =>
|
||||
Array.from({ length: count }, (_, i) => ({
|
||||
id: i + 1,
|
||||
title: `t${i}`,
|
||||
message: `m${i}`,
|
||||
time: '1m',
|
||||
read: false,
|
||||
}));
|
||||
|
||||
it('같은 notifications.length 에서 sentinel 이 재교차해도 onLoadMore 는 한 번만 호출된다', () => {
|
||||
const onLoadMore = vi.fn();
|
||||
render(
|
||||
<NotificationCenter
|
||||
notifications={makeNotifications(15)}
|
||||
hasMore={true}
|
||||
loading={false}
|
||||
onLoadMore={onLoadMore}
|
||||
/>,
|
||||
);
|
||||
fireEvent.click(screen.getByLabelText('알림'));
|
||||
|
||||
fireIntersection();
|
||||
fireIntersection();
|
||||
fireIntersection();
|
||||
|
||||
expect(onLoadMore).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('loading=true 일 때는 onLoadMore 를 발행하지 않는다', () => {
|
||||
const onLoadMore = vi.fn();
|
||||
render(
|
||||
<NotificationCenter
|
||||
notifications={makeNotifications(15)}
|
||||
hasMore={true}
|
||||
loading={true}
|
||||
onLoadMore={onLoadMore}
|
||||
/>,
|
||||
);
|
||||
fireEvent.click(screen.getByLabelText('알림'));
|
||||
fireIntersection();
|
||||
|
||||
expect(onLoadMore).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('hasMore=false 일 때는 onLoadMore 를 발행하지 않는다', () => {
|
||||
const onLoadMore = vi.fn();
|
||||
render(
|
||||
<NotificationCenter
|
||||
notifications={makeNotifications(15)}
|
||||
hasMore={false}
|
||||
loading={false}
|
||||
onLoadMore={onLoadMore}
|
||||
/>,
|
||||
);
|
||||
fireEvent.click(screen.getByLabelText('알림'));
|
||||
fireIntersection();
|
||||
|
||||
expect(onLoadMore).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('notifications.length 가 증가한 뒤 재교차하면 onLoadMore 를 다시 발행한다', () => {
|
||||
const onLoadMore = vi.fn();
|
||||
const { rerender } = render(
|
||||
<NotificationCenter
|
||||
notifications={makeNotifications(15)}
|
||||
hasMore={true}
|
||||
loading={false}
|
||||
onLoadMore={onLoadMore}
|
||||
/>,
|
||||
);
|
||||
fireEvent.click(screen.getByLabelText('알림'));
|
||||
fireIntersection();
|
||||
expect(onLoadMore).toHaveBeenCalledTimes(1);
|
||||
|
||||
rerender(
|
||||
<NotificationCenter
|
||||
notifications={makeNotifications(30)}
|
||||
hasMore={true}
|
||||
loading={false}
|
||||
onLoadMore={onLoadMore}
|
||||
/>,
|
||||
);
|
||||
|
||||
fireIntersection();
|
||||
expect(onLoadMore).toHaveBeenCalledTimes(2);
|
||||
|
||||
fireIntersection();
|
||||
expect(onLoadMore).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
});
|
||||
|
||||
describe('[회귀] 닫기 시 read-batch 불필요 호출 방지', () => {
|
||||
it('unreadCount=0 + 모든 알림 read=true 상태에서 닫으면 onClose 를 호출하지 않는다', () => {
|
||||
const onClose = vi.fn();
|
||||
const allRead: NotificationItem[] = mockNotifications.map((n) => ({ ...n, read: true }));
|
||||
|
||||
render(
|
||||
<NotificationCenter
|
||||
notifications={allRead}
|
||||
unreadCount={0}
|
||||
onClose={onClose}
|
||||
/>,
|
||||
);
|
||||
|
||||
// 레이어 열고 닫기
|
||||
const button = screen.getByLabelText('알림');
|
||||
fireEvent.click(button);
|
||||
fireEvent.click(button);
|
||||
|
||||
expect(onClose).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('뷰포트에 노출됐던 ID 라도 현재 notifications 에서 read=true 로 바뀐 것은 onClose 인자에서 제외된다', () => {
|
||||
const onClose = vi.fn();
|
||||
|
||||
const { rerender, container } = render(
|
||||
<NotificationCenter notifications={mockNotifications} unreadCount={1} onClose={onClose} />,
|
||||
);
|
||||
|
||||
const button = screen.getByLabelText('알림');
|
||||
fireEvent.click(button);
|
||||
|
||||
// data-unread 속성 시뮬레이션
|
||||
container.querySelectorAll('[data-notification-id]').forEach((el) => {
|
||||
const id = el.getAttribute('data-notification-id');
|
||||
const n = mockNotifications.find((item) => String(item.id) === String(id));
|
||||
el.setAttribute('data-unread', n?.read ? 'false' : 'true');
|
||||
});
|
||||
|
||||
// 모두 읽음 처리된 상태로 rerender
|
||||
rerender(
|
||||
<NotificationCenter
|
||||
notifications={mockNotifications.map((n) => ({ ...n, read: true }))}
|
||||
unreadCount={0}
|
||||
onClose={onClose}
|
||||
/>,
|
||||
);
|
||||
|
||||
// 레이어 닫기
|
||||
fireEvent.click(screen.getByLabelText('알림'));
|
||||
|
||||
expect(onClose).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe('[회귀] 드롭다운 뷰포트 이탈 방지', () => {
|
||||
let originalGetBoundingClientRect: typeof Element.prototype.getBoundingClientRect;
|
||||
|
||||
beforeEach(() => {
|
||||
originalGetBoundingClientRect = Element.prototype.getBoundingClientRect;
|
||||
});
|
||||
|
||||
it('드롭다운에 max-w-[calc(100vw-1rem)] 클래스가 적용된다', () => {
|
||||
const { container } = render(<NotificationCenter notifications={mockNotifications} />);
|
||||
fireEvent.click(screen.getByLabelText('알림'));
|
||||
|
||||
const dropdown = container.querySelector('.absolute.w-80');
|
||||
expect(dropdown?.className).toContain('max-w-[calc(100vw-1rem)]');
|
||||
|
||||
Element.prototype.getBoundingClientRect = originalGetBoundingClientRect;
|
||||
});
|
||||
|
||||
it('드롭다운이 뷰포트 오른쪽을 이탈하면 translateX 로 왼쪽으로 보정된다', () => {
|
||||
Element.prototype.getBoundingClientRect = vi.fn(() => ({
|
||||
left: 100,
|
||||
right: 1100,
|
||||
top: 0,
|
||||
bottom: 100,
|
||||
width: 320,
|
||||
height: 100,
|
||||
x: 100,
|
||||
y: 0,
|
||||
toJSON: () => ({}),
|
||||
}) as DOMRect);
|
||||
Object.defineProperty(window, 'innerWidth', { value: 1024, writable: true, configurable: true });
|
||||
|
||||
const { container } = render(
|
||||
<NotificationCenter notifications={mockNotifications} dropdownAlign="left" />,
|
||||
);
|
||||
fireEvent.click(screen.getByLabelText('알림'));
|
||||
|
||||
const dropdown = container.querySelector<HTMLElement>('.absolute.w-80');
|
||||
expect(dropdown?.style.transform).toBe('translateX(-84px)');
|
||||
|
||||
Element.prototype.getBoundingClientRect = originalGetBoundingClientRect;
|
||||
});
|
||||
|
||||
it('드롭다운이 뷰포트 왼쪽을 이탈하면 translateX 로 오른쪽으로 보정된다', () => {
|
||||
Element.prototype.getBoundingClientRect = vi.fn(() => ({
|
||||
left: -50,
|
||||
right: 270,
|
||||
top: 0,
|
||||
bottom: 100,
|
||||
width: 320,
|
||||
height: 100,
|
||||
x: -50,
|
||||
y: 0,
|
||||
toJSON: () => ({}),
|
||||
}) as DOMRect);
|
||||
Object.defineProperty(window, 'innerWidth', { value: 1024, writable: true, configurable: true });
|
||||
|
||||
const { container } = render(
|
||||
<NotificationCenter notifications={mockNotifications} dropdownAlign="right" />,
|
||||
);
|
||||
fireEvent.click(screen.getByLabelText('알림'));
|
||||
|
||||
const dropdown = container.querySelector<HTMLElement>('.absolute.w-80');
|
||||
expect(dropdown?.style.transform).toBe('translateX(58px)');
|
||||
|
||||
Element.prototype.getBoundingClientRect = originalGetBoundingClientRect;
|
||||
});
|
||||
|
||||
it('드롭다운이 뷰포트 안에 있으면 transform 이 적용되지 않는다', () => {
|
||||
Element.prototype.getBoundingClientRect = vi.fn(() => ({
|
||||
left: 100,
|
||||
right: 420,
|
||||
top: 0,
|
||||
bottom: 100,
|
||||
width: 320,
|
||||
height: 100,
|
||||
x: 100,
|
||||
y: 0,
|
||||
toJSON: () => ({}),
|
||||
}) as DOMRect);
|
||||
Object.defineProperty(window, 'innerWidth', { value: 1024, writable: true, configurable: true });
|
||||
|
||||
const { container } = render(
|
||||
<NotificationCenter notifications={mockNotifications} dropdownAlign="right" />,
|
||||
);
|
||||
fireEvent.click(screen.getByLabelText('알림'));
|
||||
|
||||
const dropdown = container.querySelector<HTMLElement>('.absolute.w-80');
|
||||
expect(dropdown?.style.transform).toBe('');
|
||||
|
||||
Element.prototype.getBoundingClientRect = originalGetBoundingClientRect;
|
||||
});
|
||||
});
|
||||
});
|
||||
Reference in new issue
Block a user