이름: 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,220 @@
import {useState, type CSSProperties} from 'react';
import {Bed, Calendar, Home, MapPin, Monitor, Smartphone, Sparkles, Tablet} from 'lucide-react';
import type {SectionItem, ViewportMode} from '@o2o/shared';
import {publishUrlString, toSlug} from '@o2o/shared';
import {deriveSurfaces} from '@/lib/color';
import {cn} from '@/lib/utils';
import {useBuilderStore, useCurrentTemplate} from '@/stores/builder';
import {resolveVariant} from './canvas/registry';
// ★ 호스트를 상수로 박지 않는다. PublishModal 과 **다른 주소**를 보여주면 사장님은
// 미리보기에서 본 주소와 발행 후 안내받는 주소가 달라 어느 쪽이 진짜인지 알 수 없다.
// 같은 규칙(VITE_PUBLISH_HOST → 없으면 현재 호스트)을 쓴다.
const PUBLISH_HOST = import.meta.env.VITE_PUBLISH_HOST ?? window.location.host;
const VIEWPORT_FRAME: Record<ViewportMode, string> = {
pc: 'w-full max-w-5xl shadow-md',
tablet: 'w-[768px] max-w-full border-x border-border shadow-lg',
mobile: 'w-[390px] max-w-full overflow-hidden rounded-lg border-x border-border shadow-xl',
};
const VIEWPORT_TOOLBAR: {id: ViewportMode; label: string; icon: typeof Monitor}[] = [
{id: 'pc', label: 'PC (100%)', icon: Monitor},
{id: 'tablet', label: '태블릿 (768px)', icon: Tablet},
{id: 'mobile', label: '모바일 (390px)', icon: Smartphone},
];
const MOBILE_TABS = [
{key: 'home', label: '홈', anchor: 'canvas-section-hero', icon: Home},
{key: 'rooms', label: '객실', anchor: 'canvas-section-rooms', icon: Bed},
{key: 'guide', label: '가이드', anchor: 'canvas-section-local', icon: Sparkles},
{key: 'map', label: '위치', anchor: 'canvas-section-map', icon: MapPin},
];
export function CanvasView() {
const industry = useBuilderStore((s) => s.industry);
const storeName = useBuilderStore((s) => s.storeName);
const location = useBuilderStore((s) => s.location);
const weatherLocation = useBuilderStore((s) => s.weatherLocation);
const sections = useBuilderStore((s) => s.sections);
const infoFields = useBuilderStore((s) => s.infoFields);
const photos = useBuilderStore((s) => s.photos);
const selectedSectionId = useBuilderStore((s) => s.selectedSectionId);
const viewport = useBuilderStore((s) => s.viewport);
const isPreviewMode = useBuilderStore((s) => s.isPreviewMode);
const setViewport = useBuilderStore((s) => s.setViewport);
const selectSection = useBuilderStore((s) => s.selectSection);
const setRightTab = useBuilderStore((s) => s.setRightTab);
const template = useCurrentTemplate();
const [activeMobileTab, setActiveMobileTab] = useState('home');
const scrollToSection = (anchor: string, tabKey: string) => {
setActiveMobileTab(tabKey);
document.getElementById(anchor)?.scrollIntoView({behavior: 'smooth', block: 'start'});
};
// 템플릿 색은 CSS 변수로 내려보낸다 — 관리자 토큰(--primary 등)과 이름이 겹치지 않게 --tpl-* 접두어.
// ★ 면 토큰(--tpl-surface / -alt / inverse / border)은 템플릿 색에서 유도한다.
// 이걸 안 내려보내면 SectionFrame 이 폴백(고정 stone 색)으로 떨어져서,
// 템플릿을 바꿔도 화면 면적의 대부분이 그대로다 — 쇼케이스와 같은 식(lib/color.ts)을 쓴다.
const surfaces = deriveSurfaces(template.colors);
const themeVars = {
'--tpl-surface': surfaces.surface,
'--tpl-surface-alt': surfaces.surfaceAlt,
'--tpl-inverse': surfaces.inverse,
'--tpl-border': surfaces.border,
'--tpl-primary': template.colors.primary,
'--tpl-secondary': template.colors.secondary,
'--tpl-bg': template.colors.bg,
'--tpl-card': template.colors.card,
'--tpl-text': template.colors.text,
'--tpl-accent': template.colors.accent,
} as CSSProperties;
/**
* 섹션 하나를 그린다.
*
* 어떤 레이아웃으로 그릴지는 레지스트리가 정한다 — 여기에 switch 를 두면
* 배리에이션을 하나 추가할 때마다 이 파일을 같이 고쳐야 한다.
*/
const renderSection = (section: SectionItem) => {
if (!section.isEnabled) return null;
const variant = resolveVariant(section, industry);
// 아직 배리에이션이 없는 섹션 타입 — 캔버스를 깨뜨리지 않고 조용히 건너뛴다.
if (!variant) return null;
const {Component} = variant;
return (
<Component
key={section.id}
section={section}
industryId={industry}
storeName={storeName}
location={location}
weatherLocation={weatherLocation}
template={template}
infoFields={infoFields}
photos={photos}
isSelected={!isPreviewMode && selectedSectionId === section.id}
onSelect={() => {
selectSection(section.id);
setRightTab('content');
}}
/>
);
};
return (
<div className="relative flex h-full min-w-0 flex-1 flex-col overflow-hidden bg-muted">
{!isPreviewMode && (
<div className="z-10 flex h-10 min-w-0 select-none items-center justify-between gap-2 border-b border-border bg-card px-4 text-xs">
{/* ★ min-w-0 — 이 줄이 안 줄어들면 캔버스 칸 전체의 최소 너비가 올라가고,
그 여파로 오른쪽 패널이 화면 밖으로 밀린다(EditorLayout 주석 참조). */}
<div className="flex min-w-0 items-center gap-1.5">
<span className="hidden shrink-0 font-semibold md:inline">미리보기 해상도:</span>
<div className="flex shrink-0 items-center gap-0.5 rounded border border-border bg-muted p-0.5">
{VIEWPORT_TOOLBAR.map(({id, label, icon: Icon}) => (
<button
key={id}
type="button"
onClick={() => setViewport(id)}
aria-pressed={viewport === id}
className={cn(
'flex cursor-pointer items-center gap-1 rounded px-2.5 py-1 transition-colors',
viewport === id
? 'bg-card font-semibold text-foreground shadow-xs'
: 'text-muted-foreground hover:text-foreground',
)}
>
<Icon className="size-3.5" />
<span>{label}</span>
</button>
))}
</div>
</div>
<div className="hidden shrink-0 items-center gap-2 text-[11px] text-muted-foreground xl:flex">
<span className="inline-block size-2 rounded-full bg-success" />
<span>실시간 동기화 캔버스</span>
</div>
</div>
)}
<div className="flex flex-1 items-start justify-center overflow-y-auto bg-muted/70 p-2 sm:p-6">
<div
style={themeVars}
className={cn('site-canvas my-auto transition-all duration-300', VIEWPORT_FRAME[viewport])}
>
{viewport !== 'pc' && (
<div className="flex items-center justify-between bg-foreground px-4 py-2 font-mono text-[11px] text-background">
<span className="flex items-center gap-1.5">
<span className="inline-block size-2.5 rounded-full bg-red-500" />
<span className="inline-block size-2.5 rounded-full bg-amber-500" />
<span className="inline-block size-2.5 rounded-full bg-emerald-500" />
</span>
<span className="max-w-[200px] truncate opacity-70">
{publishUrlString(toSlug(storeName) || 'my-store', PUBLISH_HOST)}
</span>
<span className="text-[10px] opacity-70">{viewport.toUpperCase()}</span>
</div>
)}
{/* 섹션은 좌측 패널이 정한 순서 그대로 그린다. */}
<div className="divide-y divide-black/5">
{sections.map((section) => renderSection(section))}
</div>
<footer
className="border-t border-black/10 p-6 text-center text-xs"
style={{backgroundColor: template.colors.bg, color: template.colors.secondary}}
>
<div className="mx-auto max-w-4xl space-y-2">
<p className="font-bold" style={{color: template.colors.text}}>
{storeName}
</p>
<p className="text-[11px]">
{infoFields.find((f) => f.id === 'address')?.value || location}
</p>
<p className="pt-2 text-[10px] opacity-60">
© {new Date().getFullYear()} {storeName}. Powered by Web4Ai.
</p>
</div>
</footer>
{viewport === 'mobile' && (
<nav
aria-label="모바일 하단 내비게이션 미리보기"
className="sticky inset-x-0 bottom-0 z-30 flex items-center justify-around border-t border-black/10 bg-white/95 px-2 py-1.5 backdrop-blur-md"
>
{MOBILE_TABS.map(({key, label, anchor, icon: Icon}) => (
<button
key={key}
type="button"
onClick={() => scrollToSection(anchor, key)}
className={cn(
'flex cursor-pointer flex-col items-center justify-center rounded-lg px-2 py-1 transition-all',
activeMobileTab === key ? 'font-bold text-zinc-950' : 'text-zinc-500',
)}
>
<Icon className="size-4" />
<span className="mt-0.5 text-[10px]">{label}</span>
</button>
))}
<span
className="flex items-center gap-1 rounded-lg px-3 py-1.5 text-[11px] font-bold text-white"
style={{backgroundColor: template.colors.primary}}
>
<Calendar className="size-3.5" />
<span>예약하기</span>
</span>
</nav>
)}
</div>
</div>
</div>
);
}
@@ -0,0 +1,99 @@
import {Eye, Pencil, Send} from 'lucide-react';
import {Link} from 'react-router';
import {SiteStatus} from '@o2o/shared';
import {getAccessToken, useGetSite} from '@/api';
import {Badge} from '@/components/ui/badge';
import {Button} from '@/components/ui/button';
import {INDUSTRY_CONFIGS} from '@/data/industryData';
import {useBuilderStore, useUnverifiedFields} from '@/stores/builder';
export function EditorHeader() {
const industry = useBuilderStore((s) => s.industry);
const storeName = useBuilderStore((s) => s.storeName);
const isPreviewMode = useBuilderStore((s) => s.isPreviewMode);
const togglePreview = useBuilderStore((s) => s.togglePreview);
const openPublishModal = useBuilderStore((s) => s.openPublishModal);
const reset = useBuilderStore((s) => s.reset);
const placeId = useBuilderStore((s) => s.placeId);
const unverifiedCount = useUnverifiedFields().length;
/**
* 한 번이라도 발행했는가 — 버튼 문구가 [사이트 발행] 인지 [사이트 재발행] 인지를 가른다.
*
* ★ usePlaceSync 가 이미 읽는 같은 쿼리다(같은 키 → 같은 캐시). 여기서 다시 부른다고
* 요청이 한 번 더 나가지 않는다.
*/
const siteQuery = useGetSite(placeId ?? '', {
query: {enabled: Boolean(placeId) && Boolean(getAccessToken())},
});
const isRepublish = siteQuery.data?.site?.status === SiteStatus.PUBLISHED;
return (
<header className="z-30 flex h-14 shrink-0 select-none items-center justify-between border-b border-border bg-card px-4 sm:px-6">
<div className="flex min-w-0 items-center gap-3.5">
{/* ★ 실사업장을 편집 중이면 로고는 **아무 데도 가지 않는다.**
예전엔 사업장 목록(/places)으로 갔지만 그 화면은 내부 운영 앱(admin)으로 나갔다 —
여기 링크를 남기면 사장님 앱에서 404 이고, 내부 경로 이름이 사장님 번들에도 남는다.
reset() 을 부르지 않는 이유는 그대로다: 편집하던 가게를 떠나 데모 위저드로
떨어지면 사장님 눈에는 자기 가게가 사라진 것으로 보인다.
(사장님용 "내 사이트 관리"가 생기면 그때 그리로 잇는다 — ARCHITECTURE.md 4절) */}
{placeId ? (
<span className="group flex items-center gap-2">
<LogoMark />
</span>
) : (
<button
type="button"
onClick={reset}
title="처음으로 이동"
className="group flex cursor-pointer items-center gap-2"
>
<LogoMark />
</button>
)}
<span className="hidden h-3.5 w-px bg-border sm:block" />
<div className="flex min-w-0 items-center gap-2">
<span className="max-w-[140px] truncate text-xs font-semibold sm:max-w-[220px] sm:text-sm">
{storeName}
</span>
<Badge className="hidden sm:inline-flex">{INDUSTRY_CONFIGS[industry].name}</Badge>
{unverifiedCount > 0 && (
<Badge variant="warning" className="hidden sm:inline-flex">
확인 필요 {unverifiedCount}
</Badge>
)}
</div>
</div>
<div className="flex items-center gap-2">
<Button
variant={isPreviewMode ? 'contrast' : 'outline'}
size="sm"
onClick={togglePreview}
>
{isPreviewMode ? <Pencil /> : <Eye />}
<span>{isPreviewMode ? '편집 모드' : '미리보기'}</span>
</Button>
{/* 발행 = 빌드다. 누르면 HTML 을 다시 굽는다(usePublishSite 주석 참고). */}
<Button variant="primary" size="sm" onClick={openPublishModal}>
<Send />
<span>{isRepublish ? '사이트 재발행' : '사이트 발행'}</span>
</Button>
</div>
</header>
);
}
function LogoMark() {
return (
<img
src="/brand/web4ai-wordmark.svg"
alt="Web4Ai"
className="h-6 w-auto opacity-100 transition-opacity group-hover:opacity-60"
/>
);
}
@@ -0,0 +1,108 @@
import {useState} from 'react';
import {Eye, Image as ImageIcon, Layers} from 'lucide-react';
import {cn} from '@/lib/utils';
import {useBuilderStore, useUnverifiedFields} from '@/stores/builder';
import {CanvasView} from './CanvasView';
import {EditorHeader} from './EditorHeader';
import {RightTabsPanel} from './RightTabsPanel';
import {SectionListPanel} from './SectionListPanel';
import {PublishModal} from '@/features/publish/PublishModal';
type NarrowTab = 'sections' | 'canvas' | 'assets';
const NARROW_TABS: {id: NarrowTab; label: string; icon: typeof Layers}[] = [
{id: 'sections', label: '섹션', icon: Layers},
{id: 'canvas', label: '미리보기', icon: Eye},
{id: 'assets', label: '에셋 / 정보', icon: ImageIcon},
];
export function EditorLayout() {
const isPreviewMode = useBuilderStore((s) => s.isPreviewMode);
const unverifiedCount = useUnverifiedFields().length;
// 1024px 미만에서는 3열이 안 들어간다 — 탭으로 하나씩 보여준다.
const [narrowTab, setNarrowTab] = useState<NarrowTab>('canvas');
return (
<div className="flex h-full w-full min-w-0 flex-col overflow-hidden bg-muted">
<EditorHeader />
{!isPreviewMode && (
<div className="z-20 flex items-center justify-around border-b border-border bg-card px-3 py-1.5 text-xs font-semibold lg:hidden">
{NARROW_TABS.map(({id, label, icon: Icon}) => (
<button
key={id}
type="button"
onClick={() => setNarrowTab(id)}
aria-pressed={narrowTab === id}
className={cn(
'flex flex-1 cursor-pointer items-center justify-center gap-1.5 rounded py-1.5 transition-colors',
narrowTab === id
? 'bg-primary text-primary-foreground'
: 'text-muted-foreground hover:bg-muted',
)}
>
<Icon className="size-3.5" />
<span>{label}</span>
{id === 'assets' && unverifiedCount > 0 && (
<span className="rounded-full bg-warning px-1.5 font-mono text-[10px] font-bold leading-tight text-white">
{unverifiedCount}
</span>
)}
</button>
))}
</div>
)}
<div className="relative flex flex-1 overflow-hidden">
{isPreviewMode ? (
<CanvasView />
) : (
<>
{/* ★ shrink-0 — 가운데가 넓어져도 이 패널은 절대 줄지 않는다. */}
<div
className={cn(
'h-full lg:flex lg:w-[250px] lg:shrink-0',
narrowTab === 'sections' ? 'flex w-full' : 'hidden',
)}
>
<SectionListPanel
onAfterSelect={() => {
if (window.innerWidth < 1024) setNarrowTab('canvas');
}}
/>
</div>
{/*
★ min-w-0 이 반드시 있어야 한다.
flex 아이템의 기본값은 `min-width: auto` 라 **콘텐츠 최소 너비 아래로 줄지 않는다**.
캔버스 툴바(해상도 버튼 + 동기화 표시)가 그 최소 너비를 밀어올리면 이 칸이
남은 공간을 다 먹고, 오른쪽 패널이 통째로 화면 밖으로 밀려난다
(바깥이 overflow-hidden 이라 스크롤도 안 생겨 그냥 사라진다 — 실제로 그랬다).
*/}
<div
className={cn(
'h-full min-w-0 flex-1 lg:flex',
narrowTab === 'canvas' ? 'flex w-full' : 'hidden',
)}
>
<CanvasView />
</div>
{/* ★ shrink-0 — 오른쪽 패널이 잘리던 자리. 폭을 양보하지 않는다. */}
<div
className={cn(
'h-full lg:flex lg:w-[290px] lg:shrink-0',
narrowTab === 'assets' ? 'flex w-full' : 'hidden',
)}
>
<RightTabsPanel />
</div>
</>
)}
</div>
<PublishModal />
</div>
);
}
@@ -0,0 +1,214 @@
import {useState} from 'react';
import {useQueryClient} from '@tanstack/react-query';
import {Check, Loader2, MessageCircleQuestion, Plus, Sparkles, X} from 'lucide-react';
import {FactStatus, PUBLISHABLE_FACT_STATUSES} from '@o2o/shared';
import {getListFaqsQueryKey, useCreateFaq, useListFaqs, useTransitionFaq} from '@/api';
import {Badge} from '@/components/ui/badge';
import {Button} from '@/components/ui/button';
import {Input} from '@/components/ui/input';
import {cn} from '@/lib/utils';
import {useBuilderStore} from '@/stores/builder';
/**
* FAQ 관리 패널.
*
* ★ 왜 별도 탭인가
* FAQ 는 AI 검색이 가장 잘 인용하는 형식이다(FAQPage 구조화 데이터). 그런데 지금까지
* 관리자에는 FAQ 를 **볼 자리조차** 없었다 — COPY 잡이 만들어 둔 FAQ 가 `UNVERIFIED` 로
* 쌓여 있는데 승인할 화면이 없으니 영원히 발행되지 않았다. 실제로 8건이 대기 중인
* 사업장이 있고, FAQ 가 나가는 사업장은 한 곳뿐이었다.
*
* ★ 이 패널이 하는 일은 둘이다.
* 1) 사장님이 **직접 질문·답변을 쓴다** → 서버가 OWNER 출처로 바로 노출값(VERIFIED)에 넣는다.
* 쓴 사람이 곧 출처이자 책임 주체이기 때문이다(fact 직접 입력과 같은 규칙).
* 2) LLM 이 만들어 둔 대기 FAQ 를 **승인한다** → VERIFIED 로 전이시켜 사이트에 내보낸다.
*/
export function FaqPanel() {
const placeId = useBuilderStore((s) => s.placeId);
if (!placeId) {
return (
<div className="flex flex-1 flex-col items-center justify-center gap-2 p-6 text-center text-muted-foreground">
<MessageCircleQuestion className="size-5" />
<p className="text-xs font-semibold text-foreground">데모에서는 FAQ 를 저장할 수 없습니다</p>
<p className="text-[11px] leading-relaxed">
FAQ 는 서버(사업장)에 저장됩니다. 실제 사업장으로 들어오면 이곳에서 추가·승인할 수 있습니다.
</p>
</div>
);
}
return <FaqEditor placeId={placeId} />;
}
function FaqEditor({placeId}: {placeId: string}) {
const queryClient = useQueryClient();
const [question, setQuestion] = useState('');
const [answer, setAnswer] = useState('');
// 어떤 항목에 요청이 나가 있는지 — 버튼마다 따로 표시해야 어느 줄이 움직이는지 보인다.
const [busyId, setBusyId] = useState<string | null>(null);
const listQuery = useListFaqs(placeId);
const createFaq = useCreateFaq();
const transitionFaq = useTransitionFaq();
/** 목록을 다시 읽는다. 추가·승인 뒤 화면이 옛 상태로 남으면 사장님이 같은 걸 두 번 누른다. */
const refresh = () =>
queryClient.invalidateQueries({queryKey: getListFaqsQueryKey(placeId)});
const faqs = listQuery.data?.faqs ?? [];
const publishable = listQuery.data?.publishable ?? 0;
const pending = listQuery.data?.pending_review ?? 0;
const submit = async () => {
const q = question.trim();
const a = answer.trim();
if (!q || !a) return;
await createFaq.mutateAsync({placeId, data: {question: q, answer: a}});
setQuestion('');
setAnswer('');
await refresh();
};
const approve = async (faqId: string) => {
setBusyId(faqId);
try {
await transitionFaq.mutateAsync({placeId, faqId, data: {status: FactStatus.VERIFIED}});
await refresh();
} finally {
setBusyId(null);
}
};
const reject = async (faqId: string) => {
setBusyId(faqId);
try {
await transitionFaq.mutateAsync({placeId, faqId, data: {status: FactStatus.REJECTED}});
await refresh();
} finally {
setBusyId(null);
}
};
return (
<div className="flex-1 space-y-3 overflow-y-auto p-3.5">
<div className="flex items-center justify-between border-b border-border pb-2">
<span className="text-xs font-bold">자주 묻는 질문</span>
<span className="text-[10px] text-muted-foreground">
노출 {publishable}건{pending > 0 && ` · 대기 ${pending}건`}
</span>
</div>
{/* ── 새 FAQ 직접 추가 ───────────────────────────────── */}
<div className="space-y-2 rounded-lg border border-dashed border-border bg-muted/30 p-3">
<div className="flex items-center gap-1.5 text-xs font-bold">
<Plus className="size-3.5" /> 질문·답변 추가
</div>
<Input
value={question}
onChange={(event) => setQuestion(event.target.value)}
placeholder="질문 (예: 주차할 수 있나요?)"
className="text-xs"
/>
<textarea
value={answer}
onChange={(event) => setAnswer(event.target.value)}
placeholder="답변 (짧고 단정적으로 쓸수록 AI 답변에 그대로 인용됩니다)"
rows={3}
className="w-full resize-y rounded-md border border-input bg-transparent px-3 py-2 text-xs shadow-xs outline-none focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50"
/>
<Button
size="sm"
className="w-full"
disabled={!question.trim() || !answer.trim() || createFaq.isPending}
onClick={() => void submit()}
>
{createFaq.isPending ? <Loader2 className="animate-spin" /> : <Plus />}
추가하고 바로 노출
</Button>
{createFaq.isError && (
<p className="text-[11px] text-destructive">저장하지 못했습니다. 잠시 후 다시 시도해 주세요.</p>
)}
</div>
{/* ── 목록 ──────────────────────────────────────────── */}
{listQuery.isPending ? (
<div className="flex items-center justify-center gap-2 py-6 text-[11px] text-muted-foreground">
<Loader2 className="size-3.5 animate-spin" /> 불러오는 중
</div>
) : faqs.length === 0 ? (
<p className="py-6 text-center text-[11px] leading-relaxed text-muted-foreground">
아직 FAQ 가 없습니다.
<br />
손님이 실제로 자주 묻는 질문부터 채워보세요.
</p>
) : (
<div className="space-y-2">
{faqs.map((faq) => {
const faqId = String(faq.faq_id);
const isLive = PUBLISHABLE_FACT_STATUSES.includes(faq.status as FactStatus);
const isBusy = busyId === faqId;
return (
<div
key={faqId}
className={cn(
'space-y-1.5 rounded-lg border p-2.5',
isLive ? 'border-border bg-card' : 'border-warning/40 bg-warning/8',
)}
>
<div className="flex items-start justify-between gap-2">
<p className="flex-1 text-xs font-semibold break-words">{faq.question}</p>
{isLive ? (
<span className="shrink-0 text-[10px] text-muted-foreground">노출 중</span>
) : (
<Badge variant="warning" className="shrink-0 text-[10px]">
승인 대기
</Badge>
)}
</div>
<p className="text-[11px] leading-relaxed break-words text-muted-foreground">{faq.answer}</p>
{/* AI 가 쓴 문장이면 무슨 사실을 근거로 썼는지 보여준다 — 승인 판단의 재료다. */}
{faq.generated_by !== undefined && !isLive && faq.source_fact_ids?.length ? (
<p className="flex items-center gap-1 text-[10px] text-muted-foreground">
<Sparkles className="size-2.5 shrink-0" />
근거: {faq.source_fact_ids.join(' · ')}
</p>
) : null}
{!isLive && (
<div className="flex gap-1.5 pt-0.5">
<Button
size="sm"
className="h-7 flex-1 text-[11px]"
disabled={isBusy}
onClick={() => void approve(faqId)}
>
{isBusy ? <Loader2 className="animate-spin" /> : <Check />}
승인하고 노출
</Button>
<Button
size="sm"
variant="outline"
className="h-7 text-[11px]"
disabled={isBusy}
onClick={() => void reject(faqId)}
>
<X /> 버리기
</Button>
</div>
)}
</div>
);
})}
</div>
)}
<p className="text-[11px] leading-relaxed text-muted-foreground">
직접 쓴 질문·답변은 <strong className="text-foreground">사장님이 확정한 값</strong>으로 바로 노출되고,
AI 가 만들어 둔 항목은 승인해야 사이트와 AI 검색용 데이터에 나갑니다.
</p>
</div>
);
}
@@ -0,0 +1,474 @@
import {useState} from 'react';
import {
AlertTriangle,
Check,
Image as ImageIcon,
Info,
FileText,
Loader2,
MessageCircleQuestion,
Pencil,
Plus,
Shapes,
Trash2,
X,
} from 'lucide-react';
import type {InfoField} from '@o2o/shared';
import {Badge} from '@/components/ui/badge';
import {Button} from '@/components/ui/button';
import {Input} from '@/components/ui/input';
import {PasteFactsPanel, RecollectPanel} from '@/features/onboarding';
import {cn} from '@/lib/utils';
import {useBuilderStore, useUnverifiedFields, type RightTab} from '@/stores/builder';
import {FaqPanel} from './FaqPanel';
import {SectionDesignPanel} from './SectionDesignPanel';
import {resolveVariant} from './canvas/registry';
const TABS: {id: RightTab; label: string; icon: typeof Info}[] = [
{id: 'content', label: '콘텐츠', icon: FileText},
{id: 'design', label: '디자인', icon: Shapes},
{id: 'photos', label: '사진', icon: ImageIcon},
{id: 'info', label: '정보', icon: Info},
{id: 'faq', label: 'FAQ', icon: MessageCircleQuestion},
{id: 'verify', label: '확인', icon: AlertTriangle},
];
export function RightTabsPanel() {
const activeTab = useBuilderStore((s) => s.rightTab);
const setRightTab = useBuilderStore((s) => s.setRightTab);
const unverified = useUnverifiedFields();
return (
<div className="flex h-full w-full shrink-0 select-none flex-col overflow-hidden border-l border-border bg-card lg:w-[290px]">
<div className="flex items-center gap-1 border-b border-border bg-muted/50 p-1">
{TABS.map(({id, label, icon: Icon}) => (
<button
key={id}
type="button"
onClick={() => setRightTab(id)}
aria-pressed={activeTab === id}
className={cn(
'flex min-w-0 flex-1 cursor-pointer items-center justify-center gap-0.5 rounded-md px-0.5 py-2 text-[11px] font-semibold transition-colors',
activeTab === id
? 'border border-border bg-card text-foreground'
: 'text-muted-foreground hover:text-foreground',
)}
>
<Icon className={cn('size-3.5', id === 'verify' && unverified.length > 0 && 'text-warning')} />
<span className="truncate">{label}</span>
{id === 'verify' && unverified.length > 0 && (
<span className="ml-0.5 rounded-full bg-warning px-1.5 font-mono text-[10px] font-bold leading-tight text-white">
{unverified.length}
</span>
)}
</button>
))}
</div>
{activeTab === 'design' && <SectionDesignPanel />}
{activeTab === 'content' && <ContentTab />}
{activeTab === 'photos' && <PhotosTab />}
{activeTab === 'info' && <InfoTab />}
{activeTab === 'faq' && <FaqPanel />}
{activeTab === 'verify' && <VerifyTab fields={unverified} />}
</div>
);
}
function ContentTab() {
const industry = useBuilderStore((s) => s.industry);
const sections = useBuilderStore((s) => s.sections);
const selectedSectionId = useBuilderStore((s) => s.selectedSectionId);
const updateSectionContent = useBuilderStore((s) => s.updateSectionContent);
const storeName = useBuilderStore((s) => s.storeName);
const setStoreName = useBuilderStore((s) => s.setStoreName);
const section = sections.find((item) => item.id === selectedSectionId);
if (!section) {
return (
<div className="flex flex-1 flex-col items-center justify-center gap-2 p-6 text-center text-muted-foreground">
<FileText className="size-5" />
<p className="text-xs font-semibold text-foreground">편집할 섹션을 선택하세요</p>
<p className="text-[11px]">왼쪽 섹션 목록이나 미리보기에서 선택할 수 있습니다.</p>
</div>
);
}
const update = (patch: {name?: string; description?: string; body?: string}) =>
updateSectionContent(section.id, {
name: patch.name ?? section.name,
description: patch.description ?? section.description,
body: patch.body ?? section.body,
});
const variantId = resolveVariant(section, industry)?.id ?? '';
const supportsTitle = section.type !== 'local';
const supportsDescription = !(
variantId.startsWith('rooms.') || variantId.startsWith('rules.') ||
variantId.startsWith('local.') || variantId === 'menu.price-table' ||
variantId === 'space.list' || variantId === 'programs.table' ||
variantId === 'exhibition.notice'
);
const supportsBody =
variantId.startsWith('intro.') || variantId.startsWith('booking.') ||
variantId === 'inquiry.cta' || variantId === 'exhibition.notice';
return (
<div className="flex-1 space-y-4 overflow-y-auto p-3.5">
<div className="border-b border-border pb-2">
<p className="text-xs font-bold">{section.name} 콘텐츠</p>
<p className="mt-0.5 text-[10px] text-muted-foreground">입력 즉시 미리보기에 반영됩니다.</p>
</div>
{supportsTitle && section.type === 'hero' ? (
<label className="block space-y-1">
<span className="text-xs font-semibold">대표 제목</span>
<Input value={storeName} onChange={(event) => setStoreName(event.target.value)} className="text-xs" />
</label>
) : supportsTitle ? (
<label className="block space-y-1">
<span className="text-xs font-semibold">섹션 제목</span>
<Input value={section.name} onChange={(event) => update({name: event.target.value})} className="text-xs" />
</label>
) : null}
{supportsDescription && <label className="block space-y-1">
<span className="text-xs font-semibold">한 줄 설명</span>
<Input
value={section.description ?? ''}
onChange={(event) => update({description: event.target.value})}
placeholder="제목 아래에 표시할 설명"
className="text-xs"
/>
</label>}
{supportsBody && <label className="block space-y-1">
<span className="text-xs font-semibold">본문</span>
<textarea
value={section.body ?? ''}
onChange={(event) => update({body: event.target.value})}
placeholder="섹션에 표시할 본문을 입력하세요"
rows={7}
className="w-full resize-y rounded-md border border-input bg-background px-3 py-2 text-xs leading-relaxed outline-none focus:border-ring focus:ring-2 focus:ring-ring/30"
/>
</label>}
{!supportsTitle && !supportsDescription && !supportsBody && (
<p className="rounded-md border border-dashed border-border p-3 text-center text-[11px] text-muted-foreground">
이 레이아웃에는 직접 입력하는 문구가 없습니다. 수집된 데이터만 표시합니다.
</p>
)}
<p className="rounded-md bg-muted/50 p-2.5 text-[10px] leading-relaxed text-muted-foreground">
목록형 데이터는 해당 관리 탭에서 편집하고, 이곳에서는 섹션의 제목·설명·소개 본문을 편집합니다.
</p>
</div>
);
}
function PhotosTab() {
const photos = useBuilderStore((s) => s.photos);
const setPrimaryPhoto = useBuilderStore((s) => s.setPrimaryPhoto);
const togglePhotoVisibility = useBuilderStore((s) => s.togglePhotoVisibility);
const visibleCount = photos.filter((photo) => photo.isVisible !== false).length;
return (
<div className="flex-1 space-y-3 overflow-y-auto p-3.5">
<div className="flex items-center justify-between border-b border-border pb-2">
<span className="text-xs font-bold">업장 이미지 에셋 ({photos.length})</span>
<span className="text-[10px] text-muted-foreground">갤러리 {visibleCount}장</span>
</div>
<div className="grid grid-cols-2 gap-2.5">
{photos.map((photo) => (
<div
key={photo.id}
className={cn(
'group relative aspect-4/3 overflow-hidden rounded-md border transition-all',
photo.isVisible === false && 'opacity-45 grayscale',
photo.isPrimary
? 'border-2 border-primary ring-1 ring-primary'
: 'border-border hover:border-muted-foreground/40',
)}
>
<button type="button" onClick={() => setPrimaryPhoto(photo.id)} className="size-full cursor-pointer">
<img
src={photo.url}
alt={photo.title}
loading="lazy"
referrerPolicy="no-referrer"
className="size-full object-cover"
/>
</button>
<span className="absolute inset-x-0 bottom-0 block truncate bg-gradient-to-t from-black/80 to-transparent p-1.5 text-left text-[10px] font-medium text-white">
{photo.title}
</span>
{photo.isPrimary ? (
<span className="absolute left-1 top-1 rounded bg-primary px-1.5 py-0.5 text-[9px] font-bold text-primary-foreground">
대표
</span>
) : (
<span className="absolute left-1 top-1 rounded bg-black/40 px-1 py-0.5 text-[9px] text-white opacity-0 transition-opacity group-hover:opacity-100">
대표 지정
</span>
)}
<label className="absolute right-1 top-1 flex cursor-pointer items-center gap-1 rounded bg-black/65 px-1.5 py-1 text-[9px] font-semibold text-white">
<input
type="checkbox"
checked={photo.isVisible !== false}
onChange={() => togglePhotoVisibility(photo.id)}
className="size-3 accent-white"
/>
표시
</label>
</div>
))}
</div>
<p className="rounded-md border border-dashed border-border bg-muted/40 p-2.5 text-center text-xs text-muted-foreground">
<span className="block font-medium">새 사진 추가</span>
<span className="text-[10px]">
업로드한 사진은 출처가 <code className="font-mono">owner</code>로 기록됩니다
</span>
</p>
</div>
);
}
function InfoTab() {
const infoFields = useBuilderStore((s) => s.infoFields);
const updateField = useBuilderStore((s) => s.updateField);
const updateFieldLabel = useBuilderStore((s) => s.updateFieldLabel);
const addInfoField = useBuilderStore((s) => s.addInfoField);
const removeInfoField = useBuilderStore((s) => s.removeInfoField);
const [newLabel, setNewLabel] = useState('');
const [newValue, setNewValue] = useState('');
const placeId = useBuilderStore((s) => s.placeId);
// ★ 셀렉터 안에서 새 배열을 만들지 않는다(스토어 상단 주의사항) — state 의 배열을 그대로 받아
// 여기서 includes 로 좁힌다. 셀렉터가 매번 새 배열을 돌려주면 무한 렌더로 죽는다.
const savingFieldIds = useBuilderStore((s) => s.savingFieldIds);
return (
<div className="flex-1 space-y-3 overflow-y-auto p-3.5">
<div className="flex items-center justify-between border-b border-border pb-2">
<span className="text-xs font-bold">기본 정보 수정</span>
{/* 데모는 이 화면 안에서만 도는 값이고, 실사업장은 고치는 즉시 서버로 올라간다. */}
<span className="text-[10px] text-muted-foreground">
{placeId ? '고치면 서버에 저장' : '캔버스 즉시 반영'}
</span>
</div>
<div className="space-y-3">
{infoFields.map((field) => {
const isHidden = field.requiresVerification && !field.isVerified;
const isSaving = savingFieldIds.includes(field.id);
return (
<div key={field.id} className="space-y-1">
<div className="flex items-center justify-between gap-2">
{field.id.startsWith('custom_') ? (
<Input
aria-label="항목 이름"
value={field.label}
onChange={(event) => updateFieldLabel(field.id, event.target.value)}
className="h-7 flex-1 text-xs font-semibold"
/>
) : <label htmlFor={`field-${field.id}`} className="text-xs font-semibold">{field.label}</label>}
{isSaving ? (
<span className="flex items-center gap-1 text-[10px] text-muted-foreground">
<Loader2 className="size-2.5 animate-spin" />
저장 중
</span>
) : isHidden ? (
<Badge variant="warning" className="text-[10px]">
확인 대기 (숨김)
</Badge>
) : (
<span className="text-[10px] text-muted-foreground">노출 중</span>
)}
</div>
<Input
id={`field-${field.id}`}
value={field.value}
onChange={(e) => updateField(field.id, e.target.value)}
className="text-xs"
/>
{field.id.startsWith('custom_') && (
<button
type="button"
onClick={() => removeInfoField(field.id)}
className="flex items-center gap-1 text-[10px] text-destructive hover:underline"
>
<Trash2 className="size-3" /> 항목 삭제
</button>
)}
</div>
);
})}
</div>
<div className="space-y-2 rounded-lg border border-dashed border-border bg-muted/30 p-3">
<div className="flex items-center gap-1.5 text-xs font-bold"><Plus className="size-3.5" /> 새 정보 항목</div>
<Input value={newLabel} onChange={(event) => setNewLabel(event.target.value)} placeholder="항목 이름 (예: 반려동물 동반)" className="text-xs" />
<Input value={newValue} onChange={(event) => setNewValue(event.target.value)} placeholder="내용" className="text-xs" />
<Button
size="sm"
className="w-full"
disabled={!newLabel.trim() || !newValue.trim()}
onClick={() => {
addInfoField(newLabel.trim(), newValue.trim());
setNewLabel('');
setNewValue('');
}}
>
<Plus /> 항목 추가
</Button>
</div>
<p className="text-[11px] leading-relaxed text-muted-foreground">
여기서 직접 고친 값은 <strong className="text-foreground">사장님이 확정한 값</strong>으로
기록되어, 이후 자동 수집이 덮어쓰지 않습니다.
</p>
{/* ★ 재수집을 [정보] 탭 아래에 둔다. 에디터에서 "이 값이 옛날 값인데"를 깨닫는 자리가
바로 여기라, 다시 가져오는 버튼도 같은 자리에 있어야 찾는다.
데모(placeId 없음)에서는 패널이 스스로 사라진다. */}
<RecollectPanel placeId={placeId} />
<PasteFactsPanel placeId={placeId} />
</div>
);
}
function VerifyTab({fields}: {fields: InfoField[]}) {
const verifyField = useBuilderStore((s) => s.verifyField);
const [editingId, setEditingId] = useState<string | null>(null);
const [draft, setDraft] = useState('');
const startEdit = (field: InfoField) => {
setEditingId(field.id);
setDraft(field.value);
};
const saveEdit = (fieldId: string) => {
const trimmed = draft.trim();
if (trimmed) verifyField(fieldId, trimmed);
setEditingId(null);
setDraft('');
};
return (
<div className="flex-1 space-y-3 overflow-y-auto p-3.5">
<div className="flex items-center justify-between border-b border-border pb-2">
<span className="text-xs font-bold">확인 필요 항목 ({fields.length})</span>
<span className="text-[10px] font-semibold text-warning">승인해야 사이트에 노출</span>
</div>
{fields.length === 0 ? (
<div className="my-4 space-y-2 rounded-lg border border-success/30 bg-success/8 p-6 text-center">
<span className="mx-auto flex size-8 items-center justify-center rounded-full bg-success/15 text-success">
<Check className="size-4" />
</span>
<h3 className="text-xs font-bold text-success">모든 정보가 확인되었습니다</h3>
<p className="text-[11px] text-success/90">
확인된 항목만 사이트와 구조화 데이터에 나갑니다.
</p>
</div>
) : (
<div className="space-y-3">
<p className="text-[11px] leading-relaxed text-muted-foreground">
공개 채널에서 자동 수집한 값입니다. 맞으면{' '}
<strong className="text-foreground">[맞아요]</strong>, 틀리면{' '}
<strong className="text-foreground">[아니에요]</strong>로 고쳐주세요. 확인 전에는{' '}
<strong className="text-foreground">사이트에 나가지 않습니다.</strong>
</p>
{fields.map((field) => {
const isEditing = editingId === field.id;
return (
<div
key={field.id}
className="space-y-2 rounded-lg border border-warning/40 bg-warning/8 p-3 text-xs"
>
<div className="flex items-center justify-between gap-2">
<span className="flex items-center gap-1 font-bold">
<AlertTriangle className="size-3.5 text-warning" />
{field.label}
</span>
{field.source && (
<span className="shrink-0 text-[10px] text-muted-foreground">
{field.source}
</span>
)}
</div>
{!isEditing ? (
<>
<p className="break-words rounded border border-warning/30 bg-card p-2 font-medium">
{field.value}
</p>
<div className="flex items-center gap-1.5 pt-1">
<Button
variant="primary"
size="sm"
className="flex-1"
onClick={() => verifyField(field.id)}
>
<Check />
<span>맞아요</span>
</Button>
<Button
variant="secondary"
size="sm"
className="flex-1"
onClick={() => startEdit(field)}
>
<Pencil />
<span>아니에요</span>
</Button>
</div>
</>
) : (
<div className="space-y-2 pt-1">
<label
htmlFor={`verify-${field.id}`}
className="block text-[11px] font-semibold"
>
정확한 정보를 입력해주세요
</label>
<Input
id={`verify-${field.id}`}
value={draft}
onChange={(e) => setDraft(e.target.value)}
placeholder={`${field.label} 정보 입력`}
autoFocus
className="text-xs"
onKeyDown={(event) => {
if (event.key === 'Enter') saveEdit(field.id);
if (event.key === 'Escape') setEditingId(null);
}}
/>
<div className="flex items-center gap-1.5">
<Button
variant="primary"
size="sm"
className="flex-1"
onClick={() => saveEdit(field.id)}
disabled={!draft.trim()}
>
반영하고 승인
</Button>
<Button
variant="ghost"
size="icon"
aria-label="수정 취소"
onClick={() => setEditingId(null)}
>
<X />
</Button>
</div>
</div>
)}
</div>
);
})}
</div>
)}
</div>
);
}
@@ -0,0 +1,176 @@
/**
* [디자인] 탭 — 고른 섹션의 레이아웃 배리에이션을 바꾸는 자리.
*
* 사장님은 코드 이름이 아니라 모양으로 고른다. 그래서 카드마다 와이어프레임을 붙이고,
* "언제 이걸 고르면 좋은지"를 한 줄로 적는다.
*/
import {Check, MousePointerClick, Palette, RotateCcw, Shapes} from 'lucide-react';
import {cn} from '@/lib/utils';
import {useBuilderStore} from '@/stores/builder';
import {COLOR_PALETTE_PRESETS} from './colorPalettes';
import {resolveVariant, variantsFor} from './canvas/registry';
import {VariantThumb} from './canvas/thumbs';
function ColorPalettePicker() {
const industry = useBuilderStore((s) => s.industry);
const selectedId = useBuilderStore((s) => s.colorPaletteId);
const selectColorPalette = useBuilderStore((s) => s.selectColorPalette);
const palettes = COLOR_PALETTE_PRESETS.filter((palette) => palette.industry === industry);
return (
<section className="space-y-2 border-b border-border pb-3">
<div className="flex items-center justify-between">
<span className="flex items-center gap-1.5 text-xs font-bold">
<Palette className="size-3.5" /> 컬러 시스템
</span>
<span className="font-mono text-[10px] text-muted-foreground">{palettes.length}종</span>
</div>
<div className="grid grid-cols-2 gap-2">
{palettes.map((palette) => {
const isActive = selectedId === palette.id;
return (
<button
key={palette.id}
type="button"
onClick={() => selectColorPalette(palette.id)}
aria-pressed={isActive}
className={cn(
'overflow-hidden rounded-lg border bg-card text-left transition-all',
isActive ? 'border-primary ring-1 ring-primary' : 'border-border hover:border-muted-foreground/50',
)}
>
<span className="grid h-7 grid-cols-4">
{palette.swatches.map((color) => (
<span key={color} style={{backgroundColor: color}} />
))}
</span>
<span className="flex items-center gap-1 px-2 py-1.5 text-[10px] font-semibold">
<span className="truncate">{palette.name}</span>
{isActive && <Check className="ml-auto size-3 shrink-0 text-primary" />}
</span>
</button>
);
})}
</div>
{selectedId && (
<button
type="button"
onClick={() => selectColorPalette(null)}
className="w-full rounded-md border border-border py-1.5 text-[10px] font-semibold text-muted-foreground hover:bg-muted"
>
템플릿 기본 색상으로 되돌리기
</button>
)}
</section>
);
}
export function SectionDesignPanel() {
const industry = useBuilderStore((s) => s.industry);
const sections = useBuilderStore((s) => s.sections);
const selectedSectionId = useBuilderStore((s) => s.selectedSectionId);
const setSectionVariant = useBuilderStore((s) => s.setSectionVariant);
const resetSectionVariants = useBuilderStore((s) => s.resetSectionVariants);
const section = sections.find((s) => s.id === selectedSectionId);
const variants = section ? variantsFor(section.type, industry) : [];
const current = section ? resolveVariant(section, industry) : undefined;
if (!section) {
return (
<div className="flex-1 space-y-4 overflow-y-auto p-3.5">
<ColorPalettePicker />
<div className="flex flex-col items-center justify-center gap-2 py-8 text-center">
<span className="flex size-9 items-center justify-center rounded-full bg-muted text-muted-foreground">
<MousePointerClick className="size-4" />
</span>
<p className="text-xs font-semibold">섹션을 먼저 고르세요</p>
<p className="text-[11px] leading-relaxed text-muted-foreground">
왼쪽 목록이나 미리보기에서 섹션을 누르면
<br />그 섹션의 레이아웃을 바꿀 수 있습니다.
</p>
</div>
</div>
);
}
return (
<div className="flex-1 space-y-3 overflow-y-auto p-3.5">
<ColorPalettePicker />
<div className="flex items-center justify-between border-b border-border pb-2">
<span className="flex min-w-0 items-center gap-1.5 text-xs font-bold">
<Shapes className="size-3.5 shrink-0" />
<span className="truncate">{section.name}</span>
</span>
<span className="shrink-0 font-mono text-[10px] text-muted-foreground">
{variants.length}종
</span>
</div>
{variants.length === 0 ? (
<p className="rounded-md border border-dashed border-border bg-muted/40 p-3 text-center text-[11px] leading-relaxed text-muted-foreground">
이 섹션은 아직 고를 수 있는 레이아웃이 하나뿐입니다.
</p>
) : (
<ul className="space-y-2">
{variants.map((variant) => {
const isActive = current?.id === variant.id;
return (
<li key={variant.id}>
<button
type="button"
onClick={() => setSectionVariant(section.id, variant.id)}
aria-pressed={isActive}
className={cn(
'flex w-full cursor-pointer items-start gap-2.5 rounded-lg border p-2.5 text-left transition-all',
isActive
? 'border-primary bg-primary/8 ring-1 ring-primary'
: 'border-border bg-card hover:bg-muted/60',
)}
>
<VariantThumb
thumb={variant.thumb}
className="h-[38px] w-[54px] shrink-0 rounded border border-border bg-white"
/>
<div className="min-w-0 flex-1 space-y-0.5">
<div className="flex items-center gap-1.5">
<span className="truncate text-xs font-bold">{variant.name}</span>
{variant.isDefault && (
<span className="shrink-0 rounded bg-muted px-1 py-px text-[9px] font-medium text-muted-foreground">
기본
</span>
)}
{isActive && <Check className="ml-auto size-3.5 shrink-0 text-primary" />}
</div>
<p className="text-[11px] leading-relaxed text-muted-foreground">
{variant.description}
</p>
</div>
</button>
</li>
);
})}
</ul>
)}
<div className="space-y-2 border-t border-border pt-3">
<button
type="button"
onClick={resetSectionVariants}
className="flex w-full cursor-pointer items-center justify-center gap-1.5 rounded-md border border-border py-2 text-[11px] font-semibold text-muted-foreground transition-colors hover:bg-muted hover:text-foreground"
>
<RotateCcw className="size-3" />
<span>모든 섹션을 기본 레이아웃으로</span>
</button>
<p className="text-[11px] leading-relaxed text-muted-foreground">
레이아웃만 바뀝니다 —{' '}
<strong className="text-foreground">입력한 내용과 사진, 섹션 순서는 그대로</strong>{' '}
유지됩니다.
</p>
</div>
</div>
);
}
@@ -0,0 +1,199 @@
import {
closestCenter, DndContext, KeyboardSensor, PointerSensor, useSensor, useSensors,
type DragEndEvent,
} from '@dnd-kit/core';
import {
SortableContext, sortableKeyboardCoordinates, useSortable, verticalListSortingStrategy,
} from '@dnd-kit/sortable';
import {CSS} from '@dnd-kit/utilities';
import type {SectionItem} from '@o2o/shared';
import {GripVertical, Layers, Lock, Shapes} from 'lucide-react';
import {Switch} from '@/components/ui/switch';
import {cn} from '@/lib/utils';
import {useBuilderStore} from '@/stores/builder';
import {resolveVariant} from './canvas/registry';
interface SectionListPanelProps {
onAfterSelect?: () => void;
}
interface SortableSectionProps extends SectionListPanelProps {
section: SectionItem;
index: number;
}
function SortableSection({section, index, onAfterSelect}: SortableSectionProps) {
const industry = useBuilderStore((s) => s.industry);
const setRightTab = useBuilderStore((s) => s.setRightTab);
const isSelected = useBuilderStore((s) => s.selectedSectionId === section.id);
const selectSection = useBuilderStore((s) => s.selectSection);
const toggleSection = useBuilderStore((s) => s.toggleSection);
const variant = resolveVariant(section, industry);
const {attributes, listeners, setNodeRef, transform, transition, isDragging} = useSortable({
id: section.id,
});
const select = () => {
selectSection(section.id);
setRightTab('content');
onAfterSelect?.();
if (!section.isEnabled) return;
// 좁은 화면에서는 onAfterSelect가 캔버스 탭을 먼저 연다. 다음 페인트가 끝난 뒤
// 실제 섹션으로 이동해야 display:none 상태의 위치를 잘못 읽지 않는다.
requestAnimationFrame(() => {
requestAnimationFrame(() => {
document
.getElementById(`canvas-section-${section.id}`)
?.scrollIntoView({behavior: 'smooth', block: 'start'});
});
});
};
return (
<li
ref={setNodeRef}
style={{transform: CSS.Transform.toString(transform), transition}}
className={cn('relative', isDragging && 'z-10')}
>
<div
role="button"
tabIndex={0}
onClick={select}
onKeyDown={(event) => {
if (event.key === 'Enter' || event.key === ' ') {
event.preventDefault();
select();
}
}}
className={cn(
'group flex cursor-pointer items-center justify-between rounded-md border p-2 text-xs transition-[background-color,border-color,opacity,box-shadow]',
isDragging && 'cursor-grabbing opacity-70 shadow-lg',
isSelected
? 'border-primary bg-primary/8 font-semibold text-foreground'
: section.isEnabled
? 'border-border bg-card hover:bg-muted/60'
: 'border-border bg-muted/40 text-muted-foreground',
)}
>
<div className="flex min-w-0 items-center gap-2 pr-1">
<button
type="button"
title={`${section.name} 드래그하여 순서 변경`}
aria-label={`${section.name} 드래그하여 순서 변경`}
onClick={(event) => event.stopPropagation()}
className="-mr-1 touch-none cursor-grab rounded p-0.5 text-muted-foreground hover:bg-accent hover:text-foreground active:cursor-grabbing"
{...attributes}
{...listeners}
>
<GripVertical className="size-3.5" />
</button>
<span className="w-3 text-right font-mono text-[10px] text-muted-foreground">
{index + 1}
</span>
<div className="min-w-0 truncate">
<span className={cn('block truncate', !section.isEnabled && 'line-through')}>
{section.name}
</span>
{variant && (
<span
role="button"
tabIndex={0}
title={`${variant.name} — 눌러서 레이아웃 바꾸기`}
onClick={(event) => {
event.stopPropagation();
selectSection(section.id);
setRightTab('design');
onAfterSelect?.();
}}
onKeyDown={(event) => {
if (event.key !== 'Enter' && event.key !== ' ') return;
event.preventDefault();
event.stopPropagation();
selectSection(section.id);
setRightTab('design');
onAfterSelect?.();
}}
className="flex cursor-pointer items-center gap-0.5 truncate text-[9px] font-normal text-muted-foreground hover:text-foreground"
>
<Shapes className="size-2.5 shrink-0" />
<span className="truncate">{variant.name}</span>
</span>
)}
{section.isLocked && (
<span className="flex items-center gap-0.5 text-[9px] font-normal text-muted-foreground">
<Lock className="size-2.5" /> 필수 고정
</span>
)}
</div>
</div>
<div className="flex shrink-0 items-center gap-1" onClick={(event) => event.stopPropagation()} role="presentation">
{section.isLocked ? (
<span title="SEO·필수 마크업이 달린 섹션이라 끌 수 없습니다." className="p-1 text-muted-foreground">
<Lock className="size-4" />
</span>
) : (
<Switch checked={section.isEnabled} onCheckedChange={() => toggleSection(section.id)} aria-label={`${section.name} 섹션 표시 여부`} />
)}
</div>
</div>
</li>
);
}
export function SectionListPanel({onAfterSelect}: SectionListPanelProps) {
const sections = useBuilderStore((s) => s.sections);
const reorderSection = useBuilderStore((s) => s.reorderSection);
const sensors = useSensors(
useSensor(PointerSensor, {activationConstraint: {distance: 6}}),
useSensor(KeyboardSensor, {coordinateGetter: sortableKeyboardCoordinates}),
);
const activeCount = sections.filter((section) => section.isEnabled).length;
const handleDragEnd = ({active, over}: DragEndEvent) => {
if (!over || active.id === over.id) return;
const fromIndex = sections.findIndex((section) => section.id === active.id);
const toIndex = sections.findIndex((section) => section.id === over.id);
reorderSection(fromIndex, toIndex);
};
return (
<div className="flex h-full w-full shrink-0 select-none flex-col overflow-hidden border-r border-border bg-card lg:w-[250px]">
<div className="flex items-center justify-between border-b border-border bg-muted/50 p-3.5">
<div className="flex items-center gap-1.5">
<Layers className="size-4" />
<span className="text-xs font-bold">섹션 관리</span>
</div>
<span className="rounded border border-border bg-card px-2 py-0.5 font-mono text-[11px] text-muted-foreground">
{activeCount} / {sections.length} 활성
</span>
</div>
<p className="border-b border-border bg-muted/30 px-3.5 py-2 text-[11px] text-muted-foreground">
핸들을 드래그해 순서를 바꾸고, 레이아웃 이름을 누르면 모양을 바꿉니다.
</p>
<DndContext sensors={sensors} collisionDetection={closestCenter} onDragEnd={handleDragEnd}>
<SortableContext items={sections.map((section) => section.id)} strategy={verticalListSortingStrategy}>
<ul className="flex-1 space-y-1.5 overflow-y-auto p-2">
{sections.map((section, index) => (
<SortableSection
key={section.id}
section={section}
index={index}
onAfterSelect={onAfterSelect}
/>
))}
</ul>
</SortableContext>
</DndContext>
<p className="border-t border-border bg-muted/30 p-2.5 text-center text-[10px] text-muted-foreground">
* 자물쇠 항목은 검색·AI 노출에 필요한 마크업이 달려 있어 고정입니다.
</p>
</div>
);
}
@@ -0,0 +1,145 @@
import React from 'react';
export interface SlateTextNode {
text: string;
bold?: boolean;
italic?: boolean;
underline?: boolean;
code?: boolean;
}
export interface SlateElementNode {
type?: string;
speaker?: string;
role?: 'buyer' | 'seller' | 'host' | 'guest' | 'ai' | 'customer';
time?: string;
children: (SlateElementNode | SlateTextNode)[];
}
interface SlateScriptRendererProps {
nodes?: (SlateElementNode | SlateTextNode)[];
primaryColor?: string;
className?: string;
}
export const SlateScriptRenderer: React.FC<SlateScriptRendererProps> = ({
nodes,
primaryColor = '#18181b',
className = '',
}) => {
if (!nodes || nodes.length === 0) {
return null;
}
const renderTextNode = (node: SlateTextNode, idx: number) => {
let content: React.ReactNode = node.text;
if (node.bold) content = <strong key={idx}>{content}</strong>;
if (node.italic) content = <em key={idx}>{content}</em>;
if (node.underline) content = <u key={idx}>{content}</u>;
if (node.code) {
content = (
<code key={idx} className="bg-slate-100 px-1 py-0.5 rounded text-[11px] font-mono">
{content}
</code>
);
}
return <React.Fragment key={idx}>{content}</React.Fragment>;
};
const renderElement = (node: SlateElementNode, idx: number) => {
switch (node.type) {
case 'chat-dialog':
case 'dialog':
case 'negotiation': {
const isHost = node.role === 'seller' || node.role === 'host' || node.role === 'ai';
return (
<div
key={idx}
className={`flex items-start gap-3 my-2.5 ${isHost ? 'flex-row-reverse' : 'flex-row'}`}
>
{/* Avatar */}
<div
className={`w-8 h-8 rounded-full flex items-center justify-center text-xs font-bold flex-shrink-0 shadow-2xs ${
isHost ? 'bg-slate-900 text-white' : 'bg-slate-200 text-slate-700'
}`}
>
{node.speaker ? node.speaker.slice(0, 1) : isHost ? '호' : '손'}
</div>
{/* Bubble */}
<div className={`max-w-[75%] space-y-1 ${isHost ? 'text-right' : 'text-left'}`}>
<div className="flex items-center gap-1.5 text-[11px] text-slate-400">
<span className="font-semibold text-slate-700">{node.speaker || (isHost ? '호스트' : '게스트')}</span>
{node.time && <span>· {node.time}</span>}
</div>
<div
className={`px-3.5 py-2.5 rounded-2xl text-xs leading-relaxed inline-block text-left ${
isHost
? 'bg-slate-900 text-white rounded-tr-xs shadow-2xs'
: 'bg-slate-100 text-slate-800 rounded-tl-xs'
}`}
>
{node.children.map((child, cIdx) =>
'text' in child ? renderTextNode(child, cIdx) : renderElement(child, cIdx)
)}
</div>
</div>
</div>
);
}
case 'heading-two':
case 'h2':
return (
<h3 key={idx} className="text-base font-bold text-slate-900 mt-4 mb-2">
{node.children.map((child, cIdx) =>
'text' in child ? renderTextNode(child, cIdx) : renderElement(child, cIdx)
)}
</h3>
);
case 'quote':
case 'blockquote':
return (
<blockquote
key={idx}
className="border-l-2 pl-3 my-3 text-xs italic text-slate-600 border-slate-400"
>
{node.children.map((child, cIdx) =>
'text' in child ? renderTextNode(child, cIdx) : renderElement(child, cIdx)
)}
</blockquote>
);
case 'callout':
case 'info-box':
return (
<div
key={idx}
className="p-3.5 my-3 bg-slate-50 border border-slate-200 rounded-xl text-xs text-slate-700 leading-relaxed"
>
{node.children.map((child, cIdx) =>
'text' in child ? renderTextNode(child, cIdx) : renderElement(child, cIdx)
)}
</div>
);
default:
return (
<p key={idx} className="text-xs text-slate-600 leading-relaxed my-1.5">
{node.children.map((child, cIdx) =>
'text' in child ? renderTextNode(child, cIdx) : renderElement(child, cIdx)
)}
</p>
);
}
};
return (
<div className={`slate-editor-script space-y-1 ${className}`}>
{nodes.map((node, idx) =>
'text' in node ? renderTextNode(node, idx) : renderElement(node, idx)
)}
</div>
);
};
@@ -0,0 +1,118 @@
import {useState} from 'react';
import {Check, Copy} from 'lucide-react';
import type {TemplateItem} from '@o2o/shared';
import {cn} from '@/lib/utils';
/**
* 주소 + 복사 + 지도 앱 링크.
*
* "오시는 길" 배리에이션들이 공통으로 쓰는 덩어리. 복사 성공 표시까지 여기 들어 있어서
* 레이아웃을 바꿔도 사장님이 확인하는 동작은 똑같이 남는다.
*/
export function AddressCard({
address,
searchName,
variant = 'card',
colors,
className,
}: {
address: string;
/** 네이버 지도에서 찾을 이름. 보통 상호. */
searchName: string;
variant?: 'card' | 'bar';
/**
* 템플릿 색 토큰. 주소 글자만 text 를 따른다.
*
* ★ 지도 버튼의 초록·노랑은 네이버/카카오의 색이라 토큰으로 바꾸지 않는다 —
* 손님이 "그 버튼"으로 알아보는 색이다.
*/
colors?: TemplateItem['colors'];
className?: string;
}) {
const [copied, setCopied] = useState(false);
const addressStyle = colors ? {color: colors.text} : undefined;
const handleCopy = (e: React.MouseEvent) => {
e.stopPropagation();
navigator.clipboard.writeText(address);
setCopied(true);
setTimeout(() => setCopied(false), 2000);
};
const links = (
<div className="flex items-center gap-2">
<a
href={`https://map.naver.com/v5/search/${encodeURIComponent(searchName)}`}
target="_blank"
rel="noopener noreferrer"
onClick={(e) => e.stopPropagation()}
className="rounded-lg bg-emerald-600 px-3.5 py-2 text-xs font-semibold text-white shadow-2xs transition-colors hover:bg-emerald-700"
>
네이버 지도 길찾기
</a>
<a
href={`https://map.kakao.com/link/search/${encodeURIComponent(address)}`}
target="_blank"
rel="noopener noreferrer"
onClick={(e) => e.stopPropagation()}
className="rounded-lg bg-amber-400 px-3.5 py-2 text-xs font-semibold text-stone-950 shadow-2xs transition-colors hover:bg-amber-500"
>
카카오맵
</a>
</div>
);
if (variant === 'bar') {
return (
<div
className={cn(
'flex flex-col items-start justify-between gap-3 rounded-xl border border-stone-200/80 bg-white px-4 py-3 sm:flex-row sm:items-center',
className,
)}
>
<span className="text-xs font-bold text-stone-900 sm:text-sm" style={addressStyle}>
{address}
</span>
<div className="flex items-center gap-2">
<button
type="button"
onClick={handleCopy}
className="inline-flex cursor-pointer items-center gap-1 rounded border border-stone-200 bg-white px-2.5 py-1 text-xs font-medium text-stone-700 shadow-2xs hover:bg-stone-100"
>
{copied ? <Check className="size-3.5 text-emerald-600" /> : <Copy className="size-3.5" />}
<span>{copied ? '복사완료' : '복사'}</span>
</button>
{links}
</div>
</div>
);
}
return (
<div
className={cn(
'flex flex-col justify-between gap-4 rounded-xl border border-stone-200/80 bg-stone-50/70 p-5 md:flex-row md:items-center',
className,
)}
>
<div className="space-y-1">
<span className="text-[11px] font-bold uppercase text-stone-400">도로명 주소</span>
<div className="flex items-center gap-2">
<strong className="text-sm font-bold text-stone-900 sm:text-base" style={addressStyle}>
{address}
</strong>
<button
type="button"
onClick={handleCopy}
className="inline-flex cursor-pointer items-center gap-1 rounded border border-stone-200 bg-white px-2.5 py-1 text-xs font-medium text-stone-700 shadow-2xs hover:bg-stone-100"
>
{copied ? <Check className="size-3.5 text-emerald-600" /> : <Copy className="size-3.5" />}
<span>{copied ? '복사완료' : '복사'}</span>
</button>
</div>
</div>
{links}
</div>
);
}
@@ -0,0 +1,80 @@
/**
* 캔버스 안의 행동 유도 링크.
*
* 캔버스는 클릭이 곧 "섹션 선택"이라, 링크는 반드시 stopPropagation 을 해야 한다.
* 그 한 줄을 배리에이션마다 손으로 쓰면 언젠가 빠진다 — 여기 한 곳에 가둔다.
*/
import type {ReactNode} from 'react';
import type {TemplateItem} from '@o2o/shared';
import {cn} from '@/lib/utils';
export type CtaStyle = 'solid' | 'outline' | 'pill' | 'ghost' | 'brand';
interface CtaLinkProps {
href: string;
children: ReactNode;
variant?: CtaStyle;
size?: 'sm' | 'md';
/** 템플릿 색 토큰. 넘기면 버튼이 브랜드 색을 따른다. */
colors?: TemplateItem['colors'];
block?: boolean;
className?: string;
}
const BASE =
'inline-flex items-center justify-center gap-1.5 font-semibold transition-all cursor-pointer';
const SIZE = {
sm: 'px-3 py-1.5 text-[11px]',
md: 'px-5 py-2.5 text-xs',
};
/**
* variant 마다 토큰이 닿는 자리가 다르다 — 채운 버튼은 배경, 흰 버튼은 글자색.
*
* ★ primary 는 이 서비스에서 "흰 글자를 얹는 어두운 색"이라는 계약이다.
* 그래서 배경으로 쓸 때는 primary 만 쓴다 — accent 를 배경에 깔면 흰 글자가 뜬다.
*/
function tokenStyle(variant: CtaStyle, colors?: TemplateItem['colors']) {
if (!colors) return undefined;
if (variant === 'brand' || variant === 'solid') return {backgroundColor: colors.primary};
if (variant === 'pill' || variant === 'outline') return {color: colors.primary};
return undefined;
}
export function CtaLink({
href,
children,
variant = 'solid',
size = 'md',
colors,
block,
className,
}: CtaLinkProps) {
return (
<a
href={href}
target="_blank"
rel="noopener noreferrer"
onClick={(e) => e.stopPropagation()}
style={tokenStyle(variant, colors)}
className={cn(
BASE,
SIZE[size],
block && 'w-full',
variant === 'solid' && 'rounded-xl bg-stone-900 text-white shadow-xs hover:bg-stone-800',
variant === 'brand' && 'rounded-xl text-white shadow-xs hover:opacity-90',
variant === 'outline' &&
'rounded-xl border border-stone-300 bg-white text-stone-800 hover:bg-stone-100',
variant === 'pill' &&
'rounded-full bg-white text-stone-900 shadow-md hover:bg-stone-100',
variant === 'ghost' && 'rounded-lg text-stone-500 hover:bg-stone-100 hover:text-stone-900',
// 배경을 인라인 스타일로 덮으면 hover 배경 클래스가 안 먹는다 — 투명도로 대신 반응시킨다.
variant === 'solid' && colors && 'hover:opacity-90',
className,
)}
>
{children}
</a>
);
}
@@ -0,0 +1,21 @@
import type {ReactNode} from 'react';
import {Clock3} from 'lucide-react';
/**
* "아직 준비 중" 한 줄.
*
* 실사업장은 객실·주변정보·영상 같은 목록이 아직 비어 있다(백엔드에 조회 창구가
* 없는 것도 있다). 목록만 조용히 비우면 에디터에서는 섹션이 통째로 사라진 것처럼 보여
* 사장님이 "내가 뭘 지웠나" 하고 되돌리려 든다 — 자리는 지키고 비었다는 사실만 말한다.
*
* 톤은 HiddenFieldsNotice 와 맞춘다: 사장님에게 하는 담백한 상태 보고지 손님용 카피가 아니다.
* (다만 저쪽은 "가리는 중"이라 경고색, 이쪽은 "아직 없음"이라 중립색이다.)
*/
export function EmptyStateNotice({children}: {children: ReactNode}) {
return (
<div className="flex items-center justify-center gap-2 rounded-xl border border-dashed border-stone-300/80 bg-stone-50/60 px-4 py-6 text-center text-xs text-stone-500">
<Clock3 className="size-3.5 shrink-0 text-stone-400" />
<span>{children}</span>
</div>
);
}
@@ -0,0 +1,47 @@
import type {LucideIcon} from 'lucide-react';
import type {TemplateItem} from '@o2o/shared';
import {cn} from '@/lib/utils';
/**
* 아이콘 + 제목 + 한 줄 설명. 주차/충전기/편의시설처럼 "있다/없다"를 알리는 칸.
*/
export function FeatureCard({
icon: Icon,
title,
description,
iconClassName,
colors,
className,
}: {
icon: LucideIcon;
title: string;
description?: string;
iconClassName?: string;
/** 템플릿 색 토큰. 제목과 아이콘이 브랜드 색을 따른다. */
colors?: TemplateItem['colors'];
className?: string;
}) {
// ★ iconClassName 은 "전기차 충전기는 초록" 처럼 뜻이 정해진 색을 넣는 자리다.
// 그 위에 토큰을 덮으면 의미가 사라지므로, 지정이 없을 때만 primary 를 쓴다.
const iconStyle = colors && !iconClassName ? {color: colors.primary} : undefined;
return (
<div
className={cn(
'flex items-start gap-3 rounded-xl border border-stone-200/80 bg-stone-50/70 p-4',
className,
)}
>
<Icon className={cn('size-5 shrink-0 text-stone-800', iconClassName)} style={iconStyle} />
<div>
<strong
className="block text-xs font-bold text-stone-900"
style={colors ? {color: colors.text} : undefined}
>
{title}
</strong>
{description && <p className="mt-0.5 text-[11px] text-stone-600">{description}</p>}
</div>
</div>
);
}
@@ -0,0 +1,18 @@
import {AlertCircle} from 'lucide-react';
/**
* "미확인 항목 N개 숨김 중" 배지.
*
* 미검증 값은 캔버스에서 아예 빼되, 빠졌다는 사실은 반드시 보여준다 —
* 조용히 사라지면 사장님은 "이미 나가고 있다"고 오해한다.
*/
export function HiddenFieldsNotice({count}: {count: number}) {
if (count <= 0) return null;
return (
<span className="flex items-center gap-1.5 rounded-lg border border-amber-200 bg-amber-50 px-2.5 py-1 text-[11px] text-amber-700">
<AlertCircle className="size-3.5 text-amber-600" />
<span>미확인 항목 {count}개 숨김 중</span>
</span>
);
}
@@ -0,0 +1,77 @@
/**
* 기본 정보 한 줄 — 라벨/값 한 쌍을 어떤 모양으로 낼지가 통째로 배리에이션이다.
* (표의 한 행 · 카드 한 장 · 문장 속 인라인)
*/
import {cn} from '@/lib/utils';
import type {InfoField, TemplateItem} from '@o2o/shared';
export type InfoRowStyle = 'row' | 'card' | 'inline';
export function InfoRow({
field,
variant = 'row',
colors,
className,
}: {
field: InfoField;
variant?: InfoRowStyle;
/** 템플릿 색 토큰. 값(굵은 글씨)만 text 를 따르고 라벨은 중립 회색으로 남는다. */
colors?: TemplateItem['colors'];
className?: string;
}) {
const valueStyle = colors ? {color: colors.text} : undefined;
if (variant === 'card') {
return (
<div
className={cn(
'space-y-1 rounded-xl border border-stone-200/80 bg-white p-4 shadow-2xs',
className,
)}
>
<span className="block text-[11px] font-semibold uppercase tracking-wide text-stone-400">
{field.label}
</span>
<span
className="block text-xs font-bold leading-relaxed text-stone-900 sm:text-sm"
style={valueStyle}
>
{field.value}
</span>
</div>
);
}
if (variant === 'inline') {
return (
<span
className={cn(
'inline-flex flex-wrap items-baseline gap-1.5 text-xs leading-relaxed',
className,
)}
>
<span className="font-semibold text-stone-400">{field.label}</span>
<span className="font-bold text-stone-900" style={valueStyle}>
{field.value}
</span>
</span>
);
}
return (
<div
className={cn(
'flex flex-col justify-between gap-1 p-4 transition-colors hover:bg-stone-100/50 sm:flex-row sm:items-center sm:gap-4',
className,
)}
>
<span className="text-xs font-semibold text-stone-500 sm:w-1/3">{field.label}</span>
<span
className="text-xs font-bold text-stone-900 sm:w-2/3 sm:text-right sm:text-sm"
style={valueStyle}
>
{field.value}
</span>
</div>
);
}
@@ -0,0 +1,80 @@
import {X, ChevronLeft, ChevronRight} from 'lucide-react';
import type {TilePhoto} from './PhotoTile';
/**
* 사진 확대 보기. 갤러리 배리에이션 세 개가 전부 이걸 그대로 쓴다 —
* 확대 동작까지 배리에이션마다 다르면 사장님이 레이아웃을 바꿀 때마다 조작법을 다시 배운다.
*/
export function Lightbox({
photos,
index,
onClose,
onMove,
}: {
photos: TilePhoto[];
index: number | null;
onClose: () => void;
onMove?: (next: number) => void;
}) {
if (index === null || !photos[index]) return null;
const photo = photos[index];
const step = (delta: number) => onMove?.((index + delta + photos.length) % photos.length);
return (
<div
onClick={(e) => {
e.stopPropagation();
onClose();
}}
className="fixed inset-0 z-50 flex items-center justify-center bg-black/90 p-4 backdrop-blur-md"
>
<button
type="button"
onClick={onClose}
aria-label="닫기"
className="absolute right-4 top-4 z-10 cursor-pointer rounded-full bg-white/10 p-2 text-white"
>
<X className="size-6" />
</button>
{onMove && photos.length > 1 && (
<>
<button
type="button"
aria-label="이전 사진"
onClick={(e) => {
e.stopPropagation();
step(-1);
}}
className="absolute left-3 z-10 cursor-pointer rounded-full bg-white/10 p-2 text-white hover:bg-white/20"
>
<ChevronLeft className="size-5" />
</button>
<button
type="button"
aria-label="다음 사진"
onClick={(e) => {
e.stopPropagation();
step(1);
}}
className="absolute right-3 z-10 cursor-pointer rounded-full bg-white/10 p-2 text-white hover:bg-white/20"
>
<ChevronRight className="size-5" />
</button>
</>
)}
<div
onClick={(e) => e.stopPropagation()}
className="flex max-h-[85vh] max-w-3xl items-center"
>
<img
src={photo.url}
alt={photo.alt ?? photo.caption ?? ''}
className="max-h-[70vh] max-w-full rounded-xl object-contain shadow-2xl"
/>
</div>
</div>
);
}
@@ -0,0 +1,72 @@
import {cn} from '@/lib/utils';
export interface TilePhoto {
id: string;
url: string;
alt?: string;
caption?: string;
category?: string;
}
type TileFit = 'square' | 'portrait' | 'landscape' | 'free';
const ASPECT: Record<TileFit, string> = {
square: 'aspect-square',
portrait: 'aspect-3/4',
landscape: 'aspect-4/3',
free: '',
};
/**
* 갤러리 한 칸. 격자든 벽돌쌓기든 슬라이드든 "칸 하나"의 모양은 같아야 한다 —
* 배리에이션이 바꾸는 건 칸의 배치이지 칸 자체가 아니다.
*/
export function PhotoTile({
photo,
fit = 'square',
onOpen,
showMeta = false,
className,
}: {
photo: TilePhoto;
fit?: TileFit;
onOpen?: () => void;
showMeta?: boolean;
className?: string;
}) {
return (
<div
onClick={(e) => {
e.stopPropagation();
onOpen?.();
}}
className={cn(
'group relative select-none overflow-hidden rounded-xl border border-stone-200/80 bg-stone-100',
ASPECT[fit],
onOpen && 'cursor-pointer',
className,
)}
>
<img
src={photo.url}
alt={photo.alt ?? photo.caption ?? ''}
loading="lazy"
className="size-full object-cover transition-transform duration-300 group-hover:scale-105"
/>
{showMeta && (photo.category || photo.caption) && (
<div className="absolute inset-0 flex flex-col justify-between bg-black/40 p-2 text-white opacity-0 transition-opacity group-hover:opacity-100">
{photo.category ? (
<span className="self-start rounded bg-black/50 px-1.5 py-0.5 text-[10px] font-medium">
{photo.category}
</span>
) : (
<span />
)}
{photo.caption && (
<span className="truncate text-[10px] font-light">{photo.caption}</span>
)}
</div>
)}
</div>
);
}
@@ -0,0 +1,38 @@
import type {ReactNode} from 'react';
import {cn} from '@/lib/utils';
type PillTone = 'neutral' | 'accent' | 'warn' | 'good' | 'dark';
const TONE: Record<PillTone, string> = {
neutral: 'bg-stone-100 text-stone-600 border-stone-200/70',
accent: 'bg-amber-100/80 text-amber-900 border-amber-200/70',
warn: 'bg-amber-50 text-amber-700 border-amber-200',
good: 'bg-emerald-50 text-emerald-700 border-emerald-200/60',
dark: 'bg-stone-900/85 text-white border-transparent',
};
/** 작은 라벨 하나. 거리·태그·가격대·"대표축제" 처럼 값 옆에 붙는 부가 정보 전용. */
export function Pill({
children,
tone = 'neutral',
mono,
className,
}: {
children: ReactNode;
tone?: PillTone;
mono?: boolean;
className?: string;
}) {
return (
<span
className={cn(
'inline-flex shrink-0 items-center gap-1 rounded border px-1.5 py-0.5 text-[10px] font-medium',
TONE[tone],
mono && 'font-mono',
className,
)}
>
{children}
</span>
);
}
@@ -0,0 +1,89 @@
import {ArrowUpRight} from 'lucide-react';
import type {TemplateItem} from '@o2o/shared';
import {cn} from '@/lib/utils';
import {Pill} from './Pill';
/**
* "이름 · 거리 · 한 줄 설명 · 바로가기" 한 행.
* 맛집 / 명소 / 축제가 전부 이 모양이라 하나로 묶는다.
*/
export function PlaceRow({
name,
meta,
description,
href,
actionLabel = '길찾기',
leading,
colors,
className,
}: {
name: string;
meta?: string;
description?: string;
href?: string;
actionLabel?: string;
leading?: React.ReactNode;
/** 템플릿 색 토큰. 상호명만 text 를 따른다 — 설명·바로가기는 중립 회색이어야 이름이 튄다. */
colors?: TemplateItem['colors'];
className?: string;
}) {
const body = (
<>
<div className="space-y-1 pr-3">
<div className="flex flex-wrap items-center gap-2">
{leading}
<span
className="text-xs font-bold text-stone-900 group-hover:text-stone-700 sm:text-sm"
style={colors ? {color: colors.text} : undefined}
>
{name}
</span>
{meta && <Pill mono>{meta}</Pill>}
</div>
{description && (
<p className="text-xs leading-relaxed text-stone-500">{description}</p>
)}
</div>
{href && (
<span className="flex shrink-0 items-center gap-0.5 text-xs font-medium text-stone-400 group-hover:text-stone-900">
<span>{actionLabel}</span>
<ArrowUpRight className="size-3.5" />
</span>
)}
</>
);
const shared = cn(
'group flex items-center justify-between p-4 transition-colors hover:bg-stone-50/80',
className,
);
if (!href) return <div className={shared}>{body}</div>;
return (
<a
href={href}
target="_blank"
rel="noopener noreferrer"
onClick={(e) => e.stopPropagation()}
className={shared}
>
{body}
</a>
);
}
/** 목록을 감싸는 카드. divide 로 행 사이 선을 긋는다. */
export function ListCard({children, className}: {children: React.ReactNode; className?: string}) {
return (
<div
className={cn(
'overflow-hidden rounded-xl border border-stone-200/80 bg-white shadow-2xs [&>*+*]:border-t [&>*+*]:border-stone-100',
className,
)}
>
{children}
</div>
);
}
@@ -0,0 +1,89 @@
import type {TemplateItem} from '@o2o/shared';
import {cn} from '@/lib/utils';
import {Pill} from './Pill';
export interface PricedItem {
name: string;
price?: string;
desc?: string;
tag?: string;
/** 소요시간 · 대상 같은 부가 스펙. 프로그램/코스에서 쓴다. */
meta?: string[];
}
/**
* "이름 · 태그 · 설명 · 가격" 한 줄.
* 메뉴 / 코스 / 체험 프로그램이 전부 같은 뼈대라 한 원자로 묶고, 배치만 배리에이션에 맡긴다.
*/
export function PriceRow({
item,
variant = 'row',
colors,
className,
}: {
item: PricedItem;
variant?: 'row' | 'card';
/** 템플릿 색 토큰. 품명은 text, 가격은 primary 를 따른다(가격이 이 원자의 주인공이다). */
colors?: TemplateItem['colors'];
className?: string;
}) {
const nameStyle = colors ? {color: colors.text} : undefined;
const priceStyle = colors ? {color: colors.primary} : undefined;
const head = (
<div className="flex flex-wrap items-center gap-2">
<span className="text-xs font-bold text-stone-900 sm:text-sm" style={nameStyle}>
{item.name}
</span>
{item.tag && <Pill tone="accent">{item.tag}</Pill>}
</div>
);
const specs = item.meta?.length ? (
<div className="flex flex-wrap gap-1.5 pt-0.5">
{item.meta.map((m) => (
<Pill key={m}>{m}</Pill>
))}
</div>
) : null;
if (variant === 'card') {
return (
<div
className={cn(
'flex flex-col justify-between gap-3 rounded-xl border border-stone-200/80 bg-white p-4 shadow-2xs',
className,
)}
>
<div className="space-y-1.5">
{head}
{item.desc && <p className="text-xs leading-relaxed text-stone-500">{item.desc}</p>}
{specs}
</div>
{item.price && (
<span className="font-mono text-sm font-extrabold text-stone-900" style={priceStyle}>
{item.price}
</span>
)}
</div>
);
}
return (
<div className={cn('flex items-start justify-between gap-4 p-4', className)}>
<div className="min-w-0 space-y-1">
{head}
{item.desc && <p className="text-xs leading-relaxed text-stone-500">{item.desc}</p>}
{specs}
</div>
{item.price && (
<span
className="shrink-0 font-mono text-xs font-extrabold text-stone-900 sm:text-sm"
style={priceStyle}
>
{item.price}
</span>
)}
</div>
);
}
@@ -0,0 +1,106 @@
/**
* 섹션 껍데기 — 배리에이션이 절대 다시 만들지 않는 부분.
*
* 앵커 id(모바일 탭이 스크롤하는 목표), 선택 링, "선택됨" 배지, 배경 톤이 여기 모여 있다.
* 배리에이션은 안쪽 내용만 책임진다 — 껍데기가 제각각이면 레이아웃을 바꿀 때마다
* 선택 표시가 사라지거나 앵커가 끊긴다.
*/
import type {ReactNode} from 'react';
import type {SectionItem} from '@o2o/shared';
import {cn} from '@/lib/utils';
import type {SectionTone} from '../types';
/**
* 섹션 배경 톤 → 실제 색.
*
* 화면 면적의 대부분이 이 네 색이라, 여기가 하드코딩이면 팔레트를 바꿔도 인상이 안 바뀐다.
* 그래서 템플릿 토큰(`--tpl-*`)을 읽고, 폴백으로 기존 색을 그대로 둔다 —
* ★ 토큰을 안 내려보내는 화면(발행 사이트·썸네일 등)에서는 지금과 픽셀 단위로 동일하다.
*/
const TONE_BG: Record<SectionTone, string> = {
paper: 'var(--tpl-surface, #faf7f2)',
// ★ 진짜 흰색으로 남긴다 — surface/surfaceAlt 와 세 단계가 있어야 섹션이 서로 구분된다.
white: 'var(--tpl-bg, #ffffff)',
tint: 'var(--tpl-surface-alt, #f4f1ec)',
dark: 'var(--tpl-inverse, #1c1917)',
};
interface SectionFrameProps {
section: SectionItem;
isSelected: boolean;
onSelect: () => void;
/** 배경 톤. 위아래 섹션과 다른 톤을 주면 경계선 없이도 구분된다. */
tone?: SectionTone;
/** 히어로처럼 자기 여백을 직접 잡는 배리에이션은 false. */
padded?: boolean;
className?: string;
children: ReactNode;
}
export function SectionFrame({
section,
isSelected,
onSelect,
tone = 'white',
padded = true,
className,
children,
}: SectionFrameProps) {
const isDark = tone === 'dark';
return (
<section
id={`canvas-section-${section.id}`}
onClick={onSelect}
className={cn(
'relative cursor-pointer transition-all',
padded && 'px-4 py-12 sm:px-6 sm:py-16 md:px-8',
isSelected
? 'ring-2 ring-stone-900 ring-offset-2'
: 'hover:outline-1 hover:outline-dashed hover:outline-stone-300',
className,
)}
style={{backgroundColor: TONE_BG[tone]}}
>
{isSelected && (
<span
className={cn(
'z-30 rounded bg-stone-900 px-2 py-0.5 text-[10px] font-semibold text-white',
padded ? 'mb-4 inline-block' : 'absolute left-3 top-3 shadow-xs',
isDark && 'bg-white text-stone-900',
)}
>
선택됨: {section.name}
{section.isLocked && ' (필수)'}
</span>
)}
{children}
</section>
);
}
/** 섹션 본문의 표준 폭. 배리에이션마다 폭이 다르면 스크롤할 때 글줄이 출렁인다. */
export function SectionBody({
children,
width = 'default',
className,
}: {
children: ReactNode;
width?: 'default' | 'wide' | 'narrow';
className?: string;
}) {
return (
<div
className={cn(
'mx-auto space-y-6',
width === 'wide' && 'max-w-[1120px]',
width === 'default' && 'max-w-[880px]',
width === 'narrow' && 'max-w-[640px]',
className,
)}
>
{children}
</div>
);
}
@@ -0,0 +1,126 @@
/**
* 섹션 제목 — 그 자체로 배리에이션을 갖는 원자.
*
* 섹션 배리에이션을 바꿔도 제목 스타일은 따로 고를 수 있어야 한다
* ("갤러리는 격자로, 제목은 가운데 정렬" 같은 조합이 실제로 나온다).
*/
import type {ReactNode} from 'react';
import type {TemplateItem} from '@o2o/shared';
import {cn} from '@/lib/utils';
export type HeadingStyle = 'underline' | 'centered' | 'eyebrow' | 'minimal';
interface SectionHeadingProps {
title: string;
subtitle?: string;
/** 제목 위에 얹는 작은 라벨. eyebrow · centered 스타일에서 쓴다. */
eyebrow?: string;
variant?: HeadingStyle;
/** 제목 오른쪽에 붙는 것(경고 배지, 추가 버튼 등). */
trailing?: ReactNode;
/**
* 템플릿 색 토큰. 넘기면 제목은 text, eyebrow 는 accent 를 따른다.
*
* ★ 부제·밑줄은 일부러 중립 회색으로 남긴다 — 여기까지 토큰을 먹이면
* accent 가 밝은 템플릿에서 부제가 배경에 묻힌다.
*/
colors?: TemplateItem['colors'];
className?: string;
}
export function SectionHeading({
title,
subtitle,
eyebrow,
variant = 'underline',
trailing,
colors,
className,
}: SectionHeadingProps) {
const titleStyle = colors ? {color: colors.text} : undefined;
const eyebrowStyle = colors ? {color: colors.accent} : undefined;
if (variant === 'centered') {
return (
<div className={cn('space-y-2 text-center', className)}>
{eyebrow && (
<span
className="text-[11px] font-semibold uppercase tracking-[0.2em] text-stone-400"
style={eyebrowStyle}
>
{eyebrow}
</span>
)}
<h2
className="serif-title text-xl font-bold tracking-tight text-stone-900 sm:text-2xl"
style={titleStyle}
>
{title}
</h2>
{subtitle && <p className="text-xs text-stone-500 sm:text-sm">{subtitle}</p>}
{trailing && <div className="flex justify-center pt-1">{trailing}</div>}
</div>
);
}
if (variant === 'eyebrow') {
return (
<div className={cn('flex items-start justify-between gap-3', className)}>
<div className="space-y-1">
{eyebrow && (
<span
className="block text-[11px] font-bold uppercase tracking-wider text-amber-700"
style={eyebrowStyle}
>
{eyebrow}
</span>
)}
<h2
className="serif-title text-xl font-bold tracking-tight text-stone-900 sm:text-2xl"
style={titleStyle}
>
{title}
</h2>
{subtitle && <p className="text-xs text-stone-500">{subtitle}</p>}
</div>
{trailing}
</div>
);
}
if (variant === 'minimal') {
// 여기서 제목은 사실상 작은 라벨이라 text 가 아니라 secondary 를 쓴다.
return (
<div className={cn('flex items-baseline justify-between gap-3', className)}>
<h2
className="text-sm font-bold uppercase tracking-[0.18em] text-stone-500"
style={colors ? {color: colors.secondary} : undefined}
>
{title}
</h2>
{trailing}
</div>
);
}
// underline — 기본. 아래 실선이 섹션의 시작을 확실히 끊어준다.
return (
<div
className={cn(
'flex flex-col justify-between gap-2 border-b border-stone-200/80 pb-4 sm:flex-row sm:items-baseline',
className,
)}
>
<div>
<h2
className="serif-title text-xl font-bold tracking-tight text-stone-900 sm:text-2xl"
style={titleStyle}
>
{title}
</h2>
{subtitle && <p className="mt-0.5 text-xs text-stone-500">{subtitle}</p>}
</div>
{trailing && <div className="self-start sm:self-auto">{trailing}</div>}
</div>
);
}
@@ -0,0 +1,19 @@
/**
* 캔버스 원자 모음.
*
* 배리에이션은 여기 있는 것만 조립한다 — 원자를 늘리면 모든 배리에이션이 같이 좋아지고,
* 배리에이션 안에서 직접 마크업을 쓰기 시작하면 레이아웃마다 디테일이 갈라진다.
*/
export {SectionFrame, SectionBody} from './SectionFrame';
export {SectionHeading, type HeadingStyle} from './SectionHeading';
export {InfoRow, type InfoRowStyle} from './InfoRow';
export {HiddenFieldsNotice} from './HiddenFieldsNotice';
export {EmptyStateNotice} from './EmptyStateNotice';
export {PhotoTile, type TilePhoto} from './PhotoTile';
export {Lightbox} from './Lightbox';
export {PlaceRow, ListCard} from './PlaceRow';
export {PriceRow, type PricedItem} from './PriceRow';
export {AddressCard} from './AddressCard';
export {FeatureCard} from './FeatureCard';
export {Pill} from './Pill';
export {CtaLink, type CtaStyle} from './CtaLink';
@@ -0,0 +1,444 @@
/**
* 배리에이션 레지스트리 — "이 섹션 타입에 어떤 레이아웃들이 있나"의 단일 출처.
*
* 캔버스 렌더러와 [디자인] 탭이 같은 표를 본다. 배리에이션을 하나 추가한다는 건
* 여기 한 줄을 더한다는 뜻이고, 그 순간 캔버스와 고르는 UI가 동시에 늘어난다.
*/
import type {IndustryType, SectionItem} from '@o2o/shared';
import type {SectionVariant} from './types';
import {HeroEditorial} from './variants/hero/HeroEditorial';
import {HeroSplit} from './variants/hero/HeroSplit';
import {HeroFullBleed} from './variants/hero/HeroFullBleed';
import {HeroTypeOnly} from './variants/hero/HeroTypeOnly';
import {IntroStory} from './variants/intro/IntroStory';
import {IntroCentered} from './variants/intro/IntroCentered';
import {IntroSideBySide} from './variants/intro/IntroSideBySide';
import {InfoTable} from './variants/info/InfoTable';
import {InfoCards} from './variants/info/InfoCards';
import {InfoInline} from './variants/info/InfoInline';
import {PhotosGrid} from './variants/photos/PhotosGrid';
import {PhotosMasonry} from './variants/photos/PhotosMasonry';
import {PhotosCarousel} from './variants/photos/PhotosCarousel';
import {PhotosWithVideos} from './variants/photos/PhotosWithVideos';
import {MapDetailed} from './variants/map/MapDetailed';
import {MapCompact} from './variants/map/MapCompact';
import {LocalFull} from './variants/local/LocalFull';
import {LocalTabs} from './variants/local/LocalTabs';
import {LocalCompact} from './variants/local/LocalCompact';
import {WeatherSection} from './variants/weather/WeatherSection';
import {FaqAccordion} from './variants/faq/FaqAccordion';
import {FaqOpenList} from './variants/faq/FaqOpenList';
import {FaqTwoColumn} from './variants/faq/FaqTwoColumn';
import {RoomsCarousel} from './variants/rooms/RoomsCarousel';
import {RoomsGrid} from './variants/rooms/RoomsGrid';
import {RoomsList} from './variants/rooms/RoomsList';
import {RulesList} from './variants/rules/RulesList';
import {RulesCards} from './variants/rules/RulesCards';
import {BookingCard} from './variants/booking/BookingCard';
import {BookingBanner} from './variants/booking/BookingBanner';
import {MenuList} from './variants/menu/MenuList';
import {MenuGrid} from './variants/menu/MenuGrid';
import {MenuPriceTable} from './variants/menu/MenuPriceTable';
import {SpaceZones} from './variants/space/SpaceZones';
import {SpaceList} from './variants/space/SpaceList';
import {InquiryCta} from './variants/inquiry/InquiryCta';
import {InquiryForm} from './variants/inquiry/InquiryForm';
import {ProgramsCards} from './variants/programs/ProgramsCards';
import {ProgramsTable} from './variants/programs/ProgramsTable';
import {ExhibitionGallery} from './variants/exhibition/ExhibitionGallery';
import {ExhibitionNotice} from './variants/exhibition/ExhibitionNotice';
export const SECTION_VARIANTS: Record<string, SectionVariant[]> = {
hero: [
{
id: 'hero.editorial',
name: '에디토리얼',
description: '상호 바 + 큰 사진 + 가운데 문구. 분위기부터 보여준다.',
thumb: 'fullbleed',
Component: HeroEditorial,
isDefault: true,
},
{
id: 'hero.split',
name: '좌우 분할',
description: '왼쪽 글 · 오른쪽 사진. 무엇을 파는 곳인지 글로 먼저 읽힌다.',
thumb: 'split',
Component: HeroSplit,
},
{
id: 'hero.full-bleed',
name: '풀스크린 사진',
description: '사진을 화면 끝까지. 사진 한 장의 힘이 강할 때.',
thumb: 'fullbleed',
Component: HeroFullBleed,
},
{
id: 'hero.type-only',
name: '타이포 중심',
description: '사진 없이 여백과 글자만. 쓸 사진이 없거나 조용한 인상을 원할 때.',
thumb: 'centered',
Component: HeroTypeOnly,
},
],
intro: [
{
id: 'intro.story',
name: '스토리',
description: '넓은 사진 아래로 문단이 흐르는 잡지식 구성.',
thumb: 'stack',
Component: IntroStory,
isDefault: true,
},
{
id: 'intro.centered',
name: '가운데 정렬',
description: '짧은 문단 하나. 가장 조용하고 짧다.',
thumb: 'centered',
Component: IntroCentered,
},
{
id: 'intro.side-by-side',
name: '사진 옆 글',
description: '세로 사진 옆에 문단과 특징 목록.',
thumb: 'split',
Component: IntroSideBySide,
},
],
info: [
{
id: 'info.table',
name: '표',
description: '라벨과 값을 선으로 나눈다. 항목이 많아도 안 흔들린다.',
thumb: 'table',
Component: InfoTable,
isDefault: true,
},
{
id: 'info.cards',
name: '카드',
description: '항목마다 한 장. 모바일에서 훑기 좋다.',
thumb: 'cards',
Component: InfoCards,
},
{
id: 'info.inline',
name: '한 줄 요약',
description: '값들을 이어 붙여 가장 좁게. 정보가 적을 때.',
thumb: 'compact',
Component: InfoInline,
},
],
photos: [
{
id: 'photos.grid',
name: '정사각 격자',
description: '같은 크기로 정렬. 장수가 많을수록 정돈돼 보인다.',
thumb: 'grid',
Component: PhotosGrid,
isDefault: true,
},
{
id: 'photos.masonry',
name: '벽돌쌓기',
description: '원본 비율 그대로 어긋나게. 사진을 잘라내지 않는다.',
thumb: 'masonry',
Component: PhotosMasonry,
},
{
id: 'photos.carousel',
name: '가로 슬라이드',
description: '큰 사진을 한 장씩. 장수가 적고 한 장이 좋을 때.',
thumb: 'carousel',
Component: PhotosCarousel,
},
{
id: 'photos.with-videos',
name: '사진 + 영상',
description: '격자 갤러리 아래 YouTube 영상까지. 영상이 더 잘 팔릴 때.',
thumb: 'stack',
Component: PhotosWithVideos,
},
],
map: [
{
id: 'map.detailed',
name: '상세 안내',
description: '주소 + 거점별 소요시간 표 + 주차/충전. 차로 오는 손님이 많을 때.',
thumb: 'table',
Component: MapDetailed,
isDefault: true,
},
{
id: 'map.compact',
name: '주소만',
description: '주소 한 줄과 길찾기 버튼. 도심처럼 찾기 쉬운 곳.',
thumb: 'compact',
Component: MapCompact,
},
],
local: [
{
id: 'local.full',
name: '전체',
description: '날씨 + 맛집 + 명소 + 축제를 전부 세로로.',
thumb: 'stack',
Component: LocalFull,
isDefault: true,
},
{
id: 'local.tabs',
name: '탭 전환',
description: '맛집/명소/축제를 탭으로. 화면 길이를 1/3 로 줄인다.',
thumb: 'accordion',
Component: LocalTabs,
},
{
id: 'local.compact',
name: '요약',
description: '날씨 한 줄과 추천 6곳만. 주인공이 아닐 때.',
thumb: 'compact',
Component: LocalCompact,
},
],
weather: [
{
id: 'weather.card',
name: '날씨 카드',
description: '현재 기온과 날씨 상태, 추천 문구를 한 장에 보여준다.',
thumb: 'compact',
Component: WeatherSection,
isDefault: true,
},
],
faq: [
{
id: 'faq.accordion',
name: '아코디언',
description: '질문만 보이고 누르면 답이 열린다. 화면이 짧다.',
thumb: 'accordion',
Component: FaqAccordion,
isDefault: true,
},
{
id: 'faq.open-list',
name: '펼친 목록',
description: '답까지 전부 열어 둔다. 훑고 지나가게 하고 싶을 때.',
thumb: 'list',
Component: FaqOpenList,
},
{
id: 'faq.two-column',
name: '2단',
description: '넓은 화면에서 두 줄씩. 세로 길이가 반으로 준다.',
thumb: 'two-column',
Component: FaqTwoColumn,
},
],
rooms: [
{
id: 'rooms.carousel',
name: '가로 슬라이드',
description: '모바일에서 한 칸씩 스와이프. 객실 2~4개일 때 자연스럽다.',
thumb: 'carousel',
Component: RoomsCarousel,
isDefault: true,
},
{
id: 'rooms.grid',
name: '격자',
description: '전부 한눈에. 객실이 많고 비교해서 고르게 할 때.',
thumb: 'cards',
Component: RoomsGrid,
},
{
id: 'rooms.list',
name: '가로 목록',
description: '사진 왼쪽 · 설명 오른쪽. 객실 설명이 길 때.',
thumb: 'list',
Component: RoomsList,
},
],
rules: [
{
id: 'rules.list',
name: '목록',
description: '한 덩어리로 짧게. 가장 눈에 덜 띈다.',
thumb: 'compact',
Component: RulesList,
isDefault: true,
},
{
id: 'rules.cards',
name: '번호 카드',
description: '규정 하나에 칸 하나. 클레임이 잦은 곳에.',
thumb: 'cards',
Component: RulesCards,
},
],
booking: [
{
id: 'booking.card',
name: '안내 카드',
description: '가운데 놓인 조용한 카드. 흐름을 끊지 않는다.',
thumb: 'centered',
Component: BookingCard,
isDefault: true,
},
{
id: 'booking.banner',
name: '띠배너',
description: '브랜드 색으로 화면을 가로지르는 강한 유도.',
thumb: 'banner',
Component: BookingBanner,
},
],
menu: [
{
id: 'menu.list',
name: '메뉴판',
description: '이름과 가격을 한 줄씩. 종이 메뉴판처럼.',
thumb: 'list',
Component: MenuList,
isDefault: true,
},
{
id: 'menu.grid',
name: '카드 격자',
description: '설명을 넉넉히. 시그니처가 몇 개뿐일 때.',
thumb: 'cards',
Component: MenuGrid,
},
{
id: 'menu.price-table',
name: '가격표',
description: '점선으로 이름과 가격만. 품목이 많을 때.',
thumb: 'table',
Component: MenuPriceTable,
},
],
space: [
{
id: 'space.zones',
name: '구역 카드',
description: '사진과 함께 자리별로. 좌석 구성이 궁금한 곳에.',
thumb: 'cards',
Component: SpaceZones,
isDefault: true,
},
{
id: 'space.list',
name: '목록',
description: '사진 없이 이름과 설명만. 사진이 부실할 때.',
thumb: 'list',
Component: SpaceList,
},
],
inquiry: [
{
id: 'inquiry.cta',
name: '연락 카드',
description: '전화 · 카카오로 바로. 폼을 받을 준비가 안 됐을 때.',
thumb: 'centered',
Component: InquiryCta,
isDefault: true,
},
{
id: 'inquiry.form',
name: '문의 양식',
description: '인원 · 일정 · 연락처를 받는 신청서.',
thumb: 'form',
Component: InquiryForm,
},
],
programs: [
{
id: 'programs.cards',
name: '카드',
description: '소요시간 · 대상까지 한 장씩. 처음 오는 손님이 고르기 쉽다.',
thumb: 'cards',
Component: ProgramsCards,
isDefault: true,
},
{
id: 'programs.table',
name: '비교표',
description: '시간 · 대상 · 가격을 열로. 조건을 견줘 고르는 곳에.',
thumb: 'table',
Component: ProgramsTable,
},
],
exhibition: [
{
id: 'exhibition.gallery',
name: '전시 갤러리',
description: '전시 사진을 크게 깔고 관람 정보를 붙인다.',
thumb: 'grid',
Component: ExhibitionGallery,
isDefault: true,
},
{
id: 'exhibition.notice',
name: '관람 공지',
description: '사진 없이 안내 문구만. 일정이 자주 바뀌는 곳에.',
thumb: 'timeline',
Component: ExhibitionNotice,
},
],
};
/** 그 업종에서 고를 수 있는 배리에이션. 업종 제한이 걸린 건 걸러낸다. */
export function variantsFor(sectionType: string, industry: IndustryType): SectionVariant[] {
const all = SECTION_VARIANTS[sectionType] ?? [];
return all.filter((v) => !v.industries || v.industries.includes(industry));
}
/** 그 타입의 기본 배리에이션. isDefault 가 없으면 첫 번째. */
export function defaultVariant(sectionType: string): SectionVariant | undefined {
const all = SECTION_VARIANTS[sectionType] ?? [];
return all.find((v) => v.isDefault) ?? all[0];
}
/**
* 실제로 그릴 배리에이션.
*
* 저장된 variantId 가 지워졌거나(배리에이션을 뺐거나) 업종이 바뀌어 못 쓰게 됐어도
* 기본값으로 떨어진다 — 빈 화면 대신 무언가는 반드시 그린다.
*/
export function resolveVariant(
section: SectionItem,
industry: IndustryType,
): SectionVariant | undefined {
const available = variantsFor(section.type, industry);
const picked = available.find((v) => v.id === section.variantId);
return picked ?? defaultVariant(section.type);
}
@@ -0,0 +1,175 @@
/**
* 배리에이션 와이어프레임 썸네일.
*
* 사장님은 "InfoTable" 이라는 이름으로 고르지 않는다 — 모양을 보고 고른다.
* 그래서 배리에이션 카드에는 반드시 그림이 붙고, 그 그림은 여기 한 곳에서만 그린다.
*/
import type {ThumbKey} from './types';
const BOX = 'fill-stone-300';
const LINE = 'fill-stone-200';
const ACCENT = 'fill-stone-500';
/** 40×28 좌표계 위에 회색 블록으로 레이아웃 얼개만 그린다. */
const SHAPES: Record<ThumbKey, React.ReactNode> = {
fullbleed: (
<>
<rect x="0" y="0" width="40" height="28" className={BOX} />
<rect x="3" y="18" width="20" height="3" className={ACCENT} />
<rect x="3" y="23" width="12" height="2" className={LINE} />
</>
),
split: (
<>
<rect x="2" y="6" width="16" height="3" className={ACCENT} />
<rect x="2" y="12" width="14" height="2" className={LINE} />
<rect x="2" y="16" width="10" height="2" className={LINE} />
<rect x="22" y="5" width="16" height="18" className={BOX} />
</>
),
stack: (
<>
<rect x="2" y="3" width="36" height="12" className={BOX} />
<rect x="2" y="18" width="24" height="2.5" className={ACCENT} />
<rect x="2" y="22" width="34" height="2" className={LINE} />
</>
),
centered: (
<>
<rect x="14" y="5" width="12" height="2" className={LINE} />
<rect x="9" y="10" width="22" height="3" className={ACCENT} />
<rect x="6" y="17" width="28" height="2" className={LINE} />
<rect x="10" y="21" width="20" height="2" className={LINE} />
</>
),
grid: (
<>
{[2, 11, 20, 29].map((x) =>
[4, 15].map((y) => (
<rect key={`${x}-${y}`} x={x} y={y} width="8" height="8" className={BOX} />
)),
)}
</>
),
masonry: (
<>
<rect x="2" y="3" width="11" height="13" className={BOX} />
<rect x="2" y="18" width="11" height="7" className={BOX} />
<rect x="15" y="3" width="11" height="8" className={BOX} />
<rect x="15" y="13" width="11" height="12" className={BOX} />
<rect x="28" y="3" width="10" height="14" className={BOX} />
<rect x="28" y="19" width="10" height="6" className={BOX} />
</>
),
carousel: (
<>
<rect x="1" y="6" width="6" height="14" className={LINE} />
<rect x="9" y="4" width="22" height="18" className={BOX} />
<rect x="33" y="6" width="6" height="14" className={LINE} />
<rect x="17" y="24" width="6" height="1.5" className={ACCENT} />
</>
),
list: (
<>
{[3, 11, 19].map((y) => (
<g key={y}>
<rect x="2" y={y} width="9" height="6" className={BOX} />
<rect x="13" y={y + 1} width="16" height="2" className={ACCENT} />
<rect x="13" y={y + 4} width="22" height="1.5" className={LINE} />
</g>
))}
</>
),
table: (
<>
<rect x="2" y="3" width="36" height="4" className={ACCENT} />
{[9, 14, 19, 24].map((y) => (
<g key={y}>
<rect x="2" y={y} width="14" height="2" className={LINE} />
<rect x="20" y={y} width="18" height="2" className={LINE} />
</g>
))}
</>
),
cards: (
<>
{[2, 21].map((x) =>
[3, 15].map((y) => (
<g key={`${x}-${y}`}>
<rect x={x} y={y} width="17" height="9" className={LINE} />
<rect x={x + 2} y={y + 2} width="9" height="2" className={ACCENT} />
<rect x={x + 2} y={y + 5.5} width="13" height="1.5" className={BOX} />
</g>
)),
)}
</>
),
accordion: (
<>
<rect x="2" y="3" width="36" height="4" className={ACCENT} />
<rect x="2" y="9" width="36" height="7" className={LINE} />
<rect x="2" y="18" width="36" height="4" className={ACCENT} />
<rect x="2" y="24" width="36" height="2" className={LINE} />
</>
),
'two-column': (
<>
{[2, 21].map((x) => (
<g key={x}>
<rect x={x} y="4" width="17" height="2.5" className={ACCENT} />
<rect x={x} y="8.5" width="15" height="1.5" className={LINE} />
<rect x={x} y="15" width="17" height="2.5" className={ACCENT} />
<rect x={x} y="19.5" width="15" height="1.5" className={LINE} />
</g>
))}
</>
),
banner: (
<>
<rect x="0" y="8" width="40" height="12" className={ACCENT} />
<rect x="4" y="11" width="16" height="2.5" className="fill-white/80" />
<rect x="26" y="11" width="10" height="5" className="fill-white/90" />
</>
),
form: (
<>
<rect x="2" y="3" width="20" height="2.5" className={ACCENT} />
<rect x="2" y="8" width="17" height="4" className={LINE} />
<rect x="21" y="8" width="17" height="4" className={LINE} />
<rect x="2" y="14" width="36" height="6" className={LINE} />
<rect x="2" y="22" width="36" height="4" className={ACCENT} />
</>
),
timeline: (
<>
<rect x="5" y="3" width="1.5" height="22" className={LINE} />
{[4, 12, 20].map((y) => (
<g key={y}>
<circle cx="5.75" cy={y + 1.5} r="2" className={ACCENT} />
<rect x="11" y={y} width="14" height="2" className={ACCENT} />
<rect x="11" y={y + 3.5} width="24" height="1.5" className={LINE} />
</g>
))}
</>
),
compact: (
<>
<rect x="2" y="8" width="12" height="2.5" className={ACCENT} />
<rect x="2" y="13" width="36" height="6" className={LINE} />
</>
),
};
export function VariantThumb({thumb, className}: {thumb: ThumbKey; className?: string}) {
return (
<svg
viewBox="0 0 40 28"
role="presentation"
className={className}
preserveAspectRatio="xMidYMid meet"
>
<rect x="0" y="0" width="40" height="28" className="fill-white" />
{SHAPES[thumb]}
</svg>
);
}
@@ -0,0 +1,76 @@
/**
* 캔버스 배리에이션 계약.
*
* 섹션 하나 = "무엇을 보여줄지"(데이터) + "어떻게 보여줄지"(배리에이션).
* 데이터는 이 props 로 고정하고, 배리에이션만 갈아끼운다 —
* 그래야 사장님이 레이아웃을 바꿔도 내용이 날아가지 않는다.
*/
import type {ComponentType, ReactNode} from 'react';
import type {
IndustryType,
InfoField,
PhotoItem,
SectionItem,
TemplateItem,
} from '@o2o/shared';
import type {WeatherLocation} from '@/stores/builder';
/** 모든 배리에이션이 동일하게 받는 입력. 배리에이션은 이 밖의 것을 요구하지 않는다. */
export interface SectionRenderProps {
/** 섹션 메타(id · type · name · variantId). 프레임의 앵커 id 와 배지 라벨이 여기서 나온다. */
section: SectionItem;
industryId: IndustryType;
storeName: string;
location: string;
weatherLocation?: WeatherLocation;
template: TemplateItem;
infoFields: InfoField[];
photos: PhotoItem[];
/** 에디터에서 선택된 섹션인가(미리보기 모드면 항상 false). */
isSelected: boolean;
onSelect: () => void;
}
export type SectionVariantComponent = ComponentType<SectionRenderProps>;
/** 디자인 탭이 카드로 그리는 배리에이션 한 칸. */
export interface SectionVariant {
/** 전역 유일. `<sectionType>.<slug>` 규칙 — 저장된 값이 어느 섹션 것인지 눈으로 읽힌다. */
id: string;
/** 사장님에게 보이는 이름. 개발 용어 말고 "왼쪽 사진 · 오른쪽 글" 같은 말로 쓴다. */
name: string;
/** 언제 이걸 고르면 좋은지 한 줄. */
description: string;
/** 와이어프레임 썸네일 키(`thumbs.tsx`). 글보다 그림이 빨리 읽힌다. */
thumb: ThumbKey;
Component: SectionVariantComponent;
/** 특정 업종에서만 의미 있는 배리에이션이면 여기로 좁힌다. 비우면 전 업종 공통. */
industries?: IndustryType[];
/** '기본'으로 표시할 배리에이션. 타입당 하나. */
isDefault?: boolean;
}
export type ThumbKey =
| 'fullbleed'
| 'split'
| 'stack'
| 'centered'
| 'grid'
| 'masonry'
| 'carousel'
| 'list'
| 'table'
| 'cards'
| 'accordion'
| 'two-column'
| 'banner'
| 'form'
| 'timeline'
| 'compact';
/** 섹션 프레임의 배경 톤. 배리에이션마다 다른 톤을 골라 리듬을 만든다. */
export type SectionTone = 'paper' | 'white' | 'tint' | 'dark';
export interface SectionFrameSlots {
children: ReactNode;
}
@@ -0,0 +1,36 @@
/**
* 예약 · 띠배너 — 브랜드 색으로 화면을 가로지르는 강한 전환 유도.
* 예약이 유일한 목표인 사이트에 맞는다(대신 자주 쓰면 광고처럼 보인다).
*/
import {Calendar} from 'lucide-react';
import {CtaLink, SectionFrame} from '../../primitives';
import type {SectionRenderProps} from '../../types';
import {bookingHref} from '../common';
export function BookingBanner(props: SectionRenderProps) {
const {section, isSelected, onSelect, industryId, storeName, template} = props;
return (
<SectionFrame section={section} isSelected={isSelected} onSelect={onSelect} padded={false}>
<div className="px-4 py-10 sm:px-6 sm:py-14" style={{backgroundColor: template.colors.primary}}>
<div className="mx-auto flex max-w-[880px] flex-col items-center justify-between gap-5 text-center sm:flex-row sm:text-left">
<div className="space-y-1.5 text-white">
<h3 className="serif-title text-lg font-bold sm:text-2xl">
{section.name}
</h3>
<p className="text-xs opacity-90 sm:text-sm">
{section.body || section.description || `${storeName} · 실시간 캘린더에서 남은 날짜를 확인할 수 있습니다`}
</p>
</div>
<div className="flex shrink-0 items-center gap-2">
<CtaLink href={bookingHref(industryId, storeName)} variant="pill">
<Calendar className="size-3.5" />
<span>예약 캘린더</span>
</CtaLink>
</div>
</div>
</div>
</SectionFrame>
);
}
@@ -0,0 +1,36 @@
/**
* 예약 · 카드 — 가운데 놓인 조용한 안내 카드. 다른 섹션의 흐름을 끊지 않는다.
*/
import {Calendar} from 'lucide-react';
import {CtaLink, SectionBody, SectionFrame, SectionHeading} from '../../primitives';
import type {SectionRenderProps} from '../../types';
import {bookingHref} from '../common';
export function BookingCard(props: SectionRenderProps) {
const {section, isSelected, onSelect, industryId, storeName, template} = props;
return (
<SectionFrame section={section} isSelected={isSelected} onSelect={onSelect} tone="white">
<SectionBody>
<SectionHeading title={section.name} subtitle={section.description} colors={template.colors} />
<div className="mx-auto max-w-lg space-y-3 rounded-xl border border-stone-200/80 bg-white p-6 text-center shadow-2xs">
<h4 className="text-sm font-bold text-stone-900" style={{color: template.colors.text}}>
네이버 실시간 온라인 예약
</h4>
<p className="text-xs text-stone-500">
{section.body || '원하시는 날짜와 객실을 선택하여 캘린더에서 바로 확정 예약하실 수 있습니다.'}
</p>
<CtaLink
href={bookingHref(industryId, storeName)}
variant="solid"
colors={template.colors}
>
<Calendar className="size-3.5" />
<span>네이버 예약 캘린더 열기</span>
</CtaLink>
</div>
</SectionBody>
</SectionFrame>
);
}
@@ -0,0 +1,101 @@
/**
* 배리에이션들이 공유하는 데이터 갈무리.
*
* "어떤 사진을 대표로 쓰나 / 예약 링크는 어디로 가나" 같은 판단은 레이아웃과 무관하다.
* 배리에이션마다 따로 정하면 같은 섹션인데 배리에이션을 바꾼 순간 링크가 달라진다.
*
* ★ 시연용 폴백은 없다.
* 한때 이 파일은 달빛스테이(숙박 시연 세트)와 업종 시드 문구를 폴백으로 들고 있었고,
* `demoOnly()` 게이트가 "실사업장에서만" 그걸 껐다. 그 구조 자체를 걷어냈다 —
* 게이트가 한 곳이라도 빠지면 남의 가게 사진·전화번호·메뉴가 사장님 화면에 뜨고,
* 사장님은 그게 자기 가게 내용인 줄 알고 그대로 발행한다.
* 값이 없으면 **아무것도 그리지 않는다.** 발행 사이트(solution/site)와 같은 규칙이다.
*/
import type {IndustryType, InfoField, PhotoItem} from '@o2o/shared';
import {INDUSTRY_CONFIGS} from '@/data/industryData';
import type {TilePhoto} from '../primitives';
/** 화면에 찍히는 "언제 기준" 표기. 발행 사이트에서는 payload 의 updatedAt 이 이 자리를 대신한다. */
export const TODAY_KO = new Date().toLocaleDateString('ko-KR', {
year: 'numeric',
month: 'long',
day: 'numeric',
});
/**
* 업종 설정(섹션 목록 · 템플릿 · 채널).
*
* ★ 여기에는 **구조만** 남아 있다. 문구·메뉴·FAQ 같은 콘텐츠 시드는 전부 지웠다 —
* 가공의 가게 이름이 박힌 문장("포레스트 힐은 산자락 아래…")이 실사업장 화면에
* 자기 소개문처럼 떴기 때문이다. 콘텐츠는 서버(fact·unit·faq)만 소유한다.
*/
export function industryConfig(industryId: IndustryType) {
return INDUSTRY_CONFIGS[industryId];
}
/**
* 소개 문구.
*
* 수집·생성된 `intro` fact 만 쓴다. 없으면 빈 값을 돌려주고, 부르는 쪽이
* "아직 소개문이 없습니다"를 그린다 — 남의 문장으로 자리를 메우지 않는다.
*/
export function introParagraph(_industryId: IndustryType, infoFields: InfoField[]): string {
const collected = infoFields.find((f) => f.id === 'intro' || f.id === 'room_intro');
return collected?.value?.trim() ?? '';
}
/**
* 이용 규정으로 읽히는 fact 들. 순서가 곧 화면 순서다.
*
* ★ 스키마에 있는 key 만 적는다. 여기 없는 규정은 만들지 않는다 —
* 예전에는 '체크인 16:00 / 체크아웃 11:00' 같은 가공의 규정이 상수로 박혀 있어
* 모든 사업장 화면에 똑같이 떴다. 사장님은 그게 자기 규정인 줄 알고 발행했다.
*/
const RULE_FIELD_IDS = [
'check_in_time',
'check_out_time',
'cancel_policy',
'cooking_allowed',
'pet_allowed',
'smoking',
'extra_person_fee',
];
/** 확인된 fact 에서만 이용 규정 줄을 만든다. 없으면 빈 목록 — 부르는 쪽이 빈 상태를 그린다. */
export function ruleItems(infoFields: InfoField[]): string[] {
return RULE_FIELD_IDS.map((id) => infoFields.find((f) => f.id === id))
.filter((f): f is InfoField => Boolean(f?.value?.trim()))
.map((f) => `${f.label}: ${f.value.trim()}`);
}
/** 대표 사진. 지정이 없으면 첫 장으로 떨어진다 — 히어로가 빈 채로 나가지 않게. */
export function primaryPhoto(photos: PhotoItem[]) {
return photos.find((p) => p.isPrimary) ?? photos[0];
}
/** 수집된 사진(props)을 갤러리 타일 모양으로. 캡션은 사진 제목을 그대로 쓴다. */
function toTiles(photos: PhotoItem[]): TilePhoto[] {
return photos.map((p) => ({
id: p.id,
url: p.url,
alt: p.title,
caption: p.title,
category: p.category,
}));
}
/** 갤러리에 깔 사진 — 수집된 것만. 없으면 빈 목록이고, 부르는 쪽이 빈 상태를 그린다. */
export function galleryPhotos(_industryId: IndustryType, photos: PhotoItem[]): TilePhoto[] {
return toTiles(photos.filter((photo) => photo.isVisible !== false));
}
/**
* 예약 버튼이 향할 곳.
*
* ★ 실사업장의 예약 채널(place_links)은 SectionRenderProps 로 흘러오지 않는다.
* 그래서 상호 검색으로 떨어뜨린다 — 시연용 예약 링크를 붙이는 것보다 안전하다.
* (확정된 링크를 쓰려면 계약에 채널 URL 을 얹어야 한다.)
*/
export function bookingHref(_industryId: IndustryType, storeName: string) {
return `https://search.naver.com/search.naver?query=${encodeURIComponent(storeName)}`;
}
@@ -0,0 +1,57 @@
/**
* 관람 안내 · 갤러리 — 전시 사진을 크게 깔고 관람 정보를 옆에 붙인다.
*/
import {Clock, Ticket} from 'lucide-react';
import {
FeatureCard,
PhotoTile,
SectionBody,
SectionFrame,
SectionHeading,
} from '../../primitives';
import type {SectionRenderProps} from '../../types';
import {galleryPhotos} from '../common';
export function ExhibitionGallery(props: SectionRenderProps) {
const {section, isSelected, onSelect, industryId, template, photos, infoFields} = props;
const items = galleryPhotos(industryId, photos).slice(0, 4);
const hours = infoFields.find((f) => f.id === 'operating_hours');
const fee = infoFields.find((f) => f.id === 'admission' || f.id === 'price_range');
return (
<SectionFrame section={section} isSelected={isSelected} onSelect={onSelect} tone="white">
<SectionBody>
<SectionHeading
title={section.name}
subtitle={section.description}
colors={template.colors}
/>
<div className="grid grid-cols-2 gap-2.5 sm:gap-3">
{items.map((photo) => (
<PhotoTile key={photo.id} photo={photo} fit="landscape" />
))}
</div>
<div className="grid grid-cols-1 gap-3 sm:grid-cols-2">
{hours && (
<FeatureCard
icon={Clock}
title="관람 시간"
description={hours.value}
colors={template.colors}
/>
)}
{fee && (
<FeatureCard
icon={Ticket}
title="관람료"
description={fee.value}
colors={template.colors}
/>
)}
</div>
</SectionBody>
</SectionFrame>
);
}
@@ -0,0 +1,44 @@
/**
* 관람 안내 · 공지 — 사진 없이 안내 문구만. 전시 일정이 자주 바뀌는 곳에 부담이 적다.
*/
import {Info} from 'lucide-react';
import {SectionBody, SectionFrame, SectionHeading} from '../../primitives';
import type {SectionRenderProps} from '../../types';
export function ExhibitionNotice(props: SectionRenderProps) {
const {section, isSelected, onSelect, storeName, template, infoFields} = props;
const notices = infoFields
.filter((f) => !f.requiresVerification || f.isVerified)
.slice(0, 4);
return (
<SectionFrame section={section} isSelected={isSelected} onSelect={onSelect} tone="paper">
<SectionBody width="narrow">
<SectionHeading
variant="eyebrow"
eyebrow="NOTICE"
title={section.name}
trailing={<Info className="size-5 text-stone-400" />}
colors={template.colors}
/>
<div className="space-y-3 rounded-2xl border border-stone-200/80 bg-white p-5 shadow-2xs">
<p className="text-xs leading-relaxed text-stone-600">
{section.body || `${storeName}의 상설 전시와 아트숍은 별도 예약 없이 관람하실 수 있습니다. 기획 전시 일정은 변경될 수 있으니 방문 전 확인해 주세요.`}
</p>
<dl className="space-y-2 border-t border-stone-100 pt-3">
{notices.map((field) => (
<div key={field.id} className="flex gap-3 text-xs">
<dt className="w-20 shrink-0 font-semibold text-stone-400">{field.label}</dt>
<dd className="font-medium text-stone-800" style={{color: template.colors.text}}>
{field.value}
</dd>
</div>
))}
</dl>
</div>
</SectionBody>
</SectionFrame>
);
}
@@ -0,0 +1,68 @@
/**
* FAQ · 아코디언 — 질문만 보이고 누르면 답이 열린다. 항목이 많아도 화면이 짧다.
*/
import {useState} from 'react';
import {ChevronDown, ChevronUp} from 'lucide-react';
import {ListCard, SectionBody, SectionFrame, SectionHeading} from '../../primitives';
import type {SectionRenderProps} from '../../types';
import {faqEntries} from './useFaqList';
export function FaqAccordion(props: SectionRenderProps) {
const {section, isSelected, onSelect, industryId, template} = props;
const faqs = faqEntries(industryId);
const [openIdx, setOpenIdx] = useState<number | null>(0);
return (
<SectionFrame section={section} isSelected={isSelected} onSelect={onSelect} tone="paper">
<SectionBody>
<SectionHeading
title={section.name}
subtitle={section.description}
colors={template.colors}
/>
<ListCard>
{faqs.map((faq, idx) => {
const isOpen = openIdx === idx;
return (
<div key={faq.question}>
<button
type="button"
onClick={(e) => {
e.stopPropagation();
setOpenIdx(isOpen ? null : idx);
}}
aria-expanded={isOpen}
style={{color: template.colors.text}}
className="flex w-full cursor-pointer items-center justify-between gap-3 p-4 text-left text-xs font-bold text-stone-900 hover:bg-stone-50 sm:text-sm"
>
<span className="flex items-center gap-2.5">
<span
className="serif-title font-normal text-stone-400"
style={{color: template.colors.accent}}
>
Q.
</span>
<span>{faq.question}</span>
</span>
{isOpen ? (
<ChevronUp className="size-4 shrink-0 text-stone-400" />
) : (
<ChevronDown className="size-4 shrink-0 text-stone-400" />
)}
</button>
{isOpen && (
<div className="border-t border-stone-50 bg-stone-50/40 px-4 pb-4 pt-1 text-xs leading-relaxed text-stone-600 sm:text-sm">
{faq.answer}
</div>
)}
</div>
);
})}
</ListCard>
</SectionBody>
</SectionFrame>
);
}
@@ -0,0 +1,50 @@
/**
* FAQ · 펼친 목록 — 질문과 답을 모두 열어 둔다.
* 손님이 클릭 없이 훑고 지나가게 하고 싶을 때(검색 노출에도 유리하다).
*/
import {SectionBody, SectionFrame, SectionHeading} from '../../primitives';
import type {SectionRenderProps} from '../../types';
import {faqEntries} from './useFaqList';
export function FaqOpenList(props: SectionRenderProps) {
const {section, isSelected, onSelect, industryId, template} = props;
const faqs = faqEntries(industryId);
return (
<SectionFrame section={section} isSelected={isSelected} onSelect={onSelect} tone="paper">
<SectionBody>
<SectionHeading
title={section.name}
subtitle={section.description}
colors={template.colors}
/>
<dl className="space-y-4">
{faqs.map((faq) => (
<div
key={faq.question}
className="space-y-1.5 rounded-xl border border-stone-200/80 bg-white p-4 shadow-2xs"
>
<dt
className="flex items-start gap-2 text-xs font-bold text-stone-900 sm:text-sm"
style={{color: template.colors.text}}
>
<span
className="serif-title font-normal text-stone-400"
style={{color: template.colors.accent}}
>
Q.
</span>
<span>{faq.question}</span>
</dt>
<dd className="flex items-start gap-2 text-xs leading-relaxed text-stone-600 sm:text-sm">
<span className="serif-title font-normal text-stone-300">A.</span>
<span>{faq.answer}</span>
</dd>
</div>
))}
</dl>
</SectionBody>
</SectionFrame>
);
}
@@ -0,0 +1,39 @@
/**
* FAQ · 2단 — 넓은 화면에서 두 줄씩 나눠 세로 길이를 반으로 줄인다.
*/
import {SectionBody, SectionFrame, SectionHeading} from '../../primitives';
import type {SectionRenderProps} from '../../types';
import {faqEntries} from './useFaqList';
export function FaqTwoColumn(props: SectionRenderProps) {
const {section, isSelected, onSelect, industryId, template} = props;
const faqs = faqEntries(industryId);
return (
<SectionFrame section={section} isSelected={isSelected} onSelect={onSelect} tone="white">
<SectionBody width="wide">
<SectionHeading
variant="centered"
eyebrow="FAQ"
title={section.name}
subtitle={section.description}
colors={template.colors}
/>
<dl className="grid grid-cols-1 gap-x-8 gap-y-5 md:grid-cols-2">
{faqs.map((faq) => (
<div key={faq.question} className="space-y-1.5 border-t border-stone-200/80 pt-4">
<dt
className="text-xs font-bold text-stone-900 sm:text-sm"
style={{color: template.colors.text}}
>
{faq.question}
</dt>
<dd className="text-xs leading-relaxed text-stone-600">{faq.answer}</dd>
</div>
))}
</dl>
</SectionBody>
</SectionFrame>
);
}
@@ -0,0 +1,24 @@
import type {IndustryType} from '@o2o/shared';
export interface FaqEntry {
question: string;
answer: string;
}
/**
* FAQ 원본.
*
* ★ 지금은 항상 빈 목록이다. 캔버스 계약(SectionRenderProps)에 FAQ 가 없기 때문이다 —
* 에디터는 구조적으로 실제 FAQ 를 받을 창구가 없다.
*
* ★ 업종 시드 FAQ 를 폴백으로 쓰던 코드를 걷어냈다. 그 안에는 가공의 값이 가격까지 붙어 있었고
* ("숯과 그릴 세트(25,000원)", "기준 2인 초과 시 1인당 30,000원"), 사장님이 팔지도 않는
* 조건을 자기 사이트로 읽었다. 손님이 그 금액으로 오면 클레임이다.
*
* 진짜 FAQ 는 COPY 잡이 **확인된 fact 만 근거로** 만들고 사장님 승인을 거쳐
* 서버(fact.faqs)에 들어간다 — 그게 유일한 출처다. 캔버스로 흘려보내려면
* SectionRenderProps 에 faqs 를 얹어야 한다.
*/
export function faqEntries(_industryId: IndustryType): FaqEntry[] {
return [];
}
@@ -0,0 +1,66 @@
/**
* 히어로 · 에디토리얼 — 상단 브랜드 바 + 큰 사진 + 가운데 세리프 카피.
* 감성 숙소/공방처럼 "분위기부터 보여주고 싶은" 곳의 기본값.
*/
import {Calendar} from 'lucide-react';
import {SectionFrame} from '../../primitives';
import {CtaLink} from '../../primitives';
import type {SectionRenderProps} from '../../types';
import {bookingHref, primaryPhoto} from '../common';
export function HeroEditorial(props: SectionRenderProps) {
const {section, isSelected, onSelect, industryId, storeName, location, template, photos} = props;
const cover = primaryPhoto(photos);
// 사진이 없으면 <img> 없이 어두운 판만 남긴다 — 시연용 사진으로 자리를 메우지 않는다.
const coverUrl = cover?.url;
return (
<SectionFrame section={section} isSelected={isSelected} onSelect={onSelect} padded={false}>
<div
className="flex w-full select-none flex-col"
style={{backgroundColor: template.colors.bg}}
>
<div className="mx-auto flex w-full max-w-[1120px] items-center justify-between border-b border-stone-200/60 bg-white/90 px-4 py-4 backdrop-blur-xs sm:px-6">
<span
className="serif-title text-base font-bold uppercase tracking-widest text-stone-800 sm:text-lg"
style={{color: template.colors.text}}
>
{storeName}
</span>
</div>
<div className="relative flex h-[50vh] w-full items-center justify-center overflow-hidden bg-stone-900 sm:h-[65vh]">
{coverUrl && (
<img
src={coverUrl}
alt={storeName}
className="absolute inset-0 size-full object-cover opacity-75"
/>
)}
<div className="absolute inset-0 bg-black/45" />
<div className="relative z-10 mx-auto w-full max-w-xl space-y-4 px-6 text-center text-white">
<h1 className="serif-title text-2xl font-bold leading-tight tracking-tight drop-shadow-xs sm:text-4xl md:text-5xl">
{storeName}
</h1>
<p className="text-xs font-light tracking-wide text-stone-200 sm:text-sm md:text-base">
{section.description || location}
</p>
<div className="flex items-center justify-center gap-2 pt-2">
<CtaLink
href={bookingHref(industryId, storeName)}
variant="pill"
colors={template.colors}
>
<Calendar className="size-3.5" />
<span>실시간 예약</span>
</CtaLink>
</div>
</div>
</div>
</div>
</SectionFrame>
);
}
@@ -0,0 +1,54 @@
/**
* 히어로 · 풀블리드 — 화면을 꽉 채운 사진 위에 왼쪽 아래로 붙는 큰 타이포.
* 사진 한 장의 힘이 강한 곳(뷰 좋은 스테이, 플레이팅이 강한 다이닝)에 맞는다.
*/
import {Calendar, MapPin} from 'lucide-react';
import {CtaLink, SectionFrame} from '../../primitives';
import type {SectionRenderProps} from '../../types';
import {bookingHref, primaryPhoto} from '../common';
export function HeroFullBleed(props: SectionRenderProps) {
const {section, isSelected, onSelect, industryId, storeName, location, template, photos} = props;
const cover = primaryPhoto(photos);
// 사진이 없으면 <img> 를 아예 렌더하지 않고 어두운 배경만 남긴다.
const coverUrl = cover?.url;
return (
<SectionFrame section={section} isSelected={isSelected} onSelect={onSelect} padded={false}>
<div className="relative h-[62vh] min-h-[380px] w-full select-none overflow-hidden bg-stone-900 sm:h-[78vh]">
{coverUrl && (
<img
src={coverUrl}
alt={storeName}
className="absolute inset-0 size-full object-cover"
/>
)}
<div className="absolute inset-0 bg-gradient-to-t from-black/85 via-black/25 to-black/10" />
<div className="absolute inset-x-0 bottom-0 px-6 pb-10 sm:px-10 sm:pb-14">
<div className="mx-auto max-w-[1120px] space-y-3 text-white">
<span className="inline-flex items-center gap-1.5 rounded-full border border-white/25 bg-white/10 px-3 py-1 text-[11px] font-medium backdrop-blur-xs">
<MapPin className="size-3" />
{section.description || location}
</span>
<h1 className="serif-title max-w-2xl text-3xl font-bold leading-[1.15] tracking-tight drop-shadow-sm sm:text-5xl md:text-6xl">
{storeName}
</h1>
<div className="flex flex-wrap items-center gap-2 pt-2">
<CtaLink
href={bookingHref(industryId, storeName)}
variant="brand"
colors={template.colors}
>
<Calendar className="size-3.5" />
<span>지금 예약하기</span>
</CtaLink>
</div>
</div>
</div>
</div>
</SectionFrame>
);
}
@@ -0,0 +1,50 @@
/**
* 히어로 · 좌우 분할 — 왼쪽 글, 오른쪽 사진.
* 첫 화면에서 "무엇을 파는 곳인지"를 글로 먼저 읽혀야 하는 업종에 맞는다.
*/
import {SectionFrame} from '../../primitives';
import type {SectionRenderProps} from '../../types';
import {industryConfig, primaryPhoto} from '../common';
export function HeroSplit(props: SectionRenderProps) {
const {section, isSelected, onSelect, industryId, storeName, location, template, photos} = props;
const config = industryConfig(industryId);
const cover = primaryPhoto(photos);
return (
<SectionFrame section={section} isSelected={isSelected} onSelect={onSelect} padded={false}>
<div className="p-6 sm:p-10" style={{backgroundColor: template.colors.bg}}>
<div className="mx-auto grid max-w-4xl grid-cols-1 items-center gap-6 md:grid-cols-12">
<div className="space-y-4 md:col-span-7">
<span
className="inline-flex items-center gap-2 rounded px-2.5 py-1 text-xs font-semibold"
style={{
backgroundColor: `${template.colors.primary}12`,
color: template.colors.primary,
}}
>
<span
className="size-1.5 rounded-full"
style={{backgroundColor: template.colors.primary}}
/>
{section.description || `${config.name} · ${location}`}
</span>
<h1
className="text-2xl font-extrabold leading-tight tracking-tight sm:text-4xl"
style={{color: template.colors.text}}
>
{storeName}
</h1>
</div>
<div className="md:col-span-5">
<div className="relative aspect-4/3 overflow-hidden rounded-lg border border-slate-200/60 shadow-xs">
<img src={cover?.url} alt={storeName} className="size-full object-cover" />
</div>
</div>
</div>
</div>
</SectionFrame>
);
}
@@ -0,0 +1,47 @@
/**
* 히어로 · 타이포 중심 — 사진 없이 여백과 글자만.
* 쓸 만한 사진이 아직 없거나, 조용한 인상을 주고 싶을 때 고른다.
*/
import {ArrowUpRight} from 'lucide-react';
import {CtaLink, SectionFrame} from '../../primitives';
import type {SectionRenderProps} from '../../types';
import {bookingHref, industryConfig} from '../common';
export function HeroTypeOnly(props: SectionRenderProps) {
const {section, isSelected, onSelect, industryId, storeName, location, template} = props;
const config = industryConfig(industryId);
return (
<SectionFrame section={section} isSelected={isSelected} onSelect={onSelect} padded={false}>
<div
className="px-6 py-20 sm:px-10 sm:py-28"
style={{backgroundColor: template.colors.bg}}
>
<div className="mx-auto max-w-2xl space-y-6 text-center">
<span
className="text-[11px] font-semibold uppercase tracking-[0.35em]"
style={{color: template.colors.accent}}
>
{section.description || `${config.name} · ${location}`}
</span>
<h1
className="serif-title text-3xl font-bold leading-[1.2] tracking-tight sm:text-5xl"
style={{color: template.colors.text}}
>
{storeName}
</h1>
<div className="mx-auto h-px w-12" style={{backgroundColor: template.colors.primary}} />
<div className="flex justify-center pt-2">
<CtaLink href={bookingHref(industryId, storeName)} variant="outline">
<span>{storeName} 둘러보기</span>
<ArrowUpRight className="size-3.5" />
</CtaLink>
</div>
</div>
</div>
</SectionFrame>
);
}
@@ -0,0 +1,41 @@
/**
* 기본 정보 · 카드 — 항목마다 한 장씩. 모바일에서 손가락으로 훑기 좋다.
*/
import {
HiddenFieldsNotice,
InfoRow,
SectionBody,
SectionFrame,
SectionHeading,
} from '../../primitives';
import type {SectionRenderProps} from '../../types';
import {TODAY_KO} from '../common';
export function InfoCards(props: SectionRenderProps) {
const {section, isSelected, onSelect, template, infoFields} = props;
const visible = infoFields.filter((f) => !f.requiresVerification || f.isVerified);
const hidden = infoFields.filter((f) => f.requiresVerification && !f.isVerified).length;
return (
<SectionFrame section={section} isSelected={isSelected} onSelect={onSelect} tone="tint">
<SectionBody>
<SectionHeading
title={section.name}
subtitle={section.description}
trailing={<HiddenFieldsNotice count={hidden} />}
colors={template.colors}
/>
<div className="grid grid-cols-1 gap-2.5 sm:grid-cols-2">
{visible.map((field) => (
<InfoRow key={field.id} field={field} variant="card" colors={template.colors} />
))}
</div>
<div className="text-right">
<span className="font-mono text-[11px] text-stone-400">* {TODAY_KO} 기준 정보입니다.</span>
</div>
</SectionBody>
</SectionFrame>
);
}
@@ -0,0 +1,41 @@
/**
* 기본 정보 · 한 줄 요약 — 값들을 문장처럼 이어 붙인 가장 좁은 형태.
* 정보가 적거나, 아래 섹션으로 빨리 넘기고 싶을 때.
*/
import {
HiddenFieldsNotice,
InfoRow,
SectionBody,
SectionFrame,
SectionHeading,
} from '../../primitives';
import type {SectionRenderProps} from '../../types';
import {TODAY_KO} from '../common';
export function InfoInline(props: SectionRenderProps) {
const {section, isSelected, onSelect, template, infoFields} = props;
const visible = infoFields.filter((f) => !f.requiresVerification || f.isVerified);
const hidden = infoFields.filter((f) => f.requiresVerification && !f.isVerified).length;
return (
<SectionFrame section={section} isSelected={isSelected} onSelect={onSelect} tone="white">
<SectionBody width="narrow">
<SectionHeading
variant="minimal"
title={section.name}
subtitle={section.description}
trailing={<HiddenFieldsNotice count={hidden} />}
colors={template.colors}
/>
<div className="flex flex-wrap gap-x-5 gap-y-2.5 rounded-xl border border-stone-200/70 bg-stone-50/60 p-4">
{visible.map((field) => (
<InfoRow key={field.id} field={field} variant="inline" colors={template.colors} />
))}
</div>
<span className="block font-mono text-[11px] text-stone-400">* {TODAY_KO} 기준</span>
</SectionBody>
</SectionFrame>
);
}
@@ -0,0 +1,42 @@
/**
* 기본 정보 · 표 — 라벨과 값을 선으로 나눈 가장 읽기 쉬운 형태.
* 항목이 많아도 눈이 안 흔들린다.
*/
import {
HiddenFieldsNotice,
InfoRow,
SectionBody,
SectionFrame,
SectionHeading,
} from '../../primitives';
import type {SectionRenderProps} from '../../types';
import {TODAY_KO} from '../common';
export function InfoTable(props: SectionRenderProps) {
const {section, isSelected, onSelect, template, infoFields} = props;
const visible = infoFields.filter((f) => !f.requiresVerification || f.isVerified);
const hidden = infoFields.filter((f) => f.requiresVerification && !f.isVerified).length;
return (
<SectionFrame section={section} isSelected={isSelected} onSelect={onSelect} tone="white">
<SectionBody>
<SectionHeading
title={section.name}
subtitle={section.description}
trailing={<HiddenFieldsNotice count={hidden} />}
colors={template.colors}
/>
<div className="overflow-hidden rounded-xl border border-stone-200/80 bg-stone-50/60 [&>*+*]:border-t [&>*+*]:border-stone-200/70">
{visible.map((field) => (
<InfoRow key={field.id} field={field} variant="row" colors={template.colors} />
))}
</div>
<div className="text-right">
<span className="font-mono text-[11px] text-stone-400">* {TODAY_KO} 기준 정보입니다.</span>
</div>
</SectionBody>
</SectionFrame>
);
}
@@ -0,0 +1,49 @@
/**
* 문의 · 연락 카드 — 전화 / 카카오 / 인스타로 바로 보낸다.
* 폼을 받을 준비가 안 된 사장님에게는 이쪽이 사고가 없다.
*/
import {Phone} from 'lucide-react';
import {
EmptyStateNotice,
SectionBody,
SectionFrame,
SectionHeading,
} from '../../primitives';
import type {SectionRenderProps} from '../../types';
export function InquiryCta(props: SectionRenderProps) {
const {section, isSelected, onSelect, storeName, template} = props;
// ★ 연락처(place_links)는 SectionRenderProps 로 흘러오지 않는다. 값이 생기기 전까지
// 버튼째 숨긴다 — 시연용 번호를 붙이면 남의 가게로 전화가 간다.
const phone = props.infoFields.find((f) => f.id === 'phone')?.value?.trim();
return (
<SectionFrame section={section} isSelected={isSelected} onSelect={onSelect} tone="white">
<SectionBody width="narrow">
<SectionHeading variant="centered" title={section.name} subtitle={section.description} />
<div className="flex flex-col items-center gap-3 rounded-2xl border border-stone-200/80 bg-stone-50/70 p-6 text-center">
<p className="text-xs leading-relaxed text-stone-600">
{section.body || `${storeName} 단체·대관 문의는 아래로 연락 주시면 담당자가 안내해 드립니다.`}
</p>
{phone ? (
<div className="flex flex-wrap items-center justify-center gap-2">
<a
href={`tel:${phone}`}
onClick={(e) => e.stopPropagation()}
className="inline-flex items-center gap-1.5 rounded-xl px-5 py-2.5 text-xs font-semibold text-white shadow-xs transition-opacity hover:opacity-90"
style={{backgroundColor: template.colors.primary}}
>
<Phone className="size-3.5" />
<span>{phone}</span>
</a>
</div>
) : (
<EmptyStateNotice>연락처는 아직 준비 중입니다.</EmptyStateNotice>
)}
</div>
</SectionBody>
</SectionFrame>
);
}
@@ -0,0 +1,71 @@
/**
* 문의 · 신청서 — 인원/일정/연락처를 받는 양식.
*
* ★ 캔버스는 미리보기다. 여기서 제출은 실제로 나가지 않는다 —
* 그 사실을 화면에 적어 둬야 사장님이 "접수됐겠지" 하고 넘어가지 않는다.
*/
import {Send} from 'lucide-react';
import {SectionBody, SectionFrame, SectionHeading} from '../../primitives';
import type {SectionRenderProps} from '../../types';
const FIELDS = [
{id: 'name', label: '성함 / 단체명', placeholder: '홍길동 / ○○기업 총무팀'},
{id: 'contact', label: '연락처', placeholder: '010-0000-0000'},
{id: 'date', label: '희망 일자', placeholder: '2026-09-14'},
{id: 'headcount', label: '예상 인원', placeholder: '20명'},
];
export function InquiryForm(props: SectionRenderProps) {
const {section, isSelected, onSelect, template} = props;
return (
<SectionFrame section={section} isSelected={isSelected} onSelect={onSelect} tone="tint">
<SectionBody width="narrow">
<SectionHeading title={section.name} subtitle={section.description} />
<div
onClick={(e) => e.stopPropagation()}
role="presentation"
className="space-y-3 rounded-2xl border border-stone-200/80 bg-white p-5 shadow-2xs"
>
<div className="grid grid-cols-1 gap-3 sm:grid-cols-2">
{FIELDS.map((field) => (
<label key={field.id} className="space-y-1">
<span className="block text-[11px] font-semibold text-stone-500">
{field.label}
</span>
<input
type="text"
placeholder={field.placeholder}
className="w-full rounded-lg border border-stone-200 bg-stone-50 px-3 py-2 text-xs focus:bg-white focus:outline-none"
/>
</label>
))}
</div>
<label className="block space-y-1">
<span className="block text-[11px] font-semibold text-stone-500">문의 내용</span>
<textarea
rows={3}
placeholder="행사 성격, 필요한 준비물, 예산 등을 적어 주세요."
className="w-full resize-none rounded-lg border border-stone-200 bg-stone-50 px-3 py-2 text-xs focus:bg-white focus:outline-none"
/>
</label>
<button
type="button"
className="inline-flex w-full cursor-not-allowed items-center justify-center gap-1.5 rounded-xl px-5 py-2.5 text-xs font-semibold text-white opacity-90"
style={{backgroundColor: template.colors.primary}}
>
<Send className="size-3.5" />
<span>문의 보내기</span>
</button>
<p className="text-center text-[10px] text-stone-400">
미리보기 화면입니다 — 실제 접수는 발행 후 동작합니다.
</p>
</div>
</SectionBody>
</SectionFrame>
);
}
@@ -0,0 +1,35 @@
/**
* 소개 · 가운데 정렬 — 짧은 문단 하나로 끝내는 가장 조용한 구성.
*/
import {SectionBody, SectionFrame, SectionHeading} from '../../primitives';
import type {SectionRenderProps} from '../../types';
import {EmptyStateNotice} from '../../primitives';
import {introParagraph} from '../common';
export function IntroCentered(props: SectionRenderProps) {
const intro = props.section.body?.trim() || introParagraph(props.industryId, props.infoFields);
const {section, isSelected, onSelect, storeName, template} = props;
return (
<SectionFrame section={section} isSelected={isSelected} onSelect={onSelect} tone="paper">
<SectionBody width="narrow">
<SectionHeading
variant="centered"
eyebrow="ABOUT US"
title={section.name}
subtitle={section.description}
colors={template.colors}
/>
{intro ? (
<p className="text-center text-xs leading-relaxed text-stone-600 sm:text-sm">
{intro}
</p>
) : (
<EmptyStateNotice>
아직 소개문이 없습니다 — 확인된 정보만 근거로 씁니다.
</EmptyStateNotice>
)}
</SectionBody>
</SectionFrame>
);
}
@@ -0,0 +1,48 @@
/**
* 소개 · 사진 옆 글 — 왼쪽 세로 사진, 오른쪽 문단 + 특징 목록.
* 사진과 설명을 같은 눈높이에서 함께 읽히고 싶을 때.
*/
import {EmptyStateNotice, SectionBody, SectionFrame, SectionHeading} from '../../primitives';
import type {SectionRenderProps} from '../../types';
import {primaryPhoto, introParagraph} from '../common';
export function IntroSideBySide(props: SectionRenderProps) {
const intro = props.section.body?.trim() || introParagraph(props.industryId, props.infoFields);
const {section, isSelected, onSelect, storeName, template, photos} = props;
const shot = photos[1] ?? primaryPhoto(photos);
// 사진이 없으면 회색 판만 남기고 <img> 는 렌더하지 않는다.
const shotUrl = shot?.url;
return (
<SectionFrame section={section} isSelected={isSelected} onSelect={onSelect} tone="paper">
<SectionBody>
<SectionHeading
variant="eyebrow"
eyebrow="ABOUT"
title={section.name}
subtitle={section.description}
/>
<div className="grid grid-cols-1 items-center gap-6 md:grid-cols-12">
<div className="md:col-span-5">
<div className="relative aspect-3/4 overflow-hidden rounded-2xl border border-stone-200/80 bg-stone-100">
{shotUrl && (
<img src={shotUrl} alt={`${storeName} 공간`} className="size-full object-cover" />
)}
</div>
</div>
<div className="space-y-4 md:col-span-7">
{intro ? (
<p className="text-xs leading-relaxed text-stone-700 sm:text-sm">{intro}</p>
) : (
<EmptyStateNotice>
아직 소개문이 없습니다 — 확인된 정보만 근거로 씁니다.
</EmptyStateNotice>
)}
</div>
</div>
</SectionBody>
</SectionFrame>
);
}
@@ -0,0 +1,42 @@
/**
* 소개 · 스토리 — 넓은 사진 한 장 아래로 문단이 흐르는 잡지식 구성.
*/
import {EmptyStateNotice, SectionBody, SectionFrame, SectionHeading} from '../../primitives';
import type {SectionRenderProps} from '../../types';
import {introParagraph} from '../common';
export function IntroStory(props: SectionRenderProps) {
const intro = props.section.body?.trim() || introParagraph(props.industryId, props.infoFields);
const {section, isSelected, onSelect, storeName, template, photos} = props;
const shotUrl = photos[1]?.url;
return (
<SectionFrame section={section} isSelected={isSelected} onSelect={onSelect} tone="paper">
<SectionBody>
<SectionHeading
title={section.name}
subtitle={section.description}
colors={template.colors}
/>
<div className="relative aspect-16/9 overflow-hidden rounded-xl border border-stone-200/80 bg-stone-100 sm:aspect-21/9">
{shotUrl && (
<img src={shotUrl} alt={`${storeName} 공간`} className="size-full object-cover" />
)}
</div>
<div className="space-y-4">
{intro ? (
<p className="font-sans text-xs leading-relaxed text-stone-700 sm:text-base">
{intro}
</p>
) : (
<EmptyStateNotice>
아직 소개문이 없습니다 — 확인된 정보만 근거로 씁니다.
</EmptyStateNotice>
)}
</div>
</SectionBody>
</SectionFrame>
);
}
@@ -0,0 +1,27 @@
import {useEffect, useState} from 'react';
/** "실시간 업데이트: 오후 4:41:56" 표시. 1초마다 갱신된다. */
export function LiveClock() {
const [clock, setClock] = useState('');
useEffect(() => {
const update = () => {
const now = new Date();
const period = now.getHours() >= 12 ? '오후' : '오전';
const hours = now.getHours() % 12 || 12;
const minutes = String(now.getMinutes()).padStart(2, '0');
const seconds = String(now.getSeconds()).padStart(2, '0');
setClock(`${period} ${hours}:${minutes}:${seconds}`);
};
update();
const timer = setInterval(update, 1000);
return () => clearInterval(timer);
}, []);
return (
<span className="flex items-center gap-1.5 rounded-full border border-stone-200/80 bg-white px-2.5 py-1 text-[11px] text-stone-500 shadow-2xs">
<span className="size-1.5 animate-pulse rounded-full bg-emerald-500" />
<span>실시간 업데이트: {clock}</span>
</span>
);
}
@@ -0,0 +1,50 @@
/**
* 지역 가이드 · 요약 — 날씨 한 줄과 추천 6곳만.
* 지역 정보가 주인공이 아닌 사이트에서 "있긴 하다" 정도로 둘 때.
*/
import {
EmptyStateNotice,
ListCard,
PlaceRow,
SectionBody,
SectionFrame,
SectionHeading,
} from '../../primitives';
import type {SectionRenderProps} from '../../types';
const naverSearch = (q: string) =>
`https://search.naver.com/search.naver?query=${encodeURIComponent(q)}`;
export function LocalCompact(props: SectionRenderProps) {
const {section, isSelected, onSelect, location, template} = props;
// 맛집·명소를 섞어 딱 6개만. 목록이 길어지면 요약이 아니게 된다.
// ★ 지역 정보는 서버(local.local_contents)가 소유하고 캔버스 계약(SectionRenderProps)에 없다.
// 시연용 목록(제주 애월)으로 자리를 메우지 않는다 — 남의 동네 맛집이 사장님 사이트에 붙는다.
const picks: {name: string; meta: string; description: string; q: string}[] = [];
return (
<SectionFrame section={section} isSelected={isSelected} onSelect={onSelect} tone="paper">
<SectionBody width="narrow">
<SectionHeading variant="minimal" title="주변 안내" colors={template.colors} />
{picks.length === 0 ? (
<EmptyStateNotice>주변 추천은 아직 준비 중입니다.</EmptyStateNotice>
) : (
<ListCard>
{picks.map((p) => (
<PlaceRow
key={p.name}
name={p.name}
meta={p.meta}
description={p.description}
href={naverSearch(p.q)}
actionLabel="보기"
colors={template.colors}
/>
))}
</ListCard>
)}
</SectionBody>
</SectionFrame>
);
}
@@ -0,0 +1,163 @@
/**
* 지역 가이드 · 전체 — 날씨 카드 + 맛집 + 명소 + 월별 축제를 세로로 전부.
* "여기 오면 근처에 뭐가 있나"를 한 화면에서 다 보여주고 싶을 때.
*/
import {Calendar, MapPin, Sparkles, Utensils} from 'lucide-react';
import type {TemplateItem} from '@o2o/shared';
import {
EmptyStateNotice,
ListCard,
PlaceRow,
Pill,
SectionBody,
SectionFrame,
SectionHeading,
} from '../../primitives';
import type {SectionRenderProps} from '../../types';
import {LiveClock} from './LiveClock';
import type {FestivalItem, NearbyPlace} from './types';
const naverSearch = (q: string) =>
`https://search.naver.com/search.naver?query=${encodeURIComponent(q)}`;
function GroupHeading({
icon: Icon,
title,
note,
colors,
}: {
icon: typeof Utensils;
title: string;
note: string;
colors: TemplateItem['colors'];
}) {
return (
<div className="flex items-center justify-between">
<h3
className="serif-title flex items-center gap-2 text-base font-bold text-stone-900 sm:text-lg"
style={{color: colors.text}}
>
<Icon className="size-4 text-stone-600" style={{color: colors.primary}} />
<span>{title}</span>
</h3>
{/* 오른쪽 출처 문구는 부가 정보라 중립 회색 그대로 둔다. */}
<span className="text-[11px] text-stone-400">{note}</span>
</div>
);
}
export function LocalFull(props: SectionRenderProps) {
const {section, isSelected, onSelect, industryId, location, template} = props;
const isStay = industryId === 'stay';
const locName = location.split(' ')[0] || '주변';
// ★ 맛집·명소·축제는 전부 제주 애월 시연용 목록이다 — 실사업장은 빈 목록으로 떨어진다.
// (지역 큐레이션을 읽어올 백엔드 창구가 아직 없어 당분간 계속 빈다.)
// 지역 정보는 서버(local.local_contents)가 소유하고 캔버스 계약에 없다 — 시연용 목록을 깔지 않는다.
const foods: NearbyPlace[] = [];
const spots: NearbyPlace[] = [];
const festivals: FestivalItem[] = [];
return (
<SectionFrame section={section} isSelected={isSelected} onSelect={onSelect} tone="paper">
<SectionBody className="space-y-8">
<SectionHeading
variant="eyebrow"
eyebrow="AI Local Guide"
title={`AI ${locName} 실시간 가이드`}
subtitle="실시간 날씨와 인근 미식·명소·축제를 AI가 큐레이션합니다"
trailing={<LiveClock />}
colors={template.colors}
/>
<div className="space-y-3.5">
<GroupHeading
icon={Utensils}
title="숙소 인근 엄선 맛집 & 카페"
note="호스트 & 네이버 플레이스 연동"
colors={template.colors}
/>
{foods.length === 0 ? (
<EmptyStateNotice>주변 맛집·카페 추천은 아직 준비 중입니다.</EmptyStateNotice>
) : (
<ListCard>
{foods.map((place) => (
<PlaceRow
key={place.name}
name={place.name}
meta={place.distance}
description={place.description}
href={naverSearch(place.searchQuery)}
colors={template.colors}
/>
))}
</ListCard>
)}
</div>
<div className="space-y-3.5">
<GroupHeading
icon={MapPin}
title="주변 힐링 명소 & 해변"
note="차량 5~20분 거리"
colors={template.colors}
/>
{spots.length === 0 ? (
<EmptyStateNotice>주변 명소 추천은 아직 준비 중입니다.</EmptyStateNotice>
) : (
<ListCard>
{spots.map((spot) => (
<PlaceRow
key={spot.name}
name={spot.name}
meta={spot.duration}
description={spot.description}
href={naverSearch(spot.searchQuery)}
actionLabel="상세정보"
colors={template.colors}
/>
))}
</ListCard>
)}
</div>
{isStay && (
<div className="space-y-3.5">
<GroupHeading
icon={Calendar}
title="월별 축제 & 문화 행사"
note="사계절 캘린더"
colors={template.colors}
/>
{festivals.length === 0 ? (
<EmptyStateNotice>월별 축제 안내는 아직 준비 중입니다.</EmptyStateNotice>
) : (
<ListCard>
{festivals.map((fest) => (
<PlaceRow
key={fest.name}
name={fest.name}
description={fest.description || fest.period}
href={naverSearch(fest.searchQuery)}
actionLabel="검색"
leading={
<>
<Pill tone="accent">{fest.month}</Pill>
{fest.isFeatured && (
<Pill tone="good">
<Sparkles className="size-2.5" />
대표축제
</Pill>
)}
</>
}
colors={template.colors}
/>
))}
</ListCard>
)}
</div>
)}
</SectionBody>
</SectionFrame>
);
}
@@ -0,0 +1,124 @@
/**
* 지역 가이드 · 탭 — 맛집/명소/축제를 탭으로 갈아 끼운다.
* 목록이 길어 스크롤이 부담스러울 때 화면 길이를 1/3 로 줄인다.
*/
import {useState} from 'react';
import {Calendar, MapPin, Utensils} from 'lucide-react';
import {cn} from '@/lib/utils';
import {
EmptyStateNotice,
ListCard,
Pill,
PlaceRow,
SectionBody,
SectionFrame,
SectionHeading,
} from '../../primitives';
import type {SectionRenderProps} from '../../types';
import type {FestivalItem, NearbyPlace} from './types';
const naverSearch = (q: string) =>
`https://search.naver.com/search.naver?query=${encodeURIComponent(q)}`;
type TabKey = 'food' | 'spots' | 'festivals';
const TABS: {key: TabKey; label: string; icon: typeof Utensils}[] = [
{key: 'food', label: '맛집 · 카페', icon: Utensils},
{key: 'spots', label: '명소', icon: MapPin},
{key: 'festivals', label: '축제', icon: Calendar},
];
export function LocalTabs(props: SectionRenderProps) {
const {section, isSelected, onSelect, industryId, location, template} = props;
const [tab, setTab] = useState<TabKey>('food');
const isStay = industryId === 'stay';
const tabs = isStay ? TABS : TABS.filter((t) => t.key !== 'festivals');
const locName = location.split(' ')[0] || '주변';
// ★ 세 탭 모두 제주 애월 시연용 목록이다 — 실사업장은 빈 목록으로 떨어진다.
// 지역 정보는 서버(local.local_contents)가 소유하고 캔버스 계약에 없다 — 시연용 목록을 깔지 않는다.
const foods: NearbyPlace[] = [];
const spots: NearbyPlace[] = [];
const festivals: FestivalItem[] = [];
// 탭을 눌렀는데 아무것도 없으면 섹션이 사라진 것처럼 보인다 — 자리는 지키고 상태만 알린다.
const isEmpty = (tab === 'food' ? foods : tab === 'spots' ? spots : festivals).length === 0;
return (
<SectionFrame section={section} isSelected={isSelected} onSelect={onSelect} tone="paper">
<SectionBody>
<SectionHeading
variant="eyebrow"
eyebrow="AI Local Guide"
title={`AI ${locName} 실시간 가이드`}
subtitle="탭을 눌러 원하는 정보만 보세요"
colors={template.colors}
/>
<div className="flex items-center gap-1 rounded-xl border border-stone-200/80 bg-white p-1">
{tabs.map(({key, label, icon: Icon}) => (
<button
key={key}
type="button"
onClick={(e) => {
e.stopPropagation();
setTab(key);
}}
aria-pressed={tab === key}
style={tab === key ? {backgroundColor: template.colors.primary} : undefined}
className={cn(
'flex flex-1 cursor-pointer items-center justify-center gap-1.5 rounded-lg py-2 text-xs font-semibold transition-colors',
tab === key ? 'text-white' : 'text-stone-500 hover:bg-stone-100',
)}
>
<Icon className="size-3.5" />
<span>{label}</span>
</button>
))}
</div>
{isEmpty ? (
<EmptyStateNotice>주변 정보는 아직 준비 중입니다.</EmptyStateNotice>
) : (
<ListCard>
{tab === 'food' &&
foods.map((place) => (
<PlaceRow
key={place.name}
name={place.name}
meta={place.distance}
description={place.description}
href={naverSearch(place.searchQuery)}
colors={template.colors}
/>
))}
{tab === 'spots' &&
spots.map((spot) => (
<PlaceRow
key={spot.name}
name={spot.name}
meta={spot.duration}
description={spot.description}
href={naverSearch(spot.searchQuery)}
actionLabel="상세정보"
colors={template.colors}
/>
))}
{tab === 'festivals' &&
festivals.map((fest) => (
<PlaceRow
key={fest.name}
name={fest.name}
description={fest.description || fest.period}
href={naverSearch(fest.searchQuery)}
actionLabel="검색"
leading={<Pill tone="accent">{fest.month}</Pill>}
colors={template.colors}
/>
))}
</ListCard>
)}
</SectionBody>
</SectionFrame>
);
}
@@ -0,0 +1,126 @@
/**
* 실시간 날씨 + AI 추천 한 덩어리.
*
* 지역 가이드 배리에이션 셋이 전부 이걸 쓴다 — 날씨 조회를 배리에이션마다 하면
* 레이아웃을 바꿀 때마다 API 를 다시 때린다.
*/
import {ArrowUpRight, Cloud, CloudRain, Snowflake, Sparkles, Sun} from 'lucide-react';
import {useWeather} from '@/hooks/useWeather';
import {cn} from '@/lib/utils';
import type {WeatherLocation} from '@/stores/builder';
import {EmptyStateNotice} from '../../primitives';
function WeatherIcon({condition, className}: {condition: string; className?: string}) {
switch (condition) {
case '맑음':
return <Sun className={cn('text-amber-500', className)} />;
case '구름많음':
return <Cloud className={cn('text-stone-500', className)} />;
case '비':
return <CloudRain className={cn('text-blue-500', className)} />;
case '눈':
return <Snowflake className={cn('text-cyan-400', className)} />;
default:
return <Cloud className={cn('text-stone-400', className)} />;
}
}
export function WeatherPanel({
location,
weatherLocation,
dense,
}: {
location: string;
weatherLocation?: WeatherLocation;
dense?: boolean;
}) {
const observed = useWeather(
weatherLocation?.regionCode,
weatherLocation?.latitude,
weatherLocation?.longitude,
);
const weather = weatherLocation ? observed : null;
if (dense) {
return (
<div className="flex flex-wrap items-center gap-3 rounded-xl border border-stone-200/80 bg-white px-4 py-3 shadow-2xs">
{weather ? (
<>
<WeatherIcon condition={weather.condition} className="size-5" />
<span className="text-lg font-extrabold tracking-tight text-stone-900">
{weather.temperature || '21.4'}°C
</span>
<span className="text-xs font-semibold text-stone-600">
{weather.condition || '구름많음'}
</span>
{weather.stale && <span className="text-[10px] text-amber-700">최근 관측값</span>}
<span className="min-w-0 flex-1 truncate text-[11px] text-stone-500">
{weather.recommendation}
</span>
</>
) : (
<span className="text-[11px] text-stone-500">
실시간 날씨는 아직 준비 중입니다.
</span>
)}
</div>
);
}
return (
<div className="space-y-4 rounded-2xl border border-stone-200/80 bg-white p-5 shadow-2xs sm:p-6">
<div className="flex flex-col justify-between gap-3 border-b border-stone-100 pb-4 sm:flex-row sm:items-center">
<div className="flex items-center gap-3.5">
<div className="flex size-12 shrink-0 items-center justify-center rounded-2xl bg-stone-100/80">
<WeatherIcon condition={weather?.condition ?? ''} className="size-6" />
</div>
<div>
<span className="block text-[11px] font-semibold text-stone-400">
{location || '제주 애월읍'} 실시간 기상
</span>
{weather ? (
<div className="mt-0.5 flex items-baseline gap-2">
<span className="font-sans text-2xl font-extrabold tracking-tight text-stone-900 sm:text-3xl">
{weather.temperature || '21.4'}°C
</span>
<span className="text-xs font-semibold text-stone-700 sm:text-sm">
{weather.condition || '구름많음'}
</span>
{weather.stale && (
<span className="text-[10px] font-medium text-amber-700">최근 관측값</span>
)}
</div>
) : (
<span className="mt-0.5 block text-xs text-stone-500">
실시간 날씨는 아직 준비 중입니다.
</span>
)}
</div>
</div>
<a
href={`https://search.naver.com/search.naver?query=${encodeURIComponent(`${location} 날씨`)}`}
target="_blank"
rel="noopener noreferrer"
onClick={(e) => e.stopPropagation()}
className="flex items-center gap-1 self-start rounded-lg border border-stone-200/60 bg-stone-50 px-3 py-1.5 text-xs text-stone-500 transition-colors hover:bg-stone-100 hover:text-stone-900 sm:self-auto"
>
<span>주간 날씨 예보</span>
<ArrowUpRight className="size-3.5" />
</a>
</div>
{weather ? (
<div className="flex items-start gap-2.5 rounded-xl border border-stone-200/60 bg-stone-50/70 p-3.5 text-xs leading-relaxed text-stone-700 sm:text-sm">
<Sparkles className="mt-0.5 size-4 shrink-0 text-amber-600" />
<div>
<strong className="font-semibold text-stone-900">AI 맞춤 추천: </strong>
<span>{weather.recommendation}</span>
</div>
</div>
) : (
<EmptyStateNotice>날씨 기반 AI 추천은 아직 준비 중입니다.</EmptyStateNotice>
)}
</div>
);
}
@@ -0,0 +1,32 @@
/**
* 지역 정보 항목의 모양.
*
* ★ 원래 이 타입들은 시연용 데이터 파일(data/stayData.ts)이 소유했다. 그 파일을 지우면서
* 실제로 쓰는 쪽인 여기로 옮겼다 — 타입이 데이터 시드에 매여 있을 이유가 없다.
*
* ★ 값은 서버(local.local_contents)가 소유한다. 지금은 캔버스 계약(SectionRenderProps)에
* 지역 정보가 없어서 배리에이션들이 빈 목록을 그린다. 흘려보낼 창구가 생기면
* 이 모양에 맞춰 매핑하면 된다.
*/
export interface NearbyPlace {
name: string;
category: string;
/** 거리 표기("차로 5분", "1.2km") — 원문 그대로 옮긴다. */
distance: string;
duration: string;
description: string;
/** 상세 페이지 대신 검색으로 보낸다 — 없는 주소를 지어내지 않기 위해서다. */
searchQuery: string;
tag: string;
}
export interface FestivalItem {
month: string;
name: string;
period: string;
location: string;
description: string;
isFeatured?: boolean;
officialUrl?: string;
searchQuery: string;
}
@@ -0,0 +1,50 @@
/**
* 오시는 길 · 간단 — 주소 한 줄과 길찾기 버튼만.
* 도심처럼 "주소만 알면 찾아오는" 곳이면 표까지 깔 이유가 없다.
*/
import {MapPin} from 'lucide-react';
import {
AddressCard,
EmptyStateNotice,
SectionBody,
SectionFrame,
SectionHeading,
} from '../../primitives';
import type {SectionRenderProps} from '../../types';
export function MapCompact(props: SectionRenderProps) {
const {section, isSelected, onSelect, storeName, location, template, infoFields} = props;
// ★ props 로 온 주소만 쓴다. 없으면 카드 대신 준비 중 안내를 둔다 —
// 시연용 주소로 떨어지면 손님을 남의 집으로 보낸다.
const address = infoFields.find((f) => f.id === 'address')?.value ?? '';
return (
<SectionFrame section={section} isSelected={isSelected} onSelect={onSelect} tone="tint">
<SectionBody width="narrow">
<SectionHeading
variant="minimal"
title={section.name}
subtitle={section.description}
trailing={
<span className="flex items-center gap-1 text-[11px] text-stone-500">
<MapPin className="size-3.5" />
{location}
</span>
}
colors={template.colors}
/>
{address ? (
<AddressCard
address={address}
searchName={storeName}
variant="bar"
colors={template.colors}
/>
) : (
<EmptyStateNotice>주소는 아직 준비 중입니다.</EmptyStateNotice>
)}
</SectionBody>
</SectionFrame>
);
}
@@ -0,0 +1,111 @@
/**
* 오시는 길 · 상세 — 주소 카드 + 거점별 소요시간 표 + 주차/충전 안내.
* 차로 찾아오는 손님이 많은 곳(외곽 스테이, 교외 카페)에 맞는다.
*/
import {Car, CarFront, Zap} from 'lucide-react';
import {
AddressCard,
EmptyStateNotice,
FeatureCard,
SectionBody,
SectionFrame,
SectionHeading,
} from '../../primitives';
import type {SectionRenderProps} from '../../types';
export function MapDetailed(props: SectionRenderProps) {
const {section, isSelected, onSelect, industryId, storeName, template, infoFields} = props;
// ★ 주소도 소요시간표도 시연용(제주 애월)이다 — 실사업장에는 한 줄도 내보내지 않는다.
const address =
infoFields.find((f) => f.id === 'address')?.value ?? '';
/**
* 소요시간 표.
*
* ★ 서버(local.routes)의 산출물이고 캔버스 계약(SectionRenderProps)에 없다 —
* 흘러올 창구가 생기기 전까지 빈다. 시연용 표(제주 애월 기준)를 깔지 않는다:
* 남의 동네 소요시간을 보고 손님이 출발 시각을 정한다.
*/
const travelTimes: {
destination: string;
byCar: string;
byWalkOrTransit: string;
distance: string;
}[] = [];
const isStay = industryId === 'stay';
return (
<SectionFrame section={section} isSelected={isSelected} onSelect={onSelect} tone="white">
<SectionBody>
<SectionHeading title={section.name} subtitle={section.description} colors={template.colors} />
{address ? (
<AddressCard
address={address}
searchName={storeName}
colors={template.colors}
/>
) : (
<EmptyStateNotice>주소는 아직 준비 중입니다.</EmptyStateNotice>
)}
{isStay && travelTimes.length === 0 && (
<EmptyStateNotice>주요 거점 소요시간은 아직 준비 중입니다.</EmptyStateNotice>
)}
{isStay && travelTimes.length > 0 && (
<div className="overflow-hidden rounded-xl border border-stone-200/80 bg-white shadow-2xs">
<div className="flex items-center gap-2 border-b border-stone-200 bg-stone-50 p-3.5 text-xs font-bold text-stone-800">
<Car className="size-4 text-stone-700" />
<span>주요 거점 이동 소요시간</span>
</div>
<div className="overflow-x-auto">
<table className="w-full text-left text-xs">
<thead className="border-b border-stone-100 bg-stone-50/50 font-medium text-stone-500">
<tr>
<th className="p-3">목적지</th>
<th className="p-3">차량</th>
<th className="p-3">도보 / 대중교통</th>
<th className="hidden p-3 sm:table-cell">거리</th>
</tr>
</thead>
<tbody className="text-stone-700 [&>tr+tr]:border-t [&>tr+tr]:border-stone-100">
{travelTimes.map((row) => (
<tr key={row.destination} className="hover:bg-stone-50/50">
<td className="p-3 font-bold text-stone-900">{row.destination}</td>
<td
className="p-3 font-semibold"
style={{color: template.colors.primary}}
>
{row.byCar}
</td>
<td className="p-3">{row.byWalkOrTransit}</td>
<td className="hidden p-3 font-mono text-stone-400 sm:table-cell">
{row.distance}
</td>
</tr>
))}
</tbody>
</table>
</div>
</div>
)}
<div className="grid grid-cols-1 gap-3 sm:grid-cols-2">
<FeatureCard
icon={CarFront}
title="전용 주차장 완비"
description="객실동 입구 전용 주차 공간 4대 무료 이용 가능"
colors={template.colors}
/>
<FeatureCard
icon={Zap}
title="전기차 완속 충전기"
description="스테이 전용 7kW 완속 충전기 1기 구비"
iconClassName="text-emerald-600"
colors={template.colors}
/>
</div>
</SectionBody>
</SectionFrame>
);
}
@@ -0,0 +1,31 @@
/**
* 메뉴 · 카드 격자 — 설명을 넉넉히 보여준다. 시그니처가 몇 개뿐일 때 강하다.
*/
import {PriceRow, SectionBody, SectionFrame, SectionHeading} from '../../primitives';
import type {SectionRenderProps} from '../../types';
import {menuItems} from './useMenuItems';
export function MenuGrid(props: SectionRenderProps) {
const {section, isSelected, onSelect, industryId, template} = props;
const items = menuItems(industryId);
return (
<SectionFrame section={section} isSelected={isSelected} onSelect={onSelect} tone="tint">
<SectionBody>
<SectionHeading
variant="centered"
eyebrow="MENU"
title={section.name}
subtitle={section.description}
colors={template.colors}
/>
<div className="grid grid-cols-1 gap-3 sm:grid-cols-2">
{items.map((item) => (
<PriceRow key={item.name} item={item} variant="card" colors={template.colors} />
))}
</div>
</SectionBody>
</SectionFrame>
);
}
@@ -0,0 +1,29 @@
/**
* 메뉴 · 목록 — 이름과 가격을 한 줄씩. 종이 메뉴판처럼 읽힌다.
*/
import {ListCard, PriceRow, SectionBody, SectionFrame, SectionHeading} from '../../primitives';
import type {SectionRenderProps} from '../../types';
import {menuItems} from './useMenuItems';
export function MenuList(props: SectionRenderProps) {
const {section, isSelected, onSelect, industryId, template} = props;
const items = menuItems(industryId);
return (
<SectionFrame section={section} isSelected={isSelected} onSelect={onSelect} tone="white">
<SectionBody>
<SectionHeading
title={section.name}
subtitle={section.description}
colors={template.colors}
/>
<ListCard>
{items.map((item) => (
<PriceRow key={item.name} item={item} colors={template.colors} />
))}
</ListCard>
</SectionBody>
</SectionFrame>
);
}
@@ -0,0 +1,45 @@
/**
* 메뉴 · 가격표 — 이름과 가격만 점선으로 이어 붙인 가장 압축된 형태.
* 품목이 많은 곳(코스 여러 개, 음료 다수)에 맞는다.
*/
import {Pill, SectionBody, SectionFrame, SectionHeading} from '../../primitives';
import type {SectionRenderProps} from '../../types';
import {menuItems} from './useMenuItems';
export function MenuPriceTable(props: SectionRenderProps) {
const {section, isSelected, onSelect, industryId, template} = props;
const items = menuItems(industryId);
return (
<SectionFrame section={section} isSelected={isSelected} onSelect={onSelect} tone="paper">
<SectionBody width="narrow">
<SectionHeading variant="minimal" title={section.name} colors={template.colors} />
<ul className="space-y-3.5">
{items.map((item) => (
<li key={item.name} className="space-y-0.5">
<div className="flex items-baseline gap-2">
<span
className="flex items-center gap-2 text-xs font-bold text-stone-900 sm:text-sm"
style={{color: template.colors.text}}
>
{item.name}
{item.tag && <Pill tone="accent">{item.tag}</Pill>}
</span>
{/* 점선 리더 — 이름과 가격 사이를 눈으로 잇는다. 선 자체는 중립 회색으로 둔다. */}
<span className="min-w-4 flex-1 translate-y-[-3px] border-b border-dotted border-stone-300" />
<span
className="font-mono text-xs font-extrabold text-stone-900 sm:text-sm"
style={{color: template.colors.primary}}
>
{item.price}
</span>
</div>
{item.desc && <p className="text-[11px] leading-relaxed text-stone-500">{item.desc}</p>}
</li>
))}
</ul>
</SectionBody>
</SectionFrame>
);
}
@@ -0,0 +1,13 @@
import type {IndustryType} from '@o2o/shared';
import type {PricedItem} from '../../primitives';
/**
* 메뉴.
*
* ★ 지금은 항상 빈 목록이다. 메뉴는 unit(하위 단위)이고, 캔버스 계약에 units 가 없다.
* 업종 시드의 menuList/courseList 를 폴백으로 쓰던 코드를 걷어냈다 —
* "포레스트 크림라떼 7,500원" 이 실제로 모든 카페 화면에 떴다.
*/
export function menuItems(_industryId: IndustryType): PricedItem[] {
return [];
}
@@ -0,0 +1,52 @@
/**
* 사진 · 가로 슬라이드 — 큰 사진을 한 장씩 넘겨 본다.
* 장수가 적고 한 장 한 장이 좋을 때 가장 세게 보인다.
*/
import {useState} from 'react';
import {
Lightbox,
PhotoTile,
SectionBody,
SectionFrame,
SectionHeading,
} from '../../primitives';
import type {SectionRenderProps} from '../../types';
import {galleryPhotos} from '../common';
export function PhotosCarousel(props: SectionRenderProps) {
const {section, isSelected, onSelect, industryId, template, photos} = props;
const items = galleryPhotos(industryId, photos);
const [openIndex, setOpenIndex] = useState<number | null>(null);
return (
<SectionFrame section={section} isSelected={isSelected} onSelect={onSelect} tone="white">
<SectionBody width="wide">
<SectionHeading title={section.name} subtitle={section.description} colors={template.colors} />
<div className="scrollbar-none flex snap-x snap-mandatory gap-3 overflow-x-auto px-1 pb-3">
{items.map((photo, idx) => (
<PhotoTile
key={photo.id}
photo={photo}
fit="landscape"
onOpen={() => setOpenIndex(idx)}
className="w-[78vw] max-w-[420px] shrink-0 snap-center"
/>
))}
</div>
<div className="flex items-center justify-center gap-1.5">
{items.map((photo) => (
<span
key={photo.id}
className="size-1.5 rounded-full"
style={{backgroundColor: `${template.colors.primary}40`}}
/>
))}
</div>
</SectionBody>
<Lightbox photos={items} index={openIndex} onClose={() => setOpenIndex(null)} onMove={setOpenIndex} />
</SectionFrame>
);
}
@@ -0,0 +1,39 @@
/**
* 사진 · 정사각 격자 — 모든 사진을 같은 크기로. 장수가 많을수록 정돈돼 보인다.
*/
import {useState} from 'react';
import {
Lightbox,
PhotoTile,
SectionBody,
SectionFrame,
SectionHeading,
} from '../../primitives';
import type {SectionRenderProps} from '../../types';
import {galleryPhotos} from '../common';
export function PhotosGrid(props: SectionRenderProps) {
const {section, isSelected, onSelect, industryId, template, photos} = props;
const items = galleryPhotos(industryId, photos);
const [openIndex, setOpenIndex] = useState<number | null>(null);
return (
<SectionFrame section={section} isSelected={isSelected} onSelect={onSelect} tone="white">
<SectionBody>
<SectionHeading
title={section.name}
subtitle={section.description || `사진 ${items.length}장 · 클릭하면 크게 보입니다`}
colors={template.colors}
/>
<div className="grid grid-cols-2 gap-2.5 sm:grid-cols-3 sm:gap-3 md:grid-cols-4">
{items.map((photo, idx) => (
<PhotoTile key={photo.id} photo={photo} fit="square" onOpen={() => setOpenIndex(idx)} />
))}
</div>
</SectionBody>
<Lightbox photos={items} index={openIndex} onClose={() => setOpenIndex(null)} onMove={setOpenIndex} />
</SectionFrame>
);
}
@@ -0,0 +1,49 @@
/**
* 사진 · 벽돌쌓기 — 세로/가로 비율을 살려 어긋나게 쌓는다.
* 사진마다 구도가 다를 때 잘라내지 않고 보여줄 수 있다.
*/
import {useState} from 'react';
import {
Lightbox,
PhotoTile,
SectionBody,
SectionFrame,
SectionHeading,
} from '../../primitives';
import type {SectionRenderProps} from '../../types';
import {galleryPhotos} from '../common';
export function PhotosMasonry(props: SectionRenderProps) {
const {section, isSelected, onSelect, industryId, template, photos} = props;
const items = galleryPhotos(industryId, photos);
const [openIndex, setOpenIndex] = useState<number | null>(null);
return (
<SectionFrame section={section} isSelected={isSelected} onSelect={onSelect} tone="paper">
<SectionBody>
<SectionHeading
variant="eyebrow"
eyebrow="GALLERY"
title={section.name}
subtitle={section.description}
colors={template.colors}
/>
{/* columns 로 쌓으면 사진 높이를 자르지 않고도 빈틈 없이 채워진다. */}
<div className="columns-2 gap-2.5 sm:columns-3 sm:gap-3 [&>*]:mb-2.5 sm:[&>*]:mb-3">
{items.map((photo, idx) => (
<PhotoTile
key={photo.id}
photo={photo}
fit="free"
onOpen={() => setOpenIndex(idx)}
className="break-inside-avoid"
/>
))}
</div>
</SectionBody>
<Lightbox photos={items} index={openIndex} onClose={() => setOpenIndex(null)} onMove={setOpenIndex} />
</SectionFrame>
);
}
@@ -0,0 +1,169 @@
/**
* 사진 · 사진 + 영상 — 격자 갤러리 아래에 YouTube 영상을 붙인다.
* 릴스·유튜브로 이미 알려진 곳이면 사진보다 영상이 더 잘 판다.
*/
import {useState} from 'react';
import {Plus} from 'lucide-react';
import {convertYouTubeToEmbed} from '@/lib/youtube';
import {
EmptyStateNotice,
Lightbox,
PhotoTile,
SectionBody,
SectionFrame,
SectionHeading,
} from '../../primitives';
import type {SectionRenderProps} from '../../types';
import {galleryPhotos} from '../common';
import {VideoCard, type VideoItem} from './VideoCard';
export function PhotosWithVideos(props: SectionRenderProps) {
const {section, isSelected, onSelect, industryId, template, photos} = props;
const items = galleryPhotos(industryId, photos);
const [openIndex, setOpenIndex] = useState<number | null>(null);
// 영상은 사장님이 이 화면에서 직접 추가한 것만 있다 — 시연용 목록을 깔지 않는다.
const [added, setAdded] = useState<VideoItem[]>([]);
const [removedIds, setRemovedIds] = useState<string[]>([]);
const videos = added.filter((v) => !removedIds.includes(v.id));
const [playingId, setPlayingId] = useState<string | null>(null);
const [isFormOpen, setIsFormOpen] = useState(false);
const [inputTitle, setInputTitle] = useState('');
const [inputUrl, setInputUrl] = useState('');
const [errorMsg, setErrorMsg] = useState('');
const handleAddVideo = (e: React.FormEvent) => {
e.preventDefault();
setErrorMsg('');
if (!inputTitle.trim() || !inputUrl.trim()) {
setErrorMsg('제목과 YouTube URL을 모두 입력해주세요.');
return;
}
const {embedUrl, isValid} = convertYouTubeToEmbed(inputUrl);
if (!isValid || !embedUrl) {
setErrorMsg('올바른 YouTube URL 형식이 아닙니다.');
return;
}
setAdded((prev) => [
{id: `canvas-v-${Date.now()}`, title: inputTitle.trim(), videoUrl: inputUrl.trim(), embedUrl},
...prev,
]);
setInputTitle('');
setInputUrl('');
setIsFormOpen(false);
};
return (
<SectionFrame section={section} isSelected={isSelected} onSelect={onSelect} tone="paper">
<SectionBody className="space-y-8">
<div className="space-y-6">
<SectionHeading title={section.name} subtitle={section.description} colors={template.colors} />
<div className="grid grid-cols-2 gap-2.5 sm:grid-cols-3 sm:gap-3 md:grid-cols-4">
{items.map((photo, idx) => (
<PhotoTile
key={photo.id}
photo={photo}
fit="square"
onOpen={() => setOpenIndex(idx)}
/>
))}
</div>
</div>
<div className="space-y-6">
<SectionHeading
title="영상 갤러리"
subtitle="공간의 분위기를 영상으로 미리 확인해 보세요"
trailing={
<button
type="button"
title="영상 추가"
onClick={(e) => {
e.stopPropagation();
setIsFormOpen((v) => !v);
}}
className="flex size-8 cursor-pointer items-center justify-center rounded-full border border-stone-300 bg-white text-stone-700 shadow-2xs transition-colors hover:bg-stone-100 hover:text-stone-900"
>
<Plus className="size-4" />
</button>
}
colors={template.colors}
/>
{isFormOpen && (
<div
onClick={(e) => e.stopPropagation()}
role="presentation"
className="rounded-xl border border-stone-200 bg-white p-4 shadow-xs"
>
<form onSubmit={handleAddVideo} className="space-y-3">
<div className="grid grid-cols-1 gap-3 sm:grid-cols-2">
<input
type="text"
value={inputTitle}
onChange={(e) => setInputTitle(e.target.value)}
placeholder="영상 제목 (예: 스테이의 아침)"
className="rounded-lg border border-stone-200 bg-stone-50 px-3 py-2 text-xs focus:bg-white focus:outline-none"
/>
<input
type="text"
value={inputUrl}
onChange={(e) => setInputUrl(e.target.value)}
placeholder="YouTube URL (https://www.youtube.com/watch?v=...)"
className="rounded-lg border border-stone-200 bg-stone-50 px-3 py-2 text-xs focus:bg-white focus:outline-none"
/>
</div>
{errorMsg && <p className="text-[11px] text-rose-600">{errorMsg}</p>}
<div className="flex justify-end gap-2">
<button
type="button"
onClick={() => setIsFormOpen(false)}
className="cursor-pointer rounded-lg px-3 py-1.5 text-xs text-stone-500 hover:bg-stone-100"
>
취소
</button>
<button
type="submit"
className="cursor-pointer rounded-lg px-4 py-1.5 text-xs font-semibold text-white"
style={{backgroundColor: template.colors.primary}}
>
등록
</button>
</div>
</form>
</div>
)}
{videos.length === 0 ? (
<EmptyStateNotice>
등록된 영상이 아직 없습니다. + 버튼으로 추가할 수 있습니다.
</EmptyStateNotice>
) : (
<div className="grid grid-cols-1 gap-5 md:grid-cols-2">
{videos.map((video) => (
<VideoCard
key={video.id}
video={video}
isPlaying={playingId === video.id}
onPlay={() => setPlayingId(video.id)}
onRemove={() => setRemovedIds((prev) => [...prev, video.id])}
/>
))}
</div>
)}
</div>
</SectionBody>
<Lightbox
photos={items}
index={openIndex}
onClose={() => setOpenIndex(null)}
onMove={setOpenIndex}
/>
</SectionFrame>
);
}
@@ -0,0 +1,108 @@
import {ExternalLink, Trash2} from 'lucide-react';
/**
* 영상 한 건. 원래 시연용 데이터 파일이 소유하던 타입을 실제로 쓰는 여기로 옮겼다.
*/
export interface VideoItem {
id: string;
title: string;
videoUrl: string;
embedUrl: string;
duration?: string;
}
/** URL 에서 YouTube 영상 id 를 뽑는다. 못 뽑으면 썸네일을 대체 이미지로 떨어뜨린다. */
export function youTubeId(url: string): string | null {
const match = url.match(/^.*(youtu\.be\/|v\/|u\/\w\/|embed\/|watch\?v=|&v=)([^#&?]*).*/);
return match && match[2].length === 11 ? match[2] : null;
}
const FALLBACK_THUMB =
'https://images.unsplash.com/photo-1582719478250-c89cae4dc85b?auto=format&fit=crop&w=800&q=80';
/** 영상 한 칸 — 썸네일을 누르면 그 자리에서 iframe 으로 바뀐다. */
export function VideoCard({
video,
isPlaying,
onPlay,
onRemove,
}: {
video: VideoItem;
isPlaying: boolean;
onPlay: () => void;
onRemove: () => void;
}) {
const ytId = youTubeId(video.videoUrl || video.embedUrl || '');
const thumb = ytId ? `https://img.youtube.com/vi/${ytId}/hqdefault.jpg` : FALLBACK_THUMB;
return (
<div className="flex flex-col overflow-hidden rounded-xl border border-stone-200/90 bg-white shadow-2xs">
<div className="group relative aspect-16/9 overflow-hidden bg-stone-900">
{isPlaying ? (
<iframe
src={`${video.embedUrl}?autoplay=1&rel=0`}
title={video.title}
allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture"
allowFullScreen
className="absolute inset-0 size-full border-0"
/>
) : (
<div
onClick={(e) => {
e.stopPropagation();
onPlay();
}}
className="absolute inset-0 cursor-pointer"
>
<img
src={thumb}
alt={video.title}
className="size-full object-cover opacity-90 transition-transform duration-300 group-hover:scale-105"
/>
<div className="absolute inset-0 flex items-center justify-center bg-black/40 transition-colors group-hover:bg-black/30">
<div className="flex size-12 items-center justify-center rounded-full bg-white/90 pl-1 text-stone-900 shadow-lg transition-transform group-hover:scale-110 group-active:scale-95">
<svg className="size-5 fill-current" viewBox="0 0 24 24">
<path d="M8 5v14l11-7z" />
</svg>
</div>
</div>
<div className="absolute left-3 top-3 flex items-center gap-1.5 rounded-md bg-black/60 px-2 py-1 text-[10px] font-medium text-white backdrop-blur-xs">
<span className="size-2 rounded-full bg-rose-500" />
<span>YouTube</span>
</div>
</div>
)}
</div>
<div className="flex items-center justify-between gap-2 border-t border-stone-100 bg-white p-3.5">
<span className="truncate text-xs font-semibold text-stone-900 sm:text-sm">
{video.title}
</span>
<div className="flex shrink-0 items-center gap-1">
<a
href={video.videoUrl || `https://www.youtube.com/watch?v=${ytId}`}
target="_blank"
rel="noopener noreferrer"
onClick={(e) => e.stopPropagation()}
title="YouTube에서 열기"
className="rounded p-1 text-stone-400 hover:text-stone-700"
>
<ExternalLink className="size-3.5" />
</a>
<button
type="button"
title="삭제"
onClick={(e) => {
e.stopPropagation();
onRemove();
}}
className="cursor-pointer p-1 text-stone-400 hover:text-rose-600"
>
<Trash2 className="size-3.5" />
</button>
</div>
</div>
</div>
);
}
@@ -0,0 +1,29 @@
/**
* 체험 프로그램 · 카드 — 소요시간·대상까지 붙여 한 장씩. 처음 오는 손님이 고르기 쉽다.
*/
import {PriceRow, SectionBody, SectionFrame, SectionHeading} from '../../primitives';
import type {SectionRenderProps} from '../../types';
import {programItems} from './useProgramItems';
export function ProgramsCards(props: SectionRenderProps) {
const {section, isSelected, onSelect, industryId, template} = props;
const items = programItems(industryId);
return (
<SectionFrame section={section} isSelected={isSelected} onSelect={onSelect} tone="white">
<SectionBody>
<SectionHeading
title={section.name}
subtitle={section.description}
colors={template.colors}
/>
<div className="grid grid-cols-1 gap-3 sm:grid-cols-2 lg:grid-cols-3">
{items.map((item) => (
<PriceRow key={item.name} item={item} variant="card" colors={template.colors} />
))}
</div>
</SectionBody>
</SectionFrame>
);
}
@@ -0,0 +1,60 @@
/**
* 체험 프로그램 · 표 — 프로그램/시간/대상/가격을 열로 세워 비교시킨다.
* 정규 클래스처럼 조건을 견줘 고르는 곳에 맞는다.
*/
import {SectionBody, SectionFrame, SectionHeading} from '../../primitives';
import type {SectionRenderProps} from '../../types';
import {programItems} from './useProgramItems';
export function ProgramsTable(props: SectionRenderProps) {
const {section, isSelected, onSelect, industryId, template} = props;
const items = programItems(industryId);
return (
<SectionFrame section={section} isSelected={isSelected} onSelect={onSelect} tone="tint">
<SectionBody>
<SectionHeading variant="minimal" title={section.name} colors={template.colors} />
<div className="overflow-hidden rounded-xl border border-stone-200/80 bg-white shadow-2xs">
<div className="overflow-x-auto">
<table className="w-full text-left text-xs">
<thead className="border-b border-stone-100 bg-stone-50/60 font-medium text-stone-500">
<tr>
<th className="p-3">프로그램</th>
<th className="hidden p-3 sm:table-cell">소요 · 대상</th>
<th className="p-3 text-right">참가비</th>
</tr>
</thead>
<tbody className="text-stone-700 [&>tr+tr]:border-t [&>tr+tr]:border-stone-100">
{items.map((item) => (
<tr key={item.name} className="hover:bg-stone-50/50">
<td className="p-3">
<span
className="block font-bold text-stone-900"
style={{color: template.colors.text}}
>
{item.name}
</span>
{item.desc && (
<span className="mt-0.5 block text-[11px] text-stone-500">{item.desc}</span>
)}
</td>
<td className="hidden p-3 text-[11px] text-stone-500 sm:table-cell">
{item.meta?.join(' · ')}
</td>
<td
className="p-3 text-right font-mono font-extrabold text-stone-900"
style={{color: template.colors.primary}}
>
{item.price}
</td>
</tr>
))}
</tbody>
</table>
</div>
</div>
</SectionBody>
</SectionFrame>
);
}
@@ -0,0 +1,13 @@
import type {IndustryType} from '@o2o/shared';
import type {PricedItem} from '../../primitives';
/**
* 체험 프로그램.
*
* ★ 지금은 항상 빈 목록이다. 프로그램은 unit(하위 단위)이고, 캔버스 계약에 units 가 없다.
* 업종 시드의 programList 를 폴백으로 쓰던 코드를 걷어냈다 — 가공의 상품이 가격까지
* 붙어 모든 사업장 화면에 똑같이 떴다.
*/
export function programItems(_industryId: IndustryType): PricedItem[] {
return [];
}
@@ -0,0 +1,169 @@
/**
* 객실 한 칸.
*
* 슬라이드든 격자든 목록이든 "객실 한 개"를 보여주는 방식은 같아야 한다 —
* 카드 안쪽이 배리에이션마다 다르면 사장님이 레이아웃을 바꿀 때 정보가 사라진 것처럼 보인다.
*/
import {ExternalLink, Sparkles} from 'lucide-react';
import type {TemplateItem} from '@o2o/shared';
import {cn} from '@/lib/utils';
import {CtaLink, Pill} from '../../primitives';
/**
* 객실 한 건.
*
* ★ 이 타입은 원래 시연용 데이터 파일(data/stayData.ts)이 소유했다. 그 파일을 지우면서
* 실제로 쓰는 쪽인 여기로 옮겼다 — 타입이 데이터 시드에 매여 있을 이유가 없다.
* 서버 unit 이 캔버스로 흘러오게 되면 이 모양에 맞춰 매핑하면 된다.
*/
export interface Room {
slug: string;
name: string;
subName: string;
type: string;
capacity: string;
bedInfo: string;
size: string;
price: string;
weekdayPrice: string;
weekendPrice: string;
/** 다른 객실과의 차이 한 줄 */
difference: string;
description: string;
features: string[];
amenities: string[];
images: {url: string; alt: string}[];
}
export function RoomCard({
room,
index,
total,
bookingUrl,
layout = 'card',
colors,
className,
}: {
room: Room;
index: number;
total: number;
bookingUrl: string;
/** card = 사진 위 / 정보 아래, row = 사진 왼쪽 / 정보 오른쪽 */
layout?: 'card' | 'row';
/**
* 템플릿 색 토큰. 객실명·요금·예약 버튼이 브랜드 색을 따른다.
*
* ★ "차별점" 상자의 호박색은 그대로 둔다 — 카드 안에서 유일하게 눈을 끄는 자리라,
* 토큰을 먹이면 제목·요금과 같은 색이 되어 강조가 사라진다.
*/
colors?: TemplateItem['colors'];
className?: string;
}) {
const specs = (
<div className="space-y-1 border-t border-stone-200/60 pt-1 text-xs text-stone-600">
<p className="flex items-center gap-1.5">
<span className="text-stone-400">•</span>
<span>수용 인원: {room.capacity}</span>
</p>
<p className="flex items-center gap-1.5">
<span className="text-stone-400">•</span>
<span>침대 구성: {room.bedInfo}</span>
</p>
<p className="flex items-center gap-1.5">
<span className="text-stone-400">•</span>
<span>면적: {room.size}</span>
</p>
</div>
);
const highlight = (
<div className="flex items-start gap-2 rounded-xl border border-amber-200/70 bg-amber-50/80 p-3 text-xs text-amber-950">
<Sparkles className="mt-0.5 size-4 shrink-0 text-amber-600" />
<div className="break-keep leading-relaxed">
<strong className="font-bold">차별점: </strong>
<span>{room.difference}</span>
</div>
</div>
);
const cover = (
<div
className={cn(
'relative overflow-hidden bg-stone-100',
layout === 'row' ? 'aspect-4/3 sm:aspect-auto sm:h-full' : 'aspect-16/10',
)}
>
<img src={room.images[0].url} alt={room.images[0].alt} className="size-full object-cover" />
<Pill tone="dark" className="absolute left-3 top-3 rounded-full px-2.5 py-1 text-[11px] backdrop-blur-md">
{room.type}
</Pill>
{layout === 'card' && (
<span className="absolute bottom-2.5 right-2.5 rounded-lg bg-white/95 px-2.5 py-1 text-xs font-bold text-stone-900 shadow-2xs backdrop-blur-md">
{index + 1} / {total}
</span>
)}
</div>
);
const body = (
<div className="space-y-3 p-4 sm:p-5">
<div className="space-y-1">
<h3
className="serif-title text-base font-bold leading-snug text-stone-900 sm:text-lg"
style={colors ? {color: colors.text} : undefined}
>
{room.name}
</h3>
<div
className="font-mono text-sm font-extrabold text-stone-900 sm:text-base"
style={colors ? {color: colors.primary} : undefined}
>
{room.price}
</div>
</div>
{highlight}
{specs}
</div>
);
const action = (
<div className="p-4 pt-0 sm:p-5 sm:pt-0">
<CtaLink href={bookingUrl} variant="solid" size="sm" colors={colors} block>
<span>실시간 예약 신청</span>
<ExternalLink className="size-3.5" />
</CtaLink>
</div>
);
if (layout === 'row') {
return (
<div
className={cn(
'grid grid-cols-1 overflow-hidden rounded-2xl border border-stone-200/90 bg-stone-50/70 shadow-2xs sm:grid-cols-12',
className,
)}
>
<div className="sm:col-span-5">{cover}</div>
<div className="flex flex-col justify-between sm:col-span-7">
{body}
{action}
</div>
</div>
);
}
return (
<div
className={cn(
'flex flex-col justify-between overflow-hidden rounded-2xl border border-stone-200/90 bg-stone-50/70 shadow-2xs',
className,
)}
>
<div>
{cover}
{body}
</div>
{action}
</div>
);
}
@@ -0,0 +1,47 @@
/**
* 객실 · 가로 슬라이드 — 모바일에서 한 칸씩 스와이프, PC 에서는 2열.
* 객실이 2~4개일 때 가장 자연스럽다.
*/
import {EmptyStateNotice, SectionBody, SectionFrame, SectionHeading} from '../../primitives';
import type {SectionRenderProps} from '../../types';
import {bookingHref} from '../common';
import {RoomCard, type Room} from './RoomCard';
export function RoomsCarousel(props: SectionRenderProps) {
const {section, isSelected, onSelect, industryId, storeName, template} = props;
const url = bookingHref(industryId, storeName);
// ★ 객실(unit)은 캔버스 계약에 없다 — 시연용 세트로 자리를 메우지 않는다.
const rooms: Room[] = [];
return (
<SectionFrame section={section} isSelected={isSelected} onSelect={onSelect} tone="white">
<SectionBody>
<SectionHeading title={section.name} subtitle="자연을 오롯이 품은 객실 타입" colors={template.colors} />
{rooms.length === 0 ? (
<EmptyStateNotice>객실 정보는 아직 준비 중입니다.</EmptyStateNotice>
) : (
<div className="space-y-4">
<div className="scrollbar-none flex snap-x snap-mandatory gap-4 overflow-x-auto px-1 pb-4 sm:grid sm:grid-cols-2 sm:gap-6 sm:overflow-visible sm:pb-0">
{rooms.map((room, idx) => (
<RoomCard
key={room.slug}
room={room}
index={idx}
total={rooms.length}
bookingUrl={url}
className="w-[85vw] max-w-[340px] shrink-0 snap-center sm:w-full"
colors={template.colors}
/>
))}
</div>
<div className="flex items-center justify-center gap-2 pt-1 text-[11px] text-stone-400 sm:hidden">
<span>← 좌우로 스와이프하여 다른 객실을 확인하세요 →</span>
</div>
</div>
)}
</SectionBody>
</SectionFrame>
);
}
@@ -0,0 +1,45 @@
/**
* 객실 · 격자 — 전부 한눈에 늘어놓는다. 객실이 많고 비교해서 고르게 하고 싶을 때.
*/
import {EmptyStateNotice, SectionBody, SectionFrame, SectionHeading} from '../../primitives';
import type {SectionRenderProps} from '../../types';
import {bookingHref} from '../common';
import {RoomCard, type Room} from './RoomCard';
export function RoomsGrid(props: SectionRenderProps) {
const {section, isSelected, onSelect, industryId, storeName, template} = props;
const url = bookingHref(industryId, storeName);
// ★ 객실(unit)은 캔버스 계약에 없다 — 시연용 세트로 자리를 메우지 않는다.
const rooms: Room[] = [];
return (
<SectionFrame section={section} isSelected={isSelected} onSelect={onSelect} tone="white">
<SectionBody width="wide">
<SectionHeading
variant="centered"
eyebrow="ROOMS"
title={section.name}
subtitle="원하는 객실을 비교해 보세요"
colors={template.colors}
/>
{rooms.length === 0 ? (
<EmptyStateNotice>객실 정보는 아직 준비 중입니다.</EmptyStateNotice>
) : (
<div className="grid grid-cols-1 gap-5 sm:grid-cols-2 lg:grid-cols-3">
{rooms.map((room, idx) => (
<RoomCard
key={room.slug}
room={room}
index={idx}
total={rooms.length}
bookingUrl={url}
colors={template.colors}
/>
))}
</div>
)}
</SectionBody>
</SectionFrame>
);
}
@@ -0,0 +1,42 @@
/**
* 객실 · 가로 목록 — 사진 왼쪽, 설명 오른쪽으로 한 줄씩.
* 객실마다 설명이 길 때 글을 넉넉히 읽힌다.
*/
import {EmptyStateNotice, SectionBody, SectionFrame, SectionHeading} from '../../primitives';
import type {SectionRenderProps} from '../../types';
import {bookingHref} from '../common';
import {RoomCard, type Room} from './RoomCard';
export function RoomsList(props: SectionRenderProps) {
const {section, isSelected, onSelect, industryId, storeName, template} = props;
const url = bookingHref(industryId, storeName);
// ★ 객실(unit)은 캔버스 계약(SectionRenderProps)에 없다 — 흘러올 창구가 생기기 전까지 빈다.
// 시연용 세트로 자리를 메우지 않는다: 남의 객실·요금이 사장님 사이트로 발행된다.
const rooms: Room[] = [];
return (
<SectionFrame section={section} isSelected={isSelected} onSelect={onSelect} tone="tint">
<SectionBody>
<SectionHeading title={section.name} subtitle="객실별 구성과 차이를 자세히" colors={template.colors} />
{rooms.length === 0 ? (
<EmptyStateNotice>객실 정보는 아직 준비 중입니다.</EmptyStateNotice>
) : (
<div className="space-y-4">
{rooms.map((room, idx) => (
<RoomCard
key={room.slug}
room={room}
index={idx}
total={rooms.length}
bookingUrl={url}
layout="row"
colors={template.colors}
/>
))}
</div>
)}
</SectionBody>
</SectionFrame>
);
}
@@ -0,0 +1,51 @@
/**
* 이용 규정 · 카드 — 규정 하나에 칸 하나. 번호가 붙어 "빠뜨리지 말라"는 인상이 강하다.
* 노쇼·소음 클레임이 잦은 곳에 맞는다.
*/
import {ShieldCheck} from 'lucide-react';
import {EmptyStateNotice, SectionBody, SectionFrame, SectionHeading} from '../../primitives';
import type {SectionRenderProps} from '../../types';
import {ruleItems} from '../common';
export function RulesCards(props: SectionRenderProps) {
const {section, isSelected, onSelect, template} = props;
// ★ 규정을 지어내지 않는다 — 확인된 fact 에서만 만든다.
const items = ruleItems(props.infoFields);
return (
<SectionFrame section={section} isSelected={isSelected} onSelect={onSelect} tone="tint">
<SectionBody>
<SectionHeading
variant="eyebrow"
eyebrow="HOUSE RULES"
title={section.name}
subtitle="예약 전 꼭 확인해 주세요"
trailing={<ShieldCheck className="size-5 text-stone-400" />}
/>
{items.length === 0 && (
<EmptyStateNotice>
확인된 이용 규정이 아직 없습니다 — 정보 탭에서 확인하면 여기에 나옵니다.
</EmptyStateNotice>
)}
<ol className="grid grid-cols-1 gap-2.5 sm:grid-cols-2">
{items.map((rule, idx) => (
<li
key={rule}
className="flex items-start gap-3 rounded-xl border border-stone-200/80 bg-white p-4 shadow-2xs"
>
<span
className="flex size-6 shrink-0 items-center justify-center rounded-full text-[11px] font-bold text-white"
style={{backgroundColor: template.colors.primary}}
>
{idx + 1}
</span>
<span className="text-xs leading-relaxed text-stone-700">{rule}</span>
</li>
))}
</ol>
</SectionBody>
</SectionFrame>
);
}
@@ -0,0 +1,58 @@
/**
* 이용 규정 · 목록 — 지켜야 할 것을 한 덩어리로 짧게. 가장 눈에 덜 띄는 형태.
*/
import {
SlateScriptRenderer,
type SlateElementNode,
type SlateTextNode,
} from '../../SlateScriptRenderer';
import {SectionBody, SectionFrame, SectionHeading} from '../../primitives';
import type {SectionRenderProps} from '../../types';
import {EmptyStateNotice} from '../../primitives';
import {ruleItems} from '../common';
export function RulesList(props: SectionRenderProps) {
const {section, isSelected, onSelect, template} = props;
// ★ 규정을 지어내지 않는다. 확인된 fact(체크인·체크아웃·취소규정·취사·반려동물…)에서만 만든다 —
// 예전에는 '체크인 16:00 / 체크아웃 11:00' 같은 가공의 규정이 모든 사업장에 똑같이 떴다.
const items = ruleItems(props.infoFields);
const script: (SlateElementNode | SlateTextNode)[] | undefined = undefined;
return (
<SectionFrame section={section} isSelected={isSelected} onSelect={onSelect} tone="white">
<SectionBody>
<SectionHeading title={section.name} subtitle="이용 안내 및 규정" />
{items.length === 0 ? (
<EmptyStateNotice>
확인된 이용 규정이 아직 없습니다 — 정보 탭에서 확인하면 여기에 나옵니다.
</EmptyStateNotice>
) : (
<div className="space-y-2 rounded-xl border border-stone-200/80 bg-stone-50/60 p-4 text-xs shadow-2xs">
<strong className="mb-2 block font-bold text-stone-900">투숙 및 이용 수칙</strong>
{items.map((rule) => (
<p key={rule} className="text-stone-600">
• {rule}
</p>
))}
</div>
)}
{script && (
<div className="space-y-3 rounded-xl border border-stone-200 bg-stone-50 p-4 sm:p-5">
<div className="flex items-center justify-between border-b border-stone-200 pb-2">
<span className="flex items-center gap-1.5 text-xs font-bold text-stone-800">
<span className="size-2 rounded-full bg-stone-900" />
호스트-게스트 실시간 문의 & 대화 가이드
</span>
<span className="rounded border border-stone-200 bg-white px-2 py-0.5 font-mono text-[11px] text-stone-400">
Slate editor_script
</span>
</div>
<SlateScriptRenderer nodes={script} primaryColor={template.colors.primary} />
</div>
)}
</SectionBody>
</SectionFrame>
);
}
@@ -0,0 +1,28 @@
/**
* 공간 안내 · 목록 — 사진 없이 구역 이름과 설명만. 사진이 부실할 때 더 깔끔하다.
*/
import {ListCard, PlaceRow, SectionBody, SectionFrame, SectionHeading} from '../../primitives';
import type {SectionRenderProps} from '../../types';
export function SpaceList(props: SectionRenderProps) {
const {section, isSelected, onSelect, template, photos} = props;
return (
<SectionFrame section={section} isSelected={isSelected} onSelect={onSelect} tone="tint">
<SectionBody width="narrow">
<SectionHeading variant="minimal" title={section.name} colors={template.colors} />
<ListCard>
{photos.map((photo) => (
<PlaceRow
key={photo.id}
name={photo.title}
meta={photo.category}
colors={template.colors}
/>
))}
</ListCard>
</SectionBody>
</SectionFrame>
);
}
@@ -0,0 +1,51 @@
/**
* 공간 안내 · 구역 카드 — 수집된 사진을 "어떤 자리인지"로 묶어 보여준다.
* 좌석/층 구성이 궁금한 카페·다이닝에 맞는다.
*/
import {PhotoTile, SectionBody, SectionFrame, SectionHeading} from '../../primitives';
import type {SectionRenderProps} from '../../types';
export function SpaceZones(props: SectionRenderProps) {
const {section, isSelected, onSelect, template, photos, infoFields} = props;
const seats = infoFields.find((f) => f.id === 'seats');
return (
<SectionFrame section={section} isSelected={isSelected} onSelect={onSelect} tone="white">
<SectionBody>
<SectionHeading
title={section.name}
subtitle={section.description}
trailing={
seats && !seats.requiresVerification ? (
<span className="rounded-lg border border-stone-200 bg-stone-50 px-2.5 py-1 text-[11px] font-medium text-stone-600">
{seats.value}
</span>
) : null
}
colors={template.colors}
/>
<div className="grid grid-cols-1 gap-4 sm:grid-cols-2 lg:grid-cols-3">
{photos.map((photo) => (
<div key={photo.id} className="space-y-2">
<PhotoTile
photo={{id: photo.id, url: photo.url, alt: photo.title}}
fit="landscape"
showMeta={false}
/>
<div className="space-y-0.5 px-0.5">
<span
className="block text-xs font-bold text-stone-900"
style={{color: template.colors.text}}
>
{photo.title}
</span>
<span className="block text-[11px] text-stone-500">{photo.category}</span>
</div>
</div>
))}
</div>
</SectionBody>
</SectionFrame>
);
}
@@ -0,0 +1,27 @@
import {SectionBody, SectionFrame, SectionHeading} from '../../primitives';
import type {SectionRenderProps} from '../../types';
import {WeatherPanel} from '../local/WeatherPanel';
/** 에디터에서 순서·노출을 독립적으로 관리하는 날씨 섹션. */
export function WeatherSection({
section,
isSelected,
onSelect,
location,
weatherLocation,
template,
}: SectionRenderProps) {
return (
<SectionFrame section={section} isSelected={isSelected} onSelect={onSelect} tone="paper">
<SectionBody width="narrow">
<SectionHeading
variant="minimal"
title="오늘의 날씨"
subtitle={`${location || '사업장 주변'}의 현재 기상 정보입니다.`}
colors={template.colors}
/>
<WeatherPanel location={location} weatherLocation={weatherLocation} />
</SectionBody>
</SectionFrame>
);
}
@@ -0,0 +1,55 @@
import type {IndustryType, TemplateItem} from '@o2o/shared';
import {derivePalette} from '@/features/dev/palette';
export interface ColorPalettePreset {
id: string;
name: string;
sourceUrl: string;
industry: IndustryType;
swatches: string[];
colors: TemplateItem['colors'];
}
const SOURCE = [
{industry: 'stay', id: 'stay-coastal', name: '코스탈 블루', swatches: ['#F2EFE7', '#C8DFDB', '#66A3BF', '#3368A0']},
{industry: 'stay', id: 'stay-warm-wood', name: '웜 우드', swatches: ['#F5EFE7', '#D8C4B6', '#4F709C', '#213555']},
{industry: 'stay', id: 'stay-forest', name: '포레스트 스테이', swatches: ['#E9EFEC', '#C4DAD2', '#6A9C89', '#16423C']},
{industry: 'stay', id: 'stay-sand', name: '샌드 앤 네이비', swatches: ['#DFD0B8', '#948979', '#393E46', '#222831']},
{industry: 'stay', id: 'stay-lavender', name: '라벤더 나이트', swatches: ['#F5EFFF', '#CDC1FF', '#A594F9', '#7371FC']},
{industry: 'cafe', id: 'cafe-mocha', name: '모카 오렌지', swatches: ['#FCF2E5', '#A8A492', '#524646', '#EC5B38']},
{industry: 'cafe', id: 'cafe-matcha', name: '말차 크림', swatches: ['#FFF7EB', '#F9F0E0', '#A2AB73', '#5F6F52']},
{industry: 'cafe', id: 'cafe-cherry', name: '체리 크림', swatches: ['#FFF5E4', '#FFE3E1', '#FFD1D1', '#FF9494']},
{industry: 'cafe', id: 'cafe-butter', name: '버터 브라운', swatches: ['#FAF7F0', '#CDFCF6', '#BCCEF8', '#98A8F8']},
{industry: 'cafe', id: 'cafe-dark', name: '다크 로스터리', swatches: ['#F3F4F4', '#853953', '#612D53', '#2C2C2C']},
{industry: 'restaurant', id: 'food-terracotta', name: '테라코타', swatches: ['#FEF2A0', '#F3CD97', '#E98B50', '#BC4F4F']},
{industry: 'restaurant', id: 'food-red', name: '클래식 레드', swatches: ['#FEF9E1', '#E5D0AC', '#A31D1D', '#6D2323']},
{industry: 'restaurant', id: 'food-olive', name: '올리브 키친', swatches: ['#EBE3A7', '#EB7D00', '#2C5745', '#2E2910']},
{industry: 'restaurant', id: 'food-sage', name: '세이지 다이닝', swatches: ['#F7E7DC', '#FFF8F3', '#758694', '#405D72']},
{industry: 'restaurant', id: 'food-night', name: '나이트 다이닝', swatches: ['#F5E8C7', '#DEBA9D', '#9E7777', '#6F4C5B']},
{industry: 'tour', id: 'tour-teal', name: '틸 앰버', swatches: ['#FFE2AF', '#E37434', '#24B1B1', '#007979']},
{industry: 'tour', id: 'tour-sky', name: '클리어 스카이', swatches: ['#F9F7F7', '#DBE2EF', '#3F72AF', '#112D4E']},
{industry: 'tour', id: 'tour-spring', name: '스프링 필드', swatches: ['#F6F193', '#C5EBAA', '#A5DD9B', '#A0D683']},
{industry: 'tour', id: 'tour-sunset', name: '선셋 어드벤처', swatches: ['#FFEEA9', '#FFBF78', '#FF7D29', '#FF4E88']},
{industry: 'tour', id: 'tour-violet', name: '바이올렛 플레이', swatches: ['#F3F8FF', '#E26EE5', '#7E30E1', '#49108B']},
] satisfies Array<{industry: IndustryType; id: string; name: string; swatches: string[]}>;
export const COLOR_PALETTE_PRESETS: ColorPalettePreset[] = SOURCE.flatMap((preset) => {
const derived = derivePalette(preset.swatches);
if (!derived) return [];
const packed = preset.swatches.map((color) => color.slice(1)).join('').toLowerCase();
return [{
...preset,
sourceUrl: `https://colorhunt.co/palette/${packed}`,
colors: {
primary: derived.primary,
secondary: derived.secondary,
bg: derived.bg,
card: derived.card,
text: derived.text,
accent: derived.accent,
},
}];
});
@@ -0,0 +1,325 @@
/**
* [정보]·[확인] 탭 편집 → 서버 저장.
*
* 사장님이 [맞아요] 를 눌렀는데 로컬 상태만 바뀌면, 리페치 한 번에 되돌아가고
* 발행 게이트는 저장되지도 않은 검증을 근거로 "발행 가능"이라고 말한다 — 판단 자체가 허상이다.
* 그래서 화면은 즉시 바꾸되(낙관적), 같은 편집을 fact 전이 API 로 올리고, 실패하면 되돌린다.
*
* ★ 왜 훅이 아니라 스토어 액션이 부르나: updateField/verifyField 의 시그니처는 그대로 둬야 하고
* (호출부 계약), 액션이 특정 컴포넌트의 마운트에 기대게 만들면 안 되기 때문이다.
* react-query 는 그대로 쓴다 — 뮤테이션 캐시로 실행하고, PlaceDetailPage 와 같은 키
* (['facts', placeId])를 같은 방식으로 무효화한다. 두 화면이 같은 캐시를 본다.
*
* ★ 왜 팩토리인가: 이 모듈은 스토어를 읽고 써야 하는데, 스토어도 이 모듈을 부른다.
* `useBuilderStore` 를 직접 import 하면 순환이 된다. 스토어를 **인자로 받으면**
* 의존이 한쪽으로만 흐르고(스토어 → factSave), 테스트에서 가짜 스토어를 끼울 수도 있다.
*/
import type {StoreApi} from 'zustand';
import type {InfoField} from '@o2o/shared';
import {FactStatus, isPublishableFact} from '@o2o/shared';
import {ApiError, getListFactsQueryKey, transitionFact} from '@/api';
import type {ReqTransitionFact, ResFact} from '@/api';
import {notify, notifyApiError} from '@/lib/notify';
import {queryClient} from '@/lib/query-client';
import type {FactRef} from '@/stores/builderTypes';
/** factSave 가 스토어에서 실제로 쓰는 부분만. 전체 BuilderState 를 알 필요가 없다. */
export interface FactSaveStoreSlice {
placeId: string | null;
factRefs: Record<string, FactRef>;
infoFields: InfoField[];
savingFieldIds: string[];
}
export interface FactSaver {
/** [정보] 탭 타이핑 — 잠깐 모았다가 마지막 값 하나만 올린다. */
queue: (fieldId: string, value: string, before?: InfoField) => void;
/** [확인] 탭 버튼 — 기다릴 이유가 없으므로 바로 올린다. */
saveNow: (fieldId: string, correctedValue?: string, before?: InfoField) => void;
/** 화면이 다른 사업장(또는 데모)로 갈아탄다 — 갈 곳 없는 저장 대기분을 버린다. */
clear: () => void;
/** 리페치 결과 위에 아직 저장 중인 편집을 다시 얹는다. */
withPendingEdits: (fields: InfoField[]) => InfoField[];
}
export function createFactSaver(store: StoreApi<FactSaveStoreSlice>): FactSaver {
/** 타이핑 한 글자마다 서버를 두드리지 않는다. 멈추면 마지막 값 하나만 올린다. */
const FACT_SAVE_DEBOUNCE_MS = 600;
/** 낙관적으로 먼저 바꿔놓는 부분. 리페치가 와도 이 만큼은 다시 얹는다. */
type FieldPatch = Partial<Pick<InfoField, 'value' | 'isVerified'>>;
interface PendingFactSave {
/** 이 필드의 마지막 편집 번호. 늦게 끝난 응답이 새 편집을 덮어쓰지 못하게 하는 표. */
seq: number;
patch: FieldPatch;
/** 실패하면 여기로 되돌린다 — 연속 편집이 시작되기 직전의 값. */
before?: InfoField;
/** 성공을 토스트로 알릴 것인가([확인] 탭 버튼만. 타이핑까지 알리면 시끄럽다). */
announce: boolean;
timer?: ReturnType<typeof setTimeout>;
}
/**
* 아직 서버 응답을 못 받은 편집들. 스토어 state 가 아니라 모듈 변수인 이유는
* 화면에 그려지는 값이 아니어서다 — state 에 넣으면 글자 하나마다 전체 구독자가 깨어난다.
*/
const pendingSaves = new Map<string, PendingFactSave>();
let factSaveSeq = 0;
/**
* 리페치 결과 위에 아직 저장 중인 편집을 다시 얹는다.
*
* ★ 이게 없으면 applyPlace 가 낙관적 반영을 덮어쓴다. query-client 는 staleTime 0 이라
* 리페치가 자주 오고, 그때마다 방금 누른 [맞아요] 가 '확인 필요'로 되튄다.
*/
function withPendingEdits(fields: InfoField[]): InfoField[] {
if (pendingSaves.size === 0) return fields;
return fields.map((field) => {
const pending = pendingSaves.get(field.id);
return pending ? {...field, ...pending.patch} : field;
});
}
/** 화면이 다른 사업장(또는 데모)로 갈아탄다 — 갈 곳 없는 저장 대기분을 버린다. */
function clearFactSaves() {
for (const pending of pendingSaves.values()) {
if (pending.timer) clearTimeout(pending.timer);
}
pendingSaves.clear();
store.setState((state) =>
state.savingFieldIds.length === 0 ? state : {savingFieldIds: []},
);
}
function markSaving(fieldId: string, saving: boolean) {
store.setState((state) => {
// 같은 상태면 같은 state 를 돌려준다 — 구독자를 괜히 깨우지 않는다.
if (state.savingFieldIds.includes(fieldId) === saving) return state;
return {
savingFieldIds: saving
? [...state.savingFieldIds, fieldId]
: state.savingFieldIds.filter((id) => id !== fieldId),
};
});
}
/**
* 이 줄을 서버에 올릴 수 있는가.
*
* ★ 제1 계약 — placeId 가 없으면(데모 경로) null 이다. 여기서 끊기므로 네트워크를 한 번도 타지 않는다.
* fact 참조가 없는 줄(상호·주소·전화)도 null 이다 — place 자체의 값이라 전이시킬 fact 가 없다.
*/
function factSaveTarget(fieldId: string): {placeId: string; ref: FactRef} | null {
const {placeId, factRefs} = store.getState();
if (!placeId) return null;
const ref = factRefs[fieldId];
return ref ? {placeId, ref} : null;
}
/**
* 화면 문자열 → 서버에 저장할 원래 값(formatFactValue 의 역).
*
* ★ 정보 표가 보여주는 건 사람이 읽는 문장이다('15,000원', '예'). 그대로 올리면 다음 렌더에서
* 단위가 두 번 붙고('15,000원원'), bool 이 '예'라는 문자열로 굳는다. 되돌려서 올린다.
*/
function toFactValue(display: string, ref: FactRef): string {
let text = display.trim();
if (ref.unit && text.endsWith(ref.unit)) text = text.slice(0, -ref.unit.length).trim();
if (ref.type === 'bool') return text === '예' ? 'true' : 'false';
if (ref.type === 'number') return text.replace(/,/g, '');
return text;
}
/**
* 지금 상태에서 밟을 전이 경로. 빈 배열이면 올릴 것이 없다.
*
* ★ 허용 전이는 백엔드 FACT_STATUS_TRANSITIONS(common/enums.py)가 유일한 소스다.
* 특히 UNVERIFIED → CORRECTED 는 그 표에 없다. 수집 직후 값(UNVERIFIED)을 사장님이 고치는 건
* [확인] 탭에서 제일 흔한 동작인데, 한 번에 보내면 전부 FACT_INVALID_TRANSITION 으로 거절된다.
* 그래서 표에 실제로 있는 두 변(UNVERIFIED → PENDING_OWNER → CORRECTED)을 차례로 밟는다.
* 중간에서 끊겨도 PENDING_OWNER 는 발행 불가 상태라 미검증 값이 새어나가지 않는다(절대규칙 1).
*/
function transitionPath(current: FactStatus, hasCorrection: boolean): FactStatus[] {
if (!hasCorrection) {
// [맞아요] — 이미 노출 가능한 값이면 보낼 것이 없다(VERIFIED → VERIFIED 는 표에 없다).
return isPublishableFact(current) ? [] : [FactStatus.VERIFIED];
}
// 사장님이 고친 값은 CORRECTED — 절대규칙 6, 이후 자동 수집이 덮어쓰지 못한다.
return current === FactStatus.UNVERIFIED
? [FactStatus.PENDING_OWNER, FactStatus.CORRECTED]
: [FactStatus.CORRECTED];
}
/**
* 전이 1건. PlaceDetailPage 의 useMutation 과 같은 옵션 모양을 렌더 트리 밖에서 쓰려고
* 뮤테이션 캐시로 직접 실행한다.
*
* scope 를 fact 별로 주면 같은 fact 의 전이가 겹치지 않고 보낸 순서대로 실행된다 —
* 두 단계(PENDING_OWNER → CORRECTED)가 뒤집히면 두 번째가 거절당한다.
*/
function runTransition(
placeId: string,
factId: string,
data: ReqTransitionFact,
): Promise<ResFact> {
return queryClient
.getMutationCache()
.build<ResFact, unknown, ReqTransitionFact, unknown>(queryClient, {
mutationKey: ['fact-transition', placeId, factId],
scope: {id: `fact-transition:${factId}`},
mutationFn: (req) => transitionFact(placeId, factId, req),
onSuccess: (res) => {
// ★ 백엔드는 거절도 200 + result.success=false 로 준다(PlaceDetailPage 와 같은 규약).
// 여기서 throw 하지 않으면 거절이 성공으로 둔갑해, 저장 안 된 값이 '확인됨'으로 남는다.
// notifyApiError 가 읽는 자리(error.data)에 응답을 그대로 실어 보낸다.
if (res.result?.success === false) {
throw new ApiError(200, 'FACT_TRANSITION_REJECTED', res);
}
},
})
.execute(data);
}
/** 낙관적 변경분을 저장 대기줄에 올린다. */
function stageFactSave(
fieldId: string,
patch: FieldPatch,
before: InfoField | undefined,
announce: boolean,
): PendingFactSave {
const existing = pendingSaves.get(fieldId);
factSaveSeq += 1;
const entry: PendingFactSave = {
seq: factSaveSeq,
patch: {...existing?.patch, ...patch},
// 되돌릴 지점은 '연속 편집이 시작되기 직전'이다 — 중간값으로 되돌리면
// 저장에 실패했는데도 사장님이 쓰던 값이 확인된 것처럼 남는다.
before: existing?.before ?? before,
announce: existing?.announce || announce,
timer: existing?.timer,
};
pendingSaves.set(fieldId, entry);
markSaving(fieldId, true);
return entry;
}
function rollbackField(fieldId: string, before?: InfoField) {
if (!before) return;
store.setState((state) => ({
infoFields: state.infoFields.map((field) => (field.id === fieldId ? {...before} : field)),
}));
}
/** 저장이 끝났다(성공이든 실패든). 그 사이 새 편집이 올라탔으면 그쪽이 끝낼 때까지 둔다. */
function settleFactSave(fieldId: string, seq: number) {
const entry = pendingSaves.get(fieldId);
if (!entry || entry.seq !== seq) return;
if (entry.timer) clearTimeout(entry.timer);
pendingSaves.delete(fieldId);
markSaving(fieldId, false);
}
/** [정보] 탭 타이핑 — 잠깐 모았다가 마지막 값 하나만 올린다. */
function queueFactSave(fieldId: string, value: string, before?: InfoField) {
const target = factSaveTarget(fieldId);
if (!target) return;
const next = toFactValue(value, target.ref);
// ★ 빈 값을 CORRECTED 로 올리면 서버의 노출값이 지워진다. 지우려는 건지 다시 쓰려고
// 잠깐 비운 건지 구분할 수 없으므로 올리지 않는다(다음 리페치가 서버 값으로 되돌린다).
if (!next) return;
const entry = stageFactSave(fieldId, {value, isVerified: true}, before, false);
if (entry.timer) clearTimeout(entry.timer);
entry.timer = setTimeout(() => {
entry.timer = undefined;
void flushFactSave(fieldId, next);
}, FACT_SAVE_DEBOUNCE_MS);
}
/** [확인] 탭 버튼 — 기다릴 이유가 없으므로 바로 올린다. */
function saveFactNow(fieldId: string, correctedValue?: string, before?: InfoField) {
const target = factSaveTarget(fieldId);
if (!target) {
// ★ 실사업장인데 올릴 fact 가 없다 = 상호·주소·전화다. 조용히 넘어가면 서버에 없는 승인을
// 화면만 '확인됨'으로 들고 있게 된다 — 발행 판단이 허상이 되는 바로 그 경우라, 알린다.
// (이 값들을 확정하는 창구는 백엔드에 동일 업소 검증뿐이다. 데모에서는 아무 말도 하지 않는다.)
if (store.getState().placeId) {
notify.warn(
'이 항목은 여기서 저장되지 않습니다',
'상호·주소·전화는 사업장 화면의 동일 업소 검증에서 확정됩니다.',
);
}
return;
}
const value = correctedValue === undefined ? undefined : toFactValue(correctedValue, target.ref);
if (value === '') return; // 빈 값은 올리지 않는다(위와 같은 이유).
stageFactSave(
fieldId,
correctedValue === undefined ? {isVerified: true} : {isVerified: true, value: correctedValue},
before,
true,
);
void flushFactSave(fieldId, value);
}
/** 대기줄에 올려둔 편집을 실제로 서버에 올린다. */
async function flushFactSave(fieldId: string, correctedValue?: string) {
const entry = pendingSaves.get(fieldId);
if (!entry) return;
const {seq} = entry;
const target = factSaveTarget(fieldId);
if (!target) {
settleFactSave(fieldId, seq);
return;
}
const path = transitionPath(target.ref.status, correctedValue !== undefined);
if (path.length === 0) {
settleFactSave(fieldId, seq);
return;
}
try {
let status = target.ref.status;
for (const step of path) {
// value 는 CORRECTED 전이에서만 의미가 있다(백엔드가 그때만 읽는다).
await runTransition(target.placeId, target.ref.factId, {
status: step,
value: step === FactStatus.CORRECTED ? (correctedValue ?? null) : null,
});
status = step;
}
// 다음 편집이 올바른 출발 상태에서 시작하도록 참조도 같이 옮긴다
// (연달아 고치면 CORRECTED → CORRECTED 로 가야 한다).
store.setState((state) => ({
factRefs: {...state.factRefs, [fieldId]: {...target.ref, status}},
}));
if (pendingSaves.get(fieldId)?.seq !== seq) return; // 새 편집이 올라탔다 — 그쪽이 마무리한다
if (entry.announce) notify.success('반영했습니다');
// ★ 무효화 타이밍 — 리페치가 끝난 뒤에 낙관적 표시를 푼다. 먼저 풀면 새 응답이 도착하기
// 전까지 옛 서버 값이 잠깐 그려진다. 키는 생성물이 정한 것을 그대로 쓴다
// (getListFactsQueryKey) — usePlaceSync·PlaceDetailPage 와 같은 캐시 항목이어야 한다.
await queryClient
.invalidateQueries({queryKey: getListFactsQueryKey(target.placeId)})
.catch(() => undefined);
settleFactSave(fieldId, seq);
} catch (error) {
if (pendingSaves.get(fieldId)?.seq !== seq) return;
// ★ 실패했는데 화면에 '확인됨'으로 남으면, 검증 안 된 값이 검증된 것처럼 발행된다.
// 그래서 편집 직전 값으로 되돌리고 반드시 알린다.
rollbackField(fieldId, entry.before);
settleFactSave(fieldId, seq);
notifyApiError(error, '저장하지 못했습니다. 값을 되돌렸습니다.');
}
}
return {
queue: queueFactSave,
saveNow: saveFactNow,
clear: clearFactSaves,
withPendingEdits,
};
}
@@ -0,0 +1 @@
export {EditorLayout} from './EditorLayout';
@@ -0,0 +1,239 @@
/**
* 백엔드 응답 → 캔버스 데이터.
*
* ★ 순수 함수만 둔다. 스토어도 네트워크도 모른다 — 입력(place·fact·media·스키마)이 같으면
* 출력이 항상 같다. 그래서 "화면이 왜 저 값을 보여주나"를 이 파일만 읽고 답할 수 있다.
*
* ★ 필드명은 지어내지 않는다. 기준은 backend/router/v1/place/protocol.py 의 PlaceData 와
* backend/router/v1/fact/protocol.py 의 FactData · FieldSpecData 다.
*/
import type {IndustryType, InfoField, PhotoItem} from '@o2o/shared';
import {isPublishableFact, PlaceCategory, SourceType} from '@o2o/shared';
import type {FactData, FieldSpecData, MediaData, PlaceData} from '@/api';
import {FALLBACK_INDUSTRY} from '@/data/industryData';
import type {FactRef, LivePlaceInput} from '@/stores/builderTypes';
/** places.category → 빌더 업종. 어떤 업종 시드(섹션·템플릿·문구)를 깔지가 여기서 갈린다. */
export const CATEGORY_TO_INDUSTRY: Record<number, IndustryType> = {
[PlaceCategory.LODGING]: 'stay',
[PlaceCategory.CAFE]: 'cafe',
[PlaceCategory.RESTAURANT]: 'restaurant',
[PlaceCategory.TOUR_ACTIVITY]: 'tour',
};
/** facts.source_type — 사장님이 [맞아요] 를 누를 판단 근거. 출처 없는 값은 보여주지 않는다. */
const SOURCE_LABEL: Record<number, string> = {
[SourceType.OWNER]: '사장님 입력',
[SourceType.API]: '외부 API',
[SourceType.CRAWL]: '채널 수집',
[SourceType.LLM]: 'AI 초안',
};
/** 출처 한 줄. URL 은 통째로 쓰면 패널을 밀어내므로 호스트만 남긴다. */
function factSource(fact: FactData): string {
const label = SOURCE_LABEL[fact.source_type] ?? '출처 미상';
if (!fact.source_url) return label;
try {
return `${label} · ${new URL(fact.source_url).hostname}`;
} catch {
return label;
}
}
/**
* fact 값을 사람이 읽는 문장으로.
*
* bool 은 'true' 가 그대로 화면에 나가면 안 되고, number 는 천 단위 구분이 없으면
* 사장님도 AI 도 자릿수를 세야 한다(shared/lib/facts.ts 의 factText 와 같은 규칙).
*/
function formatFactValue(fact: FactData, spec?: FieldSpecData): string {
const raw = (fact.value ?? '').trim();
if (!raw) return '';
const unit = fact.unit ?? spec?.unit ?? '';
if (spec?.type === 'bool') return raw === 'true' || raw === '1' || raw === 'Y' ? '예' : '아니오';
if (spec?.type === 'number') {
const num = Number(raw.replace(/,/g, ''));
return `${Number.isFinite(num) ? num.toLocaleString('ko-KR') : raw}${unit}`;
}
return `${raw}${unit}`;
}
/** place 가 소유하는 줄. fact 가 아니므로 전이시킬 대상이 없다(id 가 겹치면 안 된다). */
const IDENTITY_FIELD_IDS = new Set(['name', 'address', 'phone']);
/**
* place 응답의 신원 정보(상호·주소·전화).
*
* fact 가 아직 하나도 없어도 이건 채워진다 — 수집 전 사업장을 열어도 캔버스가 빈 껍데기가
* 되지 않게. id 는 데모 시드와 같은 이름을 쓴다(캔버스 푸터가 'address' 를 이름으로 찾는다).
*/
function identityFields(place: PlaceData): InfoField[] {
// ★ verified_at 이 NULL 이면 동일 업소 검증 전이다 — 주소·전화가 동명 업소의 것일 수 있다.
// 그래서 '확인 필요'로 올린다: 캔버스가 가리고, 발행 게이트가 잡는다(절대규칙 1).
const verified = Boolean(place.verified_at);
const address = place.road_address ?? place.address ?? '';
const fields: InfoField[] = [
{
id: 'name',
label: '상호',
value: place.name,
requiresVerification: false,
isVerified: true,
source: '사장님 등록',
},
];
if (address) {
fields.push({
id: 'address',
label: '주소',
value: address,
requiresVerification: !verified,
isVerified: verified,
source: '동일 업소 검증',
critical: true,
});
}
if (place.phone) {
fields.push({
id: 'phone',
label: '전화',
value: place.phone,
requiresVerification: !verified,
isVerified: verified,
source: '동일 업소 검증',
critical: true,
});
}
return fields;
}
/**
* key 당 대표 fact 1건(scope='unit' 인 값은 뺀다).
*
* ★ 정보 표와 저장 배선이 반드시 같은 fact 를 가리켜야 한다 — 서로 다른 걸 고르면
* 화면에서 보고 있는 줄과 실제로 전이시키는 fact 가 어긋나, 엉뚱한 값이 '확인됨'이 된다.
*/
function placeFactsByKey(facts: FactData[]): Map<string, FactData> {
const byKey = new Map<string, FactData>();
for (const fact of facts) {
if (fact.unit_id) continue;
if (!byKey.has(fact.key)) byKey.set(fact.key, fact);
}
return byKey;
}
/** 정보 표의 줄 id → 어떤 fact 를 전이시킬지. 화면과 같은 규칙(placeFactsByKey)으로 고른다. */
function toFactRefs(facts: FactData[], specs: FieldSpecData[]): Record<string, FactRef> {
const specByKey = new Map(specs.map((spec) => [spec.key, spec]));
const refs: Record<string, FactRef> = {};
for (const [key, fact] of placeFactsByKey(facts)) {
// 신원 줄과 id 가 겹치면 사장님이 보는 줄과 다른 fact 를 고치게 된다. 그럴 바엔 로컬로 둔다.
if (IDENTITY_FIELD_IDS.has(key)) continue;
const spec = specByKey.get(key);
refs[key] = {
factId: fact.fact_id,
status: fact.status,
type: spec?.type,
// 단위는 fact 가 우선이다(수집 시점의 값). 없으면 업종 스키마의 단위.
unit: fact.unit ?? spec?.unit ?? undefined,
};
}
return refs;
}
/** fact 1건 → 정보 표 한 줄. */
function factField(fact: FactData, spec?: FieldSpecData): InfoField {
const publishable = isPublishableFact(fact.status);
return {
id: fact.key,
label: spec?.label ?? fact.key,
value: formatFactValue(fact, spec),
// ★ 절대규칙 1 — VERIFIED · CORRECTED 가 아니면 캔버스가 가린다.
requiresVerification: !publishable,
isVerified: publishable,
source: factSource(fact),
critical: spec?.critical,
};
}
/**
* place + fact + 업종 스키마 → 캔버스의 infoFields.
*
* 줄 순서는 업종 스키마(FieldSpecData)가 정한다. 수집된 순서대로 늘어놓으면 재수집이
* 돌 때마다 표의 줄 순서가 바뀐다 — 사장님 눈에는 값이 바뀐 것처럼 보인다.
*
* ★ scope='unit' 인 fact(객실·메뉴별 값)는 넣지 않는다. 같은 key 가 단위 수만큼 들어와
* '기본 정보' 표에 같은 라벨이 여러 줄 겹친다 — 단위별 값은 객실/메뉴 섹션의 몫이다.
*/
function toInfoFields(place: PlaceData, facts: FactData[], specs: FieldSpecData[]): InfoField[] {
const placeFacts = placeFactsByKey(facts);
const ordered: InfoField[] = [];
const taken = new Set<string>();
for (const spec of specs) {
if (spec.scope !== 'place') continue;
const fact = placeFacts.get(spec.key);
if (!fact) continue;
taken.add(spec.key);
ordered.push(factField(fact, spec));
}
// 스키마에 없는 key 도 버리지 않는다(스키마 배포보다 수집이 앞선 경우).
for (const [key, fact] of placeFacts) {
if (!taken.has(key)) ordered.push(factField(fact));
}
// 값이 빈 fact 는 표에 넣지 않는다 — 라벨만 있는 빈 줄은 정보가 아니라 잡음이다.
return [...identityFields(place), ...ordered.filter((f) => f.value !== '')];
}
/**
* 서버 media → 캔버스 사진.
*
* ★ **발행 가능한 것만** 넘긴다(승인 + alt 있음). 미승인 사진을 캔버스에 그리면
* 사장님은 그게 사이트에 나갈 것으로 읽는데, 발행 스냅샷은 그걸 걸러낸다 —
* 화면과 발행본이 갈리는 자리다. `publishable` 은 서버가 판정해 내려준다.
*/
function toPhotos(media: MediaData[]): PhotoItem[] {
return media
.filter((m) => m.publishable !== false)
.map((m, index) => ({
id: m.media_id,
url: m.url ?? m.origin_url ?? '',
// alt 는 Vision 이 붙인 설명이다. 없으면 라벨(분류)로 떨어뜨린다.
title: m.alt_text || m.label || '수집된 사진',
category: m.label ?? '기타',
isPrimary: index === 0,
isVisible: true,
}))
.filter((p) => p.url);
}
export function toLivePlaceInput(
placeId: string,
place: PlaceData,
facts: FactData[],
specs: FieldSpecData[],
media: MediaData[],
): LivePlaceInput {
return {
placeId,
industry: CATEGORY_TO_INDUSTRY[place.category] ?? FALLBACK_INDUSTRY,
storeName: place.name,
location: place.road_address ?? place.address ?? '',
weatherLocation:
place.region_code && place.latitude != null && place.longitude != null
? {
regionCode: place.region_code,
latitude: Number(place.latitude),
longitude: Number(place.longitude),
}
: undefined,
infoFields: toInfoFields(place, facts, specs),
factRefs: toFactRefs(facts, specs),
// fact 가 하나도 없으면 아직 수집 전이다(신원 2줄은 place 가 준 것이지 수집물이 아니다).
hasCollected: facts.length > 0,
photos: toPhotos(media),
};
}
@@ -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',
]);
@@ -0,0 +1,89 @@
import {Check, ExternalLink, Loader2} from 'lucide-react';
import type {LinkData} from '@/api';
import {Badge} from '@/components/ui/badge';
import {Button} from '@/components/ui/button';
import {cn} from '@/lib/utils';
import {CHANNEL_LABEL} from './useCollectFlow';
/**
* 수집 잡이 찾아온 채널 URL 을 사장님이 확정하는 패널.
*
* ★ 이 화면이 파이프라인에서 사람이 반드시 개입해야 하는 지점이다.
* 확정 없이 긁으면 이름이 비슷한 남의 가게 페이지가 이 가게의 공식 홈페이지에 실린다.
* 그래서 기본값은 '확정 안 함'이고, 누른 것만 크롤링 대상이 된다.
*/
export function ChannelConfirmPanel({
links,
confirmedCount,
confirmingId,
onConfirm,
}: {
links: LinkData[];
confirmedCount: number;
confirmingId: string | null;
onConfirm: (linkId: string) => void;
}) {
return (
<div>
<div className="mb-2 flex items-center justify-between">
<span className="text-xs font-semibold">찾은 채널 URL</span>
<Badge variant={confirmedCount > 0 ? 'success' : 'warning'} className="text-[10px]">
확정 {confirmedCount} / {links.length}
</Badge>
</div>
<ul className="max-h-56 space-y-1.5 overflow-y-auto pr-1">
{links.map((link) => {
const isConfirmed = Boolean(link.confirmed_at);
const isBusy = confirmingId === link.link_id;
return (
<li
key={link.link_id}
className={cn(
'rounded-lg border p-2.5 text-[11px]',
isConfirmed ? 'border-success/40 bg-success/5' : 'border-border bg-muted/40',
)}
>
<div className="flex items-center justify-between gap-2">
<span className="font-semibold">
{CHANNEL_LABEL[link.channel] ?? '기타 채널'}
</span>
{isConfirmed ? (
<Badge variant="success" className="shrink-0 text-[10px]">
확정됨
</Badge>
) : (
<Button
size="sm"
variant="primary"
onClick={() => onConfirm(link.link_id)}
disabled={isBusy}
>
{isBusy ? <Loader2 className="animate-spin" /> : <Check />}
<span>내 채널 맞아요</span>
</Button>
)}
</div>
<a
href={link.url}
target="_blank"
rel="noopener noreferrer"
className="mt-1 flex items-center gap-1 break-all text-muted-foreground underline-offset-2 hover:text-foreground hover:underline"
>
<ExternalLink className="size-3 shrink-0" />
<span className="min-w-0 break-all">{link.url}</span>
</a>
</li>
);
})}
</ul>
<p className="mt-2 text-[11px] leading-relaxed text-muted-foreground">
링크를 열어 <strong>내 가게가 맞는지 직접 확인</strong>한 뒤 확정해 주세요. 확정한 URL 만
크롤링합니다 — 확정하지 않은 URL 은 건드리지 않습니다.
</p>
</div>
);
}
@@ -0,0 +1,143 @@
import {useState} from 'react';
import {Link2, Loader2, MapPin, Plus} from 'lucide-react';
import type {LinkChannel as LinkChannelCode} from '@/api';
import {LinkChannel} from '@o2o/shared';
import {Button} from '@/components/ui/button';
import {Input} from '@/components/ui/input';
/**
* 채널 URL 직접 등록 — **수집의 1순위 경로다.** 폴백이 아니다.
*
* ★ 왜 자동 발견보다 이게 먼저인가 (실측 2026-08-27)
* · Perplexity 는 네이버 플레이스를 **한 건도** 못 찾았다(도플로·버터브루·힐튼 가든 인
* 서울 강남 전부 야놀자만 물어옴). 도메인 필터를 넓혔더니 이번엔 네이버 도움말 페이지
* (pages.map.naver.com/useful-tips)를 이 가게 채널로 등록했다. 그래서 기본 경로에서 뺐다.
* · 상호로 place id 를 자동 해석하는 경로도 4곳 중 3곳만 성공한다('롯데호텔 서울' 실패).
* · 반면 **네이버 플레이스 URL 만 있으면 100% 된다** — 어댑터가 fact 5~7건 + 사진 10장을
* 안정적으로 가져온다(힐튼·스테이머뭄·롯데월드에서 검증).
* 그리고 사장님은 자기 가게 주소를 이미 알고 있다. 추측하게 두는 것보다 물어보는 것이
* 빠르고 정확하고 공짜다.
*
* 그래서 이 컴포넌트는 "네이버 지도 주소"를 전제로 말한다 — 다른 채널도 받지만,
* 사장님이 따라 할 동작 하나는 네이버 지도에서 주소를 복사하는 것이다.
*
* 붙여넣은 URL 은 그 자체로 사장님이 확인한 값이므로 등록과 동시에 확정한다.
*/
/** 호스트로 채널을 판정한다. 서버도 같은 규칙을 쓰지만, 화면이 먼저 라벨을 보여줘야 한다. */
function guessChannel(url: string): {channel: LinkChannelCode; label: string} | null {
const u = url.toLowerCase();
if (u.includes('naver.com') || u.includes('naver.me')) {
// 블로그·카페는 채널이 아니라 후기다 — 크롤링 대상이 아니므로 받지 않는다.
if (u.includes('blog.naver') || u.includes('cafe.naver')) return null;
return {channel: LinkChannel.NAVER_PLACE, label: '네이버 플레이스'};
}
if (u.includes('yanolja.com')) return {channel: LinkChannel.YANOLJA, label: '야놀자'};
if (u.includes('goodchoice.kr') || u.includes('yeogi.com')) {
return {channel: LinkChannel.GOODCHOICE, label: '여기어때'};
}
if (u.includes('instagram.com')) return {channel: LinkChannel.INSTAGRAM, label: '인스타그램'};
return {channel: LinkChannel.OFFICIAL_SITE, label: '공식 홈페이지'};
}
/** 주소를 어디서 복사해 오는지 — 사장님이 그대로 따라 할 수 있게 동작 단위로 쪼갠다. */
const HOW_TO = [
'네이버 지도(또는 네이버 검색)에서 내 가게를 찾습니다',
'가게 이름 옆 [공유] 를 누릅니다',
'[URL 복사] 를 눌러 주소를 복사합니다',
'아래 칸에 붙여넣고 [추가] 를 누릅니다',
];
export function ChannelUrlInput({
onAdd,
isBusy,
}: {
onAdd: (url: string, channel: LinkChannelCode, title: string) => Promise<void>;
isBusy?: boolean;
}) {
const [url, setUrl] = useState('');
const [error, setError] = useState<string | null>(null);
const guess = url.trim() ? guessChannel(url.trim()) : null;
const isNaver = guess?.channel === LinkChannel.NAVER_PLACE;
const submit = async () => {
const value = url.trim();
if (!value) return;
if (!/^https?:\/\//i.test(value)) {
setError('https:// 로 시작하는 주소를 붙여넣어 주세요.');
return;
}
if (!guess) {
setError('블로그·카페 글은 채널이 아니라 후기라 수집 대상이 아닙니다.');
return;
}
setError(null);
await onAdd(value, guess.channel, guess.label);
setUrl('');
};
return (
<div className="rounded-2xl border border-primary/40 bg-primary/5 p-5">
<p className="flex items-center gap-1.5 text-sm font-bold">
<MapPin className="size-4 text-primary" />
네이버 지도에서 내 가게 주소를 복사해 붙여넣어 주세요
</p>
<p className="mt-1.5 text-[11px] leading-relaxed text-muted-foreground">
가장 확실한 방법입니다. 주소 하나만 있으면 <strong>영업시간·전화·편의시설과 사진</strong>
까지 그대로 가져옵니다.
</p>
<ol className="mt-3 space-y-1.5">
{HOW_TO.map((step, index) => (
<li key={step} className="flex items-start gap-2 text-[11px] leading-relaxed">
<span className="mt-px flex size-4 shrink-0 items-center justify-center rounded-full bg-primary text-[9px] font-bold text-primary-foreground">
{index + 1}
</span>
<span>{step}</span>
</li>
))}
</ol>
<div className="mt-3 flex items-center gap-1.5">
<Input
value={url}
onChange={(e) => {
setUrl(e.target.value);
setError(null);
}}
onKeyDown={(e) => {
if (e.key === 'Enter') void submit();
}}
placeholder="https://map.naver.com/p/entry/place/1273971279"
disabled={isBusy}
/>
<Button size="sm" variant="primary" onClick={() => void submit()} disabled={isBusy || !url.trim()}>
{isBusy ? <Loader2 className="animate-spin" /> : <Plus />}
<span>추가</span>
</Button>
</div>
<p
className={`mt-1.5 text-[11px] leading-relaxed ${
error ? 'text-destructive' : isNaver ? 'text-primary' : 'text-muted-foreground'
}`}
>
{error ??
(isNaver
? '네이버 플레이스 주소입니다 — 이 경로가 가장 많이, 가장 정확하게 가져옵니다.'
: guess
? `${guess.label} 주소로 등록됩니다. 네이버 지도 주소가 있으면 그쪽이 더 많이 가져옵니다.`
: 'naver.me 단축 주소도 됩니다. 야놀자·여기어때·공식 홈페이지 주소도 받습니다.')}
</p>
<p className="mt-2 flex items-start gap-1 border-t border-primary/20 pt-2 text-[10px] leading-relaxed text-muted-foreground">
<Link2 className="mt-px size-3 shrink-0" />
<span>
붙여넣은 주소는 사장님이 확인한 것으로 보고 <strong>바로 수집 대상</strong>이 됩니다.
수집된 값은 그래도 전부 확인 대기로 들어갑니다.
</span>
</p>
</div>
);
}
@@ -0,0 +1,153 @@
import {useState} from 'react';
import {useQueryClient} from '@tanstack/react-query';
import {ClipboardPaste, Loader2, Sparkles} from 'lucide-react';
import type {ResExtractedFact} from '@/api';
import {useExtractFactsFromText} from '@/api';
import {Button} from '@/components/ui/button';
import {notify, notifyApiError} from '@/lib/notify';
import {cn} from '@/lib/utils';
/**
* 붙여넣기로 정보 채우기 — **폴백 3단계의 2번**이다.
*
* ★ 왜 필요한가 (실측 2026-08-31)
* 자동 수집만으로는 근거가 안 차는 업소가 흔하다.
* · 조이모텔: TourAPI 미등록(모텔은 관광공사 대상이 아니다) + 네이버엔 요금표뿐 →
* 수집 fact 6건이 전부 '대실 20,000 / 숙박 40,000' 같은 요금이었다.
* 체크인·주차·와이파이가 하나도 없어 소개문도 FAQ 도 만들 수 없었다.
* 이런 업소는 사장님이 이미 알고 있는 내용을 **붙여넣게 하는 것이 가장 빠르다.**
* 홈페이지 URL 이 있으면 static_html 어댑터가 대신 읽지만, 그것도 없는 업소가 많다.
*
* ★ 사장님이 쓴 글을 그대로 싣지 않는다
* 붙여넣은 원문은 저장되지 않는다. 서버가 업종 스키마 필드만 **뽑아서** 후보로 넣고,
* 그 값의 근거 문장이 원문에 실제로 있는지까지 대조한다(services/grounding/extract.py).
* 그래서 "조식 제공합니다" 를 안 썼는데 조식이 켜지는 일이 없다.
*
* ★ 결과를 통과분만 보여주지 않는다
* 버려진 항목과 사유를 같이 띄운다 — 사장님이 "내가 적은 체크인 시간이 왜 안 들어갔지"
* 를 화면에서 바로 알 수 있어야 한다. 조용히 버리면 신뢰를 잃는다.
*/
const PLACEHOLDER = `가게 소개, 이용 안내, 객실·메뉴 정보를 그대로 붙여넣어 주세요.
예시)
체크인 오후 3시 / 체크아웃 오전 11시
전 객실 무료주차 가능, 와이파이 있습니다
반려동물 동반은 어렵습니다
바비큐장 이용료 1회 20,000원
오션뷰룸 기준 2인 최대 4인 / 주중 180,000원 주말 220,000원`;
const MIN_CHARS = 80;
export function PasteFactsPanel({placeId, className}: {placeId: string | null; className?: string}) {
const [text, setText] = useState('');
const [result, setResult] = useState<{stored: number; rows: ResExtractedFact[]; rejections: string[][]} | null>(null);
const queryClient = useQueryClient();
const extract = useExtractFactsFromText();
// 데모(placeId 없음)에는 저장할 서버 상태가 없다. 눌러도 아무 일이 없는 버튼을 두지 않는다.
if (!placeId) return null;
const tooShort = text.trim().length < MIN_CHARS;
const busy = extract.isPending;
const run = async () => {
try {
const res = await extract.mutateAsync({placeId, data: {text}});
setResult({
stored: res.stored ?? 0,
rows: res.facts ?? [],
rejections: (res.rejections ?? []) as string[][],
});
if (res.stored) {
// 새 후보가 생겼으니 fact 목록을 다시 읽는다 — 사장님이 바로 확인 버튼을 눌러야 한다.
await queryClient.invalidateQueries({queryKey: ['/v1/place', placeId, 'fact']});
notify.success(`${res.stored}건을 찾았습니다. 확인 후 사이트에 반영됩니다.`);
setText('');
} else {
notify.info('가져올 수 있는 정보를 찾지 못했습니다. 아래 사유를 확인해 주세요.');
}
} catch (error) {
notifyApiError(error);
}
};
return (
<section className={cn('space-y-2.5 rounded-xl border border-border bg-card p-4', className)}>
<header className="flex items-center gap-2">
<ClipboardPaste className="size-4 shrink-0 text-muted-foreground" />
<h2 className="text-sm font-semibold">붙여넣어서 정보 채우기</h2>
</header>
<p className="text-[11px] leading-relaxed text-muted-foreground">
자동으로 못 가져온 정보는 직접 붙여넣어 주세요. 문장에서 필요한 항목만 뽑아 <strong>확인 대기</strong> 목록에
넣습니다. 원문은 저장되지 않습니다.
</p>
<textarea
value={text}
onChange={(e) => setText(e.target.value)}
placeholder={PLACEHOLDER}
rows={8}
disabled={busy}
className={cn(
'w-full resize-y rounded-lg border border-input bg-background px-3 py-2',
'text-xs leading-relaxed placeholder:text-muted-foreground/70',
'focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring disabled:opacity-60',
)}
/>
<div className="flex items-center justify-between gap-2">
<span className="text-[10px] text-muted-foreground">
{text.trim().length > 0 && tooShort
? `${MIN_CHARS}자 이상 붙여넣어 주세요 (현재 ${text.trim().length}자)`
: `${text.trim().length}자`}
</span>
<Button size="sm" disabled={busy || tooShort} onClick={() => void run()}>
{busy ? <Loader2 className="animate-spin" /> : <Sparkles />}
<span>{busy ? '읽는 중…' : '정보 뽑기'}</span>
</Button>
</div>
{result && (
<div className="space-y-2 rounded-lg border border-border bg-muted/40 p-3">
<p className="text-[11px] font-medium">
{result.stored}건 추가됨
{result.rejections.length > 0 && (
<span className="text-muted-foreground"> · {result.rejections.length}건 제외</span>
)}
</p>
{result.rows.length > 0 && (
<ul className="space-y-1">
{result.rows.map((row, i) => (
<li key={`${row.key}-${i}`} className="flex items-start gap-2 text-[11px]">
<span className={cn('mt-1 size-1.5 shrink-0 rounded-full', row.stored ? 'bg-emerald-500' : 'bg-amber-500')} />
<span className="min-w-0">
<strong className="font-medium">{row.label}</strong>
{row.unit_name && <span className="text-muted-foreground"> · {row.unit_name}</span>}
<span className="text-muted-foreground"> — {row.value}</span>
{row.reason && <span className="block text-amber-600 dark:text-amber-500">{row.reason}</span>}
</span>
</li>
))}
</ul>
)}
{/* ★ 버린 것도 보여준다. 사장님이 왜 안 들어갔는지 알아야 다시 쓸 수 있다. */}
{result.rejections.length > 0 && (
<details className="text-[10px] text-muted-foreground">
<summary className="cursor-pointer select-none">제외된 항목 보기</summary>
<ul className="mt-1 space-y-0.5 pl-3">
{result.rejections.map(([label, why], i) => (
<li key={i}>
<span className="font-medium">{label}</span> — {why}
</li>
))}
</ul>
</details>
)}
</div>
)}
</section>
);
}
@@ -0,0 +1,114 @@
import {ExternalLink, Link2, Loader2, MapPin} from 'lucide-react';
import {Button} from '@/components/ui/button';
import {Input} from '@/components/ui/input';
import {cn} from '@/lib/utils';
/**
* 자동 상호 검색이 실패했을 때 네이버 지도에서 직접 찾아 URL로 확정하는 fallback.
*
* ★ 왜 이 fallback 이 필요한가
* 상호 검색은 동명 업소·지점명 표기 차이에서 실패한다(실측: '롯데호텔 서울').
* 검색모델(Perplexity)은 네이버 플레이스를 아예 못 찾고 안내 페이지를 물어온 적도 있다.
* 반면 사장님은 자기 가게 주소를 이미 안다 — 붙여넣는 순간 신원과 수집 채널이 동시에
* 확정되고, 상호·주소·좌표는 서버가 그 URL 에서 직접 읽는다.
* (선례: o2o-castad 도 네이버 지도 URL 직접 입력을 주 경로로 둔다.)
*/
export function PlaceUrlBox({
value,
onChange,
onSubmit,
isBusy,
compact,
searchQuery,
}: {
value: string;
onChange: (next: string) => void;
onSubmit: () => void;
isBusy?: boolean;
/** 후보 목록 아래에 놓일 때는 설명을 줄인다. */
compact?: boolean;
/** 자동 검색 실패 시 네이버 지도를 이 검색어로 바로 연다. */
searchQuery?: string;
}) {
const isNaverUrl = /naver\.(com|me)/i.test(value);
const mapSearchUrl = searchQuery?.trim()
? `https://map.naver.com/p/search/${encodeURIComponent(searchQuery.trim())}`
: 'https://map.naver.com/';
return (
<div
className={cn(
'rounded-2xl border bg-card p-5',
compact ? 'border-border' : 'border-primary/40 ring-2 ring-primary/10',
)}
>
<p className="flex items-center gap-1.5 text-sm font-bold">
<MapPin className="size-4 text-primary" />
네이버 플레이스에서 직접 찾기
{!compact && (
<span className="rounded bg-primary/10 px-1.5 py-0.5 text-[10px] font-semibold text-primary">
가장 정확
</span>
)}
</p>
{!compact && (
<>
<p className="mt-2 text-[11px] leading-relaxed text-muted-foreground">
자동 검색에서 찾지 못했습니다. 네이버 지도에서 내 가게를 연 뒤 [공유] 주소를
복사해 아래에 붙여넣어 주세요.
</p>
</>
)}
<a
href={mapSearchUrl}
target="_blank"
rel="noopener noreferrer"
className="mt-3 flex w-full items-center justify-center gap-1.5 rounded-lg border border-border bg-background px-3 py-2 text-xs font-semibold transition-colors hover:bg-accent"
>
<ExternalLink className="size-3.5" />
<span>
네이버 지도에서{' '}
{searchQuery?.trim()
? `'${searchQuery.trim()}' 검색`
: compact
? '이 상호 다시 찾기'
: '검색'}
</span>
</a>
<div className="mt-3 flex items-center gap-1.5">
<Input
value={value}
onChange={(e) => onChange(e.target.value)}
onKeyDown={(e) => {
if (e.key === 'Enter' && value.trim()) onSubmit();
}}
placeholder="https://map.naver.com/p/entry/place/1133638931"
disabled={isBusy}
/>
<Button
variant="primary"
onClick={onSubmit}
disabled={isBusy || !value.trim()}
className="shrink-0"
>
{isBusy ? <Loader2 className="animate-spin" /> : <Link2 />}
<span>확인</span>
</Button>
</div>
<p
className={cn(
'mt-1.5 text-[11px]',
value.trim() && !isNaverUrl ? 'text-destructive' : 'text-muted-foreground',
)}
>
{value.trim() && !isNaverUrl
? '네이버 지도·플레이스 주소를 붙여넣어 주세요.'
: 'map.naver.com · m.place.naver.com · naver.me 주소를 지원합니다.'}
</p>
</div>
);
}
@@ -0,0 +1,129 @@
import {Loader2, PenLine, RefreshCw, Sparkles, TriangleAlert} from 'lucide-react';
import {useGetPlace} from '@/api';
import {Button} from '@/components/ui/button';
import {cn} from '@/lib/utils';
import {useCollectFlow, type RecollectTask} from './useCollectFlow';
/**
* 세 가지 재수집 동작.
*
* ★ 문구가 "다시 가져옵니다"로 읽히면 안 된다. 자동 수집(CRAWL)은 **노출 중인 값을 못 바꾼다** —
* 달라진 값은 확인 대기 후보로 쌓이고, 사장님이 [맞아요]를 눌러야 교체된다. 사장님이 직접
* 고친 값(CORRECTED)은 아예 잠겨 있다(fact_service 의 업데이트 프로세스).
* 그래서 hint 는 전부 "후보로 올립니다 / 확인 뒤 나갑니다"로 끝난다.
*/
const ACTIONS: {
task: RecollectTask;
label: string;
busyLabel: string;
icon: typeof RefreshCw;
hint: string;
}[] = [
{
task: 'facts',
label: '정보 다시 수집',
busyLabel: '수집 중…',
icon: RefreshCw,
hint: '확정한 채널을 다시 읽습니다. 달라진 값은 확인 대기 목록에 쌓입니다.',
},
{
task: 'photos',
label: '사진 다시 분석',
busyLabel: '분석 중…',
icon: Sparkles,
hint: '이미 분석한 사진까지 다시 분류하고 설명을 답니다.',
},
{
task: 'copy',
label: '소개문 다시 생성',
busyLabel: '만드는 중…',
icon: PenLine,
hint: '확인된 정보만 근거로 소개문·FAQ 를 새로 씁니다.',
},
];
/**
* 재수집 패널 — 사업장 상세와 빌더 에디터가 같이 쓴다.
*
* ★ 왜 필요한가: 재수집 버튼은 지금까지 위저드 3단계에만 있었다. 위저드를 끝내고 나면
* **이미 만든 사업장을 다시 긁을 길이 없어서** 사장님 눈에는 "재크롤링 기능이 없다"였다.
* 그래서 사업장을 다시 여는 두 자리(상세 · 에디터)에 같은 패널을 붙인다.
*
* ★ 배선은 위저드와 **같은 훅**(useCollectFlow)이다. 수집 경로를 두 벌 만들면 확정 게이트
* 같은 규칙이 한쪽에서만 지켜진다 — 다른 건 force 플래그뿐이다.
*/
export function RecollectPanel({placeId, className}: {placeId: string | null; className?: string}) {
const enabled = Boolean(placeId);
// 이미 다른 화면이 읽어둔 캐시를 그대로 본다(같은 쿼리 키) — 이 패널 때문에 새로 요청하지 않는다.
const placeQuery = useGetPlace(placeId ?? '', {query: {enabled}});
const collect = useCollectFlow(placeId);
// 데모(placeId 없음)에는 재수집할 서버 상태 자체가 없다. 눌러도 아무 일이 없는 버튼을 두지 않는다.
if (!placeId) return null;
const isVerified = Boolean(placeQuery.data?.place?.verified_at);
const busy = collect.recollectingTask;
/** 지금 이 동작을 못 누르는 이유. 없으면 누를 수 있다. ★ 이유 없이 회색으로만 두지 않는다. */
const blockedReason = (task: RecollectTask): string | null => {
// 검증·확정 게이트는 크롤링에만 걸린다(place_service.start_collect).
// 사진 분석·소개문 생성은 이미 쌓인 데이터를 다루므로 서버가 따로 막지 않는다.
if (task !== 'facts') return null;
if (!isVerified) return '동일 업소 검증을 끝내야 수집이 열립니다.';
if (collect.confirmedCount === 0) return '확정한 채널 URL 이 없습니다. 먼저 채널을 확정해 주세요.';
return null;
};
return (
<section className={cn('space-y-2.5 rounded-xl border border-border bg-card p-4', className)}>
<header className="flex items-center justify-between gap-2">
<h2 className="text-sm font-semibold">다시 수집하기</h2>
{busy && (
<span className="flex shrink-0 items-center gap-1 text-[10px] font-medium text-muted-foreground">
<Loader2 className="size-3 animate-spin" />
진행 중
</span>
)}
</header>
<div className="space-y-2">
{ACTIONS.map(({task, label, busyLabel, icon: Icon, hint}) => {
const isRunning = busy === task;
const reason = blockedReason(task);
return (
<div key={task} className="space-y-1">
<Button
variant={task === 'facts' ? 'primary' : 'outline'}
size="sm"
className="w-full justify-start"
// 하나가 도는 동안 나머지도 잠근다 — 같은 사업장에 유료 잡을 겹쳐 태우지 않는다.
disabled={Boolean(busy) || Boolean(reason)}
onClick={() => void collect.recollect(task)}
>
{isRunning ? <Loader2 className="animate-spin" /> : <Icon />}
<span>{isRunning ? busyLabel : label}</span>
</Button>
<p className="text-[10px] leading-relaxed text-muted-foreground">{reason ?? hint}</p>
</div>
);
})}
</div>
{busy && (
// 잡은 몇 분짜리다. "누르긴 눌렀는데 아무 일도 안 난다"로 읽히지 않게 소요 시간을 적는다.
<p className="rounded-lg border border-border bg-muted/40 p-2.5 text-[11px] leading-relaxed">
몇 분 걸립니다. 끝나면 이 화면이 새 값으로 바뀝니다 — 그때까지 화면을 열어두세요.
</p>
)}
{/* ★ 유료 API 재호출 안내. 겁주지 않되 숨기지도 않는다 — 누르면 돈이 나가는 버튼이다. */}
<p className="flex items-start gap-1.5 text-[10px] leading-relaxed text-muted-foreground">
<TriangleAlert className="mt-px size-3 shrink-0" />
<span>
다시 수집하면 외부 검색·사진 분석 API 를 다시 호출합니다(호출당 비용 발생). 사장님이
확인·수정한 값은 덮어쓰지 않습니다.
</span>
</p>
</section>
);
}
@@ -0,0 +1,106 @@
import {Check} from 'lucide-react';
import type {IndustryType} from '@o2o/shared';
import {INDUSTRY_CONFIGS} from '@/data/industryData';
import {cn} from '@/lib/utils';
import {useBuilderStore} from '@/stores/builder';
import {INDUSTRY_ICONS} from './industryIcons';
import {WizardFooter} from './WizardFooter';
import {WizardSteps} from './WizardSteps';
const INDUSTRY_ORDER: IndustryType[] = ['stay', 'cafe', 'restaurant', 'tour'];
export function Step1Industry() {
const industry = useBuilderStore((s) => s.industry);
const selectIndustry = useBuilderStore((s) => s.selectIndustry);
const goToStep = useBuilderStore((s) => s.goToStep);
return (
<div className="flex flex-1 flex-col justify-between bg-muted/30">
<div className="flex flex-1 flex-col items-center justify-center px-4 py-10 sm:px-6 sm:py-16 lg:px-8">
<div className="mx-auto flex w-full max-w-5xl flex-col">
<WizardSteps current={1} />
<div className="mb-10 text-center sm:mb-12">
<h1 className="text-2xl font-bold tracking-tight sm:text-3xl lg:text-4xl">
어떤 업종의 홈페이지를 만들까요?
</h1>
<p className="mx-auto mt-2.5 max-w-lg text-sm text-muted-foreground sm:text-base">
업종을 고르면 그 업종에 맞는 항목만 수집하고, 그 항목만 검증합니다.
</p>
</div>
<div className="grid grid-cols-1 gap-4 sm:grid-cols-2 sm:gap-5 lg:grid-cols-4">
{INDUSTRY_ORDER.map((id) => {
const config = INDUSTRY_CONFIGS[id];
const Icon = INDUSTRY_ICONS[id];
const isSelected = industry === id;
return (
<button
key={id}
type="button"
onClick={() => selectIndustry(id)}
aria-pressed={isSelected}
className={cn(
'flex cursor-pointer flex-col justify-between rounded-2xl border bg-card p-6 text-left transition-all',
isSelected
? 'border-primary ring-1 ring-primary'
: 'border-border hover:border-muted-foreground/30',
)}
>
<div className="mb-5 flex items-center justify-between">
<span
className={cn(
'flex size-10 items-center justify-center rounded-xl transition-colors',
isSelected
? 'bg-primary text-primary-foreground'
: 'bg-muted text-foreground',
)}
>
<Icon className="size-5" />
</span>
<span
className={cn(
'flex size-5 items-center justify-center rounded-full transition-all',
isSelected
? 'bg-primary text-primary-foreground'
: 'border border-border bg-card',
)}
>
{isSelected && <Check className="size-3" strokeWidth={3} />}
</span>
</div>
<div className="mb-2">
<h2 className="text-base font-bold sm:text-lg">{config.name}</h2>
<span className="text-xs font-medium text-muted-foreground">
{config.subName}
</span>
</div>
<p className="text-xs leading-relaxed text-muted-foreground sm:text-sm">
{config.description}
</p>
</button>
);
})}
</div>
</div>
</div>
<WizardFooter
hint={
<>
선택된 업종:{' '}
<strong className="font-semibold text-foreground">
{INDUSTRY_CONFIGS[industry].name}
</strong>{' '}
({INDUSTRY_CONFIGS[industry].subName})
</>
}
onNext={() => goToStep(2)}
nextLabel="다음: 내 가게 찾기"
/>
</div>
);
}
@@ -0,0 +1,382 @@
import {useState} from 'react';
import {useSearchParams} from 'react-router';
import {ArrowRight, Check, MapPin, Phone, Search, TriangleAlert} from 'lucide-react';
import type {PlaceCandidate} from '@/api';
import {Badge} from '@/components/ui/badge';
import {Button} from '@/components/ui/button';
import {Input} from '@/components/ui/input';
import {cn} from '@/lib/utils';
import {useBuilderStore} from '@/stores/builder';
import {PlaceUrlBox} from './PlaceUrlBox';
import {usePlaceSearch} from './usePlaceSearch';
import {WizardFooter} from './WizardFooter';
import {WizardStage, WizardWaiting} from './WizardStage';
const STAGE_TITLE: Record<string, string> = {
input: '상호명을 검색해 내 가게를 찾아주세요',
searching: '내 가게를 찾는 중입니다',
picking: '이 중에 사장님 가게가 있나요?',
unavailable: '지도 검색을 사용할 수 없습니다',
confirmed: '이 가게로 확인되었습니다',
};
const STAGE_DESCRIPTION: Record<string, string> = {
input: '지도·플레이스에 등록된 가게 중에서 사장님이 직접 고른 한 곳만 기준이 됩니다.',
searching: '',
picking: '고른 가게의 상호·주소·전화가 이 사이트의 기준 정보가 됩니다.',
unavailable: '',
confirmed: '이제 이 가게의 공개 채널에서 정보를 수집합니다.',
};
/** outcome 코드 → 사장님이 읽을 한 줄. 서버 판정은 문구를 고르는 데만 쓴다. */
const OUTCOME_TEXT: Record<string, string> = {
matched: '이 가게로 보입니다. 맞는지 한 번만 확인해 주세요.',
ambiguous: '비슷한 이름의 가게가 여럿입니다. 어느 쪽이 사장님 가게인가요?',
no_candidate: '이 이름으로는 찾지 못했습니다.',
};
/**
* 2단계 — 내 가게 확인.
*
* 한 화면에 한 가지만 묻는다: 상호를 묻거나 · 기다리거나 · 후보를 고르게 하거나 · 확정을 보여준다.
*/
export function Step2PlaceSearch() {
const industry = useBuilderStore((s) => s.industry);
const storeName = useBuilderStore((s) => s.storeName);
const location = useBuilderStore((s) => s.location);
const confirmedIdentity = useBuilderStore((s) => s.confirmedIdentity);
const setStoreName = useBuilderStore((s) => s.setStoreName);
const setLocation = useBuilderStore((s) => s.setLocation);
const confirmIdentity = useBuilderStore((s) => s.confirmIdentity);
const clearIdentity = useBuilderStore((s) => s.clearIdentity);
const goToStep = useBuilderStore((s) => s.goToStep);
// 새로고침을 넘어온 경우 이미 만들어진 사업장을 그대로 쓴다(같은 위저드에서 두 번 만들지 않는다).
const search = usePlaceSearch(industry, confirmedIdentity?.placeId ?? null);
const [searchParams, setSearchParams] = useSearchParams();
/**
* 확정된 사업장을 주소창에 남긴다 — `?placeId=...`.
*
* ★ 이게 새로고침을 넘기는 유일한 수단이다. 위저드 상태는 브라우저에 저장하지 않는다
* (stores/builder 주석): 저장하면 새 가게를 만들러 들어와도 지난 가게가 확정된 것으로
* 떠 버린다. 주소창에 두면 새로고침은 서버에서 복원되고(usePlaceSync), 주소를 새로
* 열면 깨끗하다 — 두 요구를 동시에 만족하는 자리는 여기뿐이다.
*/
const rememberPlace = (placeId: string | null) => {
const next = new URLSearchParams(searchParams);
if (placeId) {
next.set('placeId', placeId);
// 개발 서버 재시작/HMR로 BuilderPage가 다시 마운트돼도 신규 등록 흐름임을 보존한다.
next.set('flow', 'onboarding');
} else {
next.delete('placeId');
next.delete('flow');
}
setSearchParams(next, {replace: true});
};
const [pickedIndex, setPickedIndex] = useState<number | null>(null);
const [placeUrl, setPlaceUrl] = useState('');
const canSearch = storeName.trim().length > 0 && search.phase !== 'searching';
const runSearch = () => {
clearIdentity(); // 상호를 고쳐 다시 찾는 것이므로 앞서 확정한 신원은 물린다
setPickedIndex(null);
void search.search(storeName, location);
};
const backToInput = () => {
clearIdentity();
// 다른 가게를 찾으러 간다 — 주소창에 남은 사업장도 같이 놓아준다.
rememberPlace(null);
setPickedIndex(null);
search.reset();
};
const pick = async (candidate: PlaceCandidate, index: number) => {
// 지역검색 후보만 있고 네이버 플레이스를 못 찾았으면 확정하지 않는다.
// URL 확정 경로가 상호·주소·좌표와 수집 채널을 한 번에 보장한다.
if (!candidate.naver_place_url) return;
setPickedIndex(index);
const identity = await search.confirmByUrl(candidate.naver_place_url);
if (!identity) {
setPickedIndex(null);
return;
}
confirmIdentity(identity);
rememberPlace(identity.placeId);
goToStep(3);
};
/** 네이버 플레이스 URL 로 확정 — 가장 확실한 경로다(usePlaceSearch.confirmByUrl 주석 참고). */
const pickByUrl = async () => {
const url = placeUrl.trim();
if (!url) return;
const identity = await search.confirmByUrl(url);
if (!identity) return;
confirmIdentity(identity);
rememberPlace(identity.placeId);
goToStep(3);
};
// ── 화면 고르기. 위에서부터 먼저 맞는 것 하나만 그린다 ──────────────
const stage = confirmedIdentity
? 'confirmed'
: search.phase === 'searching'
? 'searching'
: search.phase === 'unavailable'
? 'unavailable'
: search.phase === 'done'
? 'picking'
: 'input';
return (
<div className="flex flex-1 flex-col justify-between bg-muted/30">
<WizardStage
current={2}
wide={stage === 'picking'}
title={STAGE_TITLE[stage]}
description={STAGE_DESCRIPTION[stage]}
>
{stage === 'input' && (
<div className="space-y-4">
<div className="space-y-4 rounded-2xl border border-border bg-card p-6">
<div>
<label htmlFor="store-name" className="mb-1.5 block text-xs font-semibold">
상호명 <span className="text-destructive">*</span>
</label>
<Input
id="store-name"
value={storeName}
onChange={(e) => setStoreName(e.target.value)}
onKeyDown={(e) => {
if (e.key === 'Enter' && canSearch) runSearch();
}}
placeholder="가게 이름을 입력하세요"
autoFocus
/>
</div>
<div>
<label htmlFor="store-location" className="mb-1.5 block text-xs font-semibold">
위치 (시/군/구/동)
</label>
<Input
id="store-location"
value={location}
onChange={(e) => setLocation(e.target.value)}
onKeyDown={(e) => {
if (e.key === 'Enter' && canSearch) runSearch();
}}
placeholder="예: 제주시 애월읍"
/>
<p className="mt-1.5 text-[11px] text-muted-foreground">
같은 이름의 가게가 많을 때 구분하는 데 쓰입니다. 비워도 검색됩니다.
</p>
</div>
<Button
variant="outline"
size="lg"
className="w-full"
onClick={runSearch}
disabled={!canSearch}
>
<Search />
<span>상호로 찾아보기</span>
</Button>
</div>
</div>
)}
{stage === 'searching' && (
<WizardWaiting
title="등록된 가게를 찾는 중입니다"
description={`'${storeName}' 와(과) 같은 이름의 가게를 지도에서 확인하고 있어요`}
/>
)}
{stage === 'picking' && (
<div className="space-y-3">
<p
className={cn(
'rounded-xl p-3 text-xs leading-relaxed',
search.candidates.length > 0
? 'border border-border bg-card text-muted-foreground'
: 'border border-warning/30 bg-warning/10 text-warning',
)}
>
{OUTCOME_TEXT[search.outcome] ?? '아래 목록에서 사장님 가게를 골라 주세요.'}
{search.sourceLabel && (
<Badge variant="outline" className="ml-2 text-[10px]">
{search.sourceLabel}
</Badge>
)}
</p>
{search.candidates.length > 0 &&
!search.candidates.some((candidate) => candidate.naver_place_url) && (
<p className="rounded-xl border border-warning/30 bg-warning/10 p-3 text-xs font-medium leading-relaxed text-warning">
<TriangleAlert className="mr-1 inline size-3.5 align-text-bottom" />
상호 후보는 찾았지만 네이버 플레이스는 찾지 못했습니다. 아래 버튼으로 네이버
지도에서 가게를 검색한 뒤 플레이스 URL을 붙여넣어 주세요.
</p>
)}
<ul className="space-y-2">
{search.candidates.map((candidate, index) => (
<li key={`${candidate.external_place_id ?? candidate.name}-${index}`}>
<button
type="button"
onClick={() => void pick(candidate, index)}
disabled={search.isConfirming || !candidate.naver_place_url}
className="w-full cursor-pointer rounded-xl border border-border bg-card p-4 text-left transition-all hover:border-primary hover:bg-accent disabled:opacity-60"
>
<div className="flex items-start justify-between gap-3">
<div className="min-w-0 flex-1">
<div className="flex flex-wrap items-center gap-2">
<span className="text-sm font-bold">{candidate.name}</span>
{candidate.category_name && (
<Badge variant="outline" className="text-[10px]">
{candidate.category_name}
</Badge>
)}
<Badge
variant={candidate.naver_place_url ? 'success' : 'warning'}
className="text-[10px]"
>
{candidate.naver_place_url
? '네이버 플레이스 찾음'
: '네이버 플레이스 못 찾음'}
</Badge>
</div>
<p className="mt-1.5 flex items-start gap-1 text-xs text-muted-foreground">
<MapPin className="mt-px size-3 shrink-0" />
<span>{candidate.road_address ?? candidate.address ?? '주소 없음'}</span>
</p>
{candidate.phone && (
<p className="mt-0.5 flex items-center gap-1 text-xs text-muted-foreground">
<Phone className="size-3 shrink-0" />
{candidate.phone}
</p>
)}
</div>
<span className="shrink-0 rounded-lg bg-primary px-3 py-1.5 text-[11px] font-bold text-primary-foreground">
{!candidate.naver_place_url
? 'URL 필요'
: search.isConfirming && pickedIndex === index
? '확정 중...'
: '이 가게예요'}
</span>
</div>
</button>
</li>
))}
</ul>
{!search.candidates.some((candidate) => candidate.naver_place_url) ? (
<PlaceUrlBox
value={placeUrl}
onChange={setPlaceUrl}
onSubmit={() => void pickByUrl()}
isBusy={search.isConfirming}
searchQuery={[storeName, location].filter(Boolean).join(' ')}
/>
) : (
<PlaceUrlBox
value={placeUrl}
onChange={setPlaceUrl}
onSubmit={() => void pickByUrl()}
isBusy={search.isConfirming}
compact
searchQuery={[storeName, location].filter(Boolean).join(' ')}
/>
)}
</div>
)}
{stage === 'unavailable' && (
<div className="space-y-3">
<p className="rounded-xl border border-warning/30 bg-warning/10 p-3 text-xs leading-relaxed text-warning">
<TriangleAlert className="mr-1 inline size-3.5 align-text-bottom" />
{search.unavailableReason}
</p>
<PlaceUrlBox
value={placeUrl}
onChange={setPlaceUrl}
onSubmit={() => void pickByUrl()}
isBusy={search.isConfirming}
searchQuery={[storeName, location].filter(Boolean).join(' ')}
/>
<Button variant="outline" className="w-full" onClick={runSearch}>
<Search />
<span>상호로 다시 검색하기</span>
</Button>
</div>
)}
{stage === 'confirmed' && confirmedIdentity && (
<div className="space-y-3">
<div className="rounded-2xl border border-success/40 bg-success/5 p-6 text-center">
<span className="mx-auto mb-3 flex size-12 items-center justify-center rounded-full bg-success text-white">
<Check className="size-6" strokeWidth={3} />
</span>
<p className="text-base font-bold">{confirmedIdentity.name}</p>
{confirmedIdentity.address && (
<p className="mt-1 text-xs text-muted-foreground">{confirmedIdentity.address}</p>
)}
{confirmedIdentity.phone && (
<p className="mt-0.5 text-xs text-muted-foreground">{confirmedIdentity.phone}</p>
)}
<div className="mt-3 flex items-center justify-center gap-1.5">
{confirmedIdentity.origin === 'external' ? (
<>
<Badge variant="outline" className="text-[10px]">
{confirmedIdentity.sourceLabel}
</Badge>
<Badge variant="success" className="text-[10px]">
동일 업소 확인됨
</Badge>
</>
) : (
<Badge variant="warning" className="text-[10px]">
직접 입력 · 동일 업소 미검증
</Badge>
)}
</div>
</div>
<Button
variant="primary"
size="lg"
className="w-full"
onClick={() => goToStep(3)}
>
<span>다음: 이 가게 정보 수집하기</span>
<ArrowRight />
</Button>
<Button variant="ghost" size="sm" className="w-full" onClick={backToInput}>
<Search />
<span>다른 가게로 다시 찾기</span>
</Button>
</div>
)}
</WizardStage>
<WizardFooter
hint={
confirmedIdentity
? `${confirmedIdentity.name} 기준으로 진행합니다.`
: '내 가게를 확인해야 다음 단계로 갈 수 있습니다.'
}
onPrev={() => goToStep(1)}
onNext={() => goToStep(3)}
nextLabel="다음: 데이터 수집"
nextDisabled={!confirmedIdentity}
/>
</div>
);
}
@@ -0,0 +1,513 @@
import {useEffect, useRef, useState} from 'react';
import {ArrowRight, Check, Loader2, MapPin, Pencil, Search, TriangleAlert} from 'lucide-react';
import {Badge} from '@/components/ui/badge';
import {Button} from '@/components/ui/button';
import {Input} from '@/components/ui/input';
import {Switch} from '@/components/ui/switch';
import {INDUSTRY_CONFIGS} from '@/data/industryData';
import {cn} from '@/lib/utils';
import {useBuilderStore, useUnverifiedFields} from '@/stores/builder';
import {ChannelConfirmPanel} from './ChannelConfirmPanel';
import {ChannelUrlInput} from './ChannelUrlInput';
import {useCollectFlow} from './useCollectFlow';
import {WizardFooter} from './WizardFooter';
import {WizardStage, WizardWaiting} from './WizardStage';
const STAGE_TITLE: Record<string, string> = {
ready: '내 가게 주소를 알려주세요',
discovering: '공개 채널을 찾는 중입니다',
channels: '이 채널들이 사장님 가게가 맞나요?',
crawling: '정보를 수집하는 중입니다',
review: '수집된 정보가 맞는지 확인해주세요',
};
const STAGE_DESCRIPTION: Record<string, string> = {
ready: '네이버 지도에서 복사한 주소 하나면 영업시간·전화·사진까지 그대로 가져옵니다.',
discovering: '',
channels: '링크를 열어 내 가게가 맞는지 확인한 뒤 확정해 주세요. 확정한 URL 만 크롤링합니다.',
crawling: '',
review: '찾은 값은 전부 출처와 함께 보여드립니다. 사장님이 [맞아요]를 누른 값만 사이트와 AI 검색 답변에 나갑니다.',
};
/** 채널 URL 확인과 수집 결과 검토 단계. */
export function Step3DataReview() {
const industry = useBuilderStore((s) => s.industry);
const storeName = useBuilderStore((s) => s.storeName);
const confirmedIdentity = useBuilderStore((s) => s.confirmedIdentity);
const gatherCompleted = useBuilderStore((s) => s.gatherCompleted);
const infoFields = useBuilderStore((s) => s.infoFields);
const photos = useBuilderStore((s) => s.photos);
const goToStep = useBuilderStore((s) => s.goToStep);
const unverified = useUnverifiedFields();
const placeId = confirmedIdentity?.placeId ?? null;
const collect = useCollectFlow(placeId);
const collectPhase = collect.phase;
const startAutomaticCollect = collect.crawl;
const autoCollectStarted = useRef(false);
// 2단계에서 네이버 플레이스를 URL로 확정하는 순간 채널도 함께 등록·확정된다.
// 이 화면에 들어오면 추가 버튼 없이 곧바로 그 채널에서 수집을 시작한다.
useEffect(() => {
if (
autoCollectStarted.current ||
!placeId ||
confirmedIdentity?.origin !== 'external' ||
gatherCompleted ||
collect.isCheckingActive ||
collectPhase !== 'idle'
) {
return;
}
autoCollectStarted.current = true;
void startAutomaticCollect();
}, [
placeId,
confirmedIdentity?.origin,
gatherCompleted,
collect.isCheckingActive,
collectPhase,
startAutomaticCollect,
]);
// 사업장 동기화는 BuilderPage 가 한 곳에서 맡는다(같은 placeId 를 두 번 구독하지 않는다).
const [activeTab, setActiveTab] = useState<'info' | 'photos'>('info');
const config = INDUSTRY_CONFIGS[industry];
const canCollect = confirmedIdentity?.origin === 'external';
/** 아직 실제 수집이 붙지 않은 줄들 — 업종 예시다. 그렇게 부른다. */
const isSample = !confirmedIdentity || confirmedIdentity.origin === 'owner';
const stage =
collect.phase === 'discovering'
? 'discovering'
: collect.phase === 'crawling'
? 'crawling'
: collect.phase === 'awaiting-confirm'
? 'channels'
: gatherCompleted || collect.phase === 'done'
? 'review'
: 'ready';
return (
<div className="flex flex-1 flex-col justify-between bg-muted/30">
<WizardStage
current={3}
wide={stage === 'review' || stage === 'channels'}
title={STAGE_TITLE[stage]}
description={STAGE_DESCRIPTION[stage]}
>
{stage === 'ready' && (
<div className="space-y-3">
<IdentityCard />
{/* ★ 자동 해석이 실패했다는 사실을 서버가 알려준 경우 —
"수집했는데 아무것도 안 나왔다"로 끝나지 않게 다음 동작을 지목한다. */}
{collect.naverPlaceMissing && (
<p className="flex items-start gap-1.5 rounded-xl border border-warning/30 bg-warning/10 p-3 text-[11px] leading-relaxed text-warning">
<TriangleAlert className="mt-px size-3.5 shrink-0" />
<span>
<strong>네이버 플레이스를 자동으로 찾지 못했습니다.</strong> 아래에 내 가게의
네이버 지도 주소를 직접 붙여넣어 주세요 — 그러면 확실하게 가져옵니다.
</span>
</p>
)}
{/* ★ 1순위 경로. URL 만 있으면 100% 되므로 화면에서도 맨 위에 둔다. */}
{canCollect && <ChannelUrlInput onAdd={collect.addLink} isBusy={collect.isAdding} />}
{canCollect && (
<Button
variant="primary"
size="lg"
className="w-full"
onClick={collect.crawl}
disabled={collect.confirmedCount === 0}
>
<Search />
<span>
{collect.confirmedCount === 0
? '주소를 먼저 붙여넣어 주세요'
: `등록한 ${collect.confirmedCount}개 주소에서 정보 가져오기`}
</span>
</Button>
)}
{/* 부차 경로 — 남겨두되 기대치를 정직하게 적는다. 실측 성공률이 낮다. */}
{canCollect && (
<div className="rounded-2xl border border-border bg-card p-4">
<p className="text-xs font-bold">주소를 못 찾겠으면</p>
<p className="mt-1 text-[11px] leading-relaxed text-muted-foreground">
상호로 {config.channels.map((c) => c.name).join(' · ')} 등 공개 채널을 대신
찾아봅니다. <strong>못 찾을 수 있습니다</strong> — 상호 표기가 조금만 달라도
실패합니다. 그때는 위에 주소를 붙여넣어 주세요.
</p>
<label
htmlFor="discover-public-channels"
className="mt-3 flex cursor-pointer items-start justify-between gap-3 rounded-xl border border-border bg-muted/40 p-3"
>
<span>
<span className="block text-xs font-semibold">추가 채널까지 AI로 찾기</span>
<span className="mt-0.5 block text-[10px] leading-relaxed text-muted-foreground">
Perplexity 유료 검색을 1회 사용합니다. URL만 후보로 저장하며, 확인한 링크만
에디터와 사이트 푸터에 표시됩니다.
</span>
</span>
<Switch
id="discover-public-channels"
checked={collect.discoverChannels}
onCheckedChange={collect.setDiscoverChannels}
aria-label="Perplexity로 추가 공개 채널 찾기"
/>
</label>
<Button
variant="outline"
size="sm"
className="mt-2.5 w-full"
onClick={collect.discover}
>
<Search />
<span>자동으로 찾아보기</span>
</Button>
</div>
)}
{confirmedIdentity?.origin === 'owner' && (
<>
<p className="rounded-xl border border-warning/30 bg-warning/10 p-3 text-[11px] leading-relaxed text-warning">
직접 입력으로 진행 중이라 수집이 열리지 않습니다. 동일 업소 검증을 통과한
가게만 채널을 긁을 수 있습니다 — 2단계에서 지도 검색으로 가게를 확인하시면
주소 붙여넣기와 자동 찾기가 모두 열립니다.
</p>
<Button variant="outline" className="w-full" onClick={() => goToStep(4)}>
<span>수집 없이 다음 단계로</span>
<ArrowRight />
</Button>
</>
)}
<Button variant="ghost" size="sm" className="w-full" onClick={() => goToStep(2)}>
가게를 다시 찾을게요
</Button>
</div>
)}
{stage === 'discovering' && (
<WizardWaiting
title="공개된 채널 URL 을 찾는 중입니다"
description={`${storeName}의 예약·지도·SNS 채널을 찾고 있어요`}
/>
)}
{stage === 'crawling' && (
<WizardWaiting
title="확정하신 채널에서 정보를 수집 중입니다"
description="운영 정보와 사진을 정돈하고 있어요"
/>
)}
{stage === 'channels' && (
<div className="space-y-3">
<div className="rounded-2xl border border-border bg-card p-5">
<ChannelConfirmPanel
links={collect.links}
confirmedCount={collect.confirmedCount}
confirmingId={collect.confirmingId}
onConfirm={collect.confirm}
/>
</div>
<ChannelUrlInput onAdd={collect.addLink} isBusy={collect.isAdding} />
<Button
variant="primary"
size="lg"
className="w-full"
onClick={collect.crawl}
disabled={collect.confirmedCount === 0}
>
<Search />
<span>
{collect.confirmedCount === 0
? '확정한 채널이 없습니다'
: `확정한 ${collect.confirmedCount}개 채널에서 수집하기`}
</span>
</Button>
</div>
)}
{stage === 'review' && (
<div className="space-y-3">
<div className="flex items-center justify-between">
<div className="flex items-center gap-2">
{isSample ? (
<Badge variant="warning">예시 데이터 ({infoFields.length}개 항목)</Badge>
) : (
<Badge variant="success">수집 완료 ({infoFields.length}개 항목)</Badge>
)}
{unverified.length > 0 && (
<Badge variant="warning">확인 필요 {unverified.length}</Badge>
)}
</div>
<div className="flex items-center gap-1 rounded-lg bg-muted p-0.5 text-xs">
{(['info', 'photos'] as const).map((tab) => (
<button
key={tab}
type="button"
onClick={() => setActiveTab(tab)}
className={cn(
'cursor-pointer rounded-md px-3 py-1 font-medium transition-all',
activeTab === tab
? 'bg-card font-semibold text-foreground shadow-xs'
: 'text-muted-foreground hover:text-foreground',
)}
>
{tab === 'info' ? `기본정보 (${infoFields.length})` : `사진 (${photos.length})`}
</button>
))}
</div>
</div>
{isSample && (
<p className="rounded-xl border border-warning/30 bg-warning/10 p-3 text-[11px] leading-relaxed text-warning">
<strong>상호·주소는 2단계에서 확인하신 값</strong>이고, 나머지 줄과 사진은 아직
실제 수집 결과가 아니라 <strong>{config.name} 업종 예시</strong>입니다.
</p>
)}
{activeTab === 'info' ? (
<ul className="space-y-2">
{infoFields.map((field) => (
<FieldRow key={field.id} fieldId={field.id} />
))}
</ul>
) : (
<div className="grid grid-cols-2 gap-2 sm:grid-cols-3">
{photos.map((photo) => (
<figure
key={photo.id}
className="group relative aspect-4/3 overflow-hidden rounded-xl border border-border bg-muted"
>
<img
src={photo.url}
alt={photo.title}
loading="lazy"
className="size-full object-cover transition-transform duration-300 group-hover:scale-105"
/>
<figcaption className="absolute inset-x-0 bottom-0 truncate bg-gradient-to-t from-black/70 to-transparent p-2 text-[11px] text-white">
{photo.title}
</figcaption>
</figure>
))}
</div>
)}
<Button variant="primary" size="lg" className="w-full" onClick={() => goToStep(4)}>
<span>다음: 템플릿 고르기</span>
<ArrowRight />
</Button>
<label
htmlFor="rediscover-public-channels"
className="flex cursor-pointer items-center justify-between gap-3 rounded-xl border border-border bg-card p-3"
>
<span>
<span className="block text-xs font-semibold">추가 채널 URL도 다시 찾기</span>
<span className="block text-[10px] text-muted-foreground">
켜면 다음 수집에서 Perplexity 유료 검색을 1회 사용합니다.
</span>
</span>
<Switch
id="rediscover-public-channels"
checked={collect.discoverChannels}
onCheckedChange={collect.setDiscoverChannels}
aria-label="Perplexity로 추가 공개 채널 다시 찾기"
/>
</label>
<Button
variant="ghost"
size="sm"
className="w-full"
onClick={collect.discover}
disabled={!canCollect}
>
<Search />
<span>채널 URL 다시 찾기</span>
</Button>
</div>
)}
</WizardStage>
<WizardFooter
hint={
stage === 'ready' ? (
'수집을 먼저 돌려야 다음으로 넘어갈 수 있습니다.'
) : stage === 'channels' ? (
'내 채널을 확정한 뒤 수집하면 다음으로 넘어갑니다.'
) : stage === 'review' && unverified.length > 0 ? (
<span className="flex items-center gap-1 text-warning">
<TriangleAlert className="size-3.5" />
확인 안 된 항목 {unverified.length}개는 사이트에 나가지 않습니다.
</span>
) : stage === 'review' ? (
'확인된 값만 사이트와 AI 검색 답변에 실립니다.'
) : (
'수집을 돌리면 찾은 값이 출처와 함께 여기에 나옵니다.'
)
}
onPrev={() => goToStep(2)}
onNext={() => goToStep(4)}
nextLabel="다음: 템플릿 선택"
/**
* ★ 수집 전에는 잠근다.
* 여기서 그냥 넘어가면 fact 도 사진도 없는 채로 템플릿을 고르고 발행까지 가서,
* 서버 게이트가 NO_UNIQUE_CONTENT 로 막는다 — 사장님은 세 화면을 지나온 뒤에야
* "처음부터 아무것도 없었다"는 사실을 알게 된다. 그 전에 막는 것이 맞다.
*/
nextDisabled={stage !== 'review'}
/>
</div>
);
}
/** 2단계에서 확인된 가게 — 3단계 내내 "무엇을 수집하는지"의 근거로 남는다. */
function IdentityCard() {
const confirmedIdentity = useBuilderStore((s) => s.confirmedIdentity);
if (!confirmedIdentity) {
return (
<div className="rounded-xl border border-warning/30 bg-warning/10 p-4 text-xs text-warning">
아직 가게를 확인하지 않았습니다. 2단계에서 내 가게를 먼저 골라주세요.
</div>
);
}
return (
<div className="rounded-2xl border border-border bg-card p-5">
<p className="text-sm font-bold">{confirmedIdentity.name}</p>
{confirmedIdentity.address && (
<p className="mt-1 flex items-start gap-1 text-xs text-muted-foreground">
<MapPin className="mt-px size-3 shrink-0" />
<span>{confirmedIdentity.address}</span>
</p>
)}
<div className="mt-2.5 flex items-center gap-1.5">
{confirmedIdentity.origin === 'external' ? (
<>
<Badge variant="outline" className="text-[10px]">
{confirmedIdentity.sourceLabel}
</Badge>
<Badge variant="success" className="text-[10px]">
동일 업소 확인됨
</Badge>
</>
) : (
<Badge variant="warning" className="text-[10px]">
직접 입력 · 동일 업소 미검증
</Badge>
)}
</div>
</div>
);
}
/**
* 수집된 값 한 줄 — 확인이 이 화면의 목적이므로 [맞아요]/[아니에요]가 줄 안에 있다.
*
* ★ 승인은 스토어의 verifyField 가 그대로 fact 전이 API 로 올린다 —
* 화면만 바뀌고 서버가 모르는 승인은 없다.
*/
function FieldRow({fieldId}: {fieldId: string}) {
const field = useBuilderStore((s) => s.infoFields.find((f) => f.id === fieldId));
const savingFieldIds = useBuilderStore((s) => s.savingFieldIds);
const verifyField = useBuilderStore((s) => s.verifyField);
const [isEditing, setIsEditing] = useState(false);
const [draft, setDraft] = useState('');
if (!field) return null;
const isSaving = savingFieldIds.includes(field.id);
const needsCheck = field.requiresVerification && !field.isVerified;
const openEditor = () => {
setDraft(field.value);
setIsEditing(true);
};
const submit = () => {
const trimmed = draft.trim();
if (trimmed) verifyField(field.id, trimmed);
setIsEditing(false);
};
return (
<li
className={cn(
'rounded-xl border p-3 text-xs transition-colors',
needsCheck ? 'border-warning/40 bg-warning/5' : 'border-border bg-card',
)}
>
<div className="flex items-start justify-between gap-3">
<div className="min-w-0 flex-1">
<div className="mb-0.5 flex flex-wrap items-center gap-1.5">
<span className="font-semibold">{field.label}</span>
{field.source && (
<Badge variant="outline" className="text-[10px]">
{field.source}
</Badge>
)}
{field.critical && (
<Badge variant="warning" className="text-[10px]">
예약 관련
</Badge>
)}
</div>
<p className="font-medium">{field.value}</p>
</div>
{needsCheck ? (
<div className="flex shrink-0 items-center gap-1">
<Button
size="sm"
variant="primary"
onClick={() => verifyField(field.id)}
disabled={isSaving}
>
{isSaving ? <Loader2 className="animate-spin" /> : <Check />}
<span>맞아요</span>
</Button>
<Button size="sm" variant="outline" onClick={openEditor} disabled={isSaving}>
<Pencil />
<span>아니에요</span>
</Button>
</div>
) : (
<Badge variant="success" className="shrink-0">
확인됨
</Badge>
)}
</div>
{isEditing && (
<div className="mt-2 flex items-center gap-1.5 border-t border-border pt-2">
<Input
value={draft}
onChange={(e) => setDraft(e.target.value)}
onKeyDown={(e) => {
if (e.key === 'Enter') submit();
if (e.key === 'Escape') setIsEditing(false);
}}
placeholder={`${field.label}의 정확한 값`}
autoFocus
/>
<Button size="sm" variant="primary" onClick={submit} disabled={!draft.trim()}>
저장
</Button>
<Button size="sm" variant="ghost" onClick={() => setIsEditing(false)}>
취소
</Button>
</div>
)}
</li>
);
}
@@ -0,0 +1,130 @@
import {Check} from 'lucide-react';
import {INDUSTRY_CONFIGS} from '@/data/industryData';
import {queueSiteTemplateSave} from '@/features/publish/siteTemplate';
import {cn} from '@/lib/utils';
import {useBuilderStore} from '@/stores/builder';
import {WizardFooter} from './WizardFooter';
import {WizardSteps} from './WizardSteps';
export function Step4Template() {
const industry = useBuilderStore((s) => s.industry);
const templateId = useBuilderStore((s) => s.templateId);
const placeId = useBuilderStore((s) => s.placeId);
const selectTemplate = useBuilderStore((s) => s.selectTemplate);
const goToStep = useBuilderStore((s) => s.goToStep);
const startGenerating = useBuilderStore((s) => s.startGenerating);
const config = INDUSTRY_CONFIGS[industry];
/**
* 고른 순간 서버에도 남긴다.
*
* ★ 화면 상태로만 두면 발행 잡이 읽을 곳이 없어 업종 기본 템플릿으로 굽는다 —
* 사장님이 고른 디자인과 실제 발행본이 갈린다. 저장은 화면을 기다리게 하지 않는다.
*/
const chooseTemplate = (id: string) => {
selectTemplate(id);
queueSiteTemplateSave(placeId, id);
};
return (
<div className="flex flex-1 flex-col justify-between bg-muted/30">
<div className="flex flex-1 flex-col items-center justify-center px-4 py-10 sm:px-6 sm:py-14 lg:px-8">
<div className="mx-auto flex w-full max-w-5xl flex-col">
<WizardSteps current={4} />
<div className="mb-8 text-center">
<h1 className="text-2xl font-bold tracking-tight sm:text-3xl">
원하시는 디자인 스타일을 선택해주세요
</h1>
<p className="mx-auto mt-2 max-w-lg text-xs text-muted-foreground sm:text-sm">
{config.name}에 맞춘 템플릿입니다. 색상과 서체는 에디터에서 언제든 바꿀 수 있고,
어떤 템플릿을 골라도 구조화 데이터와 필수 섹션은 동일하게 들어갑니다.
</p>
</div>
<div className="grid grid-cols-1 gap-4 sm:grid-cols-2 sm:gap-5 lg:grid-cols-3">
{config.templates.map((template) => {
const isSelected = templateId === template.id;
return (
<button
key={template.id}
type="button"
onClick={() => chooseTemplate(template.id)}
aria-pressed={isSelected}
className={cn(
'flex cursor-pointer flex-col justify-between rounded-2xl border bg-card p-5 text-left transition-all',
isSelected
? 'border-primary ring-1 ring-primary'
: 'border-border hover:border-muted-foreground/30',
)}
>
<div className="mb-3 flex items-start justify-between">
<div>
<h2 className="text-base font-bold">{template.name}</h2>
<span className="text-xs font-medium text-muted-foreground">
{template.toneLabel} · {template.fontStyle}
</span>
</div>
<span
className={cn(
'flex size-5 shrink-0 items-center justify-center rounded-full transition-all',
isSelected
? 'bg-primary text-primary-foreground'
: 'border border-border bg-card',
)}
>
{isSelected && <Check className="size-3" strokeWidth={3} />}
</span>
</div>
{/* 색·레이아웃 미리보기 와이어프레임 */}
<div className="my-3 space-y-2.5 rounded-xl border border-border bg-muted/50 p-3.5">
<div className="flex items-center gap-1.5">
{(['primary', 'secondary', 'card'] as const).map((key) => (
<span
key={key}
className="size-3.5 rounded-full border border-black/10"
style={{backgroundColor: template.colors[key]}}
title={key}
/>
))}
<span className="ml-1 font-mono text-[10px] text-muted-foreground">
{template.colors.primary}
</span>
</div>
<div className="space-y-1.5 pt-1">
<div
className="h-2.5 w-2/3 rounded"
style={{backgroundColor: template.colors.primary, opacity: 0.85}}
/>
<div className="h-1.5 w-full rounded bg-border" />
<div className="h-1.5 w-4/5 rounded bg-border" />
</div>
</div>
<p className="text-xs leading-relaxed text-muted-foreground">
{template.description}
</p>
</button>
);
})}
</div>
</div>
</div>
<WizardFooter
onPrev={() => goToStep(3)}
onNext={() => {
// ★ 아무것도 안 누르고 넘어가는 경우(첫 템플릿이 이미 선택돼 있다)도 서버에 남긴다 —
// 화면이 보여준 그 템플릿이 발행본이 되어야 한다. 같은 값이면 서버가 재빌드 표시도 찍지 않는다.
queueSiteTemplateSave(placeId, templateId);
startGenerating();
}}
nextLabel="이 템플릿으로 사이트 생성하기"
/>
</div>
);
}
@@ -0,0 +1,196 @@
import {useCallback, useEffect} from 'react';
import {useSearchParams} from 'react-router';
import {Check, Loader2} from 'lucide-react';
import {JobStatus} from '@o2o/shared';
import {delay, getAccessToken, pollJob, startCopy} from '@/api';
import {Progress} from '@/components/ui/progress';
import {notify, notifyApiError} from '@/lib/notify';
import {cn} from '@/lib/utils';
import {EDITOR_STEP, useBuilderStore} from '@/stores/builder';
const BUILD_STEPS = [
'수집된 사진 분류 및 대체 텍스트 생성',
'브랜드 컬러 시스템 및 타이포그래피 조합',
'확인된 사실만으로 소개 콘텐츠 구성',
'위치 기반 길찾기 및 주변 정보 연동',
'구조화 데이터(JSON-LD) 준비',
];
const STAGE_MS = 600;
/**
* ★ 잡은 PENDING/RUNNING/DONE 세 상태만 준다 — 단계별 progress 필드가 없다.
* 그래서 문구는 "지금 서버가 이 근처를 하고 있다"는 안내이고, 진짜 신호는 잡 상태다.
* RUNNING 동안 마지막 단계 직전까지만 올리고, 완료는 오직 DONE 이 만든다
* — 100%를 먼저 그려 놓고 기다리게 하지 않는다.
*/
const RUNNING_STAGE_CEILING = BUILD_STEPS.length - 1;
export function Step5Generating() {
const storeName = useBuilderStore((s) => s.storeName);
const stage = useBuilderStore((s) => s.generateStage);
const setGenerateStage = useBuilderStore((s) => s.setGenerateStage);
const goToStep = useBuilderStore((s) => s.goToStep);
const placeId = useBuilderStore((s) => s.placeId);
const [searchParams, setSearchParams] = useSearchParams();
/**
* 생성이 끝나면 곧바로 에디터다.
*
* ★ 중간에 다른 화면을 끼우지 않는다. 위저드를 끝까지 걸어온 사람의 다음 용건은
* 자기 사이트를 보는 것이고, 목록을 한 번 거치게 하면 그게 한 번 더 클릭이 된다.
* 사업장은 이미 2단계에서 등록돼 목록에 들어가 있다 — '목록에 생기는 것'과
* '목록으로 보내는 것'은 다른 얘기다.
*/
const finishOnboarding = useCallback(() => {
const next = new URLSearchParams(searchParams);
next.delete('flow');
setSearchParams(next, {replace: true});
goToStep(EDITOR_STEP);
}, [goToStep, searchParams, setSearchParams]);
/**
* 소개문·FAQ 생성(JobType.COPY). `POST /v1/place/{id}/copy` 로 잡을 넣고 폴링한다.
*
* ★ 정적 빌드(JobType.BUILD)는 여기가 아니라 발행 모달이 부른다 — 빌드는 발행 검수
* 게이트와 한 몸이고(services/build_service), 여기서 미리 구워 봐야 편집 전 스냅샷이라
* 버릴 버전만 쌓인다.
* ★ 폴백: placeId(데모 경로) 나 토큰이 없으면 백엔드를 아예 부르지 않고 타이머로 돈다.
*/
useEffect(() => {
const controller = new AbortController();
/** 타이머 시뮬레이션. 폴백 경로 전용 — 백엔드가 없어도 위저드는 끝까지 간다. */
const runSimulation = async () => {
for (let next = 1; next <= BUILD_STEPS.length; next += 1) {
await delay(STAGE_MS, controller.signal);
if (controller.signal.aborted) return;
setGenerateStage(next);
}
await delay(STAGE_MS, controller.signal);
if (!controller.signal.aborted) finishOnboarding();
};
/** RUNNING 인 동안 문구만 천천히 밀어 준다. 완료 판정은 하지 않는다. */
const creep = () =>
setGenerateStage(
Math.min(RUNNING_STAGE_CEILING, useBuilderStore.getState().generateStage + 1),
);
const runCopy = async (id: string) => {
let jobId: string;
try {
const started = await startCopy(id, {}, undefined, controller.signal);
// ★ 근거로 쓸 확인된 fact 가 0 이면 서버는 아무것도 쓰지 않는다 — LLM 은 사실을 만들지 않는다.
if (started.grounded_facts === 0) {
notify.warn(
'확인된 정보가 없어 소개문을 쓰지 않았습니다.',
'[확인] 탭에서 수집된 정보를 확정하면 그 사실만으로 소개문을 씁니다.',
);
}
if (!started.job_id) {
await runSimulation();
return;
}
jobId = started.job_id;
} catch (error) {
if (controller.signal.aborted) return;
notifyApiError(error, '소개문 생성을 시작하지 못했습니다.');
await runSimulation();
return;
}
setGenerateStage(1);
const outcome = await pollJob(jobId, {
signal: controller.signal,
onTick: (job) => {
if (job.status === JobStatus.RUNNING) creep();
},
});
if (outcome.kind === 'aborted') return;
if (outcome.kind === 'dead') {
notify.error('소개문을 만들지 못했습니다.', outcome.job.last_error ?? undefined);
} else if (outcome.kind === 'unreachable') {
notifyApiError(outcome.error, '생성 상태를 확인하지 못했습니다.');
} else if (outcome.kind === 'timeout') {
notify.warn('생성이 예상보다 오래 걸립니다.', '생성은 계속 진행됩니다.');
}
// ★ 실패해도 편집기로는 보낸다. 소개문은 없어도 확인된 fact 로 편집·발행이 되고,
// 여기서 멈추면 사장님은 되돌아갈 길이 없는 화면에 갇힌다.
setGenerateStage(BUILD_STEPS.length);
await delay(STAGE_MS, controller.signal);
if (!controller.signal.aborted) finishOnboarding();
};
if (!placeId || !getAccessToken()) void runSimulation();
else void runCopy(placeId);
return () => controller.abort();
}, [setGenerateStage, finishOnboarding, placeId]);
const progress = Math.min(100, Math.round((stage / BUILD_STEPS.length) * 100));
return (
<div className="flex flex-1 flex-col items-center justify-center bg-muted/30 px-4 py-16 sm:px-6 sm:py-24 lg:px-8">
<div className="mx-auto flex w-full max-w-md flex-col items-center text-center">
<div className="mb-6 flex size-16 items-center justify-center rounded-2xl border border-border bg-card">
<Loader2 className="size-8 animate-spin text-primary" />
</div>
<h1 className="mb-2 text-2xl font-bold tracking-tight sm:text-3xl">
웹사이트를 생성하고 있습니다
</h1>
<p className="mb-8 max-w-md text-xs text-muted-foreground sm:text-sm">
<strong className="font-semibold text-foreground">{storeName}</strong>의 확인된 정보만
담아 정적 페이지로 굽고 있어요.
</p>
<div className="w-full space-y-4 rounded-2xl border border-border bg-card p-6 text-left">
<div className="flex items-center justify-between text-xs">
<span className="font-bold">{BUILD_STEPS[Math.min(stage - 1, BUILD_STEPS.length - 1)]}</span>
<span className="font-mono font-bold">{progress}%</span>
</div>
<Progress value={progress} aria-label="사이트 생성 진행률" />
<ol className="space-y-2.5 pt-2">
{BUILD_STEPS.map((text, index) => {
const num = index + 1;
const isDone = stage > num;
const isCurrent = stage === num;
return (
<li
key={text}
className={cn(
'flex items-center gap-3 text-xs transition-colors',
isDone || isCurrent ? 'font-medium text-foreground' : 'text-muted-foreground',
)}
>
<span
className={cn(
'flex size-4 shrink-0 items-center justify-center rounded-full text-[10px] font-bold',
isDone || isCurrent
? 'bg-primary text-primary-foreground'
: 'border border-border bg-muted',
isCurrent && 'ring-2 ring-primary/20',
)}
>
{isDone ? <Check className="size-2.5" strokeWidth={3} /> : num}
</span>
<span className="truncate">{text}</span>
</li>
);
})}
</ol>
</div>
<p className="mt-6 text-xs text-muted-foreground">
생성이 끝나면 실시간 에디터로 자동 전환됩니다.
</p>
</div>
</div>
);
}
@@ -0,0 +1,44 @@
import type {ReactNode} from 'react';
import {ArrowRight} from 'lucide-react';
import {Button} from '@/components/ui/button';
interface WizardFooterProps {
hint?: ReactNode;
onPrev?: () => void;
onNext: () => void;
nextLabel: string;
nextDisabled?: boolean;
}
/** 위저드 3단계가 공유하는 하단 고정 CTA 바. */
export function WizardFooter({
hint,
onPrev,
onNext,
nextLabel,
nextDisabled,
}: WizardFooterProps) {
return (
<div className="safe-b sticky bottom-0 z-30 w-full border-t border-border bg-card/95 px-4 py-3 backdrop-blur-md sm:px-6 lg:px-8">
<div className="mx-auto flex max-w-5xl flex-col items-center justify-between gap-3 sm:flex-row">
<div className="text-center text-xs text-muted-foreground sm:text-left">{hint}</div>
<div className="flex w-full items-center justify-end gap-2 sm:w-auto">
{onPrev && (
<Button variant="outline" onClick={onPrev}>
이전
</Button>
)}
<Button
variant="primary"
onClick={onNext}
disabled={nextDisabled}
className="flex-1 sm:flex-none"
>
<span>{nextLabel}</span>
<ArrowRight />
</Button>
</div>
</div>
</div>
);
}
@@ -0,0 +1,58 @@
import type {ReactNode} from 'react';
import {WizardSteps} from './WizardSteps';
/**
* 위저드 한 화면.
*
* ★ 한 번에 한 가지만 묻는다. 입력 폼과 결과 목록을 좌우로 같이 띄우면, 사장님은
* "지금 내가 뭘 해야 하는지"를 화면에서 찾아야 한다. 그래서 단계마다 패널 하나만 세운다 —
* 묻는 것이 바뀌면 화면이 통째로 바뀐다.
*/
export function WizardStage({
current,
title,
description,
children,
wide,
}: {
current: number;
title: ReactNode;
description?: ReactNode;
children: ReactNode;
/** 목록처럼 폭이 필요한 패널에서만 넓힌다(기본은 좁은 한 칸). */
wide?: boolean;
}) {
return (
<div className="flex flex-1 flex-col items-center overflow-y-auto px-4 py-10 sm:px-6 sm:py-14">
<div className="mx-auto flex w-full max-w-5xl flex-col">
<WizardSteps current={current} />
<div className="mb-8 text-center">
<h1 className="text-2xl font-bold tracking-tight sm:text-3xl">{title}</h1>
{description && (
<p className="mx-auto mt-2.5 max-w-xl text-xs leading-relaxed text-muted-foreground sm:text-sm">
{description}
</p>
)}
</div>
<div className={wide ? 'mx-auto w-full max-w-2xl' : 'mx-auto w-full max-w-lg'}>
{children}
</div>
</div>
</div>
);
}
/** 단계 안에서 기다리는 화면(검색·수집). 스피너 하나와 지금 하는 일만 보여준다. */
export function WizardWaiting({title, description}: {title: string; description?: ReactNode}) {
return (
<div className="flex flex-col items-center gap-4 rounded-2xl border border-border bg-card p-10 text-center">
<span className="size-9 animate-spin rounded-full border-2 border-primary border-t-transparent" />
<div className="space-y-1">
<h2 className="text-sm font-bold">{title}</h2>
{description && <p className="text-xs text-muted-foreground">{description}</p>}
</div>
</div>
);
}
@@ -0,0 +1,61 @@
import {Check} from 'lucide-react';
import {cn} from '@/lib/utils';
/**
* 위저드 진행 표시.
*
* 2(신원 확인)와 3(사실 확인)이 왜 따로인지 사장님이 한눈에 알게 하는 것이 이 줄의 목적이다 —
* "가게가 맞나" 를 먼저 끝내고 "값이 맞나" 로 넘어간다.
*/
const STEPS = [
{step: 1, label: '업종'},
{step: 2, label: '내 가게 확인'},
{step: 3, label: '수집 정보 확인'},
{step: 4, label: '템플릿'},
] as const;
export function WizardSteps({current}: {current: number}) {
return (
<ol className="mx-auto mb-8 flex w-full max-w-xl items-center justify-between gap-1">
{STEPS.map(({step, label}, index) => {
const isDone = current > step;
const isCurrent = current === step;
return (
<li key={step} className="flex flex-1 items-center gap-1 last:flex-none">
<div className="flex items-center gap-1.5">
<span
className={cn(
'flex size-5 shrink-0 items-center justify-center rounded-full text-[10px] font-bold transition-colors',
isDone
? 'bg-success text-white'
: isCurrent
? 'bg-primary text-primary-foreground ring-4 ring-primary/15'
: 'border border-border bg-muted text-muted-foreground',
)}
>
{isDone ? <Check className="size-3" strokeWidth={3} /> : step}
</span>
<span
className={cn(
'whitespace-nowrap text-[11px] transition-colors',
isCurrent ? 'font-bold text-foreground' : 'text-muted-foreground',
)}
>
{label}
</span>
</div>
{index < STEPS.length - 1 && (
<span
className={cn(
'mx-1 hidden h-px flex-1 sm:block',
isDone ? 'bg-success/40' : 'bg-border',
)}
/>
)}
</li>
);
})}
</ol>
);
}
@@ -0,0 +1,52 @@
/**
* 수집 잡 결과(`job.result`) 판독 — 순수 함수만.
*
* ★ `job.result` 는 백엔드가 관측·디버깅용으로 넣어 둔 JSONB 라 타입이 없다.
* 화면이 그걸 여기저기서 직접 파헤치면, 백엔드가 키 하나를 바꿔도 조용히 0 건으로 보인다.
* 읽는 규칙을 한 곳에 모은다 — 기준은 backend/services/collect_service.py 의 반환값이다.
*/
import type {JobData} from '@/api';
/**
* 잡 결과에서 숫자 한 칸만 좁혀 읽는다.
*
* `job.result` 는 잡 종류마다 모양이 달라 스키마상 unknown 이다(readNaverPlaceMissing 과 같은 이유).
* 없으면 0 — 서버가 필드를 빼도 토스트가 `undefined 건` 이 되지 않는다.
*/
export function readNumber(source: unknown, key: string): number {
if (!source || typeof source !== 'object') return 0;
const value = (source as Record<string, unknown>)[key];
return typeof value === 'number' ? value : 0;
}
/** 결과 안의 하위 묶음(facts · media)을 꺼낸다. */
export function readGroup(job: JobData, key: string): unknown {
const result: unknown = job.result;
if (!result || typeof result !== 'object') return null;
return (result as Record<string, unknown>)[key];
}
/**
* 서버가 남긴 사유 한 줄(`result.note`).
*
* ★ "왜 아무것도 안 들어왔는지"는 서버만 안다("크롤링 대상이 없다" 등).
* 화면이 추측해서 지어내지 않고, 있으면 그대로 보여준다.
*/
export function readNote(job: JobData): string | undefined {
const result: unknown = job.result;
if (!result || typeof result !== 'object') return undefined;
const note = (result as {note?: unknown}).note;
return typeof note === 'string' && note.trim() ? note : undefined;
}
/**
* 잡 결과에서 "네이버 플레이스를 자동으로 못 찾았다" 플래그만 꺼낸다.
*
* `job.result` 는 잡 종류마다 모양이 달라 스키마상 unknown 이다. 통째로 캐스팅하지 않고
* 이 한 칸만 좁혀서 읽는다 — 서버가 필드를 안 실어도 화면은 그냥 조용해질 뿐이다.
*/
export function readNaverPlaceMissing(job: JobData): boolean {
const result: unknown = job.result;
if (!result || typeof result !== 'object') return false;
return (result as {naver_place_missing?: unknown}).naver_place_missing === true;
}
@@ -0,0 +1,128 @@
/**
* 수집에 딸린 잡 실행과 캐시 정리 — React 를 모르는 부분.
*
* ★ 훅 상태를 건드리지 않는 일만 모았다. 하는 일은 "잡을 넣고 → 폴링하고 → 캐시를
* 무효화하고 → 결과를 알린다" 뿐이라 컴포넌트 마운트와 아무 상관이 없다. 훅 안에 두면
* 수집 흐름(단계 전이)과 잡 실행이 한 덩어리로 보여 어느 쪽을 고치는지 흐려진다.
*/
import type {JobData} from '@/api';
import {
getGetPlaceQueryKey,
getListFactsQueryKey,
getListFaqsQueryKey,
getListLinksQueryKey,
getListMediaQueryKey,
pollJob,
startCopy,
startVision,
} from '@/api';
import {notify, notifyApiError} from '@/lib/notify';
import {queryClient} from '@/lib/query-client';
import {notifyCopy, notifyVision} from './collectNotify';
import type {RecollectTask} from './useCollectFlow';
/** 재수집 작업의 화면 표시명. */
export const RECOLLECT_LABEL: Record<RecollectTask, string> = {
facts: '정보',
photos: '사진',
copy: '소개문',
};
/**
* 사진 분석 · 소개문 생성 잡 1회분.
*
* 수집(runCollect)과 달리 훅 상태를 건드리지 않아 모듈 함수로 둔다 —
* 하는 일은 "잡을 넣고 → 폴링하고 → 캐시를 무효화하고 → 결과를 알린다" 뿐이다.
*/
export async function runSideJob(task: 'photos' | 'copy', placeId: string, signal: AbortSignal) {
const label = RECOLLECT_LABEL[task];
let jobId: string;
try {
const started =
task === 'photos'
? // ★ force:true — 이미 alt 가 붙은 사진도 다시 분석한다. 사장님이 일부러 누른 버튼이라
// "분석할 사진이 없습니다"로 끝나면 재분석이라는 이름값을 못 한다.
await startVision(placeId, {force: true}, undefined, signal)
: await startCopy(placeId, {}, undefined, signal);
// 거절도 HTTP 200 이다 — 사진 0장(MEDIA_NOT_FOUND)·근거 부족(FAQ_UNGROUNDED)·
// 키 미설정(GENERATOR_NOT_CONFIGURED)이 전부 이 자리로 온다.
if (started.result?.success === false || !started.job_id) {
notifyApiError({data: started}, `${label}을 시작하지 못했습니다.`);
return;
}
jobId = started.job_id;
} catch (error) {
if (signal.aborted) return;
notifyApiError(error, `${label}을 시작하지 못했습니다.`);
return;
}
const outcome = await pollJob(jobId, {signal});
switch (outcome.kind) {
case 'aborted':
return;
case 'dead':
notify.error(`${label}을 끝내지 못했습니다.`, outcome.job.last_error ?? undefined);
return;
case 'unreachable':
notifyApiError(outcome.error, `${label} 상태를 확인하지 못했습니다.`);
return;
case 'timeout':
notify.warn(
`${label}이 예상보다 오래 걸립니다.`,
'서버에서는 계속 진행됩니다. 잠시 후 다시 확인해 주세요.',
);
return;
case 'done':
if (task === 'photos') {
// 사진은 media 가 진실이다 — 라벨·alt 가 바뀌었으니 다시 읽게 한다.
await invalidate(getListMediaQueryKey(placeId));
notifyVision(outcome.job);
} else {
// 소개문은 fact(intro·meta_description)로, FAQ 는 faq 로 들어간다 — 둘 다 무효화한다.
await invalidate(getListFactsQueryKey(placeId), getListFaqsQueryKey(placeId));
notifyCopy(outcome.job);
}
}
}
/**
* 수집이 큐에 넣은 사진 분석 잡을 기다린다.
*
* 잡 id 는 수집 결과(`result.vision_job_id`)에 실려 온다 — 사진이 한 장도 없으면 없다.
* 실패·타임아웃은 조용히 넘어간다: 사진이 늦게 붙을 뿐 수집 자체는 성공이고,
* 여기서 화면을 막으면 사장님이 다음으로 못 간다.
*/
export async function waitForVision(placeId: string, job: JobData, signal: AbortSignal) {
const visionJobId = (job.result as {vision_job_id?: string} | undefined)?.vision_job_id;
if (!visionJobId) return;
const outcome = await pollJob(visionJobId, {signal});
if (outcome.kind === 'done') await refreshPlaceCaches(placeId);
}
/**
* 수집이 끝난 뒤 서버가 진실인 것들 — place(주소·갱신시각) · 링크 · fact · **사진**.
*
* ★ media 를 빠뜨리면 사진이 서버에 10장 들어와도 화면은 빈 목록을 계속 본다.
* 실제로 그랬다 — "이미지 왜 못 가져오냐"의 원인이 수집이 아니라 여기였다.
* 목록에 뭘 더할 때는 화면이 그 값을 어디서 읽는지 같이 확인해야 한다.
*/
export async function refreshPlaceCaches(placeId: string) {
await Promise.all([
queryClient.invalidateQueries({queryKey: getGetPlaceQueryKey(placeId)}),
queryClient.invalidateQueries({queryKey: getListLinksQueryKey(placeId)}),
queryClient.invalidateQueries({queryKey: getListFactsQueryKey(placeId)}),
queryClient.invalidateQueries({queryKey: getListMediaQueryKey(placeId)}),
]).catch(() => undefined);
}
/**
* 캐시 무효화 묶음. 실패해도 삼킨다 — 화면이 한 박자 늦게 갱신될 뿐이고, 잡은 이미 끝났다.
*
* 생성물 쿼리 키는 `as const` 라 안쪽도 readonly 다 — 그 모양 그대로 받는다.
*/
export async function invalidate(...queryKeys: readonly (readonly unknown[])[]) {
await Promise.all(
queryKeys.map((queryKey) => queryClient.invalidateQueries({queryKey})),
).catch(() => undefined);
}
@@ -0,0 +1,73 @@
/**
* 수집·분석·소개문 잡이 끝났을 때의 알림 문구.
*
* ★ "몇 건이 새로 들어왔는가"를 말해 주지 않으면 사장님은 버튼을 눌렀는데 아무 일도
* 일어나지 않은 것으로 읽는다. 숫자는 job.result 에만 있으므로 판독은 collectJobResult 가
* 맡고, 여기서는 문구만 만든다.
*/
import type {JobData} from '@/api';
import {notify} from '@/lib/notify';
import {readGroup, readNote, readNumber} from './collectJobResult';
/**
* 재수집(정보) 결과 알림.
*
* ★ `facts.stored` 하나만 보여주면 "N건이 반영됐다"로 읽힌다 — 사실이 아니다.
* stored 는 **후보로 새로 쌓인 것(candidate)** 과 **값이 같아 다시 확인만 된 것(refreshed)** 의
* 합이고, 노출 중인 값은 어느 쪽이든 그대로다(fact_service 의 업데이트 프로세스).
* 그래서 둘을 갈라 보여주고, 승인이 남았다는 사실을 같이 적는다.
*/
export function notifyCollected(job: JobData) {
const facts = readGroup(job, 'facts');
const media = readGroup(job, 'media');
const stored = readNumber(facts, 'stored');
const candidate = readNumber(facts, 'candidate');
const refreshed = readNumber(facts, 'refreshed');
const photos = readNumber(media, 'stored');
if (stored === 0 && photos === 0) {
notify.warn(
'새로 들어온 정보가 없습니다.',
readNote(job) ?? '확정된 채널에서 달라진 값을 찾지 못했습니다.',
);
return;
}
const parts = [`확인할 새 값 ${candidate}건`, `그대로인 값 ${refreshed}건`];
if (photos > 0) parts.push(`새 사진 ${photos}장`);
notify.success(
'다시 수집했습니다',
`${parts.join(' · ')} — 새 값은 [맞아요]를 눌러야 사이트에 나갑니다.`,
);
}
/** 재분석(사진) 결과 알림. 신뢰도가 낮은 건은 자동 반영되지 않고 확인 큐에 남는다. */
export function notifyVision(job: JobData) {
const analyzed = readNumber(job.result, 'analyzed');
if (analyzed === 0) {
notify.warn('분석한 사진이 없습니다.', readNote(job) ?? '수집된 사진이 없습니다.');
return;
}
notify.success(
'사진을 다시 분석했습니다',
`${analyzed}장 · 자동 반영 ${readNumber(job.result, 'approved')}장 · ` +
`확인 대기 ${readNumber(job.result, 'needs_review')}장`,
);
}
/** 재생성(소개문·FAQ) 결과 알림. 생성물도 미검증으로 들어가 사람이 승인해야 나간다. */
export function notifyCopy(job: JobData) {
const faqCount = readNumber(job.result, 'faqs');
const hasIntro = (job.result as {intro?: unknown} | undefined)?.intro === true;
if (!hasIntro && faqCount === 0) {
notify.warn(
'새로 만든 문장이 없습니다.',
readNote(job) ?? '근거로 쓸 확인된 정보가 부족합니다. 정보를 먼저 확인해 주세요.',
);
return;
}
notify.success(
'소개문을 다시 만들었습니다',
`소개문 ${hasIntro ? '1건' : '없음'} · FAQ ${faqCount}건 — 확인하신 뒤 사이트에 나갑니다.`,
);
}
@@ -0,0 +1,10 @@
export {Step1Industry} from './Step1Industry';
export {Step2PlaceSearch} from './Step2PlaceSearch';
export {Step3DataReview} from './Step3DataReview';
export {Step4Template} from './Step4Template';
export {Step5Generating} from './Step5Generating';
// 재수집 패널은 위저드 밖(사업장 상세 · 빌더 에디터)에서 쓰지만 배선(useCollectFlow)이
// 여기 있어서 같이 둔다 — 수집 경로를 두 곳으로 쪼개지 않는다.
export {RecollectPanel} from './RecollectPanel';
// 붙여넣기 패널도 위저드 밖에서 쓴다 — 자동 수집이 못 채운 업소의 폴백 입구다.
export {PasteFactsPanel} from './PasteFactsPanel';
Loaded 100 of 480 files, more files were not shown because too many files have changed in this diff. Show more