feat: 일정 검색에 가상 스크롤 최적화 적용

- @tanstack/react-virtual 라이브러리 추가
- Schedule.jsx, AdminSchedule.jsx에 useVirtualizer 적용
- 검색 결과가 많아도 DOM에는 화면에 보이는 요소만 렌더링
- 스크롤 성능 대폭 향상
This commit is contained in:
caadiq 2026-01-10 09:34:18 +09:00
parent 7192379eb0
commit ad2d501c39
4 changed files with 250 additions and 161 deletions

View file

@ -9,6 +9,7 @@
"version": "1.0.0", "version": "1.0.0",
"dependencies": { "dependencies": {
"@tanstack/react-query": "^5.90.16", "@tanstack/react-query": "^5.90.16",
"@tanstack/react-virtual": "^3.13.18",
"dayjs": "^1.11.19", "dayjs": "^1.11.19",
"framer-motion": "^11.0.8", "framer-motion": "^11.0.8",
"lucide-react": "^0.344.0", "lucide-react": "^0.344.0",
@ -1160,6 +1161,33 @@
"react": "^18 || ^19" "react": "^18 || ^19"
} }
}, },
"node_modules/@tanstack/react-virtual": {
"version": "3.13.18",
"resolved": "https://registry.npmjs.org/@tanstack/react-virtual/-/react-virtual-3.13.18.tgz",
"integrity": "sha512-dZkhyfahpvlaV0rIKnvQiVoWPyURppl6w4m9IwMDpuIjcJ1sD9YGWrt0wISvgU7ewACXx2Ct46WPgI6qAD4v6A==",
"license": "MIT",
"dependencies": {
"@tanstack/virtual-core": "3.13.18"
},
"funding": {
"type": "github",
"url": "https://github.com/sponsors/tannerlinsley"
},
"peerDependencies": {
"react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0",
"react-dom": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0"
}
},
"node_modules/@tanstack/virtual-core": {
"version": "3.13.18",
"resolved": "https://registry.npmjs.org/@tanstack/virtual-core/-/virtual-core-3.13.18.tgz",
"integrity": "sha512-Mx86Hqu1k39icq2Zusq+Ey2J6dDWTjDvEv43PJtRCoEYTLyfaPnxIQ6iy7YAOK0NV/qOEmZQ/uCufrppZxTgcg==",
"license": "MIT",
"funding": {
"type": "github",
"url": "https://github.com/sponsors/tannerlinsley"
}
},
"node_modules/@types/babel__core": { "node_modules/@types/babel__core": {
"version": "7.20.5", "version": "7.20.5",
"resolved": "https://registry.npmjs.org/@types/babel__core/-/babel__core-7.20.5.tgz", "resolved": "https://registry.npmjs.org/@types/babel__core/-/babel__core-7.20.5.tgz",

View file

@ -10,6 +10,7 @@
}, },
"dependencies": { "dependencies": {
"@tanstack/react-query": "^5.90.16", "@tanstack/react-query": "^5.90.16",
"@tanstack/react-virtual": "^3.13.18",
"dayjs": "^1.11.19", "dayjs": "^1.11.19",
"framer-motion": "^11.0.8", "framer-motion": "^11.0.8",
"lucide-react": "^0.344.0", "lucide-react": "^0.344.0",

View file

@ -6,6 +6,7 @@ import {
ChevronLeft, Search, ChevronDown, Bot, Tag, ArrowLeft, ExternalLink, Clock, Link2 ChevronLeft, Search, ChevronDown, Bot, Tag, ArrowLeft, ExternalLink, Clock, Link2
} from 'lucide-react'; } from 'lucide-react';
import { useInfiniteQuery } from '@tanstack/react-query'; import { useInfiniteQuery } from '@tanstack/react-query';
import { useVirtualizer } from '@tanstack/react-virtual';
import { useInView } from 'react-intersection-observer'; import { useInView } from 'react-intersection-observer';
import Toast from '../../../components/Toast'; import Toast from '../../../components/Toast';
@ -152,6 +153,7 @@ function AdminSchedule() {
const { toast, setToast } = useToast(); const { toast, setToast } = useToast();
const scrollContainerRef = useRef(null); const scrollContainerRef = useRef(null);
const SEARCH_LIMIT = 20; // 20 const SEARCH_LIMIT = 20; // 20
const ITEM_HEIGHT = 100; // (px)
// Intersection Observer for infinite scroll // Intersection Observer for infinite scroll
const { ref: loadMoreRef, inView } = useInView({ const { ref: loadMoreRef, inView } = useInView({
@ -532,6 +534,14 @@ function AdminSchedule() {
return matchesCategory && matchesDate; return matchesCategory && matchesDate;
}); });
}, [isSearchMode, searchTerm, searchResults, schedules, selectedCategories, selectedDate]); }, [isSearchMode, searchTerm, searchResults, schedules, selectedCategories, selectedDate]);
// ( )
const virtualizer = useVirtualizer({
count: isSearchMode && searchTerm ? filteredSchedules.length : 0,
getScrollElement: () => scrollContainerRef.current,
estimateSize: () => ITEM_HEIGHT,
overscan: 5, //
});
// (useMemo ) - // (useMemo ) -
const categoryCounts = useMemo(() => { const categoryCounts = useMemo(() => {
@ -1085,99 +1095,118 @@ function AdminSchedule() {
className="flex-1 overflow-y-auto divide-y divide-gray-100 py-2" className="flex-1 overflow-y-auto divide-y divide-gray-100 py-2"
> >
{isSearchMode && searchTerm ? ( {isSearchMode && searchTerm ? (
/* 검색 모드: useInView 기반 무한 스크롤 */ /* 검색 모드: 가상 스크롤 */
<> <>
{filteredSchedules.map((schedule, index) => ( <div
<motion.div style={{
key={`${schedule.id}-search-${index}`} height: `${virtualizer.getTotalSize()}px`,
initial={{ opacity: 0 }} width: '100%',
animate={{ opacity: 1 }} position: 'relative',
transition={{ delay: Math.min(index, 10) * 0.03 }} }}
className="p-6 hover:bg-gray-50 transition-colors group" >
> {virtualizer.getVirtualItems().map((virtualItem) => {
<div className="flex items-start gap-4"> const schedule = filteredSchedules[virtualItem.index];
<div className="w-20 text-center flex-shrink-0"> if (!schedule) return null;
<div className="text-xs text-gray-400 mb-0.5">
{new Date(schedule.date).getFullYear()}.{new Date(schedule.date).getMonth() + 1} return (
</div> <div
<div className="text-2xl font-bold text-gray-900"> key={virtualItem.key}
{new Date(schedule.date).getDate()} style={{
</div> position: 'absolute',
<div className="text-sm text-gray-500"> top: 0,
{['일', '월', '화', '수', '목', '금', '토'][new Date(schedule.date).getDay()]}요일 left: 0,
</div> width: '100%',
</div> height: `${virtualItem.size}px`,
transform: `translateY(${virtualItem.start}px)`,
}}
>
<div className="p-4 hover:bg-gray-50 transition-colors group h-full border-b border-gray-100">
<div className="flex items-start gap-4">
<div className="w-16 text-center flex-shrink-0">
<div className="text-xs text-gray-400 mb-0.5">
{new Date(schedule.date).getFullYear()}.{new Date(schedule.date).getMonth() + 1}
</div>
<div className="text-xl font-bold text-gray-900">
{new Date(schedule.date).getDate()}
</div>
<div className="text-xs text-gray-500">
{['일', '월', '화', '수', '목', '금', '토'][new Date(schedule.date).getDay()]}요일
</div>
</div>
<div <div
className="w-1.5 rounded-full flex-shrink-0 self-stretch" className="w-1 rounded-full flex-shrink-0 self-stretch"
style={{ backgroundColor: getColorStyle(categories.find(c => c.id === schedule.category_id)?.color)?.style?.backgroundColor || '#6b7280' }} style={{ backgroundColor: getColorStyle(categories.find(c => c.id === schedule.category_id)?.color)?.style?.backgroundColor || '#6b7280' }}
/> />
<div className="flex-1 min-w-0"> <div className="flex-1 min-w-0">
<h3 className="font-semibold text-gray-900">{decodeHtmlEntities(schedule.title)}</h3> <h3 className="font-semibold text-gray-900 text-sm">{decodeHtmlEntities(schedule.title)}</h3>
<div className="flex items-center gap-3 mt-1 text-sm text-gray-500"> <div className="flex items-center gap-2 mt-1 text-xs text-gray-500">
{schedule.time && ( {schedule.time && (
<span className="flex items-center gap-1"> <span className="flex items-center gap-1">
<Clock size={14} /> <Clock size={12} />
{schedule.time.slice(0, 5)} {schedule.time.slice(0, 5)}
</span> </span>
)} )}
<span className="flex items-center gap-1"> <span className="flex items-center gap-1">
<Tag size={14} /> <Tag size={12} />
{categories.find(c => c.id === schedule.category_id)?.name || '미분류'} {categories.find(c => c.id === schedule.category_id)?.name || '미분류'}
</span>
{schedule.source_name && (
<span className="flex items-center gap-1">
<Link2 size={14} />
{schedule.source_name}
</span>
)}
</div>
{schedule.member_names && (
<div className="flex flex-wrap gap-1.5 mt-2">
{schedule.member_names.split(',').length >= 5 ? (
<span className="px-2 py-0.5 bg-primary/10 text-primary text-xs font-medium rounded-full">
프로미스나인
</span>
) : (
schedule.member_names.split(',').map((name, i) => (
<span key={i} className="px-2 py-0.5 bg-primary/10 text-primary text-xs font-medium rounded-full">
{name.trim()}
</span> </span>
)) {schedule.source_name && (
)} <span className="flex items-center gap-1">
</div> <Link2 size={12} />
)} {schedule.source_name}
</div> </span>
)}
</div>
{schedule.member_names && (
<div className="flex flex-wrap gap-1 mt-1">
{schedule.member_names.split(',').length >= 5 ? (
<span className="px-1.5 py-0.5 bg-primary/10 text-primary text-xs font-medium rounded-full">
프로미스나인
</span>
) : (
schedule.member_names.split(',').map((name, i) => (
<span key={i} className="px-1.5 py-0.5 bg-primary/10 text-primary text-xs font-medium rounded-full">
{name.trim()}
</span>
))
)}
</div>
)}
</div>
<div className="flex items-center gap-2 opacity-0 group-hover:opacity-100 transition-opacity"> <div className="flex items-center gap-1 opacity-0 group-hover:opacity-100 transition-opacity">
{schedule.source_url && ( {schedule.source_url && (
<a <a
href={schedule.source_url} href={schedule.source_url}
target="_blank" target="_blank"
rel="noopener noreferrer" rel="noopener noreferrer"
onClick={(e) => e.stopPropagation()} onClick={(e) => e.stopPropagation()}
className="p-2 hover:bg-blue-100 rounded-lg transition-colors text-blue-500" className="p-1.5 hover:bg-blue-100 rounded-lg transition-colors text-blue-500"
> >
<ExternalLink size={18} /> <ExternalLink size={16} />
</a> </a>
)} )}
<button <button
onClick={() => navigate(`/admin/schedule/${schedule.id}/edit`)} onClick={() => navigate(`/admin/schedule/${schedule.id}/edit`)}
className="p-2 hover:bg-gray-200 rounded-lg transition-colors text-gray-500" className="p-1.5 hover:bg-gray-200 rounded-lg transition-colors text-gray-500"
> >
<Edit2 size={18} /> <Edit2 size={16} />
</button> </button>
<button <button
onClick={() => openDeleteDialog(schedule)} onClick={() => openDeleteDialog(schedule)}
className="p-2 hover:bg-red-100 rounded-lg transition-colors text-red-500" className="p-1.5 hover:bg-red-100 rounded-lg transition-colors text-red-500"
> >
<Trash2 size={18} /> <Trash2 size={16} />
</button> </button>
</div>
</div>
</div>
</div> </div>
</div> );
</motion.div> })}
))} </div>
{/* 무한 스크롤 트리거 & 로딩 인디케이터 */} {/* 무한 스크롤 트리거 & 로딩 인디케이터 */}
<div ref={loadMoreRef} className="py-4"> <div ref={loadMoreRef} className="py-4">
@ -1186,9 +1215,9 @@ function AdminSchedule() {
<div className="w-6 h-6 border-2 border-primary border-t-transparent rounded-full animate-spin" /> <div className="w-6 h-6 border-2 border-primary border-t-transparent rounded-full animate-spin" />
</div> </div>
)} )}
{!hasNextPage && searchResults.length > 0 && ( {!hasNextPage && filteredSchedules.length > 0 && (
<div className="text-center text-sm text-gray-400"> <div className="text-center text-sm text-gray-400">
{searchResults.length} / {searchTotal} 표시 (모두 로드됨) {filteredSchedules.length} 표시 (모두 로드됨)
</div> </div>
)} )}
</div> </div>

View file

@ -3,6 +3,7 @@ import { useNavigate } from 'react-router-dom';
import { motion, AnimatePresence } from 'framer-motion'; import { motion, AnimatePresence } from 'framer-motion';
import { Clock, ChevronLeft, ChevronRight, ChevronDown, Tag, Search, ArrowLeft, Link2 } from 'lucide-react'; import { Clock, ChevronLeft, ChevronRight, ChevronDown, Tag, Search, ArrowLeft, Link2 } from 'lucide-react';
import { useInfiniteQuery } from '@tanstack/react-query'; import { useInfiniteQuery } from '@tanstack/react-query';
import { useVirtualizer } from '@tanstack/react-virtual';
import { useInView } from 'react-intersection-observer'; import { useInView } from 'react-intersection-observer';
import { getTodayKST } from '../../../utils/date'; import { getTodayKST } from '../../../utils/date';
import { getSchedules, getCategories, searchSchedules as searchSchedulesApi } from '../../../api/public/schedules'; import { getSchedules, getCategories, searchSchedules as searchSchedulesApi } from '../../../api/public/schedules';
@ -42,6 +43,7 @@ function Schedule() {
const [searchInput, setSearchInput] = useState(''); const [searchInput, setSearchInput] = useState('');
const [searchTerm, setSearchTerm] = useState(''); const [searchTerm, setSearchTerm] = useState('');
const SEARCH_LIMIT = 20; // 20 const SEARCH_LIMIT = 20; // 20
const ITEM_HEIGHT = 120; // (px)
// Intersection Observer for infinite scroll // Intersection Observer for infinite scroll
const { ref: loadMoreRef, inView } = useInView({ const { ref: loadMoreRef, inView } = useInView({
@ -83,6 +85,8 @@ function Schedule() {
const searchTotal = searchData?.pages?.[0]?.total || 0; const searchTotal = searchData?.pages?.[0]?.total || 0;
// Auto fetch next page when scrolled to bottom // Auto fetch next page when scrolled to bottom
useEffect(() => { useEffect(() => {
if (inView && hasNextPage && !isFetchingNextPage && isSearchMode && searchTerm) { if (inView && hasNextPage && !isFetchingNextPage && isSearchMode && searchTerm) {
@ -285,6 +289,14 @@ function Schedule() {
}); });
}, [schedules, selectedDate, currentYearMonth, selectedCategories, isSearchMode, searchTerm, searchResults]); }, [schedules, selectedDate, currentYearMonth, selectedCategories, isSearchMode, searchTerm, searchResults]);
// ( )
const virtualizer = useVirtualizer({
count: isSearchMode && searchTerm ? filteredSchedules.length : 0,
getScrollElement: () => scrollContainerRef.current,
estimateSize: () => ITEM_HEIGHT,
overscan: 5, //
});
// (useMemo ) - // (useMemo ) -
const categoryCounts = useMemo(() => { const categoryCounts = useMemo(() => {
const source = (isSearchMode && searchTerm) ? searchResults : schedules; const source = (isSearchMode && searchTerm) ? searchResults : schedules;
@ -820,84 +832,103 @@ function Schedule() {
<div className="text-center py-20 text-gray-500">로딩 ...</div> <div className="text-center py-20 text-gray-500">로딩 ...</div>
) : filteredSchedules.length > 0 ? ( ) : filteredSchedules.length > 0 ? (
isSearchMode && searchTerm ? ( isSearchMode && searchTerm ? (
/* 검색 모드: useInView 기반 무한 스크롤 */ /* 검색 모드: 가상 스크롤 */
<> <>
{filteredSchedules.map((schedule, index) => { <div
const formatted = formatDate(schedule.date); style={{
const categoryColor = getCategoryColor(schedule.category_id); height: `${virtualizer.getTotalSize()}px`,
const categoryName = getCategoryName(schedule.category_id); width: '100%',
position: 'relative',
return ( }}
<motion.div >
key={`${schedule.id}-search-${index}`} {virtualizer.getVirtualItems().map((virtualItem) => {
initial={{ opacity: 0 }} const schedule = filteredSchedules[virtualItem.index];
animate={{ opacity: 1 }} if (!schedule) return null;
transition={{ delay: Math.min(index, 10) * 0.03 }}
onClick={() => handleScheduleClick(schedule)} const formatted = formatDate(schedule.date);
className="flex items-stretch bg-white rounded-2xl shadow-sm hover:shadow-md transition-shadow overflow-hidden cursor-pointer" const categoryColor = getCategoryColor(schedule.category_id);
> const categoryName = getCategoryName(schedule.category_id);
{/* 날짜 영역 */}
<div return (
className="w-24 flex flex-col items-center justify-center text-white py-6" <div
style={{ backgroundColor: categoryColor }} key={virtualItem.key}
style={{
position: 'absolute',
top: 0,
left: 0,
width: '100%',
height: `${virtualItem.size}px`,
transform: `translateY(${virtualItem.start}px)`,
}}
> >
<span className="text-xs font-medium opacity-60"> <div
{new Date(schedule.date).getFullYear()}.{new Date(schedule.date).getMonth() + 1} onClick={() => handleScheduleClick(schedule)}
</span> className="flex items-stretch bg-white rounded-2xl shadow-sm hover:shadow-md transition-shadow overflow-hidden cursor-pointer h-full"
<span className="text-3xl font-bold">{formatted.day}</span> >
<span className="text-sm font-medium opacity-80">{formatted.weekday}</span> {/* 날짜 영역 */}
</div> <div
className="w-24 flex flex-col items-center justify-center text-white"
{/* 스케줄 내용 */} style={{ backgroundColor: categoryColor }}
<div className="flex-1 p-6 flex flex-col justify-center"> >
<h3 className="font-bold text-lg mb-2">{decodeHtmlEntities(schedule.title)}</h3> <span className="text-xs font-medium opacity-60">
{new Date(schedule.date).getFullYear()}.{new Date(schedule.date).getMonth() + 1}
<div className="flex flex-wrap gap-3 text-base text-gray-500">
{schedule.time && (
<span className="flex items-center gap-1">
<Clock size={16} className="opacity-60" />
{schedule.time.slice(0, 5)}
</span> </span>
)} <span className="text-3xl font-bold">{formatted.day}</span>
<span className="flex items-center gap-1"> <span className="text-sm font-medium opacity-80">{formatted.weekday}</span>
<Tag size={16} className="opacity-60" /> </div>
{categoryName}
</span>
{schedule.source_name && (
<span className="flex items-center gap-1">
<Link2 size={16} className="opacity-60" />
{schedule.source_name}
</span>
)}
</div>
{(() => { {/* 스케줄 내용 */}
const memberNames = schedule.member_names || schedule.members?.map(m => m.name).join(',') || ''; <div className="flex-1 p-4 flex flex-col justify-center">
const memberList = memberNames.split(',').filter(name => name.trim()); <h3 className="font-bold text-lg mb-1">{decodeHtmlEntities(schedule.title)}</h3>
if (memberList.length === 0) return null;
if (memberList.length === 5) { <div className="flex flex-wrap gap-3 text-base text-gray-500">
return ( {schedule.time && (
<div className="flex flex-wrap gap-1.5 mt-2"> <span className="flex items-center gap-1">
<span className="px-2 py-0.5 bg-primary/10 text-primary text-sm font-medium rounded-full"> <Clock size={16} className="opacity-60" />
프로미스나인 {schedule.time.slice(0, 5)}
</span> </span>
</div> )}
); <span className="flex items-center gap-1">
} <Tag size={16} className="opacity-60" />
return ( {categoryName}
<div className="flex flex-wrap gap-1.5 mt-2"> </span>
{memberList.map((name, i) => ( {schedule.source_name && (
<span key={i} className="px-2 py-0.5 bg-primary/10 text-primary text-sm font-medium rounded-full"> <span className="flex items-center gap-1">
{name} <Link2 size={16} className="opacity-60" />
{schedule.source_name}
</span> </span>
))} )}
</div> </div>
);
})()} {(() => {
const memberNames = schedule.member_names || schedule.members?.map(m => m.name).join(',') || '';
const memberList = memberNames.split(',').filter(name => name.trim());
if (memberList.length === 0) return null;
if (memberList.length === 5) {
return (
<div className="flex flex-wrap gap-1.5 mt-1">
<span className="px-2 py-0.5 bg-primary/10 text-primary text-sm font-medium rounded-full">
프로미스나인
</span>
</div>
);
}
return (
<div className="flex flex-wrap gap-1.5 mt-1">
{memberList.map((name, i) => (
<span key={i} className="px-2 py-0.5 bg-primary/10 text-primary text-sm font-medium rounded-full">
{name}
</span>
))}
</div>
);
})()}
</div>
</div>
</div> </div>
</motion.div> );
); })}
})} </div>
{/* 무한 스크롤 트리거 & 로딩 인디케이터 */} {/* 무한 스크롤 트리거 & 로딩 인디케이터 */}
<div ref={loadMoreRef} className="py-4"> <div ref={loadMoreRef} className="py-4">
@ -906,9 +937,9 @@ function Schedule() {
<div className="w-6 h-6 border-2 border-primary border-t-transparent rounded-full animate-spin" /> <div className="w-6 h-6 border-2 border-primary border-t-transparent rounded-full animate-spin" />
</div> </div>
)} )}
{!hasNextPage && searchResults.length > 0 && ( {!hasNextPage && filteredSchedules.length > 0 && (
<div className="text-center text-sm text-gray-400"> <div className="text-center text-sm text-gray-400">
{searchResults.length} / {searchTotal} 표시 (모두 로드됨) {filteredSchedules.length} 표시 (모두 로드됨)
</div> </div>
)} )}
</div> </div>