이름: solution/front → solution/frontend

`backend` 옆에 `front` 가 있을 이유가 없었다. negosium 의 negodata/front 를 그대로
베꼈고 그게 왜 front 인지는 따져보지 않았다 — 근거 없이 들여온 이름이라 바로잡는다.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019uYhHQdssRubirPirrdJJC
This commit is contained in:
minaChoiandClaude Opus 5 committed 2026-08-31 15:27:16 +09:00
1 parent 06f6438d9b
commit c85c577349
480 files changed
+22 -22

No files matched your search

@@ -0,0 +1,224 @@
/**
* 드래그 카로셀 — 마우스로 잡아끌어 넘기는 슬라이더.
*
* ★ 캔버스의 photos.carousel 은 `overflow-x-auto + snap` 이라 데스크톱 마우스로는 못 끈다
* (트랙패드 스크롤만 먹는다). 쇼케이스는 커서로 끌어야 하므로 여기서 따로 만든다.
*
* ★ 애니메이션 라이브러리(motion)의 drag 를 쓰지 않는다.
* 그쪽은 제스처 처리를 requestAnimationFrame 프레임 루프에 태우는데, **탭이 백그라운드면
* rAF 가 멈춰서 드래그가 아예 동작하지 않는다.** 자동화 브라우저(hidden 탭)에서 검증이
* 불가능해지는 것도 같은 이유다. 여기서는 pointermove 에서 transform 을 직접 쓰고,
* 놓았을 때의 스냅만 CSS transition 에 맡긴다 — rAF 없이도 돈다.
*/
import {useCallback, useEffect, useRef, useState, type PointerEvent as ReactPointerEvent, type ReactNode} from 'react';
import {ChevronLeft, ChevronRight} from 'lucide-react';
import {cn} from '@/lib/utils';
interface DragCarouselProps {
slides: ReactNode[];
index: number;
onIndexChange: (next: number) => void;
/** 아래 점 네비게이션. 슬라이드가 아주 많으면 끈다. */
showDots?: boolean;
label?: string;
className?: string;
}
/** 이만큼 끌면 넘긴다(컨테이너 너비 대비). 너무 작으면 살짝 흔들려도 넘어간다. */
const DRAG_RATIO = 0.2;
/** 짧게 튕겨도 넘어가게 하는 속도 임계(px/ms). */
const FLICK_VELOCITY = 0.5;
/** 양 끝에서 더 끌 때의 저항. 1 이면 끝에서도 그냥 끌려서 경계가 안 느껴진다. */
const EDGE_RESISTANCE = 0.35;
const SNAP_MS = 320;
export function DragCarousel({
slides,
index,
onIndexChange,
showDots = true,
label,
className,
}: DragCarouselProps) {
const viewportRef = useRef<HTMLDivElement>(null);
const trackRef = useRef<HTMLDivElement>(null);
const [width, setWidth] = useState(0);
const [dragging, setDragging] = useState(false);
const drag = useRef({startX: 0, startTime: 0, dx: 0, active: false});
const count = slides.length;
// 너비는 창 크기·패널 접힘에 따라 바뀐다 — 측정값을 붙들고 있으면 슬라이드가 어긋난다.
useEffect(() => {
const el = viewportRef.current;
if (!el) return;
const ro = new ResizeObserver((entries) => {
const w = entries[0]?.contentRect.width;
if (typeof w === 'number') setWidth(w);
});
ro.observe(el);
setWidth(el.getBoundingClientRect().width);
return () => ro.disconnect();
}, []);
/** 트랙 위치를 직접 쓴다. 드래그 중에는 transition 을 꺼야 손가락을 따라온다. */
const paint = useCallback((offsetPx: number, animated: boolean) => {
const track = trackRef.current;
if (!track) return;
track.style.transition = animated ? `transform ${SNAP_MS}ms cubic-bezier(0.22, 1, 0.36, 1)` : 'none';
track.style.transform = `translate3d(${offsetPx}px, 0, 0)`;
}, []);
// index / width 가 바뀌면(바깥 목록 클릭 포함) 제자리로 스냅.
useEffect(() => {
paint(-index * width, true);
}, [index, width, paint]);
const settle = useCallback(
(next: number) => {
const clamped = Math.max(0, Math.min(count - 1, next));
// ★ 클램프돼서 index 가 그대로면 부모가 리렌더되지 않는다 —
// 그러면 끌어당긴 자리에 트랙이 멈춰 버리므로 여기서 직접 되돌린다.
paint(-clamped * width, true);
if (clamped !== index) onIndexChange(clamped);
},
[count, index, onIndexChange, paint, width],
);
const onPointerDown = (e: ReactPointerEvent<HTMLDivElement>) => {
if (count < 2 || e.button !== 0) return;
drag.current = {startX: e.clientX, startTime: e.timeStamp, dx: 0, active: true};
setDragging(true);
e.currentTarget.setPointerCapture(e.pointerId);
};
const onPointerMove = (e: ReactPointerEvent<HTMLDivElement>) => {
if (!drag.current.active) return;
let dx = e.clientX - drag.current.startX;
// 양 끝을 넘어가면 저항을 준다 — 끝이라는 게 손에 느껴져야 한다.
const atStart = index === 0 && dx > 0;
const atEnd = index === count - 1 && dx < 0;
if (atStart || atEnd) dx *= EDGE_RESISTANCE;
drag.current.dx = dx;
paint(-index * width + dx, false);
};
const endDrag = (e: ReactPointerEvent<HTMLDivElement>) => {
if (!drag.current.active) return;
const {dx, startTime} = drag.current;
drag.current.active = false;
setDragging(false);
if (e.currentTarget.hasPointerCapture(e.pointerId)) {
e.currentTarget.releasePointerCapture(e.pointerId);
}
const elapsed = Math.max(1, e.timeStamp - startTime);
const velocity = dx / elapsed; // px/ms
const threshold = width * DRAG_RATIO;
if (dx < -threshold || velocity < -FLICK_VELOCITY) settle(index + 1);
else if (dx > threshold || velocity > FLICK_VELOCITY) settle(index - 1);
else settle(index);
};
if (count === 0) return null;
return (
<div className={cn('flex flex-col gap-3', className)}>
<div
ref={viewportRef}
className="relative overflow-hidden"
role="group"
aria-roledescription="carousel"
aria-label={label}
tabIndex={0}
onKeyDown={(e) => {
if (e.key === 'ArrowRight') settle(index + 1);
if (e.key === 'ArrowLeft') settle(index - 1);
}}
>
<div
ref={trackRef}
onPointerDown={onPointerDown}
onPointerMove={onPointerMove}
onPointerUp={endDrag}
onPointerCancel={endDrag}
className={cn(
'flex touch-pan-y',
count > 1 && (dragging ? 'cursor-grabbing' : 'cursor-grab'),
)}
>
{slides.map((slide, i) => (
<div
key={i}
className="shrink-0 grow-0"
style={{width: width || '100%'}}
aria-hidden={i !== index}
>
{/* 드래그 중 내부 이미지가 잡히면 브라우저 기본 이미지 드래그와 싸운다. */}
<div className={cn('[&_img]:select-none', dragging && 'select-none [&_*]:pointer-events-none')}>
{slide}
</div>
</div>
))}
</div>
{count > 1 && (
<>
<CarouselArrow side="left" disabled={index === 0} onClick={() => settle(index - 1)} />
<CarouselArrow
side="right"
disabled={index === count - 1}
onClick={() => settle(index + 1)}
/>
</>
)}
</div>
{showDots && count > 1 && (
<div className="flex items-center justify-center gap-1.5">
{slides.map((_, i) => (
<button
key={i}
type="button"
aria-label={`${i + 1}번째로 이동`}
aria-current={i === index}
onClick={() => settle(i)}
className={cn(
'h-1.5 cursor-pointer rounded-full transition-all',
i === index ? 'w-5 bg-foreground' : 'w-1.5 bg-border hover:bg-muted-foreground',
)}
/>
))}
</div>
)}
</div>
);
}
function CarouselArrow({
side,
disabled,
onClick,
}: {
side: 'left' | 'right';
disabled: boolean;
onClick: () => void;
}) {
const Icon = side === 'left' ? ChevronLeft : ChevronRight;
return (
<button
type="button"
onClick={onClick}
disabled={disabled}
aria-label={side === 'left' ? '이전' : '다음'}
className={cn(
'absolute top-1/2 z-20 -translate-y-1/2 rounded-full border border-border bg-card/90 p-1.5 shadow-sm backdrop-blur-sm transition',
'disabled:pointer-events-none disabled:opacity-0',
'cursor-pointer hover:bg-card',
side === 'left' ? 'left-2' : 'right-2',
)}
>
<Icon className="size-4" />
</button>
);
}
@@ -0,0 +1,70 @@
/**
* 쇼케이스용 목업 props — 배리에이션 하나를 스토어 없이 그리기 위한 최소 입력.
*
* 캔버스(CanvasView)는 빌더 스토어에서 props 를 모으지만, 쇼케이스는 스토어를 건드리면 안 된다 —
* 개발자가 색을 구경하다가 사장님이 편집 중이던 사이트 상태를 바꿔 버리면 곤란하다.
* 그래서 여기서 업종 기본 데이터로 같은 모양의 props 를 직접 만든다.
*/
import type {IndustryType, SectionItem, TemplateItem} from '@o2o/shared';
import {INDUSTRY_CONFIGS} from '@/data/industryData';
import type {SectionRenderProps} from '@/features/builder/canvas/types';
import type {SectionVariant} from '@/features/builder/canvas/types';
import {asTemplate, type TokenGroup} from './tokenGroups';
/** 업종의 첫 템플릿 — 토큰 그룹이 색만 갈아끼울 바탕이 된다. */
export function baseTemplate(industry: IndustryType): TemplateItem {
return INDUSTRY_CONFIGS[industry].templates[0];
}
/**
* 섹션 메타를 만든다.
*
* 업종 기본 섹션 목록에 같은 타입이 있으면 그걸 쓴다(이름·잠금 상태가 실제와 같아진다).
* 없으면 최소 형태로 지어낸다 — 그 업종 메뉴엔 없지만 배리에이션은 존재하는 경우다.
*/
function sectionFor(sectionType: string, industry: IndustryType, variantId: string): SectionItem {
const found = INDUSTRY_CONFIGS[industry].sections.find((s) => s.type === sectionType);
if (found) return {...found, isEnabled: true, variantId};
return {
id: sectionType,
type: sectionType,
name: sectionType,
isLocked: false,
isEnabled: true,
variantId,
};
}
/**
* 쇼케이스 전용 자리표시 값.
*
* ★ 실제 업소처럼 보이는 값을 쓰지 않는다. 예전에는 업종 시드('달빛스테이 제주',
* '포레스트 힐 로스터스')를 그대로 썼는데, 그 값들이 캔버스 배리에이션에도
* 폴백으로 새어 사장님 화면에 남의 가게가 떴다. 그래서 시드에서 콘텐츠를 걷어냈고,
* 쇼케이스는 한눈에 가짜인 값을 **여기서만** 들고 간다 — 이 파일은 DEV 라우트
* (`/dev/showcase`, app/router.tsx)에서만 로드된다.
*/
const SHOWCASE_VALUES = {
storeName: '샘플 상호',
location: '샘플 지역',
infoFields: [],
photos: [],
};
/** 배리에이션 하나를 그릴 props 한 벌. */
export function mockPropsFor(
sectionType: string,
variant: SectionVariant,
industry: IndustryType,
group: TokenGroup,
): SectionRenderProps {
return {
section: sectionFor(sectionType, industry, variant.id),
industryId: industry,
...SHOWCASE_VALUES,
template: asTemplate(group, baseTemplate(industry)),
// 쇼케이스는 "고르는" 화면이 아니다 — 선택 링·배지가 뜨면 디자인을 가린다.
isSelected: false,
onSelect: () => {},
};
}
@@ -0,0 +1,166 @@
import {mix} from '@/lib/color';
/**
* 팔레트 → 디자인 토큰 유도.
*
* colorhunt 처럼 **색 4개**만 주어졌을 때, 그걸 화면 전체를 바꿀 수 있는 토큰 한 벌로 편다.
*
* ★ 색을 역할에 배정하는 규칙이 이 파일의 전부다. 아무 색이나 primary 로 쓰면
* 흰 글씨가 안 보이는 버튼이 나온다 — primary 는 "흰 글씨를 얹을 수 있는 어두운 색" 이라는
* 계약을 지켜야 한다(배리에이션들이 그 전제로 쓰고 있다).
*/
/** `#rrggbb` 로 정규화. 못 읽으면 null. */
function normalizeHex(raw: string): string | null {
const m = raw.trim().replace(/^#/, '');
if (/^[0-9a-fA-F]{3}$/.test(m)) {
return `#${m[0]}${m[0]}${m[1]}${m[1]}${m[2]}${m[2]}`.toLowerCase();
}
return /^[0-9a-fA-F]{6}$/.test(m) ? `#${m.toLowerCase()}` : null;
}
function rgb(hex: string): [number, number, number] {
const n = parseInt(hex.slice(1), 16);
return [(n >> 16) & 255, (n >> 8) & 255, n & 255];
}
/** 상대 휘도(WCAG). 0=검정 1=흰색. 대비 판단의 기준. */
export function luminance(hex: string): number {
const [r, g, b] = rgb(hex).map((v) => {
const c = v / 255;
return c <= 0.03928 ? c / 12.92 : ((c + 0.055) / 1.055) ** 2.4;
});
return 0.2126 * r + 0.7152 * g + 0.0722 * b;
}
/** HSL 채도. 회색인지 색이 있는지 가른다. */
function saturation(hex: string): number {
const [r, g, b] = rgb(hex).map((v) => v / 255);
const max = Math.max(r, g, b);
const min = Math.min(r, g, b);
if (max === min) return 0;
const l = (max + min) / 2;
return l > 0.5 ? (max - min) / (2 - max - min) : (max - min) / (max + min);
}
/** 본문 크기 글자의 최소 대비(WCAG AA). */
const MIN_CONTRAST = 4.5;
/** WCAG 명도 대비비. 4.5 이상이면 본문 크기 글자가 읽힌다. */
export function contrast(a: string, b: string): number {
const [hi, lo] = luminance(a) > luminance(b) ? [luminance(a), luminance(b)] : [luminance(b), luminance(a)];
return (hi + 0.05) / (lo + 0.05);
}
/** 흰 글씨를 얹을 수 있는가. primary·inverse 가 지켜야 하는 조건이다. */
export function carriesWhiteText(hex: string): boolean {
return contrast(hex, '#ffffff') >= MIN_CONTRAST;
}
/**
* 대비가 모자라면 될 때까지 어둡게(또는 밝게) 민다.
*
* ★ 팔레트 사이트의 색은 '예쁜 조합'이지 '읽히는 조합'이 아니다.
* 고른 색을 그대로 쓰면 버튼 위 흰 글씨가 안 보이는 팔레트가 절반이다 —
* 여기서 최소 대비를 보장한다. 색상(hue)은 유지되고 밝기만 움직인다.
*/
function ensureContrast(color: string, against: string, min = MIN_CONTRAST): string {
const toward = luminance(against) > 0.5 ? '#000000' : '#ffffff';
let out = color;
for (let i = 0; i < 24 && contrast(out, against) < min; i++) {
out = mix(out, toward, 0.08);
}
return out;
}
/**
* 입력에서 hex 를 뽑는다.
*
* 받아들이는 것:
* - colorhunt URL `https://colorhunt.co/palette/222831393e46948979dfd0b8`
* - `#222831 #393E46 #948979 #DFD0B8` (쉼표·줄바꿈·공백 아무거나)
* - `222831,393e46,...`
*/
export function parsePalette(input: string): string[] {
const text = input.trim();
// colorhunt 는 '#' 없이 6자리씩 이어 붙인다(보통 4색=24자).
const packed = text.match(/colorhunt\.co\/palette\/([0-9a-fA-F]{12,32})/);
if (packed) {
const body = packed[1];
const out: string[] = [];
for (let i = 0; i + 6 <= body.length; i += 6) {
const hex = normalizeHex(body.slice(i, i + 6));
if (hex) out.push(hex);
}
return out;
}
const tokens = text.split(/[\s,;|]+/).filter(Boolean);
return tokens.map(normalizeHex).filter((h): h is string => h !== null);
}
export interface DerivedPalette {
primary: string;
secondary: string;
bg: string;
card: string;
text: string;
accent: string;
surface: string;
surfaceAlt: string;
inverse: string;
border: string;
}
/**
* 색 목록 → 토큰 한 벌.
*
* 배정 규칙:
* 밝은 순으로 세워서 밝은 쪽은 바탕(surface/card), 어두운 쪽은 글자(text/inverse).
* primary 는 **어두운 것 중 가장 색이 있는 것** — 흰 글씨 계약을 지키기 위해서다.
* accent 는 밝기와 무관하게 가장 색이 진한 것(배경으로는 안 쓰이므로 자유롭다).
*/
export function derivePalette(input: string[]): DerivedPalette | null {
const hexes = [...new Set(input)];
if (hexes.length < 2) return null;
// 밝은 것부터 어두운 것 순.
const byLight = [...hexes].sort((a, b) => luminance(b) - luminance(a));
const lightest = byLight[0];
const darkest = byLight[byLight.length - 1];
const second = byLight[1] ?? lightest;
// 보조 텍스트·테두리에 쓸 중간 색. 밝은 바탕 위에서 읽혀야 하므로
// 너무 밝으면(0.6 초과) 쓰지 않고 가장 어두운 색으로 떨어뜨린다.
const midCandidate = byLight[byLight.length - 2] ?? darkest;
const mid = luminance(midCandidate) > 0.6 ? darkest : midCandidate;
const accent = [...hexes].sort((a, b) => saturation(b) - saturation(a))[0];
// primary 는 '흰 글씨를 얹는 버튼 색'이다 — 밝기 어림짐작이 아니라 실제 대비로 고른다.
const bySat = [...hexes].sort((a, b) => saturation(b) - saturation(a));
const primaryBase = bySat.find(carriesWhiteText) ?? bySat[0] ?? darkest;
// 후보가 전부 밝으면(파스텔 팔레트) 대비가 찰 때까지 어둡게 민다.
const primary = ensureContrast(primaryBase, '#ffffff');
// ★ 팔레트 4색만으로는 '면 단계'가 부족하다 — 섹션 기본 / 살짝 어두운 면 / 카드 세 단계가
// 서로 구분돼야 섹션이 경계선 없이도 나뉜다. 가장 밝은 색을 기준으로 섞어서 만든다.
return {
// 섹션 기본 바탕(가장 흔한 톤). 팔레트의 가장 밝은 색을 그대로 쓴다.
bg: lightest,
// paper 톤 — 기본보다 아주 살짝 어둡게.
surface: mix(lightest, darkest, 0.06),
// tint 톤 — 두 번째로 밝은 색(팔레트가 2색뿐이면 조금 더 어둡게).
surfaceAlt: second === lightest ? mix(lightest, darkest, 0.12) : second,
// 카드는 바탕보다 밝아야 떠 보인다.
card: mix(lightest, '#ffffff', 0.65),
// 본문·보조 텍스트는 바탕 위에서 반드시 읽혀야 한다.
text: ensureContrast(darkest, lightest),
inverse: darkest,
secondary: ensureContrast(mid, lightest),
primary,
accent,
// ★ 테두리를 card 와 같게 두면 카드 경계가 사라진다 — 한 단계 어두운 중간색을 쓴다.
border: mid,
};
}
@@ -0,0 +1,342 @@
/**
* 디자인 토큰 그룹 — "색·모서리 한 세트"를 이름 붙여 저장하고 통째로 갈아끼운다.
*
* 배리에이션 레지스트리가 "레이아웃의 단일 출처"라면, 여기는 "색의 단일 출처"다.
* 쇼케이스에서 그룹을 바꾸면 가운데 미리보기 전체가 그 그룹으로 다시 그려진다.
*
* ★ 내장 그룹은 업종 템플릿(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<TokenGroup>;
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<string, string> {
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',
]);