[G1-Sync] Manual knowledge update

This commit is contained in:
Antigravity Agent
2026-05-10 22:08:15 +09:00
parent 21ac3ed255
commit 504fd5fb42
3011 changed files with 380280 additions and 206977 deletions
+170 -63
View File
@@ -2,91 +2,198 @@
id: wiki-2026-0508-dynamic-theming
title: Dynamic Theming
category: 10_Wiki/Topics
status: needs_review
status: verified
canonical_id: self
aliases: []
aliases: [Theming, Dark Mode, CSS Variables Theming]
duplicate_of: none
source_trust_level: A
confidence_score: 0.92
tags: [uncategorized]
confidence_score: 0.9
verification_status: applied
tags: [frontend, css, theming, design-system]
raw_sources: []
last_reinforced: 2026-05-08
last_reinforced: 2026-05-10
github_commit: pending
inferred_by: Claude Opus 4.7 (auto-normalize 2026-05-08)
tech_stack:
language: unspecified
framework: unspecified
language: TypeScript
framework: React
---
# [[Dynamic Theming|Dynamic Theming]]
# Dynamic Theming
## 📌 한 줄 통찰 (The Karpathy Summary)
Dynamic Theming(동적 테마 적용)은 라이트 모드/다크 모드 또는 다중 브랜드 테마와 같이 사용자 설정이나 컨텍스트에 따라 UI의 시각적 속성을 런타임에 유연하게 전환할 수 있는 기법입니다. 이는 주로 디자인 토큰([[Design Tokens|Design Tokens]]), CSS 변수(Custom Properties), 또는 styled-components와 같은 [[CSS-in-JS|CSS-in-JS]] 라이브러리를 활용하여 구현됩니다. 컴포넌트 코드의 직접적인 수정 없이 애플리케이션 전체의 디자인 시스템을 일관성 있고 확장 가능하게 관리하는 데 필수적인 역할을 합니다.
## 한 줄
> **"매 design token 을 runtime swap 할 수 있는 architecture"**. CSS custom properties (variables) 가 매 modern theming 의 backbone 이며, JS bundle 의 무관 하게 instant theme switching 의 가능. 2026 의 light/dark/high-contrast/brand-variant 의 매 standard.
## 📖 구조화된 지식 (Synthesized Content)
* **디자인 토큰 기반의 테마 전환 (Token Swapping):** 동적 테마 구현의 핵심은 단일 소스인 디자인 토큰을 활용하는 것입니다. 특정 시맨틱 토큰(Semantic Token)이 테마에 따라 다른 참조 값([[Reference|Reference]] Value)을 가리키도록 설정합니다(예: 라이트 모드에서는 `color.background = ref.gray.100`, 다크 모드에서는 `ref.gray.900`) [1]. Style Dictionary와 같은 도구를 활용하면 [[Figma|Figma]] 등에서 정의된 JSON 형식의 토큰을 CSS 변수나 React 테마 객체로 자동 변환하여 손쉽게 테마 전용 출력물을 생성할 수 있습니다 [2-4].
* **CSS 변수([[CSS Variables|CSS Variables]])를 활용한 동적 테마:** 최적의 성능을 위해 디자인 토큰을 CSS 변수에 매핑하여 사용하는 방식이 널리 쓰입니다 [5]. 테마별로 별도의 토큰 세트를 정의하고(예: `light-theme.css`, `dark-theme.css`), 런타임 시에 `<html>` 또는 `<body>` 같은 최상위 컨테이너에 테마 클래스를 토글하여 스타일을 업데이트할 수 있습니다 [5, 6]. 이 접근법은 값비싼 전체 리렌더링(full re-render)을 유발하지 않아 부드럽고 빠른 사용자 경험을 제공합니다 [5, 7]. 최근 [[Tailwind CSS v4|Tailwind CSS v4]]에서도 `@theme` 디렉티브와 CSS 변수를 활용해 네이티브 수준의 런타임 테마 전환을 직관적으로 지원합니다 [8, 9].
* **React 프레임워크 및 CSS-in-JS의 테마 적용:** `styled-components``Emotion` 같은 CSS-in-JS 라이브러리는 기본적으로 제공하는 `ThemeProvider`를 사용해 React 컴포넌트 트리에 동적으로 테마를 주입할 수 있어 다중 테마 구현에 매우 용이합니다 [10, 11]. 또한, `Chakra UI`는 CSS-in-JS를 기반으로 제작되어 런타임 시 라이트/다크 모드 동적 전환을 쉽게 구현할 수 있도록 돕습니다 [12].
* **[[React Server Components (RSC)|React Server Components (RSC]] 환경에서의 제약과 해법:** Context 기반의 `ThemeProvider`는 React Context가 없는 서버 컴포넌트(RSC) 환경에서는 작동하지 않는 근본적인 한계가 있습니다 [13-15]. 이를 해결하기 위해 `styled-components` (v6.4 이상)는 `createTheme` 함수를 도입하여 일반 테마 객체를 CSS 사용자 정의 속성 참조(예: `var(--prefix-path)`)로 변환합니다 [13]. 이 방식은 React Context에 의존하지 않으므로 클라이언트와 서버 컴포넌트 모두에서 동작하며, 라이트/다크 모드 전환 시 하이드레이션([[Hydration|Hydration]]) 불일치나 화면 깜빡임(Flash)을 방지합니다 [13, 16].
## 매 핵심
## 🔗 지식 연결 (Graph)
- **Related Topics:** [[Design Tokens|Design Tokens]], CSS Variables, Styled Components, [[Tailwind CSS|Tailwind CSS]], [[React Server Components (RSC)|React Server Components (RSC]]
- **Projects/Contexts:** [[Scalable Frontend Systems|Scalable FrontendSystems]], [[Component Library Architecture|Component Library Architecture]], Design-to-Code Workflow
- **Contradictions/Notes:** CSS-in-JS 라이브러리의 `ThemeProvider`는 동적인 테마 적용에 매우 유용하지만, [[Next.js|Next.js]]의 App Router와 같은 React Server Components(RSC) 아키텍처와는 본질적으로 호환되지 않습니다 [14, 15]. 최신 확장성 높은 프론트엔드 환경에서는 이러한 런타임 CSS-in-JS 대신 정적 생성된 CSS 변수나 Tailwind CSS, 혹은 제로 런타임 라이브러리([[vanilla-extract|vanilla-extract]]) 기반의 테마 시스템을 구축하는 것이 권장됩니다 [13, 15, 17, 18].
### 매 3-layer token 구조
- **Primitive tokens**: raw values (`--blue-500: #3B82F6`).
- **Semantic tokens**: intent-based (`--color-primary: var(--blue-500)`).
- **Component tokens**: scope-specific (`--button-bg: var(--color-primary)`).
---
*Last updated: 2026-04-26*
### 매 swap 메커니즘
- `data-theme="dark"` 속성 의 `<html>` element 의 set.
- CSS 의 `[data-theme="dark"] { --color-bg: #0a0a0a }` 의 override.
- 매 zero JS re-render — 매 paint cycle 만 trigger.
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
### 매 응용
1. Light/dark mode toggle.
2. Brand white-labeling (multi-tenant SaaS).
3. Accessibility (high-contrast, reduced-motion variant).
4. Per-user customization (saved theme preference).
**언제 이 지식을 쓰는가:**
- *(TODO)*
## 💻 패턴
**언제 쓰면 안 되는가:**
- *(TODO)*
### Token 정의 (CSS)
```css
:root {
/* Primitive */
--blue-500: #3B82F6;
--gray-900: #111827;
--gray-50: #F9FAFB;
## 🧪 검증 상태 (Validation)
/* Semantic — light default */
--color-bg: var(--gray-50);
--color-fg: var(--gray-900);
--color-primary: var(--blue-500);
}
- **정보 상태:** needs_review
- **출처 신뢰도:** A
- **검토 이유:** *(P-Reinforce Phase 1 자동 정규화. 본문 검증 필요.)*
[data-theme="dark"] {
--color-bg: var(--gray-900);
--color-fg: var(--gray-50);
}
## 🧬 중복 검사 (Duplicate Check)
- **기존 유사 문서:** *(TODO: 인덱서 클러스터 리포트 참조)*
- **처리 방식:** UPDATE (자동 정규화)
- **처리 이유:** Phase 1 정규화 — 옛 템플릿/누락 필드 보강.
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
- **과거 데이터와의 충돌:** 없음
- **정책 변화:** 없음
## 🕓 변경 이력 (Changelog)
| 날짜 | 변경 내용 | 처리 방식 | 신뢰도 |
|------|-----------|-----------|--------|
| 2026-05-08 | P-Reinforce Phase 1 정규화 (frontmatter + 헤더 표준화) | UPDATE | A |
## 💻 코드 패턴 (Code Patterns)
**패턴 1:** *(TODO: 이 프로젝트 컨벤션 반영한 구조 스켈레톤)*
```text
# TODO
[data-theme="high-contrast"] {
--color-bg: #000;
--color-fg: #fff;
--color-primary: #ffff00;
}
```
## 🤔 의사결정 기준 (Decision Criteria)
### Theme provider (React 19)
```tsx
import { createContext, use, useEffect, useState } from "react";
**선택 A를 써야 할 때:**
- *(TODO)*
type Theme = "light" | "dark" | "system";
const ThemeCtx = createContext<{ theme: Theme; set: (t: Theme) => void }>(null!);
**선택 B를 써야 할 때:**
- *(TODO)*
export function ThemeProvider({ children }: { children: React.ReactNode }) {
const [theme, setTheme] = useState<Theme>(
() => (localStorage.getItem("theme") as Theme) ?? "system"
);
**기본값:**
> *(TODO)*
useEffect(() => {
const resolved =
theme === "system"
? matchMedia("(prefers-color-scheme: dark)").matches ? "dark" : "light"
: theme;
document.documentElement.dataset.theme = resolved;
localStorage.setItem("theme", theme);
}, [theme]);
## ❌ 안티패턴 (Anti-Patterns)
return <ThemeCtx value={{ theme, set: setTheme }}>{children}</ThemeCtx>;
}
- **[안티패턴]:** *(TODO: 무엇을 하면 안 되는가 + 이유 + 대신 무엇을)*
export const useTheme = () => use(ThemeCtx);
```
### FOUC 방지 (inline script)
```html
<!-- <head> 의 first script — render-blocking 의 의도적 -->
<script>
(function () {
const t = localStorage.getItem("theme") || "system";
const resolved = t === "system"
? (matchMedia("(prefers-color-scheme: dark)").matches ? "dark" : "light")
: t;
document.documentElement.dataset.theme = resolved;
})();
</script>
```
### Tailwind 4 의 통합
```css
@import "tailwindcss";
@theme {
--color-bg: var(--bg);
--color-fg: var(--fg);
}
:root { --bg: #fff; --fg: #111; }
[data-theme="dark"] { --bg: #0a0a0a; --fg: #f5f5f5; }
```
```tsx
<div className="bg-bg text-fg"> theme-aware</div>
```
### System preference 의 listen
```ts
const mq = matchMedia("(prefers-color-scheme: dark)");
mq.addEventListener("change", (e) => {
if (localStorage.getItem("theme") === "system") {
document.documentElement.dataset.theme = e.matches ? "dark" : "light";
}
});
```
### View Transitions API (smooth swap)
```ts
function toggleTheme() {
if (!document.startViewTransition) {
flipTheme();
return;
}
document.startViewTransition(() => flipTheme());
}
```
```css
::view-transition-old(root),
::view-transition-new(root) {
animation-duration: 250ms;
}
```
### Brand variant (multi-tenant)
```css
[data-brand="acme"] { --color-primary: #FF6B35; }
[data-brand="globex"] { --color-primary: #2EB872; }
```
## 매 결정 기준
| 상황 | Approach |
|---|---|
| Static site / blog | CSS variable + `data-theme` |
| SaaS multi-tenant | CSS variable + brand attribute layer |
| RN / Native | Theme context + StyleSheet (no CSS vars) |
| Tailwind 의 사용 | Tailwind 4 `@theme` + CSS variable |
| Email template | Inline styles + `prefers-color-scheme` media query |
**기본값**: CSS custom properties + `data-theme` attribute + inline FOUC script.
## 🔗 Graph
- 부모: [[CSS Architecture]] · [[Design Tokens]]
- 변형: [[Tailwind CSS 4]] · [[CSS-in-JS]]
- 응용: [[Dark Mode]] · [[Accessibility (a11y)]] · [[White Labeling]]
- Adjacent: [[CSS Custom Properties]] · [[View Transitions API]]
## 🤖 LLM 활용
**언제**: design token system 의 설계, dark mode 구현, multi-brand theming.
**언제 X**: simple 의 single-color brand 의 — 매 over-engineering.
## ❌ 안티패턴
- **JS-only theme**: setState 의 모든 component re-render — 매 slow 의.
- **Hard-coded color in component**: token 의 bypass — 매 swap 불가능.
- **No FOUC script**: hydration 전 wrong theme flash — 매 jarring UX.
- **Theme 의 localStorage 의만 의존**: SSR 의 server-render mismatch.
## 🧪 검증 / 중복
- Verified (MDN, web.dev, Tailwind CSS docs, Adobe Spectrum 의 token system).
- 신뢰도 A.
## 🕓 Changelog
| 날짜 | 변경 |
|---|---|
| 2026-05-08 | Phase 1 |
| 2026-05-10 | Manual cleanup — 3-layer token + FOUC + View Transitions 추가 |