[G1-Sync] Manual knowledge update
This commit is contained in:
@@ -2,100 +2,246 @@
|
||||
id: wiki-2026-0508-다크-모드-및-다중-브랜드-테마-동적-전환-시스템
|
||||
title: 다크 모드 및 다중 브랜드 테마 동적 전환 시스템
|
||||
category: 10_Wiki/Topics
|
||||
status: needs_review
|
||||
status: verified
|
||||
canonical_id: self
|
||||
aliases: []
|
||||
aliases: [Dark Mode, Theme Switching, Multi-brand 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, dark-mode, 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/CSS
|
||||
framework: React/Next.js
|
||||
---
|
||||
|
||||
# [[다크 모드 및 다중 브랜드 테마 동적 전환 시스템|다크 모드 및 다중 브랜드 테마 동적 전환 시스템]]
|
||||
# 다크 모드 및 다중 브랜드 테마 동적 전환 시스템
|
||||
|
||||
## 📌 한 줄 통찰 (The Karpathy Summary)
|
||||
다크 모드 및 다중 브랜드 테마 동적 전환 시스템은 애플리케이션의 시각적 외관을 사용자의 설정이나 브랜드 요구사항에 맞춰 유연하게 변경할 수 있도록 하는 아키텍처입니다. 이는 주로 디자인 토큰([[Design Tokens|Design Tokens]])과 시맨틱 네이밍, CSS 사용자 정의 속성(CSS Variables)을 활용하여 구현되며, CSS Modules나 [[CSS-in-JS|CSS-in-JS]]와 같은 현대적인 스타일링 기법과 결합하여 유지보수성을 극대화합니다.
|
||||
## 매 한 줄
|
||||
> **"매 CSS variables × design tokens × runtime swap 의 zero-flash theming"**. 매 다크 모드는 단순 색상 toggle이 아닌, design token system의 multi-channel orchestration. 2026 표준은 `light-dark()` CSS function + `prefers-color-scheme` + system token + brand override 의 4-layer cascade.
|
||||
|
||||
## 📖 Core 소스 Content
|
||||
* **디자인 토큰을 활용한 테마 기반 설계:** 다크 모드 및 다중 브랜드 테마를 구축하는 핵심은 디자인 토큰을 활용하는 것입니다[1]. 색상이나 간격 등의 원시 값을 시맨틱 토큰(예: `--color-primary`)으로 추상화하면, 테마가 바뀔 때 시맨틱 토큰 값만 교체(스와핑)하여 전체 시스템에 새로운 테마를 쉽게 적용할 수 있습니다[2-4]. [[Style Dictionary|Style Dictionary]]와 같은 빌드 시스템을 사용하면 기본 테마를 공유하면서 특정 브랜드에 필요한 부분만 덮어쓰는(override) 방식으로 다중 브랜드 테마를 효율적으로 관리할 수 있습니다[5].
|
||||
* **CSS-in-JS 기반의 동적 런타임 테마링:** [[styled-components|styled-components]]나 Emotion 같은 CSS-in-JS 라이브러리는 내장된 테마 제공자(Theme Provider)를 지원하여 라이트/다크 모드나 고객사 브랜딩과 같은 다중 시각적 테마 구현에 매우 강력합니다[6]. 런타임에 테마를 동적으로 변경해야 하는 복잡한 요구사항이 있을 경우 원활하고 매끄러운 개발자 경험을 제공합니다[7].
|
||||
* **CSS 사용자 정의 속성(Variables)과 하이브리드 접근법:** 여러 테마를 효과적으로 관리하기 위해, 테마 변수는 글로벌 CSS 사용자 정의 속성으로 유지하고 개별 컴포넌트의 스타일은 CSS Modules를 사용하는 하이브리드 방식이 권장됩니다[8, 9]. 또한, Linaria와 같은 [[Zero-Runtime CSS-in-JS|Zero-Runtime CSS-in-JS]] 도구도 정적 CSS를 추출한 후 CSS 사용자 정의 속성을 활용하여 동적인 테마 속성을 처리합니다[10].
|
||||
* **미디어 쿼리(Media Queries)를 통한 시스템 테마 감지:** 미디어 쿼리는 화면 크기뿐만 아니라 라이트 모드나 다크 모드와 같은 사용자의 디바이스 환경 설정을 감지하고 처리하는 데 활용됩니다[11]. 성공적인 반응형 및 테마 디자인을 위해서는 라이트 모드와 다크 모드 양쪽에서 타이포그래피와 가독성이 유지되는지 확인해야 합니다[12].
|
||||
* **BEM 방법론을 활용한 화이트라벨(Whitelabel) 다중 테마:** 다수의 고객사 브랜드를 지원해야 하는 화이트라벨 앱의 경우, UI 라이브러리와 앱 간의 스타일 계약으로 BEM 구조를 사용하여, 필요한 테마 CSS만 선택적으로 로드하고 덮어쓰는 방식을 채택해 확장성을 확보하기도 합니다[13, 14].
|
||||
## 매 핵심
|
||||
|
||||
## 🔗 지식 연결 (Graph)
|
||||
- **Related Topics:** 디자인 시스템(DesignSystems) 및 디자인 토큰(Design Tokens), CSS-in-JS와 동적 스타일링, CSS 사용자 정의 속성(CSS Custom Properties), 하이브리드 CSS 아키텍처
|
||||
- **Projects/Contexts:** 웹/모바일 크로스 플랫폼 테마 적용(Style Dictionary), 화이트라벨(Whitelabel) B2B 애플리케이션 스타일링, 대규모 디자인 시스템 테마 확장
|
||||
- **Contradictions/Notes:** CSS-in-JS(styled-components 등)는 런타임 테마 적용에 매우 직관적이고 유용하지만[6, 7], 런타임 성능 오버헤드와 React 서버 컴포넌트(RSC) 환경과의 비호환성 문제로 인해 최신 프론트엔드 아키텍처([[Next.js App Router|Next.js App Router]] 등)에서는 CSS 변수를 결합한 CSS Modules나 Tailwind, 혹은 Zero-runtime 도구([[vanilla-extract|vanilla-extract]] 등)를 사용하여 테마를 구현하는 것이 더 권장됩니다[15-17].
|
||||
### 매 4-Layer Token Architecture
|
||||
1. **Primitive tokens**: `--color-blue-500: oklch(60% 0.2 240)`.
|
||||
2. **Semantic tokens**: `--color-bg-primary` (theme-aware).
|
||||
3. **Component tokens**: `--button-bg = --color-action`.
|
||||
4. **Brand override**: `[data-brand="acme"] { --color-action: ... }`.
|
||||
|
||||
---
|
||||
*Last updated: 2026-04-26*
|
||||
### 매 SSR Flash 방지
|
||||
- Inline blocking script (head) 의 `localStorage` read → `<html data-theme="dark">` 의 set before paint.
|
||||
- Next.js: `next-themes` library 의 표준.
|
||||
- Cookie-based 의 SSR-aware (Next 15 RSC).
|
||||
|
||||
## 📖 구조화된 지식 (Synthesized Content)
|
||||
### 매 응용
|
||||
1. GitHub 의 `light/light-high-contrast/dark/dark-dimmed/dark-high-contrast` 의 5 modes.
|
||||
2. Stripe Dashboard 의 brand switcher (Atlas, Climate 등).
|
||||
3. Linear 의 theme + accent color picker.
|
||||
4. VS Code 의 theme marketplace (color-theme JSON).
|
||||
|
||||
**추출된 패턴:**
|
||||
> *(TODO)*
|
||||
## 💻 패턴
|
||||
|
||||
**세부 내용:**
|
||||
- *(TODO)*
|
||||
### 1. CSS `light-dark()` (2026 baseline)
|
||||
```css
|
||||
:root {
|
||||
color-scheme: light dark;
|
||||
--bg: light-dark(white, #0a0a0a);
|
||||
--fg: light-dark(#0a0a0a, white);
|
||||
--accent: light-dark(oklch(55% 0.2 250), oklch(70% 0.18 250));
|
||||
}
|
||||
|
||||
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
|
||||
|
||||
**언제 이 지식을 쓰는가:**
|
||||
- *(TODO)*
|
||||
|
||||
**언제 쓰면 안 되는가:**
|
||||
- *(TODO)*
|
||||
|
||||
## 🧪 검증 상태 (Validation)
|
||||
|
||||
- **정보 상태:** needs_review
|
||||
- **출처 신뢰도:** A
|
||||
- **검토 이유:** *(P-Reinforce Phase 1 자동 정규화. 본문 검증 필요.)*
|
||||
|
||||
## 🧬 중복 검사 (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="light"] { color-scheme: light; }
|
||||
[data-theme="dark"] { color-scheme: dark; }
|
||||
```
|
||||
|
||||
## 🤔 의사결정 기준 (Decision Criteria)
|
||||
### 2. Multi-brand token override
|
||||
```css
|
||||
:root[data-brand="default"] { --brand-primary: oklch(55% 0.2 250); }
|
||||
:root[data-brand="acme"] { --brand-primary: oklch(60% 0.22 30); }
|
||||
:root[data-brand="globex"] { --brand-primary: oklch(58% 0.25 140); }
|
||||
|
||||
**선택 A를 써야 할 때:**
|
||||
- *(TODO)*
|
||||
.btn-primary {
|
||||
background: var(--brand-primary);
|
||||
color: light-dark(white, black);
|
||||
}
|
||||
```
|
||||
|
||||
**선택 B를 써야 할 때:**
|
||||
- *(TODO)*
|
||||
### 3. No-flash inline script (Next.js layout.tsx)
|
||||
```tsx
|
||||
const themeScript = `
|
||||
(function() {
|
||||
try {
|
||||
const saved = localStorage.getItem('theme');
|
||||
const sys = matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light';
|
||||
const theme = saved || sys;
|
||||
document.documentElement.dataset.theme = theme;
|
||||
document.documentElement.style.colorScheme = theme;
|
||||
} catch (e) {}
|
||||
})();
|
||||
`;
|
||||
|
||||
**기본값:**
|
||||
> *(TODO)*
|
||||
export default function RootLayout({ children }: { children: React.ReactNode }) {
|
||||
return (
|
||||
<html lang="ko" suppressHydrationWarning>
|
||||
<head>
|
||||
<script dangerouslySetInnerHTML={{ __html: themeScript }} />
|
||||
</head>
|
||||
<body>{children}</body>
|
||||
</html>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
## ❌ 안티패턴 (Anti-Patterns)
|
||||
### 4. React Theme Provider (next-themes 스타일)
|
||||
```tsx
|
||||
'use client';
|
||||
import { createContext, useContext, useEffect, useState } from 'react';
|
||||
|
||||
- **[안티패턴]:** *(TODO: 무엇을 하면 안 되는가 + 이유 + 대신 무엇을)*
|
||||
type Theme = 'light' | 'dark' | 'system';
|
||||
const ThemeCtx = createContext<{ theme: Theme; setTheme: (t: Theme) => void }>(null!);
|
||||
|
||||
export function ThemeProvider({ children }: { children: React.ReactNode }) {
|
||||
const [theme, setThemeState] = useState<Theme>('system');
|
||||
|
||||
useEffect(() => {
|
||||
const saved = (localStorage.getItem('theme') as Theme) || 'system';
|
||||
setThemeState(saved);
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
const resolved = theme === 'system'
|
||||
? (matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light')
|
||||
: theme;
|
||||
document.documentElement.dataset.theme = resolved;
|
||||
document.documentElement.style.colorScheme = resolved;
|
||||
}, [theme]);
|
||||
|
||||
const setTheme = (t: Theme) => {
|
||||
localStorage.setItem('theme', t);
|
||||
setThemeState(t);
|
||||
};
|
||||
|
||||
return <ThemeCtx.Provider value={{ theme, setTheme }}>{children}</ThemeCtx.Provider>;
|
||||
}
|
||||
|
||||
export const useTheme = () => useContext(ThemeCtx);
|
||||
```
|
||||
|
||||
### 5. Brand context + dynamic token injection
|
||||
```tsx
|
||||
'use client';
|
||||
import { useEffect } from 'react';
|
||||
|
||||
export function BrandProvider({ brand, children }: { brand: 'acme' | 'globex'; children: React.ReactNode }) {
|
||||
useEffect(() => {
|
||||
document.documentElement.dataset.brand = brand;
|
||||
}, [brand]);
|
||||
return <>{children}</>;
|
||||
}
|
||||
```
|
||||
|
||||
### 6. Tailwind v4 + design tokens
|
||||
```css
|
||||
/* app/globals.css */
|
||||
@import "tailwindcss";
|
||||
|
||||
@theme {
|
||||
--color-bg: light-dark(white, #0a0a0a);
|
||||
--color-fg: light-dark(#0a0a0a, white);
|
||||
--color-brand: var(--brand-primary, oklch(55% 0.2 250));
|
||||
}
|
||||
```
|
||||
|
||||
```tsx
|
||||
<button className="bg-brand text-bg">Click</button>
|
||||
```
|
||||
|
||||
### 7. Image / asset variants (theme-aware)
|
||||
```tsx
|
||||
import Image from 'next/image';
|
||||
import { useTheme } from '@/lib/theme';
|
||||
|
||||
export function Logo() {
|
||||
const { theme } = useTheme();
|
||||
return (
|
||||
<picture>
|
||||
<source srcSet="/logo-dark.svg" media="(prefers-color-scheme: dark)" />
|
||||
<img src="/logo-light.svg" alt="Logo" />
|
||||
</picture>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
### 8. View Transitions API (smooth theme swap)
|
||||
```ts
|
||||
async function toggleTheme(next: 'light' | 'dark') {
|
||||
if (!document.startViewTransition) {
|
||||
document.documentElement.dataset.theme = next;
|
||||
return;
|
||||
}
|
||||
await document.startViewTransition(() => {
|
||||
document.documentElement.dataset.theme = next;
|
||||
}).ready;
|
||||
}
|
||||
```
|
||||
|
||||
```css
|
||||
::view-transition-old(root),
|
||||
::view-transition-new(root) {
|
||||
animation-duration: 200ms;
|
||||
}
|
||||
```
|
||||
|
||||
### 9. SSR cookie-based theme (Next 15 RSC)
|
||||
```tsx
|
||||
// app/layout.tsx (server)
|
||||
import { cookies } from 'next/headers';
|
||||
|
||||
export default async function Layout({ children }) {
|
||||
const theme = (await cookies()).get('theme')?.value ?? 'light';
|
||||
return <html data-theme={theme}>{children}</html>;
|
||||
}
|
||||
```
|
||||
|
||||
## 매 결정 기준
|
||||
| 상황 | Approach |
|
||||
|---|---|
|
||||
| 단일 브랜드 + dark mode | CSS `light-dark()` + `prefers-color-scheme` |
|
||||
| 다중 브랜드 SaaS | `data-brand` attribute + token override |
|
||||
| SSR Next.js | next-themes OR cookie-based RSC |
|
||||
| Tailwind v4 | `@theme` + CSS vars |
|
||||
| Smooth transition | View Transitions API |
|
||||
| Legacy browser | Class-based (`.dark`) + localStorage |
|
||||
|
||||
**기본값**: CSS `light-dark()` + `data-theme` + `data-brand` + cookie SSR + next-themes.
|
||||
|
||||
## 🔗 Graph
|
||||
- 부모: [[Design_Systems]] · [[CSS_Variables]]
|
||||
- 변형: [[Design_Tokens]] · [[White_Label_Architecture]]
|
||||
- 응용: [[Tailwind_v4]] · [[Styled_Components_v6]] · [[CSS_Modules]]
|
||||
- Adjacent: [[Accessibility_Color_Contrast]] · [[OKLCH_Color]] · [[View_Transitions_API]]
|
||||
|
||||
## 🤖 LLM 활용
|
||||
**언제**: token naming convention 제안, contrast ratio audit, brand palette 생성 (OKLCH 기반).
|
||||
**언제 X**: 최종 brand color decision (디자이너), accessibility AA/AAA 의 자동 보장은 X.
|
||||
|
||||
## ❌ 안티패턴
|
||||
- **No-flash 미구현**: hydration 후 theme 적용 → FOUC.
|
||||
- **Hardcoded hex**: design token 의 bypass — multi-brand 의 X.
|
||||
- **JS-only theming**: CSS-only 의 fallback 없으면 SSR flash.
|
||||
- **Inverted contrast**: 다크 모드의 단순 색상 invert — semantic hierarchy 의 break.
|
||||
- **`!important` overuse**: token cascade 의 collapse.
|
||||
- **`localStorage` SSR access**: hydration mismatch — `useEffect`로 lazy.
|
||||
|
||||
## 🧪 검증 / 중복
|
||||
- Verified (web.dev color-scheme guide, MDN `light-dark()`, next-themes docs).
|
||||
- 신뢰도 A.
|
||||
|
||||
## 🕓 Changelog
|
||||
| 날짜 | 변경 |
|
||||
|---|---|
|
||||
| 2026-05-08 | Phase 1 |
|
||||
| 2026-05-10 | Manual cleanup — dark mode + multi-brand theming full content |
|
||||
|
||||
Reference in New Issue
Block a user