1280px
설치
이 명령 한 줄이면 필요한 파일과 패키지가 함께 설치돼요.
터미널터미널터미널bash
npx shadcn@latest add https://dsui.vercel.app/r/blog-grid.json파일
components/arc/blocks/blog-grid/blog-grid-data.tscomponents/arc/blocks/blog-grid/blog-grid.module.csscomponents/arc/blocks/blog-grid/blog-grid.tsx
npm 패키지
@hugeicons/core-free-icons@^4.3.5@hugeicons/react@^1.1.10motion@^14.2.0
- v1.0.0처음 공개했어요.
blog-grid-data.tsblog-grid-data.tsblog-grid-data.tsts
/** Sample posts for the blog grid. Photos and portraits live in public/media (credits in public/media/CREDITS.md). */
export type BlogAuthor = { name: string; avatar?: string; role?: string };
export type BlogPost = {
id: string;
title: string;
excerpt: string;
category: string;
/** ISO date, used for sorting and the visible date. */
date: string;
/** Minutes to read. */
readTime: number;
author: BlogAuthor;
image?: { src: string; alt: string };
/** Paragraphs for the in-place reader. Leave out when every post links out through getHref. */
body?: string[];
featured?: boolean;
/** Draws the "new" badge on the cover. The caller decides (the page knows the clock, the block does not). */
isNew?: boolean;
/** Draws the "breaking" badge beside the "new" one (breaking news). */
isBreaking?: boolean;
/**
* Counts drawn as a quiet line under the byline ("댓글 3 · 좋아요 5", texts from `labels.comments` and `labels.likes`). Only the
* counts given are drawn, 0 included; leave the field out and the card is exactly as before. The block does not fetch them.
* `reactionIcons` are image addresses of the reactions that lead (most first, a few): when given with `likes` they are drawn small
* beside that count (and in place of its heart on the cover chip), so the count reads as "reactions" rather than "likes".
*/
stats?: { comments?: number; likes?: number; reactionIcons?: readonly string[] };
};
const emma: BlogAuthor = { name: "이하은", role: "프로덕트 디자이너", avatar: "/media/people/emma-collins.jpg" };
const marcus: BlogAuthor = { name: "박도현", role: "프런트엔드 개발자", avatar: "/media/people/marcus-johnson.jpg" };
const jasmine: BlogAuthor = { name: "김서연", role: "디자인 리드", avatar: "/media/people/jasmine-brooks.jpg" };
const daniel: BlogAuthor = { name: "김민준", role: "백엔드 개발자", avatar: "/media/people/daniel-kim.jpg" };
const sofia: BlogAuthor = { name: "정수아", role: "운영 리드", avatar: "/media/people/sofia-ramirez.jpg" };
const chloe: BlogAuthor = { name: "최지우", role: "데이터 분석가", avatar: "/media/people/chloe-nguyen.jpg" };
const nathan: BlogAuthor = { name: "한지훈", role: "개발 매니저", avatar: "/media/people/nathan-cole.jpg" };
export const blogCategories = ["제품", "디자인", "개발", "회사"];
export const blogPosts: BlogPost[] = [
{
id: "quiet-software", featured: true, category: "디자인", date: "2026-09-18", readTime: 7, author: jasmine,
title: "조용한 소프트웨어를 만들어야 하는 이유",
excerpt: "화면에서 색을 절반으로 줄였더니, 사람들이 일을 더 빨리 끝내기 시작했어요.",
image: { src: "/media/photos/living-room.jpg", alt: "나무 들보와 아치형 창, 크림색 소파가 있는 밝은 거실" },
body: [
"지난봄에 실험을 하나 했어요. 제품에서 가장 복잡한 화면을 골라, 의미를 담지 않은 색을 모두 걷어 냈어요. 상태 색은 남기고, 선택 색도 남기고, 나머지는 모두 무채색으로 바꿨어요.",
"요청한 사람은 없었고, 바뀐 걸 바로 알아챈 사람도 거의 없었어요. 다만 화면이 한결 편해졌다고 느꼈어요. 첫 달에 작업 완료율이 11% 올랐어요.",
"조용하다는 건 비어 있다는 뜻이 아니에요. 모든 요소에 맡은 일이 있고, 눈에 띄는 순간은 주목이 필요한 곳에만 아껴 둔다는 뜻이에요.",
],
},
{
id: "offline-sync", category: "개발", date: "2026-09-12", readTime: 9, author: daniel,
title: "오프라인 동기화는 실제로 어떻게 동작할까",
excerpt: "충돌 없는 복제 데이터를, 출시까지 마주친 버그와 함께 풀어 봤어요.",
image: { src: "/media/photos/curved-facade.jpg", alt: "곡선형 발코니가 있는 흰 타일 건물 외벽" },
body: ["모든 편집은 먼저 기기에 저장되고, 연결이 되면 서버로 보내져요. 어려운 부분은 떨어져 있던 두 사람이 같은 내용을 고쳤을 때 생겨요.", "글에는 시퀀스 CRDT를, 단순한 항목에는 마지막에 쓴 값이 이기는 방식을 써요. 조심스럽게 다룬 예외도 몇 가지 있어요."],
},
{
id: "lisbon-offsite", category: "회사", date: "2026-09-04", readTime: 4, author: sofia,
title: "리스본에서 일주일을 보내며 배운 것",
excerpt: "마흔 명, 하나의 로드맵, 슬라이드는 금지. 가을 워크숍 기록이에요.",
image: { src: "/media/photos/lisbon-rooftops.jpg", alt: "강까지 이어지는 리스본의 테라코타 지붕" },
body: ["일주일 동안 슬라이드를 쓰지 않았어요. 모든 세션은 글로 쓴 메모와 10분간의 조용한 읽기로 시작했어요.", "지금까지 한 워크숍 중 가장 알찼고, 그때 정한 로드맵은 이전 어느 때보다 잘 버티고 있어요."],
},
{
id: "shared-views", category: "제품", date: "2026-08-28", readTime: 3, author: emma,
title: "공유 보기가 나왔어요",
excerpt: "필터를 저장하고 이름을 붙여 팀과 나눠 보세요. 모두가 같은 화면을, 늘 최신으로 볼 수 있어요.",
image: { src: "/media/photos/home-office.jpg", alt: "나무 책상과 짙은 초록색 벽이 있는 서재" },
body: ["저장된 필터는 올해 가장 많이 요청받은 기능이었어요. 이제 공유 보기가 됐어요. 보기에 이름을 붙이고 볼 사람을 고르면, 데이터가 바뀔 때마다 함께 갱신돼요."],
},
{
id: "type-scale", category: "디자인", date: "2026-08-21", readTime: 6, author: jasmine,
title: "후회하지 않을 글자 크기 체계 고르기",
excerpt: "크기 일곱 개, 굵기 두 개, 그리고 제품이 커져도 이를 지키는 규칙이에요.",
image: { src: "/media/photos/concert-hall.jpg", alt: "파란 하늘 아래 곡선형 스테인리스 패널로 덮인 콘서트홀" },
body: ["글자 크기 체계는 약속이에요. 크기를 하나 더할 때마다 다음 결정이 어려워져요.", "크기 일곱 개와 굵기 두 개로 정하고, 각각 언제 쓸 수 있는지 적어 뒀어요."],
},
{
id: "query-planner", category: "개발", date: "2026-08-14", readTime: 11, author: marcus,
title: "검색을 열 배 빠르게 만들기",
excerpt: "새 쿼리 플래너, 더 똑똑한 인덱스, 그리고 도중에 발견한 부끄러운 N+1 문제 하나예요.",
image: { src: "/media/photos/mountain-ridges.jpg", alt: "따뜻한 저녁 하늘 아래 겹겹이 이어진 산등성이" },
body: ["검색은 예전에 상위 5% 기준으로 400밀리초쯤 걸렸어요. 지금은 38밀리초예요.", "개선의 대부분은 플래너에서 나왔어요. 나머지는 애초에 쓰지 말았어야 할 코드를 지워서 얻었어요."],
},
{
id: "remote-rituals", category: "회사", date: "2026-08-06", readTime: 5, author: nathan,
title: "원격 팀을 가깝게 해 주는 습관",
excerpt: "글로 쓰는 스탠드업, 금요일 데모, 그리고 절대 취소하지 않는 회의 하나예요.",
image: { src: "/media/photos/sunroom.jpg", alt: "둥근 식탁과 화분, 세 면이 창으로 둘러싸인 선룸" },
body: ["우리는 아홉 개 시간대에 걸쳐 일해요. 오래 살아남는 습관은 그 사실을 존중하는 습관이에요."],
},
{
id: "usage-insights", category: "제품", date: "2026-07-30", readTime: 4, author: chloe,
title: "모든 워크스페이스를 위한 사용 현황",
excerpt: "팀이 어떤 기능을 자주 쓰는지, 어디서 막히는지, 이번 주에 무엇이 바뀌었는지 볼 수 있어요.",
image: { src: "/media/photos/alpine-lake.jpg", alt: "해 질 녘 바위 봉우리가 비치는 고요한 고산 호수" },
body: ["이제 관리자는 워크스페이스 설정에서 사용 현황을 열 수 있어요. 기능별 사용률과 시간에 따른 추세, 이메일로 받는 주간 요약을 볼 수 있어요."],
},
{
id: "motion-rules", category: "디자인", date: "2026-07-22", readTime: 8, author: emma,
title: "움직임은 꾸미지 말고 설명해야 해요",
excerpt: "애니메이션 규칙은 이래요. 모든 움직임은 무언가가 어디서 왔고 어디로 갔는지 알려 줘야 해요.",
image: { src: "/media/photos/terracotta-waves.jpg", alt: "파란 하늘로 솟은 물결무늬 테라코타 벽" },
body: ["애니메이션이 무엇을 설명하는지 말할 수 없다면 없애요. 이 규칙 하나로 움직임 코드의 3분의 1이 사라졌어요."],
},
{
id: "postgres-upgrade", category: "개발", date: "2026-07-15", readTime: 10, author: daniel,
title: "중단 없이 Postgres 업그레이드하기",
excerpt: "논리 복제, 운영 환경 사본으로 한 예행연습, 그리고 4초 만에 끝난 전환이에요.",
image: { src: "/media/photos/coastline.jpg", alt: "초록 절벽 아래 해변으로 파도가 밀려오는 긴 해안선" },
body: ["고객이 계속 일하는 동안 2테라바이트를 새 메이저 버전으로 옮겼어요. 그 실행 절차를 공유해요."],
},
{
id: "series-b", category: "회사", date: "2026-07-08", readTime: 3, author: sofia,
title: "우리의 다음 장",
excerpt: "팀을 위한 가장 차분한 도구를 만들려고 시리즈 B 투자를 받았어요. 무엇이 바뀌고 무엇이 그대로인지 알려 드려요.",
image: { src: "/media/photos/sea-at-dusk.jpg", alt: "수평선에 낮은 섬이 보이는 해 질 녘의 고요한 바다" },
body: ["제품 가격은 그대로예요. 팀은 두 배로 늘어요. 로드맵은 더 빨라져요."],
},
{
id: "keyboard-first", category: "제품", date: "2026-06-30", readTime: 5, author: marcus,
title: "모든 기능에 키보드 단축키를",
excerpt: "어디서든 물음표를 누르면 모든 단축키를 볼 수 있고, 직접 바꿀 수도 있어요.",
image: { src: "/media/photos/reading-chair.jpg", alt: "짙은 초록색 방의 회색 안락의자와 발받침, 니트 담요" },
body: ["이제 제품의 모든 동작에 단축키가 있고, 설정에서 원하는 대로 바꿀 수 있어요."],
},
{
id: "color-tokens", category: "디자인", date: "2026-06-24", readTime: 6, author: jasmine,
title: "색 토큰은 색상이 아니라 역할로 이름 붙여요",
excerpt: "surface와 border가 gray-100, gray-200보다 나은 이유와, 파일 400개를 옮긴 과정이에요.",
image: { src: "/media/photos/pool-house.jpg", alt: "맑은 하늘 아래 긴 수영장 옆에 선 현대식 유리 집" },
body: ["의미 기반 토큰 덕분에 다크 모드, 고대비, 브랜드 테마가 하나의 컴포넌트 코드를 함께 써요."],
},
];
blog-grid.module.cssblog-grid.module.cssblog-grid.module.csscss
.root { width: 100%; min-width: 0; container: blog / inline-size; background: var(--background); color: var(--foreground); font-family: var(--font-body); letter-spacing: var(--tracking-body); }
/* --blog-grid-max and --blog-grid-gutter let a page line the grid up with its own measure; unset, the block is as before. */
.inner { position: relative; max-width: var(--blog-grid-max, 1180px); margin: 0 auto; padding: var(--space-16) var(--blog-grid-gutter, var(--space-6)); }
.index { display: grid; gap: var(--space-8); }
.header { display: grid; gap: var(--space-3); max-width: 600px; }
.title { margin: 0; font-family: var(--font-display); font-size: clamp(1.75rem, 1rem + 3cqi, var(--text-4xl)); font-weight: 500; letter-spacing: var(--tracking-display); line-height: var(--leading-display); }
.description { margin: 0; color: var(--text-secondary); font-size: var(--text-base); line-height: var(--leading-body); text-wrap: pretty; }
.filters { display: flex; gap: 2px; margin: 0 calc(var(--blog-grid-gutter, var(--space-6)) * -1); overflow-x: auto; padding: 0 var(--blog-grid-gutter, var(--space-6)); scrollbar-width: none; }
.filters::-webkit-scrollbar { display: none; }
.filter { position: relative; isolation: isolate; flex: none; height: 36px; border: 0; border-radius: var(--radius-pill); padding: 0 var(--space-4); background: none; color: var(--text-secondary); font: inherit; font-size: var(--text-sm); font-weight: 500; white-space: nowrap; cursor: pointer; -webkit-tap-highlight-color: transparent; transition: color var(--duration-fast) var(--ease-standard), scale var(--duration-spring) var(--ease-spring); }
.filter[aria-pressed="true"], .filter[aria-current="true"] { color: var(--background); }
@media (hover: hover) and (pointer: fine) { .filter[aria-pressed="false"]:hover, a.filter:not([aria-current]):hover { color: var(--foreground); } }
/* With getCategoryHref and getPageHref the tabs and page controls are links; they look and behave like the buttons. */
a.filter, a.pageNumber, a.pageStep { text-decoration: none; }
a.filter { display: inline-flex; align-items: center; }
.filterHighlight { position: absolute; z-index: -1; inset: 0; border-radius: inherit; background: var(--foreground); }
/* Page and pagination share one measured box, so a shorter filter or page closes its gap on a spring. It only clips while it moves. */
.clip { min-width: 0; }
.clip[data-clip] { overflow: hidden; }
/* One column that cannot grow past the box: an auto column takes the featured card's content width where a browser (Safari) counts it as wider than the screen. */
.stack { display: grid; grid-template-columns: minmax(0, 1fr); gap: var(--space-8); }
.page { display: grid; grid-template-columns: minmax(0, 1fr); gap: var(--space-12); }
.grid { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: var(--space-12) var(--space-6); }
.card, .featured { display: grid; align-content: start; gap: var(--space-4); border-radius: 22px; color: inherit; text-decoration: none; -webkit-tap-highlight-color: transparent; }
.featured { grid-template-columns: minmax(0, 1.35fr) minmax(0, 1fr); align-items: center; gap: var(--space-10); min-width: 0; }
.imageFrame { position: relative; overflow: hidden; aspect-ratio: 3 / 2; border-radius: 20px; background: var(--surface-muted); }
.featured .imageFrame { aspect-ratio: 16 / 10; border-radius: 26px; }
.image { display: block; width: 100%; height: 100%; object-fit: cover; transition: transform var(--duration-considered) var(--ease-standard); }
/* renderCover's slot. Its child is stretched to the frame; an svg covers it with preserveAspectRatio="xMidYMid slice". */
.cover { position: absolute; inset: 0; overflow: hidden; transition: transform var(--duration-considered) var(--ease-standard); }
.badges { position: absolute; top: var(--space-3); left: var(--space-3); z-index: 1; display: flex; gap: var(--space-1); pointer-events: none; }
.newBadge, .breakingBadge { border-radius: var(--radius-pill); padding: 2px 10px; background: var(--accent); color: var(--accent-foreground); box-shadow: var(--shadow-accent-resting); font-size: var(--text-xs); font-weight: 500; line-height: 1.6; }
.breakingBadge { background: var(--danger); color: var(--danger-foreground); box-shadow: var(--shadow-danger-resting); }
/* statsOnCover: counts as chips at the cover's bottom left. They sit on the surface with a hairline, so they read on any cover colour. */
.coverStats { position: absolute; left: var(--space-3); bottom: var(--space-3); z-index: 1; display: flex; gap: var(--space-1); pointer-events: none; }
.coverChip { display: inline-flex; align-items: center; gap: 4px; padding: 2px 10px; border: 1px solid var(--border); border-radius: var(--radius-pill); background: var(--surface); color: var(--foreground); font-size: var(--text-xs); font-weight: 500; line-height: 1.6; font-variant-numeric: tabular-nums; box-shadow: var(--shadow-resting); }
.coverChip[data-kind="likes"] { color: var(--danger); }
.coverChip[data-icons] { color: var(--foreground); padding-left: 6px; }
/* A count of 0 stays on the card, quieter: no colour, no shadow. */
.coverChip[data-zero] { color: var(--text-muted); box-shadow: none; font-weight: 400; }
/* The leading reactions, overlapping a little, the first on top. */
.reactionStack { display: inline-flex; align-items: center; vertical-align: -3px; margin-right: 2px; }
.reactionIcon { display: block; width: 14px; height: 14px; }
.reactionIcon + .reactionIcon { margin-left: -4px; }
.cover > * { display: block; width: 100%; height: 100%; max-width: none; object-fit: cover; }
.cardBody { display: grid; align-content: start; gap: var(--space-2); }
.featured .cardBody { gap: var(--space-3); }
.meta { display: flex; flex-wrap: wrap; gap: 6px; margin: 0; color: var(--text-muted); font-size: var(--text-xs); }
.meta span:first-child { color: var(--foreground); font-weight: 500; }
.cardTitle { margin: 0; font-size: var(--text-lg); font-weight: 500; line-height: 1.3; text-wrap: balance; transition: color var(--duration-fast) var(--ease-standard); }
.featuredTitle { margin: 0; font-family: var(--font-display); font-size: clamp(var(--text-2xl), 1rem + 2.2cqi, var(--text-3xl)); font-weight: 500; letter-spacing: var(--tracking-display); line-height: var(--leading-display); text-wrap: balance; }
.excerpt { display: -webkit-box; margin: 0; overflow: hidden; color: var(--text-secondary); font-size: var(--text-sm); line-height: 1.5; text-wrap: pretty; -webkit-box-orient: vertical; -webkit-line-clamp: 2; }
.featured .excerpt { font-size: var(--text-base); -webkit-line-clamp: 3; }
.byline { display: flex; min-width: 0; align-items: center; gap: var(--space-2); margin-top: var(--space-2); font-size: var(--text-sm); }
.avatar { width: 24px; height: 24px; flex: none; border-radius: 50%; background: var(--surface-muted); object-fit: cover; }
.authorName { min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.readTime { flex: none; color: var(--text-muted); }
.readTime::before { content: "·"; margin-right: var(--space-2); }
/* post.stats: a quiet line of counts under the byline. It wraps between counts on a narrow card, never inside one. */
.stats { margin: 0; color: var(--text-muted); font-size: var(--text-xs); font-variant-numeric: tabular-nums; }
.stats { display: flex; flex-wrap: wrap; align-items: center; gap: var(--space-3); }
.statItem { display: inline-flex; align-items: center; gap: 4px; white-space: nowrap; transition: color var(--duration-fast) var(--ease-standard); }
/* A post that has comments: the comment icon and its count take the accent (the active state); with none it stays quiet. */
.statItem[data-kind="comments"][data-active] { color: var(--accent-strong, var(--accent)); }
.statItem[data-kind="comments"]:not([data-active]) { opacity: .6; }
/* Text for assistive tech only: the ", " between the counts (the visible dot is aria-hidden). */
.srOnly { position: absolute; width: 1px; height: 1px; overflow: hidden; clip-path: inset(50%); white-space: nowrap; }
.card:active .imageFrame, .featured:active .imageFrame { transform: scale(.99); }
.imageFrame { transition: transform var(--duration-fast) var(--ease-standard); }
@media (hover: hover) and (pointer: fine) {
.card:hover .image, .featured:hover .image, .card:hover .cover, .featured:hover .cover { transform: scale(1.03); }
.card:hover .cardTitle { color: var(--text-secondary); }
}
.empty { margin: 0; padding: var(--space-16) 0; color: var(--text-secondary); text-align: center; }
.pagination { position: relative; display: flex; align-items: center; justify-content: space-between; gap: var(--space-3); padding-top: var(--space-6); }
.pagination::before { content: ""; position: absolute; top: 0; right: 0; left: 0; height: 1px; background: var(--border); }
.pageNumbers { display: flex; min-width: 0; gap: 2px; }
.pageNumber, .pageStep { position: relative; isolation: isolate; display: inline-flex; height: 36px; min-width: 36px; align-items: center; justify-content: center; gap: 6px; border: 0; border-radius: var(--radius-pill); padding: 0 var(--space-3); background: none; color: var(--text-secondary); font: inherit; font-size: var(--text-sm); font-weight: 500; font-variant-numeric: tabular-nums; cursor: pointer; -webkit-tap-highlight-color: transparent; transition: color var(--duration-fast) var(--ease-standard), transform var(--duration-instant) var(--ease-standard); }
.pageNumber { padding: 0; }
.pageGap { display: inline-flex; height: 36px; min-width: 20px; align-items: center; justify-content: center; color: var(--text-muted); font-size: var(--text-sm); }
.pageNumber[aria-current="page"] { color: var(--foreground); }
.pageHighlight { position: absolute; z-index: -1; inset: 0; border-radius: inherit; background: var(--surface-muted); }
.pageStep:disabled, .pageStep[aria-disabled="true"] { color: var(--text-muted); opacity: .5; cursor: default; }
.pageStep:not(:disabled):not([aria-disabled="true"]):active { transform: scale(.97); }
@media (hover: hover) and (pointer: fine) { .pageNumber:hover, .pageStep:not(:disabled):not([aria-disabled="true"]):hover { color: var(--foreground); } }
.reader { display: grid; max-width: 760px; gap: var(--space-8); margin: 0 auto; }
.back { display: inline-flex; width: fit-content; height: 36px; align-items: center; gap: 6px; border: 0; border-radius: var(--radius-pill); padding: 0 var(--space-3) 0 var(--space-2); margin-left: calc(var(--space-2) * -1); background: none; color: var(--text-secondary); font: inherit; font-size: var(--text-sm); font-weight: 500; cursor: pointer; transition: color var(--duration-fast) var(--ease-standard), background-color var(--duration-fast) var(--ease-standard); }
@media (hover: hover) and (pointer: fine) { .back:hover { background: var(--surface-muted); color: var(--foreground); } }
.readerHead { display: grid; gap: var(--space-3); }
.readerTitle { margin: 0; font-family: var(--font-display); font-size: clamp(var(--text-2xl), 1rem + 3.4cqi, var(--text-4xl)); font-weight: 500; letter-spacing: var(--tracking-display); line-height: var(--leading-display); text-wrap: balance; }
.readerImage { overflow: hidden; aspect-ratio: 16 / 9; border-radius: 26px; background: var(--surface-muted); }
.readerBody { display: grid; gap: var(--space-5); }
.readerBody p { margin: 0; color: var(--text-secondary); font-size: var(--text-lg); line-height: 1.65; text-wrap: pretty; }
.readerBody .lead { color: var(--foreground); font-size: var(--text-xl); line-height: 1.5; }
@container blog (max-width: 900px) {
.grid { grid-template-columns: repeat(2, minmax(0, 1fr)); }
.featured { gap: var(--space-6); }
}
@container blog (max-width: 680px) {
.inner { padding: var(--space-12) var(--blog-grid-gutter, var(--space-4)); }
.filters { margin: 0 calc(var(--blog-grid-gutter, var(--space-4)) * -1); padding: 0 var(--blog-grid-gutter, var(--space-4)); }
.featured { grid-template-columns: minmax(0, 1fr); gap: var(--space-4); }
.featured .imageFrame { aspect-ratio: 3 / 2; border-radius: 20px; }
.page { gap: var(--space-10); }
.grid { gap: var(--space-10) var(--space-4); }
.readerBody p { font-size: var(--text-base); }
.readerBody .lead { font-size: var(--text-lg); }
}
@container blog (max-width: 540px) {
.grid { grid-template-columns: minmax(0, 1fr); }
.pageStep span { display: none; }
.pageStep { padding: 0; }
}
@media (prefers-reduced-motion: reduce) {
.image, .imageFrame, .cover { transition: none; }
.card:hover .image, .featured:hover .image, .card:hover .cover, .featured:hover .cover { transform: none; }
}
/* Studio feel: a visible hover (swell, soft fill) and a deeper press. */
@media (hover: hover) and (pointer: fine) {
.filter:hover:not(:disabled):not([aria-disabled="true"]) { scale: 1.04; }
.filter:hover:not(:disabled):not([aria-disabled="true"]):not([aria-pressed="true"]):not([aria-selected="true"]):not([aria-current]):not([data-selected]):not([data-active]) { background: var(--control-track-hover); }
}
.filter:active:not(:disabled):not([aria-disabled="true"]) { scale: .94; }
@media (prefers-reduced-motion: reduce) { .filter:hover, .filter:active { scale: none; } }
blog-grid.test.tsblog-grid.test.tsblog-grid.test.tsts
import { readFileSync } from "node:fs";
import { createElement } from "react";
import { renderToStaticMarkup } from "react-dom/server";
import { describe, expect, it } from "vitest";
import { BlogGrid, DEFAULT_BLOG_GRID_LABELS, pageWindow, shouldInterceptClick, slideDirection } from "./blog-grid";
import type { BlogGridProps, BlogPost } from "./blog-grid";
import { blogPosts } from "./blog-grid-data";
const render = (props: BlogGridProps = {}) => renderToStaticMarkup(createElement(BlogGrid, props));
const englishLabels: BlogGridProps["labels"] = {
all: "All",
filterGroup: "Filter by category",
pagination: "Pages",
previous: "Previous",
next: "Next",
previousAria: "Previous page",
nextAria: "Next page",
pageAria: n => `Page ${n}`,
backToAll: "All posts",
readTime: m => `${m} min read`,
empty: category => `No posts in ${category} yet.`,
};
const koreanOnly = ["전체", "읽는 데", "카테고리별로", "페이지 이동", "이전", "다음", "모든 글 보기", "카테고리에는"];
describe("BlogGrid server render", () => {
it("renders the Korean defaults exactly as before", () => {
const html = render();
expect(html).toContain("전체");
expect(html).toContain('aria-label="카테고리별로 거르기"');
expect(html).toContain("읽는 데 7분");
expect(html).toContain("2026년 9월 18일");
expect(html).toContain('aria-label="페이지 이동"');
expect(html).toContain('aria-label="이전 페이지"');
expect(html).toContain('aria-label="2페이지"');
expect(html).toMatch(/<h2[^>]*>저널<\/h2>/);
});
it("pins the default output: no new prop, no change (snapshot taken equal to the block before the link and cover props)", () => {
// Checked once against the pre-link version of this file (git a63e285~1): byte-identical for these props. Any change to the
// default markup must be deliberate and update this snapshot.
expect(render()).toMatchSnapshot("default");
expect(render({ pageSize: 2 })).toMatchSnapshot("default with pages");
expect(render({ page: 2, pageSize: 2 })).toMatchSnapshot("controlled page 2");
});
it("renders the Korean pagination exactly as before on several pages", () => {
const html = render({ pageSize: 2 });
expect(html).toContain('<nav class="');
expect(html).toContain('aria-label="페이지 이동"');
expect(html).toContain('aria-label="이전 페이지"');
expect(html).toContain('aria-label="다음 페이지"');
expect(html).toContain('aria-label="1페이지"');
expect(html).toContain('aria-label="3페이지"');
expect(html).toContain("<span>이전</span>");
expect(html).toContain("<span>다음</span>");
});
it("switches language and date format with locale and labels", () => {
const html = render({ locale: "en-US", labels: englishLabels });
expect(html).toContain("All");
expect(html).toContain("7 min read");
expect(html).toContain("Sep 18, 2026");
expect(html).toContain('aria-label="Filter by category"');
for (const text of koreanOnly) expect(html).not.toContain(text);
});
it("uses the English labels on every pagination control, with several pages", () => {
const html = render({ locale: "en-US", labels: englishLabels, pageSize: 2 });
expect(html).toContain('<nav class="');
expect(html).toContain('aria-label="Pages"');
expect(html).toContain('aria-label="Previous page"');
expect(html).toContain('aria-label="Next page"');
expect(html).toContain('aria-label="Page 1"');
expect(html).toContain('aria-label="Page 3"');
expect(html).toContain("<span>Previous</span>");
expect(html).toContain("<span>Next</span>");
for (const text of koreanOnly) expect(html).not.toContain(text);
expect(html).not.toMatch(/\d페이지/);
});
it("drops the header but keeps the section label with hideHeader", () => {
const html = render({ hideHeader: true });
expect(html).not.toContain("<h2");
expect(html).not.toContain("<header");
expect(html).toContain('aria-label="저널"');
});
it("drops every filter button with hideFilters", () => {
expect(render()).toContain("aria-pressed");
const html = render({ hideFilters: true });
expect(html).not.toContain("aria-pressed");
expect(html).not.toContain("카테고리별로 거르기");
});
it("shows the empty text from labels when there are no posts", () => {
expect(render({ posts: [] })).toContain(DEFAULT_BLOG_GRID_LABELS.empty("전체"));
expect(render({ posts: [], labels: englishLabels })).toContain("No posts in All yet.");
});
it("keeps the other defaults when labels are partial", () => {
const html = render({ labels: { all: "All" } });
expect(html).toContain("<span>All</span>");
expect(html).not.toContain("<span>전체</span>");
expect(html).toContain('aria-label="카테고리별로 거르기"');
expect(html).toContain("읽는 데");
});
});
const navOf = (html: string) => html.slice(html.indexOf("<nav"), html.indexOf("</nav>"));
const filtersOf = (html: string) => {
const start = html.indexOf('role="group"');
return html.slice(start, html.indexOf("</div>", start));
};
const pageHref = (n: number) => `/blog?page=${n}`;
const categoryHref = (c: string) => (c === "전체" ? "/blog" : `/blog?category=${encodeURIComponent(c)}`);
describe("BlogGrid page links", () => {
it("renders every page number as a link with its href, and the current page as aria-current", () => {
const nav = navOf(render({ pageSize: 2, getPageHref: pageHref }));
expect(nav).not.toContain("<button");
for (let n = 1; n <= 6; n++) expect(nav).toMatch(new RegExp(`<a [^>]*href="/blog\\?page=${n}"[^>]*aria-label="${n}페이지"`));
expect(nav).toMatch(/<a [^>]*href="\/blog\?page=1"[^>]*aria-current="page"/);
expect(nav.match(/aria-current="page"/g)).toHaveLength(1);
});
it("makes previous on page one a disabled link with no href, and next a link to page two", () => {
const nav = navOf(render({ pageSize: 2, getPageHref: pageHref }));
const previous = nav.match(/<a [^>]*aria-label="이전 페이지"[^>]*>/)?.[0] ?? "";
expect(previous).toContain('aria-disabled="true"');
expect(previous).not.toContain("href=");
const next = nav.match(/<a [^>]*aria-label="다음 페이지"[^>]*>/)?.[0] ?? "";
expect(next).toContain('href="/blog?page=2"');
expect(next).not.toContain("aria-disabled");
});
it("links previous and next around a middle page and disables next on the last", () => {
const middle = navOf(render({ pageSize: 2, defaultPage: 3, getPageHref: pageHref }));
expect(middle).toMatch(/<a [^>]*href="\/blog\?page=2"[^>]*aria-label="이전 페이지"/);
expect(middle).toMatch(/<a [^>]*href="\/blog\?page=4"[^>]*aria-label="다음 페이지"/);
const last = navOf(render({ pageSize: 2, defaultPage: 6, getPageHref: pageHref }));
expect(last.match(/<a [^>]*aria-label="다음 페이지"[^>]*>/)?.[0]).toContain('aria-disabled="true"');
});
it("keeps buttons when getPageHref is not given", () => {
const nav = navOf(render({ pageSize: 2 }));
expect(nav).toContain("<button");
expect(nav).not.toContain("<a ");
});
});
describe("BlogGrid category links", () => {
it("renders every tab, the all tab included, as a link with its href", () => {
const tabs = filtersOf(render({ getCategoryHref: categoryHref }));
expect(tabs).not.toContain("<button");
expect(tabs).toMatch(/<a [^>]*href="\/blog"[^>]*>/);
for (const c of ["제품", "디자인", "개발", "회사"]) expect(tabs).toContain(`href="/blog?category=${encodeURIComponent(c)}"`);
});
it("marks the active tab with aria-current and drops aria-pressed on links", () => {
const tabs = filtersOf(render({ getCategoryHref: categoryHref, defaultCategory: "개발" }));
expect(tabs).not.toContain("aria-pressed");
expect(tabs.match(/aria-current="true"/g)).toHaveLength(1);
expect(tabs).toMatch(/<a [^>]*href="\/blog\?category=%EA%B0%9C%EB%B0%9C"[^>]*aria-current="true"/);
});
it("keeps aria-pressed buttons when getCategoryHref is not given", () => {
const tabs = filtersOf(render());
expect(tabs).toContain("<button");
expect(tabs).toContain('aria-pressed="true"');
expect(tabs).not.toContain("<a ");
});
});
describe("BlogGrid cover slot", () => {
const cover = (post: BlogPost, { featured }: { featured: boolean }) => createElement("svg", { "data-cover": post.id, "data-featured": String(featured) });
it("draws the supplied node in each frame instead of an img", () => {
const html = render({ renderCover: cover });
expect(html).not.toMatch(/<img [^>]*src="\/media\/photos/);
expect(html).toContain('data-cover="quiet-software" data-featured="true"');
expect(html).toContain('data-cover="offline-sync" data-featured="false"');
const frames = html.match(/data-cover="/g) ?? [];
expect(frames).toHaveLength(7);
});
it("still draws a frame for a post without an image", () => {
const posts = blogPosts.map(post => ({ ...post, image: undefined }));
expect(render({ posts })).not.toContain("data-cover");
const html = render({ posts, renderCover: cover });
expect(html.match(/data-cover="/g)).toHaveLength(7);
});
it("keeps the img when renderCover is not given", () => {
expect(render()).toMatch(/<img [^>]*src="\/media\/photos/);
});
});
describe("shouldInterceptClick", () => {
const plain = { button: 0, metaKey: false, ctrlKey: false, shiftKey: false, altKey: false, defaultPrevented: false };
it("takes a plain left click", () => {
expect(shouldInterceptClick(plain)).toBe(true);
expect(shouldInterceptClick({ ...plain, target: "_self" })).toBe(true);
expect(shouldInterceptClick({ ...plain, target: "" })).toBe(true);
});
it("leaves modified, middle, prevented and targeted clicks to the browser", () => {
for (const key of ["metaKey", "ctrlKey", "shiftKey", "altKey"] as const) expect(shouldInterceptClick({ ...plain, [key]: true })).toBe(false);
expect(shouldInterceptClick({ ...plain, button: 1 })).toBe(false);
expect(shouldInterceptClick({ ...plain, defaultPrevented: true })).toBe(false);
expect(shouldInterceptClick({ ...plain, target: "_blank" })).toBe(false);
});
});
describe("BlogGrid stylesheet: measure and gutter hooks", () => {
const css = readFileSync(new URL("./blog-grid.module.css", import.meta.url), "utf8");
const rule = (selector: string, from = 0) => {
const start = css.indexOf(`${selector} {`, from);
expect(start, selector).toBeGreaterThanOrEqual(0);
return css.slice(start, css.indexOf("}", start));
};
const narrow = css.indexOf("@container blog (max-width: 680px)");
it("keeps today's measure and gutters as the defaults of two optional variables", () => {
expect(rule(".inner")).toContain("max-width: var(--blog-grid-max, 1180px)");
expect(rule(".inner")).toContain("padding: var(--space-16) var(--blog-grid-gutter, var(--space-6))");
expect(rule(".filters")).toContain("margin: 0 calc(var(--blog-grid-gutter, var(--space-6)) * -1)");
expect(rule(".filters")).toContain("padding: 0 var(--blog-grid-gutter, var(--space-6))");
expect(narrow).toBeGreaterThan(0);
expect(rule(".inner", narrow)).toContain("padding: var(--space-12) var(--blog-grid-gutter, var(--space-4))");
expect(rule(".filters", narrow)).toContain("margin: 0 calc(var(--blog-grid-gutter, var(--space-4)) * -1)");
expect(rule(".filters", narrow)).toContain("padding: 0 var(--blog-grid-gutter, var(--space-4))");
});
it("fills the image frame with the cover slot and stretches its svg or img", () => {
expect(rule(".cover")).toContain("position: absolute");
expect(rule(".cover")).toContain("inset: 0");
expect(rule(".cover")).toContain("overflow: hidden");
expect(rule(".cover > *")).toContain("width: 100%");
expect(rule(".cover > *")).toContain("height: 100%");
});
it("styles link tabs and disabled link steps like their button forms", () => {
expect(css).toMatch(/\.filter\[aria-current="true"\][^{]*\{[^}]*color: var\(--background\)/);
expect(css).toMatch(/\.pageStep\[aria-disabled="true"\][^{]*\{[^}]*opacity: \.5/);
});
it("has no other raw measure or gutter left on the inner box or the tab row", () => {
expect(css).not.toMatch(/max-width: 1180px/);
expect(css).not.toMatch(/\.inner \{[^}]*var\(--space-[46]\);/);
});
});
describe("slideDirection", () => {
it("slides forward to a larger page, back to a smaller one, and not at all for the same page", () => {
expect(slideDirection(1, 2)).toBe(1);
expect(slideDirection(1, 5)).toBe(1);
expect(slideDirection(3, 2)).toBe(-1);
expect(slideDirection(5, 1)).toBe(-1);
expect(slideDirection(2, 2)).toBe(0);
});
});
describe("BlogGrid card stats", () => {
const two: BlogPost[] = [
{ ...blogPosts[0], stats: { comments: 3, likes: 5 } },
{ ...blogPosts[1], stats: { comments: 0, likes: 0 } },
blogPosts[2],
];
const statsLines = (html: string) => [...html.matchAll(/<p class="[^"]*stats[^"]*"[^>]*>(.*?)<\/p>/g)].map(m => m[1].replace(/<[^>]+>/g, "|"));
it("has Korean defaults for the two count labels", () => {
expect(DEFAULT_BLOG_GRID_LABELS.comments?.(3)).toBe("댓글 3");
expect(DEFAULT_BLOG_GRID_LABELS.likes?.(0)).toBe("좋아요 0");
});
it("draws a quiet line with both counts, zeros included, only on cards that have stats", () => {
const html = render({ posts: two, categories: [] });
expect(statsLines(html)).toHaveLength(2);
expect(html).toContain("댓글 3");
expect(html).toContain("좋아요 5");
expect(html).toContain("댓글 0");
expect(html).toContain("좋아요 0");
// Each count is an icon and a number for the eye; the phrase is visually hidden for assistive tech, and shows in a tooltip.
const line = html.match(/<p class="[^"]*stats[^"]*"[^>]*>(.*?)<\/p>/)?.[1] ?? "";
const spoken = line.replace(/<span aria-hidden="true">[^<]*<\/span>/g, "").replace(/<svg.*?<\/svg>/g, "").replace(/<[^>]+>/g, "").replace(/\s+/g, " ").trim();
expect(spoken).toBe(", 댓글 3, 좋아요 5");
expect(line.replace(/<span class="[^"]*srOnly[^"]*">[^<]*<\/span>/g, "").replace(/<svg.*?<\/svg>/g, "").replace(/<[^>]+>/g, "")).toBe("35");
});
it("draws the leading reactions small before the like count, in the line and on the cover chip, and keeps the words", () => {
const withIcons: BlogPost[] = [{ ...blogPosts[0], stats: { comments: 1, likes: 7, reactionIcons: ["/e/fire.png", "/e/heart.png"] } }, blogPosts[1]];
const line = render({ posts: withIcons, categories: [] });
expect(line).toContain('src="/e/fire.png"');
expect(line.indexOf("/e/fire.png")).toBeLessThan(line.indexOf("/e/heart.png"));
expect(line.indexOf("/e/heart.png")).toBeLessThan(line.indexOf("좋아요 7"));
const cover = render({ posts: withIcons, categories: [], statsOnCover: true });
expect(cover).toContain("/e/fire.png");
expect(cover).toContain("좋아요 7");
// No pictures for a zero count or when none are given.
expect(render({ posts: [{ ...blogPosts[0], stats: { likes: 0, reactionIcons: ["/e/fire.png"] } }, blogPosts[1]], categories: [] })).not.toContain("/e/fire.png");
expect(render({ posts: two, categories: [] })).not.toContain("<img class=\"BlogGrid_reactionIcon");
});
it("keeps both chips on a cover when the counts are 0, quieter, and draws none for a post without stats", () => {
const html = render({ posts: [{ ...blogPosts[0], stats: { comments: 0, likes: 0 } }, blogPosts[1]], categories: [], statsOnCover: true });
expect(html.match(/data-zero/g)?.length).toBe(2);
expect(html).toContain("댓글 0");
expect(html).toContain("좋아요 0");
// A post that was never looked up (no stats at all) has no chips.
expect(render({ posts: [blogPosts[0]], categories: [], statsOnCover: true })).not.toContain("coverChip");
});
it("keeps the line inside the card link, after the byline", () => {
const html = render({ posts: two, categories: [], getHref: post => `/p/${post.id}` });
const card = html.match(/<a [^>]*href="\/p\/offline-sync"[^>]*>(.*?)<\/a>/)?.[1] ?? "";
expect(card.indexOf("읽는 데")).toBeGreaterThan(-1);
expect(card.indexOf("댓글 0")).toBeGreaterThan(card.indexOf("읽는 데"));
});
it("shows only the count that is given, and takes labels", () => {
const html = render({
posts: [{ ...blogPosts[0], stats: { likes: 1 } }, blogPosts[1]],
categories: [],
labels: { comments: n => `${n} comments`, likes: n => (n === 1 ? "1 like" : `${n} likes`) },
});
expect(html).toContain(", 1 like</span>");
expect(html).not.toContain("comments");
expect(html).toMatch(/<span class="[^"]*srOnly[^"]*">, 1 like<\/span>/);
});
it("draws nothing extra when no post has stats (the snapshots above pin the markup)", () => {
expect(statsLines(render())).toEqual([]);
expect(render()).not.toContain("댓글");
});
});
describe("pageWindow", () => {
it("lists every page while there are few", () => {
expect(pageWindow(1, 1)).toEqual([1]);
expect(pageWindow(3, 7)).toEqual([1, 2, 3, 4, 5, 6, 7]);
});
it("keeps the first, the last and the current page with its neighbours, never more than seven entries", () => {
expect(pageWindow(1, 20)).toEqual([1, 2, 3, 4, 5, "gap", 20]);
expect(pageWindow(4, 20)).toEqual([1, 2, 3, 4, 5, "gap", 20]);
expect(pageWindow(10, 20)).toEqual([1, "gap", 9, 10, 11, "gap", 20]);
expect(pageWindow(17, 20)).toEqual([1, "gap", 16, 17, 18, 19, 20]);
expect(pageWindow(20, 20)).toEqual([1, "gap", 16, 17, 18, 19, 20]);
for (let current = 1; current <= 30; current++) expect(pageWindow(current, 30).length).toBeLessThanOrEqual(7);
});
});
blog-grid.tsxblog-grid.tsxblog-grid.tsxtsx
"use client";
/* eslint-disable @next/next/no-img-element -- plain images keep the block portable outside Next.js. */
import { Fragment, useEffect, useId, useLayoutEffect, useRef, useState } from "react";
import type { MouseEvent, ReactNode } from "react";
import { HugeiconsIcon } from "@hugeicons/react";
import { Comment01Icon, FavouriteIcon } from "@hugeicons/core-free-icons";
import { AnimatePresence, LayoutGroup, animate, motion, useMotionValue } from "motion/react";
import { useReducedMotion } from "../../lib/use-reduced-motion";
import { motionTokens } from "../../lib/motion-tokens";
import { blogCategories, blogPosts } from "./blog-grid-data";
import type { BlogPost } from "./blog-grid-data";
import styles from "./blog-grid.module.css";
import { UiIcon } from "../../theme/ui-icon";
import { playUiSound } from "../../sound/play";
import { Tooltip } from "../../tooltip/tooltip";
export type { BlogAuthor, BlogPost } from "./blog-grid-data";
export interface BlogGridProps {
title?: string;
description?: string;
posts?: BlogPost[];
/** Category filter labels, in order. "전체" is added in front. */
categories?: string[];
/** Active category, or "전체" (controlled). */
category?: string;
defaultCategory?: string;
onCategoryChange?: (category: string) => void;
/** One based page (controlled). */
page?: number;
defaultPage?: number;
onPageChange?: (page: number) => void;
/** Cards per page below the featured post. Defaults to 6. */
pageSize?: number;
/** Shows the newest post of the current filter as a large card on page one. Defaults to true. */
showFeatured?: boolean;
/** Link for each post. When set, cards render as links and the in-place reader is off. */
getHref?: (post: BlogPost) => string;
/** Called when a post opens, from a link or the in-place reader. */
onPostOpen?: (post: BlogPost) => void;
className?: string;
/** BCP 47 tag for the visible dates. Defaults to "ko-KR". */
locale?: string;
/** Replaces any of the built in Korean texts. */
labels?: Partial<BlogGridLabels>;
/** Leaves out the title and description, for a page that draws its own header. The section keeps `title` as its accessible name. */
hideHeader?: boolean;
/** Leaves out the category tabs. */
hideFilters?: boolean;
/**
* Address of each page. When set, the page numbers and the previous and next steps render as real links (crawlable,
* working without JavaScript). A plain left click still changes the page in place with the usual sound and slide; keeping
* the address bar in step (for example with `history.pushState` in `onPageChange`) is the page's job. A step with nowhere
* to go is a link without `href`, marked `aria-disabled="true"`.
*/
getPageHref?: (page: number) => string;
/**
* Address of each category tab, called with the category value (`"전체"` for the unfiltered tab, whatever `labels.all` says).
* When set, the tabs render as links and the active one carries `aria-current="true"` (a link cannot be `aria-pressed`).
* A plain left click filters in place, as with `getPageHref`.
*/
getCategoryHref?: (category: string) => string;
/**
* Draws each card cover instead of `post.image`, inside the same frame (3:2, 16:10 for the featured card) and the same
* morph. The node is stretched to fill the frame; an svg covers it when it uses `preserveAspectRatio="xMidYMid slice"`.
* With it, a post without `image` still gets a frame. The in-place reader keeps using `post.image`.
* The node is decorative by default: give it aria-hidden, or role=img with a label.
*/
renderCover?: (post: BlogPost, context: { featured: boolean }) => ReactNode;
/** Draws a card's category in its own way (a badge with an icon, say) in place of the plain name. Receives the category and its post; the filter tabs keep the plain name. */
renderCategory?: (category: string, post: BlogPost) => ReactNode;
/**
* Draws the counts of a post with `stats` as small chips (an icon and a number) floating at the bottom left of its cover, instead of the
* quiet line under the byline. A count of 0 is left out, and a card with no counts draws no chips. Needs a cover (`renderCover` or `post.image`).
*/
statsOnCover?: boolean;
}
/** The parts of a click that decide whether a link should change the grid in place or be left to the browser. */
export interface LinkClickLike {
button: number;
metaKey: boolean;
ctrlKey: boolean;
shiftKey: boolean;
altKey: boolean;
defaultPrevented: boolean;
/** The link's `target`, if any. */
target?: string;
}
/** True for a plain left click on a link that opens in the same tab: the grid takes it over. Modified, middle and targeted clicks open the link as usual. */
export function shouldInterceptClick(event: LinkClickLike): boolean {
if (event.defaultPrevented || event.button !== 0) return false;
if (event.metaKey || event.ctrlKey || event.shiftKey || event.altKey) return false;
return !event.target || event.target === "_self";
}
/**
* The page numbers a pager draws: all of them while there are few, else the first, the last and the current page with its neighbours, with `"gap"` where numbers
* are left out. Never more than seven entries, so the row fits a phone.
*/
export function pageWindow(current: number, count: number): (number | "gap")[] {
if (count <= 7) return Array.from({ length: count }, (_, i) => i + 1);
if (current <= 4) return [1, 2, 3, 4, 5, "gap", count];
if (current >= count - 3) return [1, "gap", count - 4, count - 3, count - 2, count - 1, count];
return [1, "gap", current - 1, current, current + 1, "gap", count];
}
/** Which way the card page slides when the shown page changes: forward to a larger page, back to a smaller one. */
export function slideDirection(previous: number, next: number): -1 | 0 | 1 {
return next > previous ? 1 : next < previous ? -1 : 0;
}
export interface BlogGridLabels {
/** The first tab and the name of the unfiltered view. */
all: string;
filterGroup: string;
pagination: string;
previous: string;
next: string;
previousAria: string;
nextAria: string;
pageAria(n: number): string;
backToAll: string;
readTime(minutes: number): string;
empty(category: string): string;
/** The badge on the cover of a post marked `isNew`. */
newBadge: string;
/** The badge beside it on a post marked `isBreaking`. Optional: left out, "Breaking" is used. */
breakingBadge?: string;
/** The comment count on a card with `stats.comments`. Optional: left out, the Korean default ("댓글 3") is used. */
comments?(n: number): string;
/** The like count on a card with `stats.likes`. Optional: left out, the Korean default ("좋아요 5") is used. */
likes?(n: number): string;
}
export const DEFAULT_BLOG_GRID_LABELS: BlogGridLabels = {
all: "전체",
filterGroup: "카테고리별로 거르기",
pagination: "페이지 이동",
previous: "이전",
next: "다음",
previousAria: "이전 페이지",
nextAria: "다음 페이지",
pageAria: n => `${n}페이지`,
backToAll: "모든 글 보기",
readTime: minutes => `읽는 데 ${minutes}분`,
empty: category => `${category} 카테고리에는 아직 글이 없어요.`,
newBadge: "New",
breakingBadge: "Breaking",
comments: n => `댓글 ${n}`,
likes: n => `좋아요 ${n}`,
};
/** The category value that means "no filter". Kept as is for the `category` props, whatever the tab says. */
const ALL = "전체";
const smooth = motionTokens.spring.smooth;
const morph = motionTokens.spring.morph;
const standard = [...motionTokens.ease.standard] as [number, number, number, number];
const dateFormats = new Map<string, Intl.DateTimeFormat>();
function formatDate(iso: string, locale: string) {
let format = dateFormats.get(locale);
if (!format) { format = new Intl.DateTimeFormat(locale, { month: "short", day: "numeric", year: "numeric", timeZone: "UTC" }); dateFormats.set(locale, format); }
return format.format(new Date(`${iso}T00:00:00Z`));
}
function useControllable<T>(value: T | undefined, initial: T, onChange?: (next: T) => void) {
const [inner, setInner] = useState(initial);
const current = value !== undefined ? value : inner;
const set = (next: T) => { if (value === undefined) setInner(next); onChange?.(next); };
return [current, set] as const;
}
/** Springs its height when the page or filter changes, so the pagination below glides instead of jumping. Other resizes (a late font, a narrower window) apply at once. */
function AutoHeight({ changeKey, reduced, className, children }: { changeKey: string; reduced: boolean; className?: string; children: ReactNode }) {
const clipRef = useRef<HTMLDivElement>(null);
const contentRef = useRef<HTMLDivElement>(null);
const height = useMotionValue<number | "auto">("auto");
const lastKey = useRef(changeKey), armedUntil = useRef(0);
useLayoutEffect(() => {
if (lastKey.current === changeKey) return;
lastKey.current = changeKey;
armedUntil.current = performance.now() + 900;
}, [changeKey]);
useEffect(() => {
const clip = clipRef.current, content = contentRef.current;
if (!clip || !content || typeof ResizeObserver === "undefined") return;
let controls: ReturnType<typeof animate> | undefined;
const observer = new ResizeObserver(() => {
const next = content.offsetHeight;
controls?.stop();
if (!next || reduced || height.get() === "auto" || performance.now() > armedUntil.current) { height.jump(next || "auto"); delete clip.dataset.clip; return; }
clip.dataset.clip = "";
controls = animate(height, next, { ...smooth, onComplete: () => { delete clip.dataset.clip; } });
});
observer.observe(content);
return () => { observer.disconnect(); controls?.stop(); };
}, [height, reduced]);
return <motion.div ref={clipRef} className={styles.clip} style={{ height }}>
<div ref={contentRef} className={className}>{children}</div>
</motion.div>;
}
function Meta({ post, locale, renderCategory }: { post: BlogPost; locale: string; renderCategory?: (category: string, post: BlogPost) => ReactNode }) {
return <p className={styles.meta}><span>{renderCategory ? renderCategory(post.category, post) : post.category}</span><span aria-hidden="true">·</span><time dateTime={post.date}>{formatDate(post.date, locale)}</time></p>;
}
function Byline({ post, readTime }: { post: BlogPost; readTime: string }) {
return <div className={styles.byline}>
{post.author.avatar ? <img className={styles.avatar} src={post.author.avatar} alt="" width={24} height={24} loading="lazy" /> : <span className={styles.avatar} aria-hidden="true" />}
<span className={styles.authorName}>{post.author.name}</span>
<span className={styles.readTime}>{readTime}</span>
</div>;
}
/**
* The counts under the byline, for a post with `stats`: "댓글 3 · 좋아요 5". Each count is its own span with plain spaces around the dot. The
* dot is hidden from assistive tech and a visually hidden ", " stands in for it (and opens the line, after the read time), so the card
* link's name reads "… 읽는 데 5분, 댓글 3, 좋아요 5" as separate phrases while the eye sees only the dot. A count left out of `stats` is not drawn.
*/
function Stats({ stats, labels }: { stats: NonNullable<BlogPost["stats"]>; labels: BlogGridLabels }) {
const icons = stats.likes && stats.reactionIcons && stats.reactionIcons.length > 0 ? stats.reactionIcons : undefined;
const parts = [
stats.comments !== undefined ? { key: "comments" as const, n: stats.comments, text: (labels.comments ?? DEFAULT_BLOG_GRID_LABELS.comments!)(stats.comments) } : null,
stats.likes !== undefined ? { key: "likes" as const, n: stats.likes, text: (labels.likes ?? DEFAULT_BLOG_GRID_LABELS.likes!)(stats.likes) } : null,
].filter((part): part is NonNullable<typeof part> => part !== null);
if (parts.length === 0) return null;
return <p className={styles.stats} data-duo="">{parts.map(part => <Tooltip key={part.key} content={part.text}><span className={styles.statItem} data-kind={part.key} data-active={part.n > 0 ? "" : undefined}>
<span className={styles.srOnly}>, {part.text}</span>
{part.key === "likes" && icons ? <ReactionIcons icons={icons} /> : <HugeiconsIcon icon={CHIP_ICONS[part.key]} size={14} strokeWidth={1.75} aria-hidden="true" />}
<span aria-hidden="true">{part.n}</span>
</span></Tooltip>)}</p>;
}
/** The leading reactions as a small overlapping stack of images; decorative, the count's own phrase names them. */
function ReactionIcons({ icons }: { icons: readonly string[] }) {
return <span className={styles.reactionStack} aria-hidden="true">{icons.slice(0, 3).map((src, index) => <img key={src} className={styles.reactionIcon} src={src} alt="" width={14} height={14} style={{ zIndex: 3 - index }} draggable={false} />)}</span>;
}
const CHIP_ICONS = { comments: Comment01Icon, likes: FavouriteIcon } as const;
/**
* The counts of a post as chips on its cover: an icon and a number each, with the labelled phrase ("댓글 3") for assistive tech and the
* number alone for the eye. A count that is 0 is still drawn, quieter, so every card reads the same and the reader sees where to join in
* (a count that was never looked up, `undefined`, is not drawn). Decorative for pointers (the card link carries the phrases).
*/
function CoverStats({ stats, labels }: { stats: NonNullable<BlogPost["stats"]>; labels: BlogGridLabels }) {
const chips = [
stats.comments !== undefined ? { key: "comments" as const, n: stats.comments, text: (labels.comments ?? DEFAULT_BLOG_GRID_LABELS.comments!)(stats.comments) } : null,
stats.likes !== undefined ? { key: "likes" as const, n: stats.likes, text: (labels.likes ?? DEFAULT_BLOG_GRID_LABELS.likes!)(stats.likes) } : null,
].filter((chip): chip is NonNullable<typeof chip> => chip !== null);
const icons = stats.likes && stats.reactionIcons && stats.reactionIcons.length > 0 ? stats.reactionIcons : undefined;
if (chips.length === 0) return null;
return <span className={styles.coverStats}>{chips.map(chip => <span key={chip.key} className={styles.coverChip} data-kind={chip.key} data-icons={chip.key === "likes" && icons ? "" : undefined} data-zero={chip.n === 0 ? "" : undefined}>
{chip.key === "likes" && icons ? <ReactionIcons icons={icons} /> : <HugeiconsIcon icon={CHIP_ICONS[chip.key]} size={14} strokeWidth={1.75} aria-hidden="true" />}
<span className={styles.srOnly}>, {chip.text}</span><span aria-hidden="true">{chip.n}</span>
</span>)}</span>;
}
export function BlogGrid({
title = "저널",
description = "팀이 전하는 제품 소식, 디자인 노트, 엔지니어링 이야기를 모았어요.",
posts = blogPosts,
categories = blogCategories,
category: categoryProp,
defaultCategory = ALL,
onCategoryChange,
page: pageProp,
defaultPage = 1,
onPageChange,
pageSize = 6,
showFeatured = true,
getHref,
onPostOpen,
className,
locale = "ko-KR",
labels: labelsProp,
hideHeader = false,
hideFilters = false,
getPageHref,
getCategoryHref,
renderCover,
renderCategory,
statsOnCover = false,
}: BlogGridProps) {
const labels: BlogGridLabels = { ...DEFAULT_BLOG_GRID_LABELS, ...labelsProp };
const reduced = useReducedMotion();
const uid = useId();
const rootRef = useRef<HTMLElement>(null);
const [category, setCategoryState] = useControllable(categoryProp, defaultCategory, onCategoryChange);
const [page, setPageState] = useControllable(pageProp, defaultPage, onPageChange);
const [direction, setDirection] = useState(0);
const [reading, setReading] = useState<BlogPost | null>(null);
/** The post the reader just closed. Its image morphs back into its card while the rest of the index fades in around it. */
const [returning, setReturning] = useState<string | null>(null);
const lastOpened = useRef<string | null>(null);
const sorted = [...posts].sort((a, b) => b.date.localeCompare(a.date));
const filtered = category === ALL ? sorted : sorted.filter(post => post.category === category);
const featured = showFeatured && filtered.length > 1 ? (filtered.find(post => post.featured) ?? filtered[0]) : null;
const rest = featured ? filtered.filter(post => post !== featured) : filtered;
const pageCount = Math.max(1, Math.ceil(rest.length / pageSize));
const safePage = Math.min(Math.max(1, page), pageCount);
const pagePosts = rest.slice((safePage - 1) * pageSize, safePage * pageSize);
// With a controlled `page` the view can change from outside (history, the address), not only from a click here, so the slide
// follows the change of the shown page: a larger page slides forward, a smaller one back, a new category not at all.
const [shown, setShown] = useState({ page: safePage, category });
if (pageProp !== undefined && (shown.page !== safePage || shown.category !== category)) {
setShown({ page: safePage, category });
setDirection(shown.category !== category ? 0 : slideDirection(shown.page, safePage));
}
function scrollToTop() {
const node = rootRef.current;
if (node && node.getBoundingClientRect().top < 0) node.scrollIntoView({ behavior: reduced ? "auto" : "smooth", block: "start" });
}
function setCategory(next: string) {
if (next === category) return;
playUiSound("tick");
setDirection(0);
setReturning(null);
setCategoryState(next);
setPageState(1);
}
function setPage(next: number) {
if (next === safePage || next < 1 || next > pageCount) return;
playUiSound("tick");
setDirection(next > safePage ? 1 : -1);
setReturning(null);
setPageState(next);
scrollToTop();
}
/** Click handler for a page or tab link: a plain click runs `action` in place, anything else is the browser's. */
function linkClick(event: MouseEvent<HTMLAnchorElement>, action: () => void) {
if (!shouldInterceptClick({ button: event.button, metaKey: event.metaKey, ctrlKey: event.ctrlKey, shiftKey: event.shiftKey, altKey: event.altKey, defaultPrevented: event.defaultPrevented, target: event.currentTarget.target })) return;
event.preventDefault();
action();
}
function open(post: BlogPost, event: MouseEvent) {
playUiSound("tick");
onPostOpen?.(post);
if (getHref) return;
event.preventDefault();
lastOpened.current = post.id;
setReading(post);
scrollToTop();
}
function close() {
playUiSound("tick");
setReturning(lastOpened.current);
setReading(null);
requestAnimationFrame(() => {
const card = rootRef.current?.querySelector<HTMLElement>(`[data-post="${lastOpened.current}"]`);
card?.focus({ preventScroll: true });
card?.scrollIntoView({ block: "nearest", behavior: reduced ? "auto" : "smooth" });
});
}
const renderCard = (post: BlogPost, isFeatured = false) => {
const href = getHref?.(post);
const inner = <>
{(renderCover || post.image) && <motion.div layoutId={reduced ? undefined : `${uid}-image-${post.id}`} transition={morph} className={styles.imageFrame}>
{renderCover
? <div className={styles.cover}>{renderCover(post, { featured: isFeatured })}</div>
: post.image && <img className={styles.image} src={post.image.src} alt={post.image.alt} loading={isFeatured ? "eager" : "lazy"} />}
{(post.isNew || post.isBreaking) && <span className={styles.badges}>
{post.isNew && <span className={styles.newBadge}>{labels.newBadge}</span>}
{post.isBreaking && <span className={styles.breakingBadge}>{labels.breakingBadge ?? DEFAULT_BLOG_GRID_LABELS.breakingBadge}</span>}
</span>}
{statsOnCover && post.stats && <CoverStats stats={post.stats} labels={labels} />}
</motion.div>}
<div className={styles.cardBody}>
<Meta post={post} locale={locale} renderCategory={renderCategory} />
<h3 className={isFeatured ? styles.featuredTitle : styles.cardTitle}>{post.title}</h3>
<p className={styles.excerpt}>{post.excerpt}</p>
<Byline post={post} readTime={labels.readTime(post.readTime)} />
{post.stats && !(statsOnCover && (renderCover || post.image)) && <Stats stats={post.stats} labels={labels} />}
</div>
</>;
const className = isFeatured ? styles.featured : styles.card;
const fades = returning !== null && (reduced || post.id !== returning);
return <motion.a key={post.id} className={className} href={href ?? `#${post.id}`} data-post={post.id} onClick={event => open(post, event)} {...enterFade(fades)}>{inner}</motion.a>;
};
/** Fades a piece of the index or reader in on its own, so the shared image is never dimmed by a fading parent mid morph. */
const enterFade = (on: boolean) => ({ initial: on ? { opacity: 0 } : false as const, animate: { opacity: 1 }, transition: { duration: motionTokens.duration.standard, ease: standard } });
const back = returning !== null;
const tabs = [ALL, ...categories];
const tabLabel = (tab: string) => tab === ALL ? labels.all : tab;
const pageKey = `${category}-${safePage}`;
/** Previous or next. As a link, a step with nowhere to go keeps its place as a link without `href` (not focusable, like a disabled button). */
const pageStep = (target: number, disabled: boolean, label: string, content: ReactNode) => {
if (!getPageHref) return <button type="button" className={styles.pageStep} onClick={() => setPage(target)} disabled={disabled} aria-label={label}>{content}</button>;
if (disabled) return <a role="link" className={styles.pageStep} aria-disabled="true" aria-label={label}>{content}</a>;
return <a href={getPageHref(target)} className={styles.pageStep} aria-label={label} onClick={event => linkClick(event, () => setPage(target))}>{content}</a>;
};
return <section ref={rootRef} className={[styles.root, className].filter(Boolean).join(" ")} aria-label={title}>
<LayoutGroup id={uid}>
<div className={styles.inner}>
<AnimatePresence mode="popLayout" initial={false}>
{reading ? <motion.article key="reader" className={styles.reader} exit={{ opacity: 0, transition: { duration: motionTokens.duration.exit, ease: standard } }} aria-labelledby={`${uid}-reader-title`}>
<motion.button type="button" className={styles.back} onClick={close} autoFocus {...enterFade(true)}><UiIcon iconRole="arrow-left" size={16} aria-hidden="true" />{labels.backToAll}</motion.button>
<motion.header className={styles.readerHead} {...enterFade(true)}>
<Meta post={reading} locale={locale} />
<h2 id={`${uid}-reader-title`} className={styles.readerTitle}>{reading.title}</h2>
<Byline post={reading} readTime={labels.readTime(reading.readTime)} />
</motion.header>
{reading.image && <motion.div layoutId={reduced ? undefined : `${uid}-image-${reading.id}`} className={styles.readerImage} {...(reduced ? enterFade(true) : { transition: morph })}>
<img className={styles.image} src={reading.image.src} alt={reading.image.alt} />
</motion.div>}
<motion.div className={styles.readerBody} initial={{ opacity: 0, y: reduced ? 0 : 12 }} animate={{ opacity: 1, y: 0 }} transition={{ ...smooth, delay: reduced ? 0 : motionTokens.duration.instant }}>
<p className={styles.lead}>{reading.excerpt}</p>
{(reading.body ?? []).map(paragraph => <p key={paragraph}>{paragraph}</p>)}
</motion.div>
</motion.article> : <motion.div key="index" className={styles.index} exit={{ opacity: 0, transition: { duration: motionTokens.duration.exit, ease: standard } }}>
{!hideHeader && <motion.header className={styles.header} {...enterFade(back)}>
<h2 className={styles.title}>{title}</h2>
{description && <p className={styles.description}>{description}</p>}
</motion.header>}
{!hideFilters && <motion.div className={styles.filters} role="group" aria-label={labels.filterGroup} {...enterFade(back)}>
{tabs.map(tab => {
const content = <>
{tab === category && <motion.span layoutId={`${uid}-filter`} className={styles.filterHighlight} transition={reduced ? { duration: 0 } : morph} />}
<span>{tabLabel(tab)}</span>
</>;
return getCategoryHref
? <a key={tab} href={getCategoryHref(tab)} className={styles.filter} aria-current={tab === category ? "true" : undefined} onClick={event => linkClick(event, () => setCategory(tab))}>{content}</a>
: <button key={tab} type="button" className={styles.filter} aria-pressed={tab === category} onClick={() => setCategory(tab)}>{content}</button>;
})}
</motion.div>}
<AutoHeight changeKey={`${pageKey}-${pageCount}`} reduced={Boolean(reduced)} className={styles.stack}>
<AnimatePresence mode="wait" initial={false} custom={direction}>
<motion.div
key={pageKey}
className={styles.page}
initial={reduced ? { opacity: 0 } : { opacity: 0, x: direction * 24, y: direction ? 0 : 10 }}
animate={{ opacity: 1, x: 0, y: 0 }}
exit={reduced ? { opacity: 0 } : { opacity: 0, x: direction * -24, transition: { duration: motionTokens.duration.exit, ease: standard } }}
transition={{ ...smooth, opacity: { duration: motionTokens.duration.standard } }}
>
{featured && safePage === 1 && renderCard(featured, true)}
{pagePosts.length > 0 && <div className={styles.grid}>{pagePosts.map(post => renderCard(post))}</div>}
{filtered.length === 0 && <p className={styles.empty}>{labels.empty(tabLabel(category))}</p>}
</motion.div>
</AnimatePresence>
<AnimatePresence initial={back}>
{pageCount > 1 && <motion.nav key="pagination" className={styles.pagination} aria-label={labels.pagination} initial={{ opacity: 0 }} animate={{ opacity: 1 }} exit={{ opacity: 0, transition: { duration: motionTokens.duration.exit, ease: standard } }} transition={{ duration: motionTokens.duration.standard, ease: standard }}>
{pageStep(safePage - 1, safePage === 1, labels.previousAria, <><UiIcon iconRole="chevron-left" size={16} aria-hidden="true" /><span>{labels.previous}</span></>)}
<div className={styles.pageNumbers}>
{pageWindow(safePage, pageCount).map((number, slot) => {
if (number === "gap") return <span key={`gap-${slot}`} className={styles.pageGap} aria-hidden="true">…</span>;
const content = <>
{number === safePage && <motion.span layoutId={`${uid}-page`} className={styles.pageHighlight} transition={reduced ? { duration: 0 } : morph} />}
<span>{number}</span>
</>;
const current = number === safePage ? "page" as const : undefined;
return getPageHref
? <a key={number} href={getPageHref(number)} className={styles.pageNumber} aria-current={current} aria-label={labels.pageAria(number)} onClick={event => linkClick(event, () => setPage(number))}>{content}</a>
: <button key={number} type="button" className={styles.pageNumber} aria-current={current} aria-label={labels.pageAria(number)} onClick={() => setPage(number)}>{content}</button>;
})}
</div>
{pageStep(safePage + 1, safePage === pageCount, labels.nextAria, <><span>{labels.next}</span><UiIcon iconRole="chevron-right" size={16} aria-hidden="true" /></>)}
</motion.nav>}
</AnimatePresence>
</AutoHeight>
</motion.div>}
</AnimatePresence>
</div>
</LayoutGroup>
</section>;
}
/** Preview: the blog index with the in-place reader. */
export function BlogGridBlock() {
return <BlogGrid />;
}
export default BlogGridBlock;