/** * 디자인 토큰 그룹 — "색·모서리 한 세트"를 이름 붙여 저장하고 통째로 갈아끼운다. * * 배리에이션 레지스트리가 "레이아웃의 단일 출처"라면, 여기는 "색의 단일 출처"다. * 쇼케이스에서 그룹을 바꾸면 가운데 미리보기 전체가 그 그룹으로 다시 그려진다. * * ★ 내장 그룹은 업종 템플릿(INDUSTRY_CONFIGS[*].templates)에서 그대로 끌어온다 — * 쇼케이스용으로 색을 따로 적어두면 실제 템플릿과 갈라져서, 여기서 예뻐도 캔버스에선 다르다. */ import type {IndustryType, TemplateItem} from '@o2o/shared'; import {INDUSTRY_CONFIGS} from '@/data/industryData'; import {derivePalette} from './palette'; export type TokenColors = TemplateItem['colors']; /** * 면(surface) 토큰 — **화면 면적의 대부분**을 차지하는 색이다. * * ★ 색 6개(TemplateItem.colors)만으로는 팔레트를 바꿔도 인상이 안 바뀐다. * 섹션 바탕과 카드 면이 하드코딩돼 있었기 때문이다. 그걸 여기로 끌어냈다. * `white` 톤은 일부러 진짜 흰색으로 남긴다 — surface/surfaceAlt 와 함께 세 단계가 있어야 * 섹션이 서로 구분되는 리듬이 생긴다. */ export interface TokenSurfaces { /** 섹션 기본 바탕(paper 톤). */ surface: string; /** 섹션 대체 바탕(tint 톤) — 위아래 섹션과 다르게 보이게 하는 색. */ surfaceAlt: string; /** 어두운 섹션(dark 톤). 흰 글씨를 얹는다. */ inverse: string; /** 카드·표 테두리. */ border: string; } export interface TokenFonts { heading: string; body: string; } /** * 고를 수 있는 서체. * * ★ 새 폰트를 내려받지 않는다 — 전부 이미 있는 것(Pretendard self-host)이나 * OS 기본 폰트로만 스택을 짠다. 미리보기 하나 때문에 네트워크를 타면 안 된다. */ export const FONT_PRESETS: {id: string; label: string; stack: string}[] = [ {id: 'sans', label: '고딕', stack: "'Pretendard Variable', 'Noto Sans KR', system-ui, sans-serif"}, {id: 'serif', label: '명조', stack: "'Noto Serif KR', 'Batang', 'Times New Roman', serif"}, {id: 'system', label: '시스템', stack: "system-ui, -apple-system, 'Apple SD Gothic Neo', sans-serif"}, {id: 'mono', label: '모노', stack: "'JetBrains Mono', Consolas, ui-monospace, monospace"}, ]; const FONT_SANS = FONT_PRESETS[0].stack; const FONT_SERIF = FONT_PRESETS[1].stack; /** 스택 문자열 → 프리셋 id(고르는 UI 가 현재 값을 표시할 때 쓴다). */ export function fontPresetId(stack: string): string { return FONT_PRESETS.find((f) => f.stack === stack)?.id ?? 'sans'; } export interface TokenGroup { id: string; name: string; description: string; colors: TokenColors; /** 모서리 반경(px). --tpl-radius 로 내려간다. */ radius: number; /** 제목·본문 서체. CSS font-family 스택을 그대로 담는다(--tpl-font-* 로 내려간다). */ fonts: TokenFonts; /** 섹션 바탕·카드 면·테두리. 팔레트 인상을 좌우하는 쪽은 사실 이쪽이다. */ surfaces: TokenSurfaces; /** 내장 그룹은 수정·삭제 대신 "복제해서 편집" 만 된다. */ builtin?: boolean; } export const TOKEN_COLOR_KEYS: {key: keyof TokenColors; label: string; hint: string}[] = [ {key: 'primary', label: 'Primary', hint: '예약·문의 버튼처럼 누르게 만드는 색'}, {key: 'secondary', label: 'Secondary', hint: '본문 보조 텍스트'}, {key: 'bg', label: 'Background', hint: '페이지 바탕'}, {key: 'card', label: 'Card', hint: '카드·패널 바탕'}, {key: 'text', label: 'Text', hint: '제목·본문 기본색'}, {key: 'accent', label: 'Accent', hint: '배지·강조 포인트'}, ]; const STORAGE_KEY = 'o2o.dev.tokenGroups'; /** * colorhunt 인기 팔레트에서 고른 것들. * * ★ 아무 팔레트나 쓰면 안 된다 — 웹사이트로 쓰려면 최소 조건이 있다: * ① 아주 밝은 색(바탕용) ② 흰 글씨를 얹을 수 있는 어두운 색(버튼·제목용) * ③ 채도 있는 포인트 색. 파스텔만 있는 팔레트는 글자가 안 읽힌다. * 여기 있는 건 그 조건으로 걸러낸 것들이다. */ const COLORHUNT_PALETTES: {name: string; hexes: string[]}[] = [ {name: '네이비 & 샌드', hexes: ['#222831', '#393e46', '#948979', '#dfd0b8']}, {name: '블루 그라데이션', hexes: ['#e3f2fd', '#90caf9', '#2196f3', '#0d47a1']}, {name: '바다와 모래', hexes: ['#3368a0', '#66a3bf', '#c8dfdb', '#f2efe7']}, {name: '포레스트 크림', hexes: ['#1d4533', '#f7eae0', '#f9d2ba', '#5e3122']}, {name: '크림 & 체리', hexes: ['#fff7eb', '#f9f0e0', '#a2ab73', '#cc3a63']}, {name: '모카 & 오렌지', hexes: ['#524646', '#a8a492', '#fcf2e5', '#ec5b38']}, {name: '선셋 테라코타', hexes: ['#fef2a0', '#f3cd97', '#e98b50', '#bc4f4f']}, {name: '틸 & 앰버', hexes: ['#007979', '#24b1b1', '#ffe2af', '#e37434']}, {name: '차콜 플럼', hexes: ['#2c2c2c', '#853953', '#612d53', '#f3f4f4']}, {name: '네이비 골드', hexes: ['#133458', '#838921', '#d99b21', '#faf7bb']}, {name: '올리브 & 오렌지', hexes: ['#2e2910', '#2c5745', '#ebe3a7', '#eb7d00']}, ]; /** colorhunt 팔레트 → 내장 토큰 그룹. 유도 규칙은 붙여넣기와 완전히 같다(palette.ts). */ function paletteGroups(): TokenGroup[] { return COLORHUNT_PALETTES.flatMap(({name, hexes}) => { const d = derivePalette(hexes); if (!d) return []; return [ { id: `builtin:palette:${name}`, name: `팔레트 · ${name}`, description: hexes.join(' '), colors: { primary: d.primary, secondary: d.secondary, bg: d.bg, card: d.card, text: d.text, accent: d.accent, }, radius: 8, fonts: {heading: FONT_SANS, body: FONT_SANS}, surfaces: { surface: d.surface, surfaceAlt: d.surfaceAlt, inverse: d.inverse, border: d.border, }, builtin: true, }, ]; }); } /** 업종 템플릿에서 뽑아낸 내장 그룹. 실제 서비스가 쓰는 색 그대로다. */ export function builtinGroups(): TokenGroup[] { const out: TokenGroup[] = []; (Object.keys(INDUSTRY_CONFIGS) as IndustryType[]).forEach((industry) => { INDUSTRY_CONFIGS[industry].templates.forEach((t) => { out.push({ id: `builtin:${industry}:${t.id}`, name: `${INDUSTRY_CONFIGS[industry].name} · ${t.name}`, description: t.description, colors: {...t.colors}, radius: 8, // 사진 중심 템플릿은 제목을 명조로 — 기존 캔버스의 serif-title 과 같은 인상이다. fonts: {heading: t.tone === 'photo' ? FONT_SERIF : FONT_SANS, body: FONT_SANS}, // 템플릿이 이미 갖고 있던 bg·card 를 섹션 바탕으로 쓴다 — // 그래야 템플릿을 바꿀 때 버튼 색만이 아니라 화면 전체가 바뀐다. surfaces: { surface: t.colors.bg, surfaceAlt: t.colors.card, inverse: '#1c1917', border: t.colors.secondary, }, builtin: true, }); }); }); // ★ 팔레트를 앞에 둔다 — 색을 고르러 온 사람이 제일 먼저 보는 게 팔레트여야 한다. return [...paletteGroups(), ...out]; } /** 저장해 둔 커스텀 그룹. 깨진 값이 들어 있으면 조용히 버린다 — 개발 도구가 흰 화면이 되면 안 된다. */ export function loadCustomGroups(): TokenGroup[] { try { const raw = localStorage.getItem(STORAGE_KEY); if (!raw) return []; const parsed: unknown = JSON.parse(raw); if (!Array.isArray(parsed)) return []; // ★ 폰트가 없던 시절에 저장된 그룹이 있다 — 없으면 기본값으로 채운다(그 항목만 버리면 사용자 작업이 날아간다). return parsed.filter(isTokenGroup).map((g) => ({ ...g, radius: typeof g.radius === 'number' ? g.radius : 8, fonts: { heading: g.fonts?.heading || FONT_SANS, body: g.fonts?.body || FONT_SANS, }, surfaces: { surface: g.surfaces?.surface || g.colors.bg, surfaceAlt: g.surfaces?.surfaceAlt || g.colors.card, inverse: g.surfaces?.inverse || '#1c1917', border: g.surfaces?.border || g.colors.secondary, }, builtin: false, })); } catch { return []; } } function isTokenGroup(value: unknown): value is TokenGroup { if (!value || typeof value !== 'object') return false; const g = value as Partial; if (typeof g.id !== 'string' || typeof g.name !== 'string') return false; if (!g.colors || typeof g.colors !== 'object') return false; return TOKEN_COLOR_KEYS.every(({key}) => typeof g.colors?.[key] === 'string'); } function persist(groups: TokenGroup[]) { try { localStorage.setItem(STORAGE_KEY, JSON.stringify(groups)); } catch { // 저장 실패(시크릿 모드·용량 초과)해도 화면은 계속 돈다. } } /** 저장(같은 id 면 덮어쓴다). 저장 후 전체 커스텀 목록을 돌려준다. */ export function saveCustomGroup(group: TokenGroup): TokenGroup[] { const next = loadCustomGroups().filter((g) => g.id !== group.id); next.push({...group, builtin: false}); persist(next); return next; } export function deleteCustomGroup(id: string): TokenGroup[] { const next = loadCustomGroups().filter((g) => g.id !== id); persist(next); return next; } /** 편집 시작점. 내장 그룹을 고른 채로 색을 만지면 이 함수로 복제본을 만든다. */ export function duplicateGroup(source: TokenGroup, name: string): TokenGroup { return { id: `custom:${Date.now().toString(36)}`, name, description: `${source.name} 에서 복제`, colors: {...source.colors}, radius: source.radius, fonts: {...source.fonts}, surfaces: {...source.surfaces}, builtin: false, }; } /** * 내장 그룹을 만지는 순간 자동으로 생기는 편집본. * * ★ id 를 원본에서 결정론적으로 만든다 — 색상 피커는 드래그하는 동안 onChange 가 * 연달아 터지는데, 매번 새 id 를 뽑으면 복사본이 수십 개 쌓인다. * 같은 내장 그룹을 다시 편집하면 같은 편집본을 이어서 고치게 된다. */ export function autoForkOf(source: TokenGroup): TokenGroup { return { id: `custom:edit:${source.id}`, name: `${source.name} 편집본`, description: `${source.name} 를 편집한 사본`, colors: {...source.colors}, radius: source.radius, fonts: {...source.fonts}, surfaces: {...source.surfaces}, builtin: false, }; } /** * 토큰 그룹을 캔버스가 읽는 모양(TemplateItem)으로 바꾼다. * * 배리에이션들은 `template.colors` 로 색을 읽으므로, 그룹을 통째로 갈아끼우려면 * 새 TemplateItem 을 만들어 props 로 내려보내는 게 유일한 경로다. */ export function asTemplate(group: TokenGroup, base: TemplateItem): TemplateItem { return {...base, colors: {...group.colors}}; } /** 미리보기 프레임에 씌울 CSS 변수. 캔버스(CanvasView)와 같은 --tpl-* 이름을 쓴다. */ export function tokenCssVars(group: TokenGroup): Record { return { '--tpl-primary': group.colors.primary, '--tpl-secondary': group.colors.secondary, '--tpl-bg': group.colors.bg, '--tpl-card': group.colors.card, '--tpl-text': group.colors.text, '--tpl-accent': group.colors.accent, '--tpl-radius': `${group.radius}px`, '--tpl-font-heading': group.fonts.heading, '--tpl-font-body': group.fonts.body, '--tpl-surface': group.surfaces.surface, '--tpl-surface-alt': group.surfaces.surfaceAlt, '--tpl-inverse': group.surfaces.inverse, '--tpl-border': group.surfaces.border, }; } /** * `template.colors` 를 실제로 읽는 배리에이션 목록. * * ★ 나머지는 stone-* 나 #hex 로 색을 박아 두어서 **토큰 그룹을 바꿔도 안 변한다.** * 쇼케이스가 이걸 배지로 표시해서, 토큰을 바꿨는데 화면이 그대로인 걸 * "버그" 로 오해하지 않게 한다. * * 목록 갱신: * grep -rln "template.colors" src/features/builder/canvas/variants */ export const TOKEN_AWARE_VARIANT_IDS = new Set([ 'hero.editorial', 'hero.split', 'hero.full-bleed', 'hero.type-only', 'intro.story', 'intro.centered', 'intro.side-by-side', 'info.table', 'info.cards', 'info.inline', 'photos.grid', 'photos.masonry', 'photos.carousel', 'photos.with-videos', 'map.detailed', 'map.compact', 'local.full', 'local.tabs', 'local.compact', 'faq.accordion', 'faq.open-list', 'faq.two-column', 'rooms.carousel', 'rooms.grid', 'rooms.list', 'rules.list', 'rules.cards', 'booking.card', 'booking.banner', 'menu.list', 'menu.grid', 'menu.price-table', 'space.zones', 'space.list', 'inquiry.cta', 'inquiry.form', 'programs.cards', 'programs.table', 'exhibition.gallery', 'exhibition.notice', ]);