Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions app/api/posts/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ export async function GET(req: Request) {
// 기존 파라미터
const query = searchParams.get('query') || '';
const seriesSlug = searchParams.get('series') || '';
const tagParam = searchParams.get('tag') || '';
const isCompact = searchParams.get('compact') === 'true';
const isCanViewPrivate = searchParams.get('private') === 'true';

Expand Down Expand Up @@ -59,6 +60,13 @@ export async function GET(req: Request) {
} as QuerySelector<string>);
}

// 태그 필터
if (tagParam) {
(searchConditions.$and as QuerySelector<string>[]).push({
tags: tagParam,
} as QuerySelector<string>);
}

// 검색 조건을 만족하는 총 문서 수 계산
const totalPosts = await Post.countDocuments(searchConditions);

Expand Down
30 changes: 30 additions & 0 deletions app/api/tags/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
import dbConnect from '@/app/lib/dbConnect';
import Post from '@/app/models/Post';

// GET /api/tags
export async function GET() {
try {
await dbConnect();

const tagStats = await Post.aggregate([
{ $match: { isPrivate: { $ne: true } } },
{ $unwind: '$tags' },
{ $group: { _id: '$tags', count: { $sum: 1 } } },
{ $sort: { count: -1 } },
{ $project: { tag: '$_id', count: 1, _id: 0 } },
]);

return Response.json(tagStats, {
status: 200,
headers: {
'Cache-Control': 'public, max-age=300',
},
});
} catch (error) {
console.error('Tags API error:', error);
return Response.json(
{ success: false, error: '태그 목록 불러오기 실패', detail: error },
{ status: 500 }
);
}
}
3 changes: 3 additions & 0 deletions app/entities/common/Footer.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,9 @@ const Footer = () => {
<div>
<Link href={'/portfolio'}>Portfolio</Link>
</div>
<div>
<Link href={'/tags'}>Tags</Link>
</div>
<div>
<Link href={'/admin'}>Admin</Link>
</div>
Expand Down
11 changes: 9 additions & 2 deletions app/entities/post/list/SearchSection.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -15,13 +15,15 @@ interface SearchSectionProps {
setQuery: (query: string) => void;
resetSearchCondition: () => void;
searchSeries: string;
searchTag?: string;
}

const SearchSection = ({
query,
setQuery,
resetSearchCondition,
searchSeries,
searchTag,
}: SearchSectionProps) => {
const [searchOpen, setSearchOpen] = useState(false);
const [seriesOpen, setSeriesOpen] = useState(false);
Expand Down Expand Up @@ -76,7 +78,7 @@ const SearchSection = ({

{/* 검색 버튼 및 검색창 */}
<div className={'flex items-center'}>
{(query || searchSeries) && (
{(query || searchSeries || searchTag) && (
<div
className={
'bg-neutral-600 rounded-lg px-2 text-sm py-0.5 text-white'
Expand All @@ -87,12 +89,17 @@ const SearchSection = ({
<b>{searchSeries} </b> 시리즈에서{' '}
</span>
)}
{searchTag && (
<span>
<b>#{searchTag}</b> 태그로{' '}
</span>
)}
<span>
<b>{query ? query : '전체'}</b>로 검색 중...
</span>
</div>
)}
{(query || searchSeries) && (
{(query || searchSeries || searchTag) && (
<button
onClick={resetSearchCondition}
className="p-2 hover:bg-gray-100 hover:text-black rounded-full transition-colors"
Expand Down
256 changes: 256 additions & 0 deletions app/entities/tag/TagCloud.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,256 @@
'use client';

import { motion } from 'motion/react';
import Link from 'next/link';
import { useEffect, useMemo, useState } from 'react';
import { TagData, TagWithPosition } from '@/app/types/Tag';

interface TagCloudProps {
tags: TagData[];
}

interface Particle {
id: number;
x: number;
y: number;
z: number;
size: number;
speedX: number;
speedY: number;
speedZ: number;
opacity: number;
}

const TagCloud = ({ tags }: TagCloudProps) => {
const [hoveredTag, setHoveredTag] = useState<string | null>(null);
const [particles, setParticles] = useState<Particle[]>([]);

// 마법 가루 파티클 생성
useEffect(() => {
const particleCount = 120;
const radius = 250;

const newParticles: Particle[] = Array.from(
{ length: particleCount },
(_, i) => {
// 랜덤 구형 좌표
const theta = Math.random() * Math.PI * 2;
const phi = Math.acos(2 * Math.random() - 1);
const r = radius * (0.6 + Math.random() * 0.5);

return {
id: i,
x: r * Math.sin(phi) * Math.cos(theta),
y: r * Math.sin(phi) * Math.sin(theta),
z: r * Math.cos(phi),
size: 2 + Math.random() * 3,
speedX: (Math.random() - 0.5) * 0.5,
speedY: (Math.random() - 0.5) * 0.5,
speedZ: (Math.random() - 0.5) * 0.5,
opacity: 0.3 + Math.random() * 0.4,
};
}
);

setParticles(newParticles);

// 파티클 애니메이션
const interval = setInterval(() => {
setParticles((prev) =>
prev.map((p) => {
let newX = p.x + p.speedX;
let newY = p.y + p.speedY;
let newZ = p.z + p.speedZ;

// 경계 체크 및 반사
const maxRadius = radius * 1.1;
const distance = Math.sqrt(newX ** 2 + newY ** 2 + newZ ** 2);
if (distance > maxRadius) {
newX = p.x - p.speedX;
newY = p.y - p.speedY;
newZ = p.z - p.speedZ;
}

return {
...p,
x: newX,
y: newY,
z: newZ,
};
})
);
}, 50);

return () => clearInterval(interval);
}, []);

// Fibonacci Sphere 알고리즘으로 3D 구형 좌표 계산
const tagsWithPositions = useMemo(() => {
const total = tags.length;
const goldenRatio = (1 + Math.sqrt(5)) / 2;

return tags.map((tag, index) => {
const phi = Math.acos(1 - (2 * (index + 0.5)) / total);
const theta = 2 * Math.PI * index * goldenRatio;

// 반응형 반지름
const radius =
typeof window !== 'undefined'
? window.innerWidth < 768
? 150 // 모바일
: window.innerWidth < 1024
? 200 // 태블릿
: 250 // 데스크톱
: 250;

const x = radius * Math.sin(phi) * Math.cos(theta);
const y = radius * Math.sin(phi) * Math.sin(theta);
const z = radius * Math.cos(phi);

return {
...tag,
position: { x, y, z },
};
});
}, [tags]);

// Z축 기반 스타일 계산
const getTagStyle = (tagWithPos: TagWithPosition, isHovered: boolean) => {
const { position, count } = tagWithPos;
const { x, y, z } = position;

// z값 정규화 (-radius ~ radius → 0 ~ 1)
const radius = 250;
const normalized = (z + radius) / (radius * 2);

// 태그 빈도에 따른 기본 크기 조정 (추가)
const countFactor = Math.log(count + 1) / Math.log(tags[0].count + 1);
const baseSize = 0.7 + countFactor * 0.6; // 0.7 ~ 1.3

const scale = (0.5 + normalized * 1.5) * baseSize;
const opacity = 0.3 + normalized * 0.7;
const blur = (1 - normalized) * 2;
const fontSize = (12 + normalized * 24) * baseSize * 0.7;

return {
x,
y,
scale: isHovered ? scale * 1.3 : scale,
opacity,
filter: `blur(${blur}px)`,
fontSize: `${fontSize}px`,
zIndex: Math.round(normalized * 100),
};
};

// 주변 태그 밀어내기 효과 계산
const calculatePushEffect = (
targetPos: TagWithPosition,
hoveredPos: TagWithPosition
) => {
if (!hoveredTag || hoveredTag !== hoveredPos.tag) {
return { x: 0, y: 0 };
}

const dx = targetPos.position.x - hoveredPos.position.x;
const dy = targetPos.position.y - hoveredPos.position.y;
const distance = Math.sqrt(dx * dx + dy * dy);

const threshold = 100;
if (distance > threshold || distance === 0) return { x: 0, y: 0 };

const force = (1 - distance / threshold) * 30;
const angle = Math.atan2(dy, dx);

return {
x: Math.cos(angle) * force,
y: Math.sin(angle) * force,
};
};

const hoveredTagData = tagsWithPositions.find((t) => t.tag === hoveredTag);

return (
<div className="relative w-full h-[600px] flex items-center justify-center overflow-hidden">
{/* 마법 가루 파티클 */}
{particles.map((particle) => {
const radius = 250;
const normalized = (particle.z + radius) / (radius * 2);
const particleScale = 0.3 + normalized * 0.7;
const particleOpacity = particle.opacity * normalized;

return (
<motion.div
key={`particle-${particle.id}`}
className="absolute rounded-full pointer-events-none"
style={{
width: `${particle.size}px`,
height: `${particle.size}px`,
background: `radial-gradient(circle, rgba(0, 223, 129, ${particleOpacity}), rgba(44, 194, 149, 0))`,
boxShadow: `0 0 ${particle.size * 2}px rgba(0, 223, 129, ${particleOpacity * 0.5})`,
zIndex: Math.round(normalized * 50),
}}
animate={{
x: particle.x,
y: particle.y,
scale: particleScale,
opacity: particleOpacity,
}}
transition={{
duration: 0.05,
ease: 'linear',
}}
/>
);
})}

{/* 태그들 */}
{tagsWithPositions.map((tagWithPos) => {
const style = getTagStyle(tagWithPos, hoveredTag === tagWithPos.tag);
const pushEffect = hoveredTagData
? calculatePushEffect(tagWithPos, hoveredTagData)
: { x: 0, y: 0 };

return (
<motion.div
key={tagWithPos.tag}
className="absolute"
initial={{ opacity: 0, scale: 0 }}
animate={{
x: style.x + pushEffect.x,
y: style.y + pushEffect.y,
scale: style.scale,
opacity: style.opacity,
}}
transition={{
type: 'spring',
stiffness: 150,
damping: 20,
opacity: { duration: 0.5 },
}}
style={{
filter: style.filter,
fontSize: style.fontSize,
zIndex: style.zIndex,
}}
onHoverStart={() => setHoveredTag(tagWithPos.tag)}
onHoverEnd={() => setHoveredTag(null)}
>
<Link
href={`/posts?page=1&tag=${encodeURIComponent(tagWithPos.tag)}`}
className="font-bold text-primary-bangladesh hover:text-primary-mountain
dark:text-primary-caribbean dark:hover:text-primary-mountain
transition-colors duration-300 cursor-pointer
whitespace-nowrap select-none"
aria-label={`${tagWithPos.tag} 태그 (${tagWithPos.count}개 글)`}
>
#{tagWithPos.tag}
</Link>
</motion.div>
);
})}
</div>
);
};

export default TagCloud;
Loading