최초 커밋 — 기존 코드 전체 + 문서 체계 신설

git 저장소가 없어 히스토리·협업 기반이 아예 없던 상태를 연다.
함께 문서를 재편했다. 그동안 문서가 있어도 "이 제품이 뭘 푸는가"와
"어떻게 도는가"를 담은 문서가 없어서, 목표 문장이 backend/frontend
README 두 곳에 복붙돼 있었다 — 상위 문서가 없어 아래로 샌 것이다.

신설
  README.md               레포 진입점 + 문서 지도 + 문서 규칙 4가지
  AGENTS.md               에이전트·신규 합류자용 함정 목록과 규약
                          (CLAUDE.md 는 여기로 걸린 심볼릭 링크)
  docs/PRODUCT.md         제품 정의 — 문제·사용자·원칙·**non-goals**·성공 기준
  docs/ARCHITECTURE.md    payload 경계·발행 파이프라인·서빙 결정·앱 분리 설계

이동
  backend/docs/DECISIONS.md → docs/DECISIONS.md
    백엔드만의 결정이 아니다. 게다가 코드 주석 ~25곳이 이미
    `docs/DECISIONS.md` 로 적고 있어 레포 루트 기준으로는 그게 맞다.

갱신
  docs/DEPLOY.md          서빙 결정 반영 — nginx 정적 서빙이 지금 경로(3절),
                          Azure 는 나중에 켤 때(4절)로 분리
  docs/ARCHITECTURE.md    사이트 = 한 장(2026-08-31) 구조 반영
  docs/COLLECTION_SEO_AEO_FLOW.md
                          robots.txt·sitemap.xml 은 오리진 루트에만 굽는다는 점 명시
  frontend/site/scripts/prerender.ts
                          헤더 주석의 렌더 보고서 경로가 실제(422줄)와 달라 수정

.gitignore
  ★ CLAUDE.md 를 더 이상 무시하지 않는다. 에이전트 지침은 팀과 모든
    에이전트가 공유하는 규약이라 커밋해야 한다 — 무시하면 클론한 사람이
    "배포 후 republish_all.py 필수" 같은 함정을 전달받지 못한다.
    개인용 오버라이드는 ~/.claude/CLAUDE.md 에 둔다.
This commit is contained in:
minaChoi committed 2026-08-31 13:57:59 +09:00
commit 6784e59ca5
713 files changed
+68390

No files matched your search

+33
View File
@@ -0,0 +1,33 @@
import type {SitePayload} from '@o2o/shared';
import {MobileTabBar, SiteFooter, SiteHeader} from '@/sections';
import {SiteProvider} from '@/lib/site-context';
import {HomePage} from '@/pages';
/**
* 발행 사이트 — **한 장짜리다.**
*
* ★ 왜 라우터를 쓰지 않나 (2026-08-31 결정)
* 소상공인 사이트는 원래 내용이 적다. 그걸 홈·객실·주변·오시는길·FAQ 로 쪼개면
* 페이지마다 얇아지고, 검색엔진은 그런 페이지를 색인에서 버린다("Crawled – currently
* not indexed"). 한 장에 모으면 알찬 페이지 하나가 된다.
* 덤으로 `basename` 을 맞추던 문제(SSR 은 /faq, 하이드레이션 후엔 /s/mmg/faq)가
* 통째로 사라진다 — 섹션 이동은 전부 앵커(#faq)다.
*
* 섹션 순서·표시 여부는 HomePage 가 theme.sections 로 정한다.
*/
export function App({payload}: {payload: SitePayload}) {
return (
<SiteProvider payload={payload}>
<div className="flex min-h-screen w-full flex-col">
<SiteHeader />
<div className="flex w-full flex-1 flex-col">
<HomePage />
</div>
<SiteFooter />
<MobileTabBar />
</div>
</SiteProvider>
);
}
+35
View File
@@ -0,0 +1,35 @@
import {StrictMode} from 'react';
import {createRoot, hydrateRoot} from 'react-dom/client';
import type {SitePayload} from '@o2o/shared';
import {App} from './App';
import './index.css';
declare global {
interface Window {
/** 프리렌더가 HTML 안에 심어 둔 payload. 이게 있으면 하이드레이션, 없으면 개발 모드. */
__SITE_PAYLOAD__?: SitePayload;
}
}
const container = document.getElementById('root')!;
const injected = window.__SITE_PAYLOAD__;
if (injected) {
// 정적 HTML 위에 하이드레이션. 서버가 그린 마크업과 1:1 이어야 하므로
// 여기서 payload 를 바꾸거나 fetch 를 걸지 않는다.
hydrateRoot(
container,
<StrictMode>
<App payload={injected} />
</StrictMode>,
);
} else {
// 개발 서버(vite dev) — 데모 payload 로 CSR 렌더. 프로덕션 경로가 아니다.
void import('./fixtures/moonlight-stay').then(({MOONLIGHT_STAY_PAYLOAD}) => {
createRoot(container).render(
<StrictMode>
<App payload={MOONLIGHT_STAY_PAYLOAD} />
</StrictMode>,
);
});
}
+22
View File
@@ -0,0 +1,22 @@
import {StrictMode} from 'react';
import {renderToString} from 'react-dom/server';
import type {SitePayload} from '@o2o/shared';
import {App} from './App';
/**
* SSR 엔트리. prerender 스크립트가 이 함수를 불러 HTML 을 얻는다.
*
* ★ renderToString 을 쓴다(스트리밍이 아니라). 파일로 굽는 게 목적이라
* 전체 문자열이 한 번에 필요하고, 스트리밍의 이점이 없다.
*
* ★ 사이트가 한 장이라 라우터도 url 인자도 없다. 섹션 이동은 앵커다.
*/
export function render(payload: SitePayload): string {
return renderToString(
<StrictMode>
<App payload={payload} />
</StrictMode>,
);
}
export {collectJsonLd} from './seo/jsonld';
@@ -0,0 +1,544 @@
import {
FactStatus,
LinkChannel,
PlaceCategory,
SiteStatus,
SourceType,
type FactEntry,
type SitePayload,
} from '@o2o/shared';
/**
* 데모 payload — "달빛스테이 제주"(숙박).
*
* 백엔드 sites API 가 붙기 전까지 프리렌더와 개발 서버가 먹는 입력이다.
* ★ 일부러 `pickup_service` 한 건을 UNVERIFIED 로 남겨 두었다.
* 확인 안 된 값이 화면·JSON-LD·llms.txt 어디에도 안 나가는지 눈으로 확인하는 용도다.
* 전부 VERIFIED 인 fixture 로는 그 규칙이 지켜지는지 알 수 없다.
*/
const UPDATED_AT = '2026-08-27T02:00:00+09:00';
/** fact 한 건을 짧게 만드는 헬퍼. 기본값은 "확인됨". */
function fact(
key: string,
label: string,
value: string,
options: Partial<FactEntry> = {},
): FactEntry {
return {
key,
label,
value,
type: 'text',
scope: 'place',
status: FactStatus.VERIFIED,
sourceType: SourceType.OWNER,
critical: false,
required: false,
verifiedAt: UPDATED_AT,
...options,
};
}
const PLACE_FACTS: FactEntry[] = [
fact('check_in_time', '체크인 시간', '16:00', {type: 'time', critical: true, required: true}),
fact('check_out_time', '체크아웃 시간', '11:00', {type: 'time', critical: true, required: true}),
fact(
'cancel_policy',
'취소·환불 규정',
'이용일 10일 전 100% 환불, 7일 전 80%, 5일 전 50%, 3일 전 30%, 2일 전부터는 환불 불가',
{critical: true, required: true, status: FactStatus.CORRECTED},
),
fact('cooking_allowed', '취사 가능', 'true', {type: 'bool', critical: true, required: true}),
fact('pet_allowed', '반려동물 동반', 'false', {type: 'bool', critical: true, required: true}),
fact('smoking', '흡연 가능', 'false', {type: 'bool', critical: true}),
fact('parking', '주차 가능', 'true', {type: 'bool'}),
fact('parking_capacity', '주차 대수', '4', {type: 'number', unit: '대'}),
fact('wifi', '와이파이', 'true', {type: 'bool'}),
fact('bbq_available', '바비큐 이용', 'false', {type: 'bool'}),
fact('breakfast', '조식 제공', 'false', {type: 'bool'}),
fact('baby_amenities', '유아용품 비치', 'true', {type: 'bool'}),
fact('reception_hours', '문의 가능 시간', '09:00 ~ 21:00'),
fact(
'extra_person_fee',
'인원 추가 요금',
'30000',
{type: 'number', unit: '원', critical: true},
),
// ★ 확인 전 — 화면에도, JSON-LD 에도, llms.txt 에도 나오면 안 된다.
fact('pickup_service', '픽업 서비스', 'true', {
type: 'bool',
status: FactStatus.UNVERIFIED,
sourceType: SourceType.CRAWL,
sourceUrl: 'https://example.com/listing/1234',
verifiedAt: null,
}),
];
function unitFact(
key: string,
label: string,
value: string,
unitId: string,
options: Partial<FactEntry> = {},
): FactEntry {
return fact(key, label, value, {...options, scope: 'unit', unitId});
}
export const MOONLIGHT_STAY_PAYLOAD: SitePayload = {
schemaVersion: 1,
site: {
siteId: 'demo-site-0001',
placeId: 'demo-place-0001',
status: SiteStatus.PUBLISHED,
origin: 'https://moonlight-stay-jeju.w4ai.o2o.kr',
basePath: '',
slug: 'moonlight-stay-jeju',
publishedAt: '2026-08-20T10:00:00+09:00',
updatedAt: UPDATED_AT,
version: 3,
},
place: {
name: '달빛스테이 제주',
englishName: 'Moonlight Stay Jeju',
category: PlaceCategory.LODGING,
roadAddress: '제주특별자치도 제주시 애월읍 애월해안로 382-12',
address: '제주특별자치도 제주시 애월읍 고내리 1108-4',
addressRegion: '제주특별자치도',
addressLocality: '제주시 애월읍',
phone: '0507-1345-8821',
email: 'contact@moonlightstay.kr',
latitude: 33.4658,
longitude: 126.3195,
regionCode: '50110253',
kakaoPlaceId: '1234567890',
legal: {
representative: '김달빛',
businessRegistrationNumber: '618-24-99812',
mailOrderNumber: '제2025-제주애월-0142호',
licenseNumber: '제2024-0038호',
licenseLabel: '농어촌민박 신고번호',
},
},
facts: PLACE_FACTS,
units: [
{
unitId: 'unit-a',
name: 'Moonlight A동',
slug: 'moonlight-a',
sortOrder: 1,
mediaIds: ['m-a1', 'm-a2', 'm-a3'],
facts: [
unitFact('room_type', '객실 타입', '독채형 빌라 (복층)', 'unit-a', {required: true}),
unitFact('standard_capacity', '기준 인원', '2', 'unit-a', {
type: 'number',
unit: '명',
critical: true,
required: true,
}),
unitFact('max_capacity', '최대 인원', '4', 'unit-a', {
type: 'number',
unit: '명',
critical: true,
required: true,
}),
unitFact('bed_type', '침대 구성', '퀸 사이즈 1개 + 토퍼 1세트', 'unit-a'),
unitFact('room_size', '객실 면적', '76', 'unit-a', {type: 'number', unit: '㎡'}),
unitFact('has_kitchen', '주방 여부', 'true', 'unit-a', {type: 'bool', critical: true}),
unitFact('view', '전망', '돌담 정원 뷰', 'unit-a'),
unitFact('weekday_price', '주중 요금', '280000', 'unit-a', {
type: 'number',
unit: '원',
critical: true,
}),
unitFact('weekend_price', '주말 요금', '350000', 'unit-a', {
type: 'number',
unit: '원',
critical: true,
}),
unitFact(
'room_intro',
'객실 소개',
'높은 층고와 통창 너머로 애월의 돌담 풍경이 펼쳐지는 독채입니다. 뒷마당의 현무암 자쿠지에서 사계절 온수 스파를 이용할 수 있습니다.',
'unit-a',
),
],
},
{
unitId: 'unit-b',
name: 'Starlight B동',
slug: 'starlight-b',
sortOrder: 2,
mediaIds: ['m-b1', 'm-b2', 'm-b3'],
facts: [
unitFact('room_type', '객실 타입', '독채형 빌라 (2층 테라스)', 'unit-b', {required: true}),
unitFact('standard_capacity', '기준 인원', '2', 'unit-b', {
type: 'number',
unit: '명',
critical: true,
required: true,
}),
unitFact('max_capacity', '최대 인원', '4', 'unit-b', {
type: 'number',
unit: '명',
critical: true,
required: true,
}),
unitFact('bed_type', '침대 구성', '킹 사이즈 1개', 'unit-b'),
unitFact('room_size', '객실 면적', '82', 'unit-b', {type: 'number', unit: '㎡'}),
unitFact('has_kitchen', '주방 여부', 'true', 'unit-b', {type: 'bool', critical: true}),
unitFact('view', '전망', '2층 루프탑 오션뷰', 'unit-b'),
unitFact('weekday_price', '주중 요금', '300000', 'unit-b', {
type: 'number',
unit: '원',
critical: true,
}),
unitFact('weekend_price', '주말 요금', '370000', 'unit-b', {
type: 'number',
unit: '원',
critical: true,
}),
unitFact(
'room_intro',
'객실 소개',
'2층 테라스에서 애월 바다의 수평선과 일몰을 볼 수 있습니다. 아일랜드형 오픈 키친을 갖췄습니다.',
'unit-b',
),
],
},
],
media: [
{
mediaId: 'm-hero',
url: 'https://images.unsplash.com/photo-1582719478250-c89cae4dc85b?auto=format&fit=crop&w=2000&q=85',
alt: '달빛스테이 제주 독채 외관과 현무암 돌담 정원',
category: '외관',
caption: '제주 돌담에 둘러싸인 독채 전경',
width: 2000,
height: 1333,
isPrimary: true,
sourceType: SourceType.OWNER,
},
{
mediaId: 'm-about',
url: 'https://images.unsplash.com/photo-1493809842364-78817add7ffb?auto=format&fit=crop&w=1200&q=80',
alt: '목재 다도 테이블과 다기 세트가 놓인 실내 공간',
category: '다도 공간',
caption: '제주 유기농 녹차와 함께하는 티타임',
width: 1200,
height: 800,
sourceType: SourceType.OWNER,
},
{
mediaId: 'm-a1',
url: 'https://images.unsplash.com/photo-1582719478250-c89cae4dc85b?auto=format&fit=crop&w=1200&q=80',
alt: 'Moonlight A동 거실과 통창 너머 돌담 풍경',
category: '객실',
width: 1200,
height: 800,
sourceType: SourceType.OWNER,
unitId: 'unit-a',
},
{
mediaId: 'm-a2',
url: 'https://images.unsplash.com/photo-1590490360182-c33d57733427?auto=format&fit=crop&w=1200&q=80',
alt: 'Moonlight A동 퀸사이즈 침실과 간접 조명',
category: '객실',
width: 1200,
height: 800,
sourceType: SourceType.OWNER,
unitId: 'unit-a',
},
{
mediaId: 'm-a3',
url: 'https://images.unsplash.com/photo-1584622650111-993a426fbf0a?auto=format&fit=crop&w=1200&q=80',
alt: 'Moonlight A동 야외 현무암 노천 온수 자쿠지',
category: '부대시설',
caption: '사계절 온수 노천 자쿠지',
width: 1200,
height: 800,
sourceType: SourceType.OWNER,
unitId: 'unit-a',
},
{
mediaId: 'm-b1',
url: 'https://images.unsplash.com/photo-1618773928121-c32242e63f39?auto=format&fit=crop&w=1200&q=80',
alt: 'Starlight B동 침실과 창밖 바다 전경',
category: '객실',
width: 1200,
height: 800,
sourceType: SourceType.OWNER,
unitId: 'unit-b',
},
{
mediaId: 'm-b2',
url: 'https://images.unsplash.com/photo-1556911220-e15b29be8c8f?auto=format&fit=crop&w=1200&q=80',
alt: 'Starlight B동 아일랜드 키친과 다이닝 테이블',
category: '주방',
width: 1200,
height: 800,
sourceType: SourceType.OWNER,
unitId: 'unit-b',
},
{
mediaId: 'm-b3',
url: 'https://images.unsplash.com/photo-1512917774080-9991f1c4c750?auto=format&fit=crop&w=1200&q=80',
alt: 'Starlight B동 2층 루프탑 테라스에서 본 일몰',
category: '테라스',
caption: '애월의 노을이 내려앉는 루프탑',
width: 1200,
height: 800,
sourceType: SourceType.OWNER,
unitId: 'unit-b',
},
{
mediaId: 'm-g1',
url: 'https://images.unsplash.com/photo-1507089947368-19c1da9775ae?auto=format&fit=crop&w=1200&q=80',
alt: '현무암 돌담으로 둘러싸인 독채 입구와 잔디 마당',
category: '외관 및 정원',
caption: '돌담과 단독 잔디 정원',
width: 1200,
height: 800,
sourceType: SourceType.OWNER,
},
{
mediaId: 'm-g2',
url: 'https://images.unsplash.com/photo-1566073771259-6a8506099945?auto=format&fit=crop&w=1200&q=80',
alt: '야간 조명이 켜진 잔디 정원',
category: '야경',
caption: '해가 지면 켜지는 정원 조명',
width: 1200,
height: 800,
sourceType: SourceType.OWNER,
},
],
faqs: [
{
faqId: 'faq-1',
question: '체크인과 체크아웃 시간은 어떻게 되나요?',
answer:
'체크인은 16:00부터, 체크아웃은 11:00까지입니다. 비대면 도어락 비밀번호는 입실 당일 11:00에 예약자 휴대폰으로 발송됩니다.',
status: FactStatus.VERIFIED,
sourceType: SourceType.OWNER,
sortOrder: 1,
},
{
faqId: 'faq-2',
question: '객실 내 취사가 가능한가요?',
answer:
'인덕션·전자레인지·조리도구를 이용한 조리가 가능합니다. 다만 실내에서 고기나 생선을 굽는 조리는 불가하며, 야외 바비큐 시설은 운영하지 않습니다.',
status: FactStatus.CORRECTED,
sourceType: SourceType.OWNER,
sortOrder: 2,
},
{
faqId: 'faq-3',
question: '주차는 몇 대까지 가능한가요?',
answer: '객실동별 전용 주차공간에 2대씩, 총 4대까지 무료로 주차하실 수 있습니다.',
status: FactStatus.VERIFIED,
sourceType: SourceType.OWNER,
sortOrder: 3,
},
{
faqId: 'faq-4',
question: '반려동물 동반 입실이 가능한가요?',
answer:
'반려동물 동반 입실은 불가합니다. 알레르기 예방과 객실 청결 유지를 위한 방침입니다.',
status: FactStatus.VERIFIED,
sourceType: SourceType.OWNER,
sortOrder: 4,
},
{
faqId: 'faq-5',
question: '기준 인원을 넘으면 추가 요금이 있나요?',
answer: '기준 2인 초과 시 1인당 1박 30,000원의 추가 요금이 있으며 침구가 제공됩니다.',
status: FactStatus.VERIFIED,
sourceType: SourceType.OWNER,
sortOrder: 5,
},
{
faqId: 'faq-6',
question: '예약 취소 및 환불 규정은 어떻게 되나요?',
answer:
'이용일 10일 전 취소 시 100% 환불, 7일 전 80%, 5일 전 50%, 3일 전 30% 환불되며, 2일 전부터 당일 취소는 환불이 불가합니다.',
status: FactStatus.CORRECTED,
sourceType: SourceType.OWNER,
sortOrder: 6,
},
],
links: [
{
channel: LinkChannel.NAVER_PLACE,
url: 'https://m.place.naver.com/accommodation/1234567890',
title: '네이버 플레이스',
confirmed: true,
},
{
channel: LinkChannel.INSTAGRAM,
url: 'https://instagram.com/moonlightstay.jeju',
title: '공식 인스타그램',
confirmed: true,
},
{
// ★ 확정 전 — sameAs 와 푸터 어디에도 나오면 안 된다.
channel: LinkChannel.YANOLJA,
url: 'https://www.yanolja.com/pension/0000000',
title: '야놀자',
confirmed: false,
},
],
local: {
syncedAt: '2026-08-26T08:00:00+09:00',
weather: {
temperature: 26.4,
condition: '맑음',
note: '맑고 바람이 약해 해안 산책로를 걷기 좋은 날씨입니다.',
observedAt: '2026-08-27T09:00:00+09:00',
},
restaurants: [
{
name: '닻',
category: '해산물 · 이자카야',
distanceText: '450m',
durationText: '도보 6분',
description: '숙성 딱새우 사시미와 뿔소라 버터구이를 내는 애월의 심야 식당',
searchQuery: '애월 닻',
},
{
name: '우니담 애월본점',
category: '성게 · 솥밥',
distanceText: '1.2km',
durationText: '차량 3분',
description: '성게미역국과 성게비빔밥을 내는 바다 전망 한식당',
searchQuery: '애월 우니담',
},
{
name: '해월정 애월직영점',
category: '보말칼국수',
distanceText: '2.1km',
durationText: '차량 5분',
description: '보말 육수로 끓인 칼국수와 죽을 내는 아침·점심 식당',
searchQuery: '애월 해월정',
},
],
attractions: [
{
name: '한담해변 산책로',
category: '해안 산책로',
distanceText: '2.0km',
durationText: '차량 5분 / 도보 25분',
description: '바다를 끼고 이어지는 제주 서쪽 해안 산책길',
searchQuery: '한담해안산책로',
},
{
name: '곽지해수욕장',
category: '해수욕장',
distanceText: '3.5km',
durationText: '차량 7분',
description: '수심이 얕고 천연 용천수 노천탕이 있는 백사장',
searchQuery: '곽지해수욕장',
},
{
name: '새별오름',
category: '오름',
distanceText: '11km',
durationText: '차량 18분',
description: '가을 억새로 알려진 완만한 능선의 기생화산',
searchQuery: '제주 새별오름',
},
],
festivals: [
{
month: '10월',
name: '제주 올레걷기축제',
period: '2026.10.15 ~ 2026.10.17',
location: '제주 올레길 15~16코스',
description: '올레길을 걸으며 참여하는 제주의 가을 축제',
searchQuery: '제주 올레걷기축제',
},
{
month: '11월',
name: '제주 감귤 박람회',
period: '2026.11.20 ~ 2026.11.24',
location: '서귀포 농업기술센터 일원',
description: '감귤 수확 체험과 농수산물 직거래 행사',
searchQuery: '제주 감귤 박람회',
},
],
},
routes: [
{
destination: '제주국제공항',
byCar: '약 32분',
byTransit: '약 55분 (급행 102번)',
distanceText: '19.5km',
note: '공항로 · 애월해안로 경유',
},
{
destination: '애월 한담해변',
byCar: '약 4분',
byTransit: '도보 약 20분',
distanceText: '1.9km',
note: '해안 산책로 연결',
},
{
destination: '곽지해수욕장',
byCar: '약 7분',
byTransit: '도보 약 35분',
distanceText: '3.4km',
},
{
destination: '협재해수욕장',
byCar: '약 16분',
byTransit: '버스 약 30분 (간선 202번)',
distanceText: '11.8km',
},
],
narrative: {
heroHeadline: '바람과 돌담이 품은 고요',
heroSubline: '제주 자연의 질감이 머무는 독채 스테이',
tagline: '하루 두 팀만 머무는, 애월의 프라이빗 독채',
summary:
'제주시 애월읍에 있는 달빛스테이 제주입니다. 독채 2동을 운영하며 체크인 16:00, 체크아웃 11:00입니다. 반려동물 동반은 불가하고, 주차는 4대까지 무료입니다.',
about: [
'달빛스테이 제주는 제주의 현무암 돌담과 편백나무를 그대로 살려 지은 독채 숙소입니다.',
'애월 해안도로에서 한 블록 안쪽 마을 골목에 있어, 파도 소리와 밤하늘을 조용히 누릴 수 있습니다.',
'하루에 두 팀만 받으며, 각 동마다 독립된 마당과 야외 자쿠지, 다도 공간이 따로 있습니다.',
],
},
theme: {
templateId: 'stay-warm-wood',
colors: {
primary: '#43302b',
secondary: '#786055',
bg: '#faf8f5',
card: '#f2ece4',
text: '#29201d',
accent: '#c27847',
},
fontStyle: 'Warm Natural',
sections: [
{id: 'hero', name: '히어로', enabled: true, locked: true},
{id: 'intro', name: '소개', enabled: true, locked: false},
{id: 'rooms', name: '객실 안내', enabled: true, locked: false},
{id: 'info', name: '기본 정보', enabled: true, locked: true},
{id: 'photos', name: '사진 갤러리', enabled: true, locked: false},
{id: 'weather', name: '날씨', enabled: true, locked: false},
{id: 'local', name: '지역 정보', enabled: true, locked: false},
{id: 'map', name: '오시는 길', enabled: true, locked: true},
{id: 'faq', name: 'FAQ', enabled: true, locked: false},
],
},
};
+62
View File
@@ -0,0 +1,62 @@
@import "tailwindcss";
@import "@o2o/shared/styles/base.css";
/*
* 발행 사이트의 색은 사장님이 고른 템플릿에서 온다.
* 프리렌더가 <head> 에 --tpl-* 를 심고(`seo/head.ts` themeStyle), 여기서 Tailwind 색으로 연결한다.
* 관리자 토큰(tokens.css)은 이 앱에 들어오지 않는다 — 두 색 체계를 섞지 않는다.
*
* 개발 서버에서는 <head> 주입이 없으므로 아래 :root 기본값이 쓰인다.
*/
:root {
--tpl-primary: #18181b;
--tpl-secondary: #52525b;
--tpl-bg: #ffffff;
--tpl-card: #fafafa;
--tpl-text: #09090b;
--tpl-accent: #2563eb;
}
@theme inline {
--color-brand: var(--tpl-primary);
--color-brand-soft: var(--tpl-secondary);
--color-surface: var(--tpl-bg);
--color-surface-alt: var(--tpl-card);
--color-ink: var(--tpl-text);
--color-accent: var(--tpl-accent);
--font-sans: 'Pretendard Variable', 'Noto Sans KR', system-ui, sans-serif;
--font-serif: 'Noto Serif KR', 'Batang', 'Times New Roman', serif;
}
html {
scroll-behavior: smooth;
/* 고정 헤더에 앵커가 가리지 않게. */
scroll-padding-top: 5rem;
}
body {
background-color: var(--color-surface);
color: var(--color-ink);
font-family: var(--font-sans);
font-feature-settings: "tnum" 1;
}
@layer components {
.serif {
font-family: var(--font-serif);
}
/* 섹션 공통 폭 — 본문이 한 줄에 너무 길어지지 않게. */
.shell {
width: 100%;
max-width: 1120px;
margin-inline: auto;
padding-inline: 1rem;
}
@media (min-width: 640px) {
.shell {
padding-inline: 1.5rem;
}
}
}
+297
View File
@@ -0,0 +1,297 @@
import {
LinkChannel,
PlaceCategory,
factText,
sanitizeUnits,
selectPublishable,
selectPublishableFaqs,
type ChannelLink,
type FactEntry,
type MediaItem,
type SitePayload,
type UnitInfo,
} from '@o2o/shared';
import {UNIT_SPEC} from '@/seo/jsonld';
/**
* payload → 화면이 바로 쓰는 모양.
*
* 컴포넌트가 fact 배열을 직접 뒤지지 않게 한 층 둔다. 여기 한 곳에서만
* selectPublishable() 을 통과시키므로, 컴포넌트가 실수로 미검증 값을 그릴 수가 없다.
*/
export interface InfoRow {
label: string;
value: string;
/** 부가 설명. 출처가 아니라 사장님이 붙인 보충 문구. */
note?: string;
}
/** 사업장 단위 이용 정보 표. 확인된 것만 들어간다. */
export function essentialRows(payload: SitePayload): InfoRow[] {
return selectPublishable(payload.facts)
.filter((fact) => fact.scope === 'place')
.map((fact) => ({
label: fact.label,
value: displayValue(fact, payload.facts),
}))
.filter((row) => row.value !== '');
}
function displayValue(fact: FactEntry, all: FactEntry[]): string {
const text = factText(all, fact.key);
if (!text) return '';
if (fact.type !== 'bool') return text;
if (text === 'true') return '가능';
if (text === 'false') return '불가';
return text;
}
export interface UnitView {
unitId: string;
slug: string;
name: string;
intro?: string;
/** 스펙 칩 — 인원 · 침대 · 면적처럼 한눈에 보는 값. */
chips: {label: string; value: string}[];
rows: InfoRow[];
images: MediaItem[];
priceText?: string;
href: string;
}
export function unitViews(payload: SitePayload): UnitView[] {
const spec = UNIT_SPEC[payload.place.category];
const mediaById = new Map(payload.media.map((m) => [m.mediaId, m]));
return sanitizeUnits(payload.units).map((unit) => {
const intro = factText(unit.facts, 'room_intro') ?? factText(unit.facts, 'description');
const chipKeys =
payload.place.category === PlaceCategory.LODGING
? ['max_capacity', 'bed_type', 'room_size']
: ['price', 'volume', 'origin'];
return {
unitId: unit.unitId,
slug: unit.slug,
name: unit.name,
intro,
chips: chipKeys
.map((key) => {
const value = factText(unit.facts, key);
const label = unit.facts.find((f) => f.key === key)?.label ?? key;
return value ? {label, value} : null;
})
.filter((chip): chip is {label: string; value: string} => chip !== null),
rows: unit.facts
.map((fact) => ({label: fact.label, value: displayValue(fact, unit.facts)}))
.filter((row) => row.value !== ''),
images: unit.mediaIds
.map((id) => mediaById.get(id))
.filter((m): m is MediaItem => Boolean(m?.alt?.trim())),
priceText: unitPriceText(unit),
href: `/${spec.path}/${unit.slug}`,
};
});
}
function unitPriceText(unit: UnitInfo): string | undefined {
const weekday = Number(factText(unit.facts, 'weekday_price')?.replace(/[^0-9]/g, ''));
const price = Number(factText(unit.facts, 'price')?.replace(/[^0-9]/g, ''));
const base = Number.isFinite(weekday) && weekday > 0 ? weekday : price;
if (!Number.isFinite(base) || base <= 0) return undefined;
return `${base.toLocaleString('ko-KR')}원부터`;
}
/** 갤러리에 낼 이미지 — 대체 텍스트 없는 것은 뺀다(검색·낭독기 모두 못 읽는다). */
export function galleryImages(payload: SitePayload): MediaItem[] {
return payload.media.filter((m) => m.alt?.trim() && !m.unitId);
}
export function faqList(payload: SitePayload) {
return selectPublishableFaqs(payload.faqs);
}
/** 켜져 있는 섹션인지. 순서도 payload 가 정한다. */
export function enabledSections(payload: SitePayload) {
return payload.theme.sections.filter((section) => section.enabled);
}
export function isSectionEnabled(payload: SitePayload, id: string): boolean {
return payload.theme.sections.find((section) => section.id === id)?.enabled ?? false;
}
export function unitSpec(payload: SitePayload) {
return UNIT_SPEC[payload.place.category];
}
/**
* 섹션 제목 — 사장님이 [섹션] 패널에서 붙인 이름(`theme.sections[].name`)을 그대로 쓴다.
*
* ★ 왜 필요한가
* 지금까지 발행본 소제목은 컴포넌트에 박힌 문자열이었다. 사장님이 "객실 안내"를
* "우리 방 소개"로 바꿔도 에디터 캔버스만 바뀌고 발행본은 옛 문구로 나갔다 —
* 사장님 입장에서는 고친 게 반영이 안 된 것이고, 실제로 반영이 안 된 게 맞다.
*
* ★ **모든 섹션이 이걸 쓰는 건 아니다.** 기준은 하나다 — 에디터 캔버스가 그 섹션에서
* 무엇을 제목으로 쓰는가. 두 화면이 같아야 하므로 발행본은 에디터를 따라간다.
*
* 이걸 쓰는 섹션 rules · booking · inquiry · space · exhibition · rooms/menu/programs
* (에디터: `title={section.name}`)
* 쓰지 않는 섹션 intro · info · photos · map · local · faq
* (에디터가 자체 제목을 쓴다: "공간 갤러리", "오시는 길", `${상호} 소개` …)
*
* 한때 발행본에서 여섯 섹션 전부에 이걸 걸었다가 소개 제목이 "조이모텔 소개" 에서
* "소개" 로 짧아졌다. `theme.sections[].name` 은 사장님이 붙인 이름이기도 하지만,
* 아직 아무것도 안 바꿨으면 서버 기본표(_DEFAULT_THEME)의 짧은 목록 라벨이다 —
* 그 라벨은 좌측 패널의 navigation 용이지 <h2> 용이 아니다.
*
* ★ 폴백을 두는 이유
* name 이 비어 있는 payload(옛 버전·손으로 만든 fixture)에서 제목 없는 <h2> 가
* 나가면 문서 구조가 무너지고 검색·낭독기가 섹션을 못 읽는다. 제목은 반드시 채운다.
*/
export function sectionName(payload: SitePayload, id: string, fallback: string): string {
const name = payload.theme.sections.find((section) => section.id === id)?.name?.trim();
return name ? name : fallback;
}
/**
* key 목록 순서대로 확인된 place fact 를 표 행으로.
*
* ★ 순서가 곧 화면 순서다. 값이 없거나 미검증인 key 는 조용히 빠진다 —
* "확인 중"이라는 빈 줄을 그리면 손님은 그걸 규정으로 읽는다.
*/
function placeRowsByKeys(payload: SitePayload, keys: readonly string[]): InfoRow[] {
const map = new Map(
selectPublishable(payload.facts)
.filter((fact) => fact.scope === 'place')
.map((fact) => [fact.key, fact] as const),
);
return keys
.map((key) => map.get(key))
.filter((fact): fact is FactEntry => fact !== undefined)
.map((fact) => ({label: fact.label, value: displayValue(fact, payload.facts)}))
.filter((row) => row.value !== '');
}
/**
* 이용 규정으로 읽히는 fact key.
*
* ★ 관리자 캔버스의 `builder/canvas/variants/common.ts` RULE_FIELD_IDS 와 같은 목록이다.
* 에디터에서 규정으로 보인 항목이 발행본에서 다른 항목이 되면 사장님은 어느 쪽을
* 믿어야 할지 모른다. 목록이 바뀌면 양쪽을 같이 고친다.
* ★ 여기 없는 규정은 만들어 내지 않는다. 업종 스키마(lodging.json)에 있는 key 만 적는다.
*/
const RULE_FACT_KEYS = [
'check_in_time',
'check_out_time',
'cancel_policy',
'cooking_allowed',
'pet_allowed',
'smoking',
'extra_person_fee',
] as const;
/** 이용 규정 줄. 확인된 fact 에서만 만든다 — 없으면 빈 목록이고 섹션 자체가 안 나간다. */
export function ruleRows(payload: SitePayload): InfoRow[] {
return placeRowsByKeys(payload, RULE_FACT_KEYS);
}
/**
* 예약 안내에 실을 fact.
*
* 숙박에는 없고(예약은 채널이 받는다) 음식점·관광체험 스키마에만 있는 key 다.
* 값이 없는 업종에서는 그냥 빠진다.
*/
const BOOKING_FACT_KEYS = ['reservation_required', 'reservation_channel'] as const;
export function bookingRows(payload: SitePayload): InfoRow[] {
return placeRowsByKeys(payload, BOOKING_FACT_KEYS);
}
/**
* 공간 안내에 실을 fact — "자리가 어떻게 생겼나"에 답하는 것만.
*
* ★ 주차·와이파이 같은 편의시설은 넣지 않는다. 그건 이용 정보(info) 표가 이미 낸다.
*/
const SPACE_FACT_KEYS = [
'seat_count',
'terrace',
'room_available',
'group_seat_max',
'power_outlet',
'study_allowed',
'wheelchair_accessible',
] as const;
export function spaceRows(payload: SitePayload): InfoRow[] {
return placeRowsByKeys(payload, SPACE_FACT_KEYS);
}
/**
* 관람 안내에 실을 fact — 관광체험 스키마(tour_activity.json)의 관람 관련 key.
*
* ★ 준비물·안전 유의사항은 뺐다. 그건 "관람 안내"가 아니라 체험 전 주의사항이고,
* 이용 정보(info) 표에 이미 나간다.
*/
const EXHIBITION_FACT_KEYS = [
'operating_hours',
'session_times',
'closed_days',
'age_limit',
'guide_language',
] as const;
export function exhibitionRows(payload: SitePayload): InfoRow[] {
return placeRowsByKeys(payload, EXHIBITION_FACT_KEYS);
}
/** 채널 코드 → 사람이 읽는 이름. link.title 이 있으면 그쪽이 우선이다. */
export const CHANNEL_LABEL: Record<number, string> = {
[LinkChannel.YANOLJA]: '야놀자',
[LinkChannel.GOODCHOICE]: '여기어때',
[LinkChannel.NAVER_PLACE]: '네이버 플레이스',
[LinkChannel.INSTAGRAM]: '인스타그램',
[LinkChannel.OFFICIAL_SITE]: '공식 사이트',
[LinkChannel.BLOG]: '블로그',
[LinkChannel.ETC]: '채널',
};
export function channelLabel(link: ChannelLink): string {
return link.title ?? CHANNEL_LABEL[link.channel] ?? '채널';
}
/**
* 예약을 실제로 받는 채널.
*
* ★ 블로그·인스타그램은 뺀다. 눌러도 예약 화면이 안 나오는 링크를 "예약하기" 자리에
* 두면 손님이 예약한 줄 알고 안 온다. 공식 사이트도 뺀다 — 지금 보고 있는 이 사이트가
* 그 자리라, 자기 자신으로 돌려보내는 버튼이 된다.
*/
const BOOKING_CHANNELS: readonly number[] = [
LinkChannel.YANOLJA,
LinkChannel.GOODCHOICE,
LinkChannel.NAVER_PLACE,
];
/**
* 문의를 실제로 받을 수 있는 채널 — 네이버 톡톡·인스타 DM 처럼 말을 걸 수 있는 곳만.
*
* ★ 블로그·공식 사이트·기타(ETC)는 뺀다. 읽기만 되는 링크를 "문의" 버튼으로 두면
* 손님이 남긴 말이 아무 데도 도착하지 않는다.
*/
const CONTACT_CHANNELS: readonly number[] = [LinkChannel.NAVER_PLACE, LinkChannel.INSTAGRAM];
/** 확정된 링크만. 확정 전 URL 은 동명 업소일 수 있다(sanitizePayloadForPublish 와 같은 규칙). */
function confirmedLinks(payload: SitePayload, channels: readonly number[]): ChannelLink[] {
return payload.links.filter((link) => link.confirmed && channels.includes(link.channel));
}
export function bookingLinks(payload: SitePayload): ChannelLink[] {
return confirmedLinks(payload, BOOKING_CHANNELS);
}
export function contactLinks(payload: SitePayload): ChannelLink[] {
return confirmedLinks(payload, CONTACT_CHANNELS);
}
+73
View File
@@ -0,0 +1,73 @@
/** "280000" → "280,000원". 숫자가 아니면 원문 그대로 돌려준다. */
export function formatWon(value: string | number | null | undefined): string {
if (value == null || value === '') return '';
const num = typeof value === 'string' ? Number(value.replace(/,/g, '')) : value;
if (!Number.isFinite(num)) return String(value);
return `${num.toLocaleString('ko-KR')}원`;
}
/** ISO → "2026년 8월 27일". 화면에 "언제 기준"을 찍는 데 쓴다. */
export function formatKoreanDate(iso: string | null | undefined): string {
if (!iso) return '';
const date = new Date(iso);
if (Number.isNaN(date.getTime())) return '';
return `${date.getFullYear()}년 ${date.getMonth() + 1}월 ${date.getDate()}일`;
}
/** 네이버 검색으로 보내는 링크. 우리가 지어낸 URL 을 링크하지 않기 위한 통로. */
export function naverSearchUrl(query: string): string {
return `https://search.naver.com/search.naver?query=${encodeURIComponent(query)}`;
}
/**
* 카카오맵 **길찾기**. 좌표가 있으면 목적지가 찍힌 길찾기 화면으로 바로 열린다.
*
* ★ 좌표가 없으면 검색으로 떨어진다 — 없는 좌표를 지어내면 엉뚱한 곳으로 안내하게 되고,
* 그건 검색 결과를 한 번 더 누르게 하는 것보다 훨씬 나쁘다.
*/
export function kakaoDirectionsUrl(name: string, lat?: number, lng?: number): string {
if (lat == null || lng == null) {
return `https://map.kakao.com/link/search/${encodeURIComponent(name)}`;
}
return `https://map.kakao.com/link/to/${encodeURIComponent(name)},${lat},${lng}`;
}
/**
* 네이버지도 **길찾기**. v5 주소 형식은 `/p/directions/{출발}/{도착}/{경유}/{수단}` 이고,
* 각 지점은 `경도,위도,이름` 이다. 출발지를 `-` 로 비워 두면 네이버가 방문자의 현재 위치를
* 채운다 — 우리가 방문자 위치를 알 필요도, 물어볼 필요도 없다.
*
* ★ 수단을 대중교통(transit)으로 고정하는 이유: 차로 오는 사람은 화면에서 한 번만 바꾸면 되지만,
* 대중교통으로 오는 사람에게는 이 화면이 곧 답이다. 기본값은 덜 아는 쪽에 맞춘다.
*/
export function naverDirectionsUrl(name: string, lat?: number, lng?: number): string {
if (lat == null || lng == null) {
return `https://map.naver.com/p/search/${encodeURIComponent(name)}`;
}
return `https://map.naver.com/p/directions/-/${lng},${lat},${encodeURIComponent(name)}/-/transit`;
}
/**
* 지도 그림(OpenStreetMap 임베드) 주소.
*
* ★ 왜 카카오·네이버 지도가 아닌가
* 둘 다 지도를 그리려면 키가 필요하다(카카오는 JS 키, 네이버 정적지도는 NCP 헤더 인증).
* 그런데 이 렌더러는 **런타임 환경변수를 쓰지 않는다**(site/.env.example) — payload 하나로
* 같은 HTML 이 재현되어야 하기 때문이다. 키를 읽는 순간 그 규칙이 깨진다.
* OSM 임베드는 키가 없고 좌표만으로 만들어져 payload 만으로 재현된다.
*
* ★ 지도는 사람이 보는 것이고, 기계가 읽을 위치 정보는 이미 따로 나간다
* (JSON-LD 의 geo·PostalAddress, 화면의 <address>). 그래서 지도가 iframe 이어도
* AEO 는 손해 보지 않는다.
*/
export function osmEmbedUrl(lat: number, lng: number, aspect = 16 / 9, halfLat = 0.0022): string {
// ★ bbox 의 종횡비를 iframe 과 맞춰야 한다. OSM 임베드는 bbox 모양대로 지도 캔버스를 잡고
// 남는 자리를 흰색으로 둔다 — 안 맞추면 넓은 프레임 왼쪽 3분의 1만 지도가 그려진다(실측).
// ★ 경도는 cos(위도) 만큼 좁다. 이 보정을 빼면 한국(위도 37도)에서 가로로 눌린 지도가 나온다.
const cos = Math.max(Math.cos((lat * Math.PI) / 180), 0.01);
const halfLng = (aspect * halfLat) / cos;
const bbox = [lng - halfLng, lat - halfLat, lng + halfLng, lat + halfLat]
.map((n) => n.toFixed(6))
.join(',');
return `https://www.openstreetmap.org/export/embed.html?bbox=${bbox}&layer=mapnik&marker=${lat},${lng}`;
}
+24
View File
@@ -0,0 +1,24 @@
import {createContext, useContext, type ReactNode} from 'react';
import type {SitePayload} from '@o2o/shared';
/**
* payload 를 트리 전체에 흘린다.
*
* ★ 컴포넌트가 데이터를 *가져오지* 않는다. 발행 사이트에는 API 호출이 없다 —
* 빌드 시점에 확정된 사실만 그린다. 그래서 서버 렌더와 브라우저 렌더가 항상 같고,
* 크롤러가 보는 HTML 과 사람이 보는 화면이 어긋날 수 없다.
*/
const SiteContext = createContext<SitePayload | null>(null);
export function SiteProvider({payload, children}: {payload: SitePayload; children: ReactNode}) {
return <SiteContext.Provider value={payload}>{children}</SiteContext.Provider>;
}
export function useSite(): SitePayload {
const payload = useContext(SiteContext);
if (!payload) {
// payload 없이 렌더되면 조용히 빈 화면이 나가는 게 최악이다 — 빌드를 실패시킨다.
throw new Error('SiteProvider 밖에서 useSite() 를 불렀습니다. payload 없이는 렌더할 수 없습니다.');
}
return payload;
}
@@ -0,0 +1,41 @@
import {useEffect, useState} from 'react';
/**
* 화면에 보이는 섹션의 id — 한 장짜리 사이트의 내비게이션 활성 표시용.
*
* ★ 라우터를 걷어내면서 `useLocation` 으로 하던 활성 표시가 사라졌다. 한 장이 되면
* 하단 탭이 유일한 내비게이션이라, 지금 어디인지 안 보이면 이전보다 나빠진다.
*
* ★ rootMargin 으로 판정선을 화면 위쪽 35% 지점에 둔다. 가운데로 두면 짧은 섹션이
* 영영 활성화되지 않고, 위쪽 0 으로 두면 스크롤 도중 두 섹션이 번갈아 깜빡인다.
*
* ★ 배열을 문자열 키로 바꿔 의존성에 넣는다. `ids` 를 그대로 넣으면 부모가 매 렌더마다
* 새 배열을 만들어 넘기므로 옵저버가 계속 재생성된다.
*/
export function useActiveSection(ids: string[]): string | null {
const key = ids.join('|');
const [active, setActive] = useState<string | null>(ids[0] ?? null);
useEffect(() => {
const targets = key
.split('|')
.map((id) => document.getElementById(id))
.filter((el): el is HTMLElement => el !== null);
if (targets.length === 0) return;
const observer = new IntersectionObserver(
(entries) => {
const visible = entries
.filter((entry) => entry.isIntersecting)
.sort((a, b) => a.boundingClientRect.top - b.boundingClientRect.top)[0];
if (visible) setActive(visible.target.id);
},
{rootMargin: '-35% 0px -55% 0px'},
);
for (const target of targets) observer.observe(target);
return () => observer.disconnect();
}, [key]);
return active;
}
+69
View File
@@ -0,0 +1,69 @@
import {useEffect, useState} from 'react';
import type {WeatherSnapshot} from '@o2o/shared';
export interface LiveWeather extends WeatherSnapshot {
stale?: boolean;
}
function condition(code: number): string {
if (code === 0) return '맑음';
if (code >= 1 && code <= 3) return '구름많음';
if (code >= 50 && code <= 69) return '비';
if (code >= 70 && code <= 79) return '눈';
return '흐림';
}
/** 프리렌더 스냅샷으로 시작하고, 하이드레이션이 끝난 뒤에만 최신 캐시를 반영한다. */
export function useLiveWeather({
initial,
regionCode,
latitude,
longitude,
}: {
initial?: WeatherSnapshot;
regionCode?: string;
latitude?: number;
longitude?: number;
}): LiveWeather | undefined {
const [weather, setWeather] = useState<LiveWeather | undefined>(initial);
useEffect(() => {
if (!regionCode || latitude == null || longitude == null) return;
const controller = new AbortController();
async function refresh() {
try {
const baseUrl = import.meta.env.VITE_API_BASE_URL ?? 'http://localhost:9800';
const query = new URLSearchParams({
region_code: regionCode!,
latitude: String(latitude),
longitude: String(longitude),
});
const response = await fetch(`${baseUrl}/v1/local/weather?${query}`, {
signal: controller.signal,
});
if (!response.ok) return;
const body = await response.json();
if (!body?.result?.success || !body.weather) return;
setWeather((previous) => ({
temperature: Number(body.weather.temperature),
condition: condition(Number(body.weather.weather_code)),
note: previous?.note,
observedAt: body.weather.observed_at,
stale: Boolean(body.stale),
}));
} catch {
// 정적 payload의 날씨를 유지한다. 날씨 장애가 사이트 렌더를 깨면 안 된다.
}
}
void refresh();
const timer = window.setInterval(() => void refresh(), 10 * 60 * 1000);
return () => {
controller.abort();
window.clearInterval(timer);
};
}, [latitude, longitude, regionCode]);
return weather;
}
+88
View File
@@ -0,0 +1,88 @@
import {
AboutSection,
AnswerBlock,
BookingSection,
EssentialInfoSection,
ExhibitionSection,
FaqSection,
GallerySection,
HeroSection,
InquirySection,
LocalGuideSection,
WeatherSection,
LocationSection,
RulesSection,
SpaceSection,
UnitsSection,
} from '@/sections';
import {useSite} from '@/lib/site-context';
import {isSectionEnabled} from '@/lib/derive';
/**
* 홈.
*
* 섹션 순서는 관리자 에디터가 정한 것(theme.sections)을 따른다.
* ★ 히어로 바로 다음에 AnswerBlock 이 온다. 이 자리는 순서 설정과 무관하게 고정이다 —
* AI 검색이 답을 뽑아 가는 자리라, 사장님이 아래로 내리면 인용률이 떨어진다.
*
* ★ variantId 는 아직 해석하지 않는다.
* `SectionSetting.variantId` 에 사장님이 [디자인] 탭에서 고른 배리에이션 키
* (예: 'rules.cards')가 실려 오지만, 발행본은 그 값을 보지 않고 섹션마다 하나뿐인
* 기본 레이아웃으로 그린다. 배리에이션 40종을 발행본에 옮기는 건 별도 작업이다.
* 렌더러가 모르는 키가 와도 화면이 깨지지 않아야 한다는 규칙(site-payload.ts)은
* "값을 통째로 무시한다"로 이미 지켜진다.
*/
export function HomePage() {
const payload = useSite();
/**
* 섹션 id → 발행본 컴포넌트.
*
* ★ 에디터의 섹션 타입(admin `builder/canvas/registry.ts`)과 이 표의 키가 어긋나면,
* 사장님이 켜 둔 섹션이 아래 `if (!Component) return null` 에서 말없이 사라진다.
* 실제로 rules(이용 규정)·booking·space·inquiry·exhibition 다섯이 그렇게 빠져 있었고,
* 숙박 사장님이 써 넣은 환불 규정이 payload 까지 실려 오고도 발행본에 없었다.
* 에디터에 섹션 타입을 늘릴 때는 여기도 같이 늘린다.
*/
const SECTION_COMPONENTS: Record<string, () => React.ReactElement | null> = {
intro: AboutSection,
info: EssentialInfoSection,
rooms: UnitsSection,
menu: UnitsSection,
programs: UnitsSection,
rules: RulesSection,
booking: BookingSection,
space: SpaceSection,
inquiry: InquirySection,
exhibition: ExhibitionSection,
photos: GallerySection,
local: LocalGuideSection,
weather: WeatherSection,
map: LocationSection,
faq: FaqSection,
};
const rendered = new Set<string>();
return (
<main className="w-full flex-1">
<HeroSection />
<AnswerBlock />
{payload.theme.sections
.filter((section) => section.enabled && section.id !== 'hero')
.map((section) => {
const Component = SECTION_COMPONENTS[section.id];
if (!Component) return null;
// 같은 컴포넌트를 두 번 그리지 않는다(rooms/menu/programs 가 모두 UnitsSection).
const key = Component.name;
if (rendered.has(key)) return null;
rendered.add(key);
return <Component key={section.id} />;
})}
{/* 섹션 설정에 없더라도 오시는 길은 항상 나간다 — 위치 질의의 근거다. */}
{!isSectionEnabled(payload, 'map') && <LocationSection />}
</main>
);
}
+1
View File
@@ -0,0 +1 @@
export {HomePage} from './HomePage';
@@ -0,0 +1,58 @@
import {useSite} from '@/lib/site-context';
import {galleryImages} from '@/lib/derive';
export function AboutSection() {
const payload = useSite();
const {narrative, place} = payload;
if (narrative.about.length === 0) return null;
// 대표가 아닌 사진 중 첫 장. 히어로와 같은 사진이 두 번 나오지 않게.
const image = galleryImages(payload).find((m) => !m.isPrimary);
return (
<section
id="about"
aria-labelledby="about-heading"
className="w-full border-b border-black/8 py-16 sm:py-24"
>
<div className="shell">
<p className="mb-3 text-xs font-semibold uppercase tracking-wider opacity-50">About</p>
<div className="grid grid-cols-1 items-center gap-8 md:grid-cols-12 lg:gap-12">
{image && (
<figure className="md:col-span-6">
<div className="relative aspect-4/3 overflow-hidden rounded-2xl md:aspect-5/4">
<img
src={image.url}
alt={image.alt}
loading="lazy"
decoding="async"
width={image.width}
height={image.height}
className="size-full object-cover"
/>
</div>
{image.caption && (
<figcaption className="mt-2 text-xs opacity-60">{image.caption}</figcaption>
)}
</figure>
)}
<div className={image ? 'md:col-span-6' : 'md:col-span-12'}>
{/* 제목은 사장님이 붙인 섹션 이름이 먼저다. 이름이 비어 있을 때만
지금까지 쓰던 문구(한 줄 소개 → "○○ 소개")로 떨어진다. */}
<h2 id="about-heading" className="serif mb-4 text-2xl font-bold leading-snug tracking-tight sm:text-3xl lg:text-4xl">
{narrative.heroSubline ?? `${place.name} 소개`}
</h2>
<div className="space-y-3 text-sm leading-relaxed opacity-80">
{narrative.about.map((paragraph, index) => (
<p key={index}>{paragraph}</p>
))}
</div>
</div>
</div>
</div>
</section>
);
}
@@ -0,0 +1,56 @@
import {useSite} from '@/lib/site-context';
import {factualSummary} from '@/seo/meta';
import {essentialRows} from '@/lib/derive';
import {formatKoreanDate} from '@/lib/format';
/**
* 핵심 정보 요약 — AEO 의 핵심 블록.
*
* AI 검색은 페이지 전체를 요약하지 않는다. "답이 될 만한 문장"을 찾아 그대로 인용한다.
* 그래서 상단에 단정문을 둔다: "체크인은 16:00입니다." 형태.
* 표(dl)로 두는 이유는 label-value 관계가 마크업으로 드러나야 기계가 짝을 짓기 때문이다.
*
* ★ 여기 나오는 값은 전부 확인된 fact 다. essentialRows() 가 걸러 준다.
*/
export function AnswerBlock() {
const payload = useSite();
const rows = essentialRows(payload).slice(0, 6);
const summary = payload.narrative.summary ?? factualSummary(payload);
if (rows.length === 0 && !summary) return null;
return (
<section
id="summary"
aria-labelledby="summary-heading"
className="w-full border-b border-black/8 py-10 sm:py-12"
style={{backgroundColor: 'var(--color-surface-alt)'}}
>
<div className="shell">
<h2 id="summary-heading" className="serif mb-1 text-lg font-bold sm:text-xl">
한눈에 보는 {payload.place.name}
</h2>
<p className="mb-5 text-xs opacity-60">
{formatKoreanDate(payload.site.updatedAt)} 기준, 사업자가 확인한 정보입니다.
</p>
{/* 단정문 한 덩어리 — 인용되기 좋은 형태. */}
<p className="mb-5 max-w-3xl text-sm leading-relaxed sm:text-base">{summary}</p>
{rows.length > 0 && (
<dl className="grid grid-cols-1 gap-x-8 gap-y-0 sm:grid-cols-2">
{rows.map((row) => (
<div
key={row.label}
className="flex items-start justify-between gap-4 border-b border-black/8 py-2.5 text-sm"
>
<dt className="shrink-0 font-medium opacity-60">{row.label}</dt>
<dd className="text-right font-semibold">{row.value}</dd>
</div>
))}
</dl>
)}
</div>
</section>
);
}
@@ -0,0 +1,96 @@
import {ArrowUpRight, CalendarCheck, Phone} from 'lucide-react';
import {useSite} from '@/lib/site-context';
import {bookingLinks, bookingRows, channelLabel, sectionName} from '@/lib/derive';
/**
* 예약 안내.
*
* ★ 무엇을 근거로 그리나
* 1) `payload.links` 중 예약을 실제로 받는 확정 채널(야놀자·여기어때·네이버 플레이스).
* 2) 예약 관련 확인 fact(예약 필수 / 예약 방법) — 음식점·관광체험 스키마에 있다.
* 3) `place.phone` — 국내 소규모 사업장에서 전화는 여전히 1순위 예약 창구다.
*
* ★ 예약 링크를 지어내지 않는다
* 관리자 캔버스는 채널 URL 이 안 흘러와서 상호 검색으로 떨어뜨리지만(`bookingHref`),
* 발행본에는 확정된 채널 URL 이 실려 온다. 그러니 여기서는 검색으로 떨어뜨리지 않는다 —
* "예약하기"를 눌렀는데 검색 결과가 뜨면 손님은 예약을 포기한다.
* 근거가 하나도 없으면 섹션째 그리지 않는다.
*/
export function BookingSection() {
const payload = useSite();
const links = bookingLinks(payload);
const rows = bookingRows(payload);
const phone = payload.place.phone;
if (links.length === 0 && rows.length === 0 && !phone) return null;
return (
<section
id="booking"
aria-labelledby="booking-heading"
className="w-full border-b border-black/8 py-16 sm:py-24"
style={{backgroundColor: 'var(--color-surface-alt)'}}
>
<div className="shell">
<p className="mb-2 flex items-center gap-2 text-xs font-semibold uppercase tracking-wider opacity-50">
<CalendarCheck className="size-4" />
<span>Booking</span>
</p>
<h2 id="booking-heading" className="serif mb-2 text-2xl font-bold tracking-tight sm:text-3xl lg:text-4xl">
{sectionName(payload, 'booking', '예약 안내')}
</h2>
<p className="mb-8 max-w-xl text-xs opacity-60 sm:text-sm">
{payload.place.name} 예약은 아래 경로로 받습니다.
</p>
<div
className="max-w-3xl overflow-hidden rounded-2xl border border-black/8"
style={{backgroundColor: 'var(--color-surface)'}}
>
{rows.length > 0 && (
<dl className="divide-y divide-black/5">
{rows.map((row) => (
<div
key={row.label}
className="flex flex-col justify-between gap-1 p-4 sm:flex-row sm:items-start sm:gap-4 sm:p-5"
>
<dt className="shrink-0 text-xs font-bold sm:w-32 sm:text-sm">{row.label}</dt>
<dd className="flex-1 text-left text-xs sm:text-right sm:text-sm">{row.value}</dd>
</div>
))}
</dl>
)}
<div className="flex flex-wrap items-center gap-2 border-t border-black/8 p-4 sm:p-5">
{phone && (
<a
href={`tel:${phone}`}
className="inline-flex items-center gap-1.5 rounded-xl px-4 py-2.5 text-xs font-semibold text-white transition-opacity hover:opacity-90"
style={{backgroundColor: 'var(--color-brand)'}}
>
<Phone className="size-3.5" />
<span>전화 예약 {phone}</span>
</a>
)}
{/* 확정된 채널만 나간다 — 확정 전 URL 은 동명 업소의 예약 페이지일 수 있다. */}
{links.map((link) => (
<a
key={link.url}
href={link.url}
target="_blank"
rel="noopener noreferrer"
className="inline-flex items-center gap-1.5 rounded-xl border border-black/10 px-4 py-2.5 text-xs font-semibold transition-colors hover:bg-black/5"
style={{backgroundColor: 'var(--color-surface-alt)'}}
>
<span>{channelLabel(link)}</span>
<ArrowUpRight className="size-3.5" />
</a>
))}
</div>
</div>
</div>
</section>
);
}
@@ -0,0 +1,83 @@
import {Info} from 'lucide-react';
import {useSite} from '@/lib/site-context';
import {essentialRows} from '@/lib/derive';
import {formatKoreanDate} from '@/lib/format';
/**
* 이용 정보 표 전체.
*
* AnswerBlock 이 상위 6개만 보여준다면 여기는 확인된 것 전부를 낸다.
* ★ "확인 안 된 항목이 N개 있다"를 숨기지 않는다 — 없는 척하면
* 손님이 다른 데서 틀린 값을 찾아 온다. 있다고 말하고 문의로 보낸다.
*/
export function EssentialInfoSection() {
const payload = useSite();
const rows = essentialRows(payload);
const hiddenCount = payload.facts.filter(
(fact) => fact.scope === 'place' && !rows.some((row) => row.label === fact.label),
).length;
if (rows.length === 0) return null;
const half = Math.ceil(rows.length / 2);
return (
<section
id="info"
aria-labelledby="info-heading"
className="w-full border-b border-black/8 py-16 sm:py-24"
style={{backgroundColor: 'var(--color-surface-alt)'}}
>
<div className="shell">
<p className="mb-2 flex items-center gap-2 text-xs font-semibold uppercase tracking-wider opacity-50">
<Info className="size-4" />
<span>Essential Information</span>
</p>
<div className="mb-8 flex flex-col justify-between gap-4 md:flex-row md:items-end">
<div>
<h2 id="info-heading" className="serif text-2xl font-bold tracking-tight sm:text-3xl">
{'이용 및 예약 안내'}
</h2>
<p className="mt-1 text-xs opacity-60 sm:text-sm">
방문 전 확인이 필요한 운영 규정과 시설 안내입니다.
</p>
</div>
</div>
<div
className="overflow-hidden rounded-2xl border border-black/8"
style={{backgroundColor: 'var(--color-surface)'}}
>
<div className="grid grid-cols-1 divide-y divide-black/8 md:grid-cols-2 md:divide-x md:divide-y-0">
{[rows.slice(0, half), rows.slice(half)].map((column, columnIndex) => (
<dl key={columnIndex} className="divide-y divide-black/5">
{column.map((row) => (
<div
key={row.label}
className="flex flex-col justify-between gap-1 p-4 sm:flex-row sm:items-start sm:gap-4 sm:p-5"
>
<dt className="shrink-0 text-xs font-bold sm:w-32 sm:text-sm">{row.label}</dt>
<dd className="flex-1 text-left sm:text-right">
<p className="text-xs font-medium sm:text-sm">{row.value}</p>
{row.note && <p className="mt-0.5 text-[11px] opacity-50">{row.note}</p>}
</dd>
</div>
))}
</dl>
))}
</div>
<div className="flex flex-col items-center justify-between gap-2 border-t border-black/8 px-4 py-3.5 text-xs opacity-60 sm:flex-row sm:px-6">
<span>
{hiddenCount > 0
? `확인 중인 항목 ${hiddenCount}개는 표시하지 않았습니다. 필요하시면 전화로 문의해 주세요.`
: '모든 항목이 사업자 확인을 거쳤습니다.'}
</span>
<span className="font-medium">{formatKoreanDate(payload.site.updatedAt)} 기준</span>
</div>
</div>
</div>
</section>
);
}
@@ -0,0 +1,65 @@
import {Ticket} from 'lucide-react';
import {useSite} from '@/lib/site-context';
import {exhibitionRows, sectionName} from '@/lib/derive';
/**
* 전시 · 관람 안내.
*
* ★ payload 에 없는 것 — 전시 자체
* 에디터의 `exhibition.gallery` 는 전시 사진 + 관람 시간 + 관람료를 그린다. 그런데
* SitePayload 에도, 관광체험 업종 스키마(tour_activity.json)에도 전시 목록(작품·기획전),
* 전시 기간, 관람료(admission) 필드가 없다. 그래서 "○○ 기획전 · 3월 1일까지 · 성인 5,000원"
* 같은 화면은 근거 없이는 못 만든다 — 전시 기간과 관람료는 틀리면 그대로 헛걸음이다.
* (요금은 프로그램 단위 fact(price_adult/price_child)로 들어와 프로그램 섹션이 낸다.)
* 전시 모델이 스키마에 생기면 그때 사진·기간·관람료를 여기에 붙인다.
*
* ★ 지금 그릴 수 있는 것 — 관람 조건에 답하는 확인 fact
* 운영시간 · 회차 시간 · 휴무일 · 연령 제한 · 안내 언어.
* "언제 가면 볼 수 있나"에 답하는 값만 고른다. 한 줄도 없으면 섹션째 그리지 않는다.
*/
export function ExhibitionSection() {
const payload = useSite();
const rows = exhibitionRows(payload);
if (rows.length === 0) return null;
return (
<section
id="exhibition"
aria-labelledby="exhibition-heading"
className="w-full border-b border-black/8 py-16 sm:py-24"
style={{backgroundColor: 'var(--color-surface-alt)'}}
>
<div className="shell">
<p className="mb-2 flex items-center gap-2 text-xs font-semibold uppercase tracking-wider opacity-50">
<Ticket className="size-4" />
<span>Exhibition</span>
</p>
<h2 id="exhibition-heading" className="serif mb-2 text-2xl font-bold tracking-tight sm:text-3xl lg:text-4xl">
{sectionName(payload, 'exhibition', '관람 안내')}
</h2>
<p className="mb-8 max-w-xl text-xs opacity-60 sm:text-sm">
방문 전 관람 조건을 확인해 주세요.
</p>
<div
className="max-w-3xl overflow-hidden rounded-2xl border border-black/8"
style={{backgroundColor: 'var(--color-surface)'}}
>
<dl className="divide-y divide-black/5">
{rows.map((row) => (
<div
key={row.label}
className="flex flex-col justify-between gap-1 p-4 sm:flex-row sm:items-start sm:gap-4 sm:p-5"
>
<dt className="shrink-0 text-xs font-bold sm:w-32 sm:text-sm">{row.label}</dt>
<dd className="flex-1 text-left text-xs sm:text-right sm:text-sm">{row.value}</dd>
</div>
))}
</dl>
</div>
</div>
</section>
);
}
+61
View File
@@ -0,0 +1,61 @@
import {HelpCircle} from 'lucide-react';
import {useSite} from '@/lib/site-context';
import {faqList} from '@/lib/derive';
/**
* FAQ.
*
* ★ <details>/<summary> 로 만든다. 리액트 상태로 접었다 폈다 하면
* 닫힌 답변이 DOM 에 없거나 hidden 이라, 크롤러가 못 읽는 일이 생긴다.
* 네이티브 details 는 닫혀 있어도 내용이 문서에 있고, 검색·AI 가 그대로 읽는다.
* FAQPage 구조화 데이터와 화면 텍스트가 같아야 하는 규칙도 이 방식이라야 지켜진다.
*/
export function FaqSection() {
const payload = useSite();
const faqs = faqList(payload);
if (faqs.length === 0) return null;
return (
<section
id="faq"
aria-labelledby="faq-heading"
className="w-full border-b border-black/8 py-16 sm:py-24"
style={{backgroundColor: 'var(--color-surface-alt)'}}
>
<div className="shell">
<p className="mb-2 flex items-center gap-2 text-xs font-semibold uppercase tracking-wider opacity-50">
<HelpCircle className="size-4" />
<span>FAQ</span>
</p>
<h2 id="faq-heading" className="serif mb-2 text-2xl font-bold tracking-tight sm:text-3xl lg:text-4xl">
{'자주 묻는 질문'}
</h2>
<p className="mb-8 max-w-xl text-xs opacity-60 sm:text-sm">
아래 답변은 모두 사업자가 확인한 내용입니다.
</p>
<div className="max-w-3xl space-y-3">
{faqs.map((faq, index) => (
<details
key={faq.faqId}
// 첫 항목만 펼쳐 둔다 — 나머지도 DOM 에는 그대로 있다.
open={index === 0}
className="overflow-hidden rounded-2xl border border-black/8"
style={{backgroundColor: 'var(--color-surface)'}}
>
<summary className="flex cursor-pointer items-center gap-2.5 p-4 text-xs font-bold marker:content-none sm:p-5 sm:text-sm [&::-webkit-details-marker]:hidden">
<span className="serif shrink-0 opacity-50">Q.</span>
<span>{faq.question}</span>
</summary>
<div className="border-t border-black/5 px-4 pb-4 pt-3 text-xs leading-relaxed opacity-80 sm:px-5 sm:pb-5 sm:text-sm">
{faq.answer}
</div>
</details>
))}
</div>
</div>
</section>
);
}
@@ -0,0 +1,234 @@
import {useCallback, useEffect, useState} from 'react';
import useEmblaCarousel from 'embla-carousel-react';
import {ChevronLeft, ChevronRight, X} from 'lucide-react';
import {useSite} from '@/lib/site-context';
import {galleryImages} from '@/lib/derive';
export function GallerySection() {
const payload = useSite();
const images = galleryImages(payload);
const setting = payload.theme.sections.find((section) => section.id === 'photos');
const variantId = setting?.variantId ?? 'photos.grid';
const [openIndex, setOpenIndex] = useState<number | null>(null);
/**
* ★ 슬라이드를 화면 폭보다 좁게 잡아 **양옆이 보이게** 한다.
* 100% 폭이면 정지 화면에서 사진 한 장과 구분이 안 된다 — 손님은 옆으로 더 있다는 걸
* 모르고 지나간다. 옆 사진이 살짝 걸쳐 보이는 것이 "밀어서 볼 수 있다"는 유일한 신호다.
*/
const [carouselRef, carouselApi] = useEmblaCarousel({loop: true, align: 'center', skipSnaps: false});
const [selected, setSelected] = useState(0);
// 화살표·드래그·키보드 어느 쪽으로 움직여도 인디케이터가 따라오게 한다.
useEffect(() => {
if (!carouselApi) return;
const sync = () => setSelected(carouselApi.selectedScrollSnap());
sync();
carouselApi.on('select', sync);
return () => {
carouselApi.off('select', sync);
};
}, [carouselApi]);
const scrollTo = useCallback((index: number) => carouselApi?.scrollTo(index), [carouselApi]);
if (images.length === 0) return null;
const step = (delta: number) => {
setOpenIndex((current) =>
current === null ? null : (current + delta + images.length) % images.length,
);
};
return (
<section
id="gallery"
aria-labelledby="gallery-heading"
className="w-full border-b border-black/8 py-16 sm:py-24"
>
<div className="shell">
<p className="mb-2 text-xs font-semibold uppercase tracking-wider opacity-50">Gallery</p>
<h2 id="gallery-heading" className="serif mb-8 text-2xl font-bold tracking-tight sm:text-3xl lg:text-4xl">
{setting?.name || '공간 갤러리'}
</h2>
{/* 비전 분석 결과는 검색·접근성 메타데이터로만 사용하고 화면에는 사진만 보인다. */}
{variantId === 'photos.carousel' ? (
<div
className="relative mx-auto max-w-5xl"
role="group"
aria-roledescription="캐러셀"
aria-label={`사진 ${images.length}장`}
// 좌우 키로도 넘길 수 있어야 한다 — 마우스가 없는 사람에게 화살표 버튼만 남기지 않는다.
tabIndex={0}
onKeyDown={(event) => {
if (event.key === 'ArrowLeft') carouselApi?.scrollPrev();
if (event.key === 'ArrowRight') carouselApi?.scrollNext();
}}
>
{/* 양옆 사진이 걸쳐 보이도록 컨테이너 밖으로 넘치는 부분만 잘라낸다. */}
<div ref={carouselRef} className="overflow-hidden">
<ul className="-ml-3 flex touch-pan-y sm:-ml-4">
{images.map((image, index) => (
<li
key={image.mediaId}
className="min-w-0 flex-[0_0_88%] pl-3 sm:flex-[0_0_72%] sm:pl-4"
aria-roledescription="슬라이드"
aria-label={`${index + 1} / ${images.length}`}
>
<GalleryImage
image={image}
onOpen={() => setOpenIndex(index)}
// 지금 보고 있지 않은 사진은 눌러서 흐리게 — 어느 것이 현재인지 눈에 바로 들어온다.
className={`aspect-16/9 rounded-2xl transition-opacity duration-300 ${
index === selected ? 'opacity-100' : 'opacity-45'
}`}
/>
</li>
))}
</ul>
</div>
{images.length > 1 && (
<>
<CarouselButton label="이전 사진" side="left" onClick={() => carouselApi?.scrollPrev()} />
<CarouselButton label="다음 사진" side="right" onClick={() => carouselApi?.scrollNext()} />
{/* 몇 장 중 몇 번째인지. 점만 있으면 사진이 많을 때 셀 수 없다. */}
<div className="mt-4 flex items-center justify-center gap-3">
<ul className="flex items-center gap-1.5">
{images.map((image, index) => (
<li key={image.mediaId}>
<button
type="button"
onClick={() => scrollTo(index)}
aria-label={`${index + 1}번째 사진으로`}
aria-current={index === selected}
className={`h-1.5 rounded-full transition-all ${
index === selected ? 'w-5 bg-black/70' : 'w-1.5 bg-black/20 hover:bg-black/40'
}`}
/>
</li>
))}
</ul>
<span className="text-xs tabular-nums opacity-50">
{selected + 1} / {images.length}
</span>
</div>
</>
)}
</div>
) : variantId === 'photos.masonry' ? (
<ul className="columns-2 gap-2 sm:columns-3 sm:gap-4 [&>li]:mb-2 sm:[&>li]:mb-4">
{images.map((image, index) => (
<li key={image.mediaId} className="break-inside-avoid">
<GalleryImage image={image} onOpen={() => setOpenIndex(index)} className="rounded-xl" free />
</li>
))}
</ul>
) : (
<ul className="grid grid-cols-3 gap-2 sm:gap-4 md:grid-cols-4">
{images.map((image, index) => (
<li key={image.mediaId}>
<GalleryImage image={image} onOpen={() => setOpenIndex(index)} className="aspect-square rounded-xl" />
</li>
))}
</ul>
)}
</div>
{openIndex !== null && (
<div
role="dialog"
aria-modal="true"
aria-label="사진 크게 보기"
className="fixed inset-0 z-50 flex items-center justify-center bg-black/90 p-4 backdrop-blur-md"
onClick={() => setOpenIndex(null)}
>
<button
type="button"
onClick={() => setOpenIndex(null)}
aria-label="닫기"
className="absolute right-4 top-4 z-10 rounded-full bg-white/10 p-2.5 text-white transition-colors hover:bg-white/20"
>
<X className="size-6" />
</button>
<button
type="button"
onClick={(event) => {
event.stopPropagation();
step(-1);
}}
aria-label="이전 사진"
className="absolute left-3 z-10 rounded-full bg-white/10 p-2.5 text-white transition-colors hover:bg-white/20 sm:left-6"
>
<ChevronLeft className="size-6" />
</button>
<button
type="button"
onClick={(event) => {
event.stopPropagation();
step(1);
}}
aria-label="다음 사진"
className="absolute right-3 z-10 rounded-full bg-white/10 p-2.5 text-white transition-colors hover:bg-white/20 sm:right-6"
>
<ChevronRight className="size-6" />
</button>
<div
className="flex max-h-[85vh] max-w-4xl items-center justify-center"
onClick={(event) => event.stopPropagation()}
>
<img
src={images[openIndex].url}
alt={images[openIndex].alt}
className="max-h-[72vh] max-w-full rounded-xl object-contain"
/>
</div>
</div>
)}
</section>
);
}
function GalleryImage({image, onOpen, className, free = false}: {
image: ReturnType<typeof galleryImages>[number];
onOpen: () => void;
className: string;
free?: boolean;
}) {
return (
<button
type="button"
onClick={onOpen}
className={`group relative block w-full cursor-pointer overflow-hidden border border-black/8 ${className}`}
aria-label={`${image.alt} 크게 보기`}
>
<img
src={image.url}
alt={image.alt}
loading="lazy"
decoding="async"
width={image.width}
height={image.height}
className={free ? 'h-auto w-full' : 'size-full object-cover transition-transform duration-500 group-hover:scale-105'}
/>
</button>
);
}
function CarouselButton({label, side, onClick}: {label: string; side: 'left' | 'right'; onClick: () => void}) {
const Icon = side === 'left' ? ChevronLeft : ChevronRight;
return (
<button
type="button"
onClick={onClick}
aria-label={label}
className={`absolute top-1/2 z-10 -translate-y-1/2 rounded-full bg-black/55 p-2.5 text-white backdrop-blur transition-colors hover:bg-black/75 ${side === 'left' ? 'left-3' : 'right-3'}`}
>
<Icon className="size-5" />
</button>
);
}
@@ -0,0 +1,80 @@
import {ArrowRight, MapPin} from 'lucide-react';
import {useSite} from '@/lib/site-context';
import {primaryImage} from '@/seo/meta';
import {unitSpec} from '@/lib/derive';
export function HeroSection() {
const payload = useSite();
const {place, narrative} = payload;
const image = primaryImage(payload);
const spec = unitSpec(payload);
// id="top" — 상단 로고와 하단 탭의 '홈' 이 여기로 돌아온다.
return (
<section
id="top"
className="relative flex min-h-[420px] w-full items-center justify-center overflow-hidden bg-zinc-950 md:min-h-[580px] md:h-[78vh]"
>
{image && (
<div className="absolute inset-0 z-0">
<img
src={image.url}
alt={image.alt}
// 첫 화면 이미지는 지연 로딩하지 않는다 — LCP 가 그만큼 늦어진다.
fetchPriority="high"
decoding="async"
width={image.width}
height={image.height}
className="size-full object-cover object-center"
/>
<div className="absolute inset-0 bg-gradient-to-t from-zinc-950 via-zinc-950/60 to-zinc-950/30" />
</div>
)}
<div className="shell relative z-10 flex flex-col items-center py-16 text-center text-white">
{(place.addressLocality ?? place.addressRegion) && (
<p className="mb-4 inline-flex items-center gap-1.5 rounded-full border border-white/20 bg-white/10 px-3 py-1 text-xs backdrop-blur-md sm:mb-6 sm:text-sm">
<MapPin className="size-3.5" />
<span>{place.addressLocality ?? place.addressRegion}</span>
</p>
)}
{/* h1 은 페이지에 하나. 가게 이름이 들어가야 "○○ 홈페이지" 질의에 잡힌다. */}
<h1 className="serif mb-4 text-2xl font-medium leading-tight tracking-tight sm:text-4xl md:text-5xl lg:text-6xl">
{narrative.heroHeadline ? (
<>
<span className="block">{narrative.heroHeadline}</span>
<span className="mt-1 block font-semibold">{place.name}</span>
</>
) : (
place.name
)}
</h1>
{(narrative.tagline ?? narrative.heroSubline) && (
<p className="mb-8 max-w-2xl text-xs font-light leading-relaxed text-white/80 sm:text-base md:text-lg">
{narrative.tagline ?? narrative.heroSubline}
</p>
)}
<div className="flex w-full flex-col items-center gap-3 sm:w-auto sm:flex-row">
{payload.units.length > 0 && (
<a
href="#units"
className="flex w-full items-center justify-center gap-2 rounded-xl bg-white px-6 py-3 text-xs font-medium text-zinc-950 transition-all hover:bg-white/90 sm:w-auto sm:text-sm"
>
<span>{spec.label} 둘러보기</span>
<ArrowRight className="size-4" />
</a>
)}
<a
href="#info"
className="flex w-full items-center justify-center gap-2 rounded-xl border border-white/30 bg-white/15 px-6 py-3 text-xs font-medium backdrop-blur-md transition-all hover:bg-white/25 sm:w-auto sm:text-sm"
>
<span>이용 정보 보기</span>
</a>
</div>
</div>
</section>
);
}
@@ -0,0 +1,98 @@
import {ArrowUpRight, Mail, MessageCircle, Phone} from 'lucide-react';
import {useSite} from '@/lib/site-context';
import {channelLabel, contactLinks, sectionName} from '@/lib/derive';
/**
* 문의 · 연락.
*
* ★ 무엇을 근거로 그리나
* `place.phone` · `place.email` · 확정된 연락 채널(네이버 플레이스·인스타그램)뿐이다.
* 하나도 없으면 섹션째 그리지 않는다.
*
* ★ 문의 양식(폼)은 만들지 않는다
* 에디터에는 `inquiry.form` 배리에이션이 있지만, 발행 사이트는 정적 HTML 이라
* 제출을 받을 곳이 없다. 눌러도 아무 데도 도착하지 않는 [문의 보내기] 버튼은
* 연락처가 없는 것보다 나쁘다 — 손님은 문의를 남겼다고 믿고 답을 기다린다.
* 접수 엔드포인트가 생기기 전까지는 "바로 연락되는 창구"만 낸다.
*/
export function InquirySection() {
const payload = useSite();
const {place} = payload;
const links = contactLinks(payload);
if (!place.phone && !place.email && links.length === 0) return null;
return (
<section
id="inquiry"
aria-labelledby="inquiry-heading"
className="w-full border-b border-black/8 py-16 sm:py-24"
>
<div className="shell">
<p className="mb-2 flex items-center gap-2 text-xs font-semibold uppercase tracking-wider opacity-50">
<MessageCircle className="size-4" />
<span>Contact</span>
</p>
<h2 id="inquiry-heading" className="serif mb-2 text-2xl font-bold tracking-tight sm:text-3xl lg:text-4xl">
{sectionName(payload, 'inquiry', '문의 안내')}
</h2>
<p className="mb-8 max-w-xl text-xs opacity-60 sm:text-sm">
궁금한 점은 아래로 연락 주시면 {place.name}에서 직접 안내해 드립니다.
</p>
<ul
className="max-w-3xl divide-y divide-black/5 overflow-hidden rounded-2xl border border-black/8"
style={{backgroundColor: 'var(--color-surface-alt)'}}
>
{place.phone && (
<li>
<a
href={`tel:${place.phone}`}
className="flex items-center justify-between gap-3 p-4 transition-colors hover:bg-black/[0.02] sm:p-5"
>
<span className="flex items-center gap-2.5">
<Phone className="size-4 shrink-0 opacity-50" />
<span className="text-xs font-bold sm:text-sm">전화</span>
</span>
<span className="text-xs font-semibold sm:text-sm">{place.phone}</span>
</a>
</li>
)}
{place.email && (
<li>
<a
href={`mailto:${place.email}`}
className="flex items-center justify-between gap-3 p-4 transition-colors hover:bg-black/[0.02] sm:p-5"
>
<span className="flex items-center gap-2.5">
<Mail className="size-4 shrink-0 opacity-50" />
<span className="text-xs font-bold sm:text-sm">이메일</span>
</span>
<span className="break-all text-xs font-semibold sm:text-sm">{place.email}</span>
</a>
</li>
)}
{links.map((link) => (
<li key={link.url}>
<a
href={link.url}
target="_blank"
rel="noopener noreferrer"
className="flex items-center justify-between gap-3 p-4 transition-colors hover:bg-black/[0.02] sm:p-5"
>
<span className="flex items-center gap-2.5">
<MessageCircle className="size-4 shrink-0 opacity-50" />
<span className="text-xs font-bold sm:text-sm">{channelLabel(link)}</span>
</span>
<ArrowUpRight className="size-4 shrink-0 opacity-40" />
</a>
</li>
))}
</ul>
</div>
</section>
);
}
@@ -0,0 +1,145 @@
import {ArrowUpRight, Calendar, MapPin, Utensils} from 'lucide-react';
import type {LocalPlace} from '@o2o/shared';
import {useSite} from '@/lib/site-context';
import {formatKoreanDate, naverSearchUrl} from '@/lib/format';
/**
* 주변 정보.
*
* "○○ 근처 숙소" 같은 지역 질의에 걸리려면 지역 고유명사가 본문에 있어야 한다.
* ★ 우리가 남의 가게 URL 을 지어내지 않는다 — 검색 링크로만 보낸다.
* 틀린 링크는 사용자를 엉뚱한 데로 보내고, 그 책임은 이 홈페이지가 진다.
*/
export function LocalGuideSection() {
const payload = useSite();
const {local} = payload;
const hasAnything =
local.restaurants.length > 0 || local.attractions.length > 0 || local.festivals.length > 0;
if (!hasAnything) return null;
return (
<section
id="guide"
aria-labelledby="guide-heading"
className="w-full border-b border-black/8 py-12 sm:py-20"
style={{backgroundColor: 'var(--color-surface-alt)'}}
>
<div className="shell max-w-[880px]">
<div className="mb-8 flex flex-col justify-between gap-2 border-b border-black/8 pb-4 sm:flex-row sm:items-baseline">
<div>
<h2 id="guide-heading" className="serif text-2xl font-bold tracking-tight sm:text-3xl">
{'주변 안내'}
</h2>
<p className="mt-1 text-xs opacity-60 sm:text-sm">
{payload.place.addressLocality ?? '주변'} 지역의 맛집 · 명소 · 행사 안내입니다.
</p>
</div>
{local.syncedAt && (
<p className="self-start text-[11px] opacity-50 sm:self-auto">
{formatKoreanDate(local.syncedAt)} 갱신
</p>
)}
</div>
{local.restaurants.length > 0 && (
<PlaceList title="주변 맛집" icon={Utensils} places={local.restaurants} />
)}
{local.attractions.length > 0 && (
<PlaceList title="주변 명소" icon={MapPin} places={local.attractions} />
)}
{local.festivals.length > 0 && (
<div className="space-y-4">
<h3 className="serif flex items-center gap-2 text-base font-bold sm:text-lg">
<Calendar className="size-4 opacity-50" />
<span>지역 행사</span>
</h3>
<ul
className="divide-y divide-black/5 overflow-hidden rounded-xl border border-black/8"
style={{backgroundColor: 'var(--color-surface)'}}
>
{local.festivals.map((festival) => (
<li key={festival.name} className="flex items-center justify-between gap-3 p-4">
<div className="min-w-0 space-y-0.5">
<div className="flex items-center gap-2">
<span className="rounded bg-black/5 px-1.5 py-0.5 text-[11px] font-bold">
{festival.month}
</span>
<h4 className="truncate text-xs font-bold sm:text-sm">{festival.name}</h4>
</div>
<p className="text-xs opacity-60">
{festival.description ?? festival.period}
</p>
</div>
<a
href={festival.officialUrl ?? naverSearchUrl(festival.searchQuery)}
target="_blank"
rel="noopener noreferrer nofollow"
className="shrink-0 rounded-lg border border-black/10 px-3 py-1.5 text-xs font-medium transition-colors hover:bg-black/5"
>
자세히
</a>
</li>
))}
</ul>
</div>
)}
</div>
</section>
);
}
function PlaceList({
title,
icon: Icon,
places,
}: {
title: string;
icon: typeof MapPin;
places: LocalPlace[];
}) {
return (
<div className="mb-8 space-y-4">
<h3 className="serif flex items-center gap-2 text-base font-bold sm:text-lg">
<Icon className="size-4 opacity-50" />
<span>{title}</span>
</h3>
<ul
className="divide-y divide-black/5 overflow-hidden rounded-xl border border-black/8"
style={{backgroundColor: 'var(--color-surface)'}}
>
{places.map((place) => (
<li key={place.name}>
<a
href={naverSearchUrl(place.searchQuery)}
target="_blank"
rel="noopener noreferrer nofollow"
className="group flex items-center justify-between gap-3 p-4 transition-colors hover:bg-black/[0.02]"
>
<div className="min-w-0 space-y-0.5 pr-3">
<div className="flex items-center gap-2">
<span className="truncate text-xs font-bold sm:text-sm">{place.name}</span>
{(place.distanceText ?? place.durationText) && (
<span className="shrink-0 font-mono text-[10px] opacity-50">
{place.distanceText ?? place.durationText}
</span>
)}
</div>
{place.description && (
<p className="truncate text-xs opacity-60">{place.description}</p>
)}
</div>
<span className="flex shrink-0 items-center gap-0.5 text-xs opacity-40 transition-opacity group-hover:opacity-80">
<span>검색</span>
<ArrowUpRight className="size-3.5" />
</span>
</a>
</li>
))}
</ul>
</div>
);
}
@@ -0,0 +1,166 @@
import {useState} from 'react';
import {Car, Check, Copy, MapPin, Navigation} from 'lucide-react';
import {useSite} from '@/lib/site-context';
import {kakaoDirectionsUrl, naverDirectionsUrl, osmEmbedUrl} from '@/lib/format';
export function LocationSection() {
const payload = useSite();
const {place, routes} = payload;
const [copied, setCopied] = useState(false);
const address = place.roadAddress ?? place.address;
if (!address) return null;
// 좌표가 있어야 지도도 길찾기도 정확해진다. 없으면 지도를 그리지 않고,
// 버튼은 검색으로 떨어진다(format.ts) — 틀린 핀을 찍느니 안 찍는다.
const {latitude: lat, longitude: lng} = place;
const hasGeo = lat != null && lng != null;
const handleCopy = async () => {
try {
await navigator.clipboard.writeText(address);
setCopied(true);
setTimeout(() => setCopied(false), 2000);
} catch {
// 클립보드 권한이 없으면 조용히 넘어간다 — 주소는 화면에 그대로 있다.
}
};
return (
<section
id="location"
aria-labelledby="location-heading"
className="w-full border-b border-black/8 py-16 sm:py-24"
>
<div className="shell">
<p className="mb-2 flex items-center gap-2 text-xs font-semibold uppercase tracking-wider opacity-50">
<MapPin className="size-4" />
<span>Location</span>
</p>
<h2 id="location-heading" className="serif mb-2 text-2xl font-bold tracking-tight sm:text-3xl lg:text-4xl">
{'오시는 길'}
</h2>
<p className="mb-8 max-w-xl text-xs opacity-60 sm:text-sm">
주소와 주요 거점까지의 이동 시간을 안내합니다.
</p>
{hasGeo && (
<div className="mb-6 overflow-hidden rounded-2xl border border-black/8">
{/* ★ loading="lazy" — 지도는 접힌 화면 아래에 있는 경우가 많고, 첫 화면 속도를
남의 서버 응답에 맡기지 않는다. title 은 스크린리더가 읽을 유일한 설명이다. */}
<iframe
title={`${place.name} 위치 지도`}
src={osmEmbedUrl(lat, lng)}
loading="lazy"
referrerPolicy="no-referrer-when-downgrade"
className="block aspect-[16/9] w-full border-0"
/>
</div>
)}
<div
className="mb-8 rounded-2xl border border-black/8 p-5 sm:p-6"
style={{backgroundColor: 'var(--color-surface-alt)'}}
>
<div className="flex flex-col justify-between gap-4 md:flex-row md:items-center">
<div className="space-y-1">
<p className="text-[11px] font-bold uppercase tracking-wide opacity-50">주소</p>
<div className="flex flex-wrap items-center gap-2">
{/* address 태그로 감싼다 — 기계가 "이게 이 업소의 주소"임을 안다. */}
<address className="text-base font-bold not-italic sm:text-lg">{address}</address>
<button
type="button"
onClick={handleCopy}
title="주소 복사"
className="inline-flex items-center gap-1 rounded-lg border border-black/10 px-2.5 py-1 text-xs font-medium transition-colors hover:bg-black/5"
style={{backgroundColor: 'var(--color-surface)'}}
>
{copied ? <Check className="size-3.5" /> : <Copy className="size-3.5" />}
<span>{copied ? '복사완료' : '복사'}</span>
</button>
</div>
{place.phone && (
<p className="text-xs opacity-60">
문의: <a href={`tel:${place.phone}`} className="underline-offset-2 hover:underline">{place.phone}</a>
</p>
)}
</div>
<div className="flex items-center gap-2">
<a
href={naverDirectionsUrl(place.name, lat, lng)}
target="_blank"
rel="noopener noreferrer nofollow"
className="flex items-center gap-1.5 rounded-xl bg-emerald-600 px-4 py-2.5 text-xs font-semibold text-white transition-opacity hover:opacity-90"
>
<Navigation className="size-3.5" />
<span>네이버 길찾기</span>
</a>
<a
href={kakaoDirectionsUrl(place.name, lat, lng)}
target="_blank"
rel="noopener noreferrer nofollow"
className="flex items-center gap-1.5 rounded-xl bg-amber-400 px-4 py-2.5 text-xs font-semibold text-zinc-950 transition-opacity hover:opacity-90"
>
<Navigation className="size-3.5" />
<span>카카오 길찾기</span>
</a>
</div>
</div>
</div>
{routes.length > 0 && (
<div>
<h3 className="mb-3 flex items-center gap-2 text-sm font-bold sm:text-base">
<Car className="size-4 opacity-60" />
<span>주요 거점 소요시간</span>
</h3>
<div
className="overflow-hidden rounded-2xl border border-black/8"
style={{backgroundColor: 'var(--color-surface)'}}
>
<div className="overflow-x-auto">
<table className="w-full text-left text-xs sm:text-sm">
<caption className="sr-only">
{payload.place.name}에서 주요 거점까지의 이동 시간
</caption>
<thead
className="border-b border-black/8 font-semibold"
style={{backgroundColor: 'var(--color-surface-alt)'}}
>
<tr>
<th scope="col" className="p-3.5 sm:p-4">목적지</th>
<th scope="col" className="p-3.5 sm:p-4">차량</th>
<th scope="col" className="p-3.5 sm:p-4">도보 / 대중교통</th>
<th scope="col" className="hidden p-3.5 sm:table-cell sm:p-4">거리</th>
<th scope="col" className="hidden p-3.5 md:table-cell sm:p-4">비고</th>
</tr>
</thead>
<tbody className="divide-y divide-black/5">
{routes.map((route) => (
<tr key={route.destination}>
<th scope="row" className="p-3.5 text-left font-bold sm:p-4">
{route.destination}
</th>
<td className="p-3.5 font-semibold sm:p-4">{route.byCar ?? '—'}</td>
<td className="p-3.5 opacity-70 sm:p-4">{route.byTransit ?? '—'}</td>
<td className="hidden p-3.5 font-mono opacity-50 sm:table-cell sm:p-4">
{route.distanceText ?? '—'}
</td>
<td className="hidden p-3.5 text-xs opacity-50 md:table-cell sm:p-4">
{route.note ?? ''}
</td>
</tr>
))}
</tbody>
</table>
</div>
</div>
</div>
)}
</div>
</section>
);
}
@@ -0,0 +1,50 @@
import {Home, Image as ImageIcon, MapPin, Sparkles} from 'lucide-react';
import {useSite} from '@/lib/site-context';
import {isSectionEnabled, unitSpec} from '@/lib/derive';
import {useActiveSection} from '@/lib/use-active-section';
/**
* 모바일 하단 탭.
*
* ★ 사이트가 한 장이 되면서 이게 사실상 유일한 내비게이션이 됐다. 그래서 활성 표시를
* 버리지 않고 스크롤 위치로 다시 계산한다(useActiveSection) — 예전에는 라우터의
* 현재 경로로 알았다.
*
* ★ 없는 섹션으로는 보내지 않는다. 앵커는 대상이 없으면 아무 일도 일어나지 않는데,
* 눌러도 반응이 없는 탭은 고장으로 읽힌다.
*/
export function MobileTabBar() {
const payload = useSite();
const spec = unitSpec(payload);
const tabs = [
{id: 'top', label: '홈', icon: Home},
...(payload.units.length > 0 ? [{id: 'units', label: spec.label, icon: ImageIcon}] : []),
...(isSectionEnabled(payload, 'local') ? [{id: 'guide', label: '주변', icon: Sparkles}] : []),
{id: 'location', label: '위치', icon: MapPin},
];
const active = useActiveSection(tabs.map((tab) => tab.id));
return (
<nav
aria-label="하단 내비게이션"
className="safe-b fixed inset-x-0 bottom-0 z-50 flex items-center justify-around border-t border-black/8 px-3 py-2 backdrop-blur-md md:hidden"
style={{backgroundColor: 'color-mix(in srgb, var(--color-surface) 94%, transparent)'}}
>
{tabs.map(({id, label, icon: Icon}) => (
<a
key={id}
href={`#${id}`}
aria-current={active === id ? 'true' : undefined}
className={`flex flex-1 flex-col items-center justify-center py-1 transition-opacity ${
active === id ? 'font-bold opacity-100' : 'font-medium opacity-55'
}`}
>
<Icon className="size-5" />
<span className="mt-0.5 text-[10px] tracking-tight">{label}</span>
</a>
))}
</nav>
);
}
@@ -0,0 +1,64 @@
import {ShieldCheck} from 'lucide-react';
import {useSite} from '@/lib/site-context';
import {ruleRows, sectionName} from '@/lib/derive';
import {formatKoreanDate} from '@/lib/format';
/**
* 이용 규정.
*
* ★ 왜 별도 섹션인가
* 이용 정보(info) 표에도 같은 fact 가 들어가지만, 거기서는 와이파이·주차와 같은 무게로
* 섞인다. 취소·환불 규정과 입실 수칙은 "몰랐다"가 곧 클레임이 되는 항목이라
* 사장님이 따로 세워 둘 수 있어야 한다. 실제로 이 섹션이 발행본에 없던 동안,
* 에디터에서 켜 둔 환불 규정이 payload 까지 실려 오고도 화면에서 말없이 사라졌다.
*
* ★ 규정을 지어내지 않는다
* 확인된 fact(RULE_FACT_KEYS)만 줄이 된다. 한 줄도 없으면 섹션째 그리지 않는다 —
* "규정 없음"으로 읽히는 빈 껍데기가 가장 위험하다.
*/
export function RulesSection() {
const payload = useSite();
const rows = ruleRows(payload);
if (rows.length === 0) return null;
return (
<section
id="rules"
aria-labelledby="rules-heading"
className="w-full border-b border-black/8 py-16 sm:py-24"
>
<div className="shell">
<p className="mb-2 flex items-center gap-2 text-xs font-semibold uppercase tracking-wider opacity-50">
<ShieldCheck className="size-4" />
<span>House Rules</span>
</p>
<h2 id="rules-heading" className="serif mb-2 text-2xl font-bold tracking-tight sm:text-3xl lg:text-4xl">
{sectionName(payload, 'rules', '이용 규정')}
</h2>
<p className="mb-8 max-w-xl text-xs opacity-60 sm:text-sm">
예약 전에 꼭 확인해 주세요. 아래 내용은 모두 사업자가 확인한 규정입니다.
</p>
{/* dl 로 둔다 — 규정 이름과 내용의 짝이 마크업에 드러나야 AI 검색이 그대로 인용한다. */}
<dl className="grid max-w-4xl grid-cols-1 gap-3 sm:grid-cols-2">
{rows.map((row) => (
<div
key={row.label}
className="rounded-2xl border border-black/8 p-4 sm:p-5"
style={{backgroundColor: 'var(--color-surface-alt)'}}
>
<dt className="mb-1 text-xs font-bold sm:text-sm">{row.label}</dt>
<dd className="text-xs leading-relaxed opacity-80 sm:text-sm">{row.value}</dd>
</div>
))}
</dl>
<p className="mt-4 text-xs opacity-50">
{formatKoreanDate(payload.site.updatedAt)} 기준
</p>
</div>
</section>
);
}
+94
View File
@@ -0,0 +1,94 @@
import {ExternalLink, Mail, MapPin, Phone} from 'lucide-react';
import {useSite} from '@/lib/site-context';
import {formatKoreanDate} from '@/lib/format';
// 채널 이름표는 예약·문의 섹션과 같은 표를 쓴다 — 같은 채널이 자리마다 다른 이름으로 뜨면 안 된다.
import {channelLabel} from '@/lib/derive';
export function SiteFooter() {
const payload = useSite();
const {place, site} = payload;
// 확정된 채널만 — 확정 전 URL 은 동명 업소일 수 있다.
const links = payload.links.filter((link) => link.confirmed);
const address = place.roadAddress ?? place.address;
return (
<footer className="w-full bg-zinc-950 pb-24 pt-12 text-zinc-400 md:pb-14">
<div className="shell">
<div className="grid grid-cols-1 gap-8 border-b border-white/10 pb-10 md:grid-cols-12">
<div className="space-y-3 md:col-span-6">
<p className="serif text-lg font-bold tracking-tight text-white">{place.name}</p>
<div className="space-y-1.5 text-xs font-light">
{address && (
<p className="flex items-start gap-1.5">
<MapPin className="mt-0.5 size-3.5 shrink-0 opacity-60" />
<span>{address}</span>
</p>
)}
{place.phone && (
<p className="flex items-center gap-1.5">
<Phone className="size-3.5 shrink-0 opacity-60" />
<a href={`tel:${place.phone}`} className="hover:text-white">
{place.phone}
</a>
</p>
)}
{place.email && (
<p className="flex items-center gap-1.5">
<Mail className="size-3.5 shrink-0 opacity-60" />
<a href={`mailto:${place.email}`} className="hover:text-white">
{place.email}
</a>
</p>
)}
</div>
</div>
{links.length > 0 && (
<nav aria-label="공식 채널" className="md:col-span-6 md:justify-self-end">
<h2 className="mb-3 text-xs font-bold uppercase tracking-wider text-zinc-200">
공식 채널
</h2>
<ul className="space-y-2 text-xs">
{links.map((link) => (
<li key={link.url}>
<a
href={link.url}
target="_blank"
rel="noopener noreferrer"
className="inline-flex items-center gap-1 transition-colors hover:text-white"
>
<span>{channelLabel(link)}</span>
<ExternalLink className="size-3" />
</a>
</li>
))}
</ul>
</nav>
)}
</div>
<div className="flex flex-col items-center justify-between gap-3 pt-6 text-[11px] text-zinc-500 sm:flex-row">
<div className="flex flex-wrap items-center gap-x-3 gap-y-1 text-center sm:text-left">
<span>상호: {place.name}</span>
{place.legal?.representative && <span>대표: {place.legal.representative}</span>}
{place.legal?.businessRegistrationNumber && (
<span>사업자등록번호: {place.legal.businessRegistrationNumber}</span>
)}
{place.legal?.mailOrderNumber && (
<span>통신판매업신고: {place.legal.mailOrderNumber}</span>
)}
{place.legal?.licenseNumber && (
<span>
{place.legal.licenseLabel ?? '인허가번호'}: {place.legal.licenseNumber}
</span>
)}
</div>
{/* 마지막 갱신을 화면에도 적는다 — 사람도 AI 도 신선도를 여기서 본다. */}
<p>최종 갱신 {formatKoreanDate(site.updatedAt)}</p>
</div>
</div>
</footer>
);
}
+76
View File
@@ -0,0 +1,76 @@
import {Phone} from 'lucide-react';
import {useSite} from '@/lib/site-context';
import {isSectionEnabled, unitSpec} from '@/lib/derive';
/**
* 상단 내비.
*
* ★ 메뉴를 <nav> + <a> 로 그대로 둔다. 자바스크립트로 만드는 메뉴는
* 크롤러가 링크 그래프를 못 읽는다.
*
* ★ 사이트가 한 장이라 전부 앵커다. 예전에는 페이지 이동이 섞여 있어서
* 라우터의 basename 을 타야 했는데(`<a href="/guide">` 는 호스트 루트로 가서 404),
* 앵커만 남으니 그 문제가 없다.
*/
export function SiteHeader() {
const payload = useSite();
const spec = unitSpec(payload);
const items = [
{label: '소개', href: '#about', show: isSectionEnabled(payload, 'intro')},
{label: spec.label, href: '#units', show: payload.units.length > 0},
{label: '주변 정보', href: '#guide', show: isSectionEnabled(payload, 'local')},
{label: '오시는 길', href: '#location', show: true},
{label: 'FAQ', href: '#faq', show: payload.faqs.length > 0},
].filter((item) => item.show);
return (
<header className="sticky top-0 z-40 w-full border-b border-black/8 bg-[color-mix(in_srgb,var(--color-surface)_92%,transparent)] backdrop-blur-md">
<div className="shell flex h-16 items-center justify-between">
<a href="#top" className="flex min-w-0 items-center gap-2">
<span
className="serif flex size-7 shrink-0 items-center justify-center rounded-lg text-sm font-semibold text-white"
style={{backgroundColor: 'var(--color-brand)'}}
aria-hidden
>
{payload.place.name.slice(0, 1)}
</span>
<span className="flex min-w-0 flex-col">
<span className="serif truncate text-base font-bold leading-none tracking-tight sm:text-lg">
{payload.place.name}
</span>
{payload.place.englishName && (
<span className="mt-0.5 truncate text-[10px] uppercase leading-tight tracking-wider opacity-50">
{payload.place.englishName}
</span>
)}
</span>
</a>
<nav aria-label="주요 메뉴" className="hidden items-center gap-6 md:flex">
{items.map((item) => (
<a
key={item.label}
href={item.href}
className="py-1 text-sm font-medium opacity-70 transition-opacity hover:opacity-100"
>
{item.label}
</a>
))}
</nav>
{payload.place.phone && (
<a
href={`tel:${payload.place.phone}`}
className="flex items-center gap-1.5 rounded-xl px-3 py-2 text-xs font-semibold text-white transition-opacity hover:opacity-90"
style={{backgroundColor: 'var(--color-brand)'}}
>
<Phone className="size-3.5" />
<span className="hidden sm:inline">{payload.place.phone}</span>
<span className="sm:hidden">전화</span>
</a>
)}
</div>
</header>
);
}
@@ -0,0 +1,61 @@
import {Armchair} from 'lucide-react';
import {useSite} from '@/lib/site-context';
import {sectionName, spaceRows} from '@/lib/derive';
/**
* 공간 안내.
*
* ★ payload 에 없는 것 — 구역(zone) 모델
* 에디터의 기본 배리에이션 `space.zones` 는 "1층 창가석 / 루프탑" 처럼 자리별 카드를
* 그린다. 그러려면 구역 이름 · 구역 설명 · 구역별 사진이라는 데이터가 있어야 하는데,
* SitePayload 에는 그런 필드가 없다. `media.category`("좌석", "테라스", "음료" …)가
* 비슷해 보이지만 그건 사진 분류이지 좌석 구역이 아니다 — 그걸 구역 이름으로 쓰면
* "음료"라는 이름의 자리가 생긴다. 그래서 사진 구역 카드는 그리지 않는다.
* 백엔드에 구역 모델이 생기면 그때 여기에 붙인다.
*
* ★ 지금 그릴 수 있는 것 — 공간을 설명하는 확인 fact
* 좌석 수 · 테라스 · 룸/별실 · 단체석 최대 인원 · 콘센트 · 장시간 이용 · 휠체어 접근.
* "자리가 어떻게 생겼고 얼마나 앉을 수 있나"에 답하는 값만 고른다.
* 한 줄도 없으면 섹션째 그리지 않는다.
*/
export function SpaceSection() {
const payload = useSite();
const rows = spaceRows(payload);
if (rows.length === 0) return null;
return (
<section
id="space"
aria-labelledby="space-heading"
className="w-full border-b border-black/8 py-16 sm:py-24"
>
<div className="shell">
<p className="mb-2 flex items-center gap-2 text-xs font-semibold uppercase tracking-wider opacity-50">
<Armchair className="size-4" />
<span>Space</span>
</p>
<h2 id="space-heading" className="serif mb-2 text-2xl font-bold tracking-tight sm:text-3xl lg:text-4xl">
{sectionName(payload, 'space', '공간 안내')}
</h2>
<p className="mb-8 max-w-xl text-xs opacity-60 sm:text-sm">
좌석과 이용 환경 안내입니다.
</p>
<dl className="grid max-w-4xl grid-cols-1 gap-3 sm:grid-cols-2 lg:grid-cols-3">
{rows.map((row) => (
<div
key={row.label}
className="rounded-2xl border border-black/8 p-4 sm:p-5"
style={{backgroundColor: 'var(--color-surface-alt)'}}
>
<dt className="mb-1 text-xs font-medium opacity-60">{row.label}</dt>
<dd className="text-sm font-bold sm:text-base">{row.value}</dd>
</div>
))}
</dl>
</div>
</section>
);
}
+160
View File
@@ -0,0 +1,160 @@
import {ChevronDown, Phone} from 'lucide-react';
import {useSite} from '@/lib/site-context';
import {sectionName, unitSpec, unitViews} from '@/lib/derive';
/**
* 객실 · 메뉴 · 프로그램 — 업종에 따라 이름만 달라진다.
*
* ★ 예전에는 카드가 상세 **페이지**로 넘어갔다. 사이트를 한 장으로 합치면서
* 그 페이지의 내용(이용 정보 표 · 사진 전체 · 전화 문의)을 카드 안으로 들여왔다.
* 빼고 합쳤으면 확인된 fact 가 화면에서 사라지고, JSON-LD 에는 남아 있어
* 발행 게이트(화면 ↔ 구조화 데이터 대조)에 걸린다.
*
* ★ 펼침은 <details> 다. 자바스크립트 없이 동작하고, 크롤러는 접힌 내용도 읽는다 —
* 조건부 렌더로 감추면 HTML 에 아예 없어서 AI 가 못 본다.
*/
export function UnitsSection() {
const payload = useSite();
const spec = unitSpec(payload);
const units = unitViews(payload);
if (units.length === 0) return null;
return (
<section
id="units"
aria-labelledby="units-heading"
className="w-full border-b border-black/8 py-16 sm:py-24"
>
<div className="shell">
<div className="mb-10 flex flex-col justify-between gap-4 sm:flex-row sm:items-end">
<div>
<p className="mb-2 text-xs font-semibold uppercase tracking-wider opacity-50">
{spec.label}
</p>
{/* 섹션 id 는 업종마다 다르다(rooms · menu · programs) — spec.path 가 그 id 다.
사장님이 이름을 안 바꿨으면 지금까지 쓰던 "객실 3개 안내" 꼴로 떨어진다. */}
<h2 id="units-heading" className="serif text-2xl font-bold tracking-tight sm:text-3xl lg:text-4xl">
{sectionName(payload, spec.path, `${spec.label} ${units.length}개 안내`)}
</h2>
</div>
</div>
<ul className="grid grid-cols-1 gap-4 sm:grid-cols-2 sm:gap-6 lg:gap-8">
{units.map((unit) => (
<li
key={unit.unitId}
className="flex flex-col justify-between overflow-hidden rounded-2xl border border-black/8"
style={{backgroundColor: 'var(--color-surface-alt)'}}
>
<div>
{unit.images[0] && (
<div className="relative aspect-16/10 overflow-hidden sm:aspect-16/9">
<img
src={unit.images[0].url}
alt={unit.images[0].alt}
loading="lazy"
decoding="async"
className="size-full object-cover"
/>
{unit.priceText && (
<span
className="absolute bottom-3 right-3 rounded-lg px-2.5 py-1 text-xs font-bold"
style={{
backgroundColor: 'var(--color-surface)',
color: 'var(--color-ink)',
}}
>
{unit.priceText}
</span>
)}
</div>
)}
<div className="space-y-3 p-4 sm:space-y-4 sm:p-6">
<h3 className="serif text-base font-bold leading-snug sm:text-xl">
{unit.name}
</h3>
{unit.chips.length > 0 && (
<ul className="flex flex-wrap items-center gap-1.5 sm:gap-2">
{unit.chips.map((chip) => (
<li
key={chip.label}
className="rounded-lg border border-black/8 px-2.5 py-1 text-xs"
style={{backgroundColor: 'var(--color-surface)'}}
>
<span className="opacity-50">{chip.label} </span>
<span className="font-medium">{chip.value}</span>
</li>
))}
</ul>
)}
{unit.intro && (
<p className="text-xs leading-relaxed opacity-70">{unit.intro}</p>
)}
</div>
</div>
{(unit.rows.length > 0 || unit.images.length > 1) && (
<details className="group border-t border-black/8">
<summary className="flex cursor-pointer list-none items-center justify-between gap-2 p-4 text-xs font-semibold sm:p-6">
<span>{unit.name} 자세히</span>
<ChevronDown className="size-4 transition-transform group-open:rotate-180" />
</summary>
<div className="space-y-5 px-4 pb-4 sm:px-6 sm:pb-6">
{unit.rows.length > 0 && (
<dl className="divide-y divide-black/5 border-t border-black/8">
{unit.rows.map((row) => (
<div
key={row.label}
className="flex items-start justify-between gap-4 py-2 text-xs"
>
<dt className="shrink-0 opacity-55">{row.label}</dt>
<dd className="text-right font-semibold">{row.value}</dd>
</div>
))}
</dl>
)}
{unit.images.length > 1 && (
<ul className="grid grid-cols-2 gap-2">
{unit.images.slice(1).map((image) => (
<li
key={image.mediaId}
className="relative aspect-16/10 overflow-hidden rounded-xl"
>
<img
src={image.url}
alt={image.alt}
loading="lazy"
decoding="async"
className="size-full object-cover"
/>
</li>
))}
</ul>
)}
{payload.place.phone && (
<a
href={`tel:${payload.place.phone}`}
className="flex w-full items-center justify-center gap-1.5 rounded-xl px-3 py-2.5 text-xs font-semibold text-white transition-opacity hover:opacity-90"
style={{backgroundColor: 'var(--color-brand)'}}
>
<Phone className="size-3.5" />
<span>{payload.place.phone} 문의</span>
</a>
)}
</div>
</details>
)}
</li>
))}
</ul>
</div>
</section>
);
}
@@ -0,0 +1,47 @@
import {Cloud} from 'lucide-react';
import {useSite} from '@/lib/site-context';
import {useLiveWeather} from '@/lib/use-live-weather';
/** 프리렌더 스냅샷으로 시작해 하이드레이션 후 최신 캐시로 갱신되는 독립 날씨 섹션. */
export function WeatherSection() {
const payload = useSite();
const weather = useLiveWeather({
initial: payload.local.weather,
regionCode: payload.place.regionCode,
latitude: payload.place.latitude,
longitude: payload.place.longitude,
});
if (!weather) return null;
return (
<section
id="weather"
aria-labelledby="weather-heading"
className="w-full border-b border-black/8 py-10 sm:py-14"
style={{backgroundColor: 'var(--color-surface-alt)'}}
>
<div className="shell max-w-[880px]">
<h2 id="weather-heading" className="serif mb-4 text-xl font-bold tracking-tight sm:text-2xl">
오늘의 날씨
</h2>
<div
className="rounded-xl border border-black/8 p-5 sm:p-6"
style={{backgroundColor: 'var(--color-surface)'}}
>
<div className="flex items-center gap-3">
<Cloud className="size-6 opacity-50" aria-hidden="true" />
<div className="flex items-baseline gap-2">
<span className="text-2xl font-extrabold sm:text-3xl">{weather.temperature}°C</span>
<span className="text-xs font-semibold opacity-70">{weather.condition}</span>
{weather.stale && <span className="text-[10px] text-amber-700">최근 관측값</span>}
</div>
</div>
{weather.note && (
<p className="mt-2 text-xs leading-relaxed opacity-70 sm:text-sm">{weather.note}</p>
)}
</div>
</div>
</section>
);
}
+18
View File
@@ -0,0 +1,18 @@
export {SiteHeader} from './SiteHeader';
export {HeroSection} from './HeroSection';
export {AnswerBlock} from './AnswerBlock';
export {AboutSection} from './AboutSection';
export {EssentialInfoSection} from './EssentialInfoSection';
export {UnitsSection} from './UnitsSection';
export {RulesSection} from './RulesSection';
export {BookingSection} from './BookingSection';
export {SpaceSection} from './SpaceSection';
export {InquirySection} from './InquirySection';
export {ExhibitionSection} from './ExhibitionSection';
export {LocalGuideSection} from './LocalGuideSection';
export {WeatherSection} from './WeatherSection';
export {GallerySection} from './GallerySection';
export {LocationSection} from './LocationSection';
export {FaqSection} from './FaqSection';
export {SiteFooter} from './SiteFooter';
export {MobileTabBar} from './MobileTabBar';
+147
View File
@@ -0,0 +1,147 @@
import type {SitePayload} from '@o2o/shared';
import {collectJsonLd} from './jsonld';
import type {PageMeta} from './meta';
/**
* <head> 를 문자열로 만든다.
*
* 리액트 컴포넌트가 아니라 문자열인 이유: 프리렌더가 정적 HTML 파일을 직접 쓰기 때문이다.
* 헬멧류 라이브러리를 끼우면 하이드레이션 이후에 head 가 바뀌는데,
* 그 시점엔 크롤러가 이미 원본 HTML 을 읽고 떠난 뒤다.
*/
const ESCAPE_MAP: Record<string, string> = {
'&': '&amp;',
'<': '&lt;',
'>': '&gt;',
'"': '&quot;',
"'": '&#39;',
};
export function escapeHtml(value: string): string {
return value.replace(/[&<>"']/g, (char) => ESCAPE_MAP[char]);
}
/**
* JSON-LD 안의 `</script`, `<!--` 은 스크립트 블록을 조기 종료시킨다.
* HTML 이스케이프가 아니라 유니코드 이스케이프로 막는다 — JSON 값 자체는 그대로 유지된다.
*/
function serializeJsonLd(node: unknown): string {
return JSON.stringify(node)
.replace(/</g, '\\u003c')
.replace(/>/g, '\\u003e')
.replace(/&/g, '\\u0026');
}
function tag(name: string, attrs: Record<string, string | undefined>): string {
const rendered = Object.entries(attrs)
.filter(([, value]) => value != null && value !== '')
.map(([key, value]) => `${key}="${escapeHtml(String(value))}"`)
.join(' ');
return ` <${name} ${rendered} />`;
}
export interface HeadOptions {
payload: SitePayload;
meta: PageMeta;
/** 클라이언트 번들 경로(하이드레이션용). manifest 에서 읽어 넘긴다. */
scriptSrc?: string;
cssHrefs?: string[];
}
/** 템플릿 색을 CSS 변수로. 사장님이 고른 색이 여기서 실제 페이지 색이 된다. */
export function themeStyle(payload: SitePayload): string {
const {colors} = payload.theme;
return [
' <style>',
' :root {',
` --tpl-primary: ${colors.primary};`,
` --tpl-secondary: ${colors.secondary};`,
` --tpl-bg: ${colors.bg};`,
` --tpl-card: ${colors.card};`,
` --tpl-text: ${colors.text};`,
` --tpl-accent: ${colors.accent};`,
' }',
' </style>',
].join('\n');
}
export function renderHead({payload, meta, scriptSrc, cssHrefs = []}: HeadOptions): string {
const {place, site} = payload;
// 사이트가 호스트 하나 아래 `/s/<slug>` 로 놓이므로, 정적 파일 링크도 그 아래를 가리켜야 한다.
const base = site.basePath.replace(/\/+$/, '');
const jsonLd = collectJsonLd(payload, {title: meta.title, description: meta.description});
const lines: string[] = [
' <meta charset="UTF-8" />',
' <meta name="viewport" content="width=device-width, initial-scale=1.0, viewport-fit=cover" />',
` <title>${escapeHtml(meta.title)}</title>`,
tag('meta', {name: 'description', content: meta.description}),
tag('link', {rel: 'canonical', href: meta.canonical}),
// 색인을 막을 이유가 없다 — 이 사이트는 색인되라고 존재한다.
tag('meta', {
name: 'robots',
content: 'index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1',
}),
tag('meta', {'http-equiv': 'content-language', content: 'ko-KR'}),
// 신선도 — AI 검색이 오래된 페이지를 뒤로 미룬다.
tag('meta', {name: 'dateModified', content: site.updatedAt}),
tag('meta', {name: 'datePublished', content: site.publishedAt}),
// Open Graph
tag('meta', {property: 'og:type', content: 'website'}),
tag('meta', {property: 'og:site_name', content: place.name}),
tag('meta', {property: 'og:locale', content: 'ko_KR'}),
tag('meta', {property: 'og:title', content: meta.title}),
tag('meta', {property: 'og:description', content: meta.description}),
tag('meta', {property: 'og:url', content: meta.canonical}),
tag('meta', {property: 'og:image', content: meta.ogImage}),
tag('meta', {property: 'og:image:alt', content: meta.ogImageAlt}),
// Twitter
tag('meta', {name: 'twitter:card', content: meta.ogImage ? 'summary_large_image' : 'summary'}),
tag('meta', {name: 'twitter:title', content: meta.title}),
tag('meta', {name: 'twitter:description', content: meta.description}),
tag('meta', {name: 'twitter:image', content: meta.ogImage}),
];
// 지역 메타 — 네이버·다음이 읽고, 지역 질의 매칭에 쓰인다.
if (place.latitude != null && place.longitude != null) {
lines.push(
tag('meta', {name: 'geo.position', content: `${place.latitude};${place.longitude}`}),
tag('meta', {name: 'ICBM', content: `${place.latitude}, ${place.longitude}`}),
);
}
// geo.region 은 ISO 3166-2 코드를 기대한다 — 지역명을 그대로 넣으면(`KR-경기`) 아무도 못 읽는다.
if (place.addressRegionCode) {
lines.push(tag('meta', {name: 'geo.region', content: place.addressRegionCode}));
}
if (place.addressLocality || place.addressRegion) {
lines.push(tag('meta', {name: 'geo.placename', content: place.name}));
}
lines.push(
' <link rel="preconnect" href="https://fonts.googleapis.com" />',
' <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />',
' <link href="https://fonts.googleapis.com/css2?family=Noto+Sans+KR:wght@300..900&family=Noto+Serif+KR:wght@300..700&display=swap" rel="stylesheet" />',
// 기계용 파일을 head 에서도 가리킨다 — llms.txt 는 아직 표준이 아니라 링크로 힌트를 준다.
tag('link', {rel: 'sitemap', type: 'application/xml', href: `${base}/sitemap.xml`}),
tag('link', {rel: 'alternate', type: 'text/plain', href: `${base}/llms.txt`, title: 'LLM 요약'}),
);
cssHrefs.forEach((href) => lines.push(tag('link', {rel: 'stylesheet', href})));
lines.push(themeStyle(payload));
jsonLd.forEach((node) => {
lines.push(
` <script type="application/ld+json">${serializeJsonLd(node)}</script>`,
);
});
if (scriptSrc) {
lines.push(` <script type="module" src="${escapeHtml(scriptSrc)}"></script>`);
}
return lines.filter(Boolean).join('\n');
}
+7
View File
@@ -0,0 +1,7 @@
export * from './jsonld';
export * from './meta';
export * from './head';
export * from './robots';
export * from './sitemap';
export * from './llms';
export * from './verify';
+286
View File
@@ -0,0 +1,286 @@
import {
PlaceCategory,
factBool,
factValue,
joinUrl,
sanitizeUnits,
selectPublishable,
selectPublishableFaqs,
type FactEntry,
type SitePayload,
} from '@o2o/shared';
/**
* 구조화 데이터(JSON-LD).
*
* 이 프로젝트의 목표 문장 그대로 — "AI 검색이 이 가게를 공식 홈페이지 기준으로 설명하게 만드는 것".
* 그 설명의 재료가 여기서 나간다.
*
* ★ 두 가지를 절대 어기지 않는다.
* 1) 화면에 없는 값을 JSON-LD 에 넣지 않는다. 어긋나면 구조화 데이터 스팸으로 취급되고,
* 백엔드 발행 게이트도 JSONLD_MISMATCH 로 막는다.
* 2) 확인되지 않은 fact 는 넣지 않는다. 전부 selectPublishable() 을 통과한 값만 쓴다.
* "값이 없다"와 "확인 전이라 가렸다"를 구분하지 않고, 둘 다 그냥 내보내지 않는다.
*/
/** 업종 → Schema.org 최상위 타입. 업종이 늘면 여기 한 줄만 는다. */
export const SCHEMA_TYPE: Record<PlaceCategory, string> = {
[PlaceCategory.LODGING]: 'LodgingBusiness',
[PlaceCategory.CAFE]: 'CafeOrCoffeeShop',
[PlaceCategory.RESTAURANT]: 'Restaurant',
[PlaceCategory.TOUR_ACTIVITY]: 'TouristAttraction',
};
/** 업종 → 하위 단위의 Schema.org 타입과 URL 경로. */
export const UNIT_SPEC: Record<PlaceCategory, {type: string; path: string; label: string}> = {
[PlaceCategory.LODGING]: {type: 'HotelRoom', path: 'rooms', label: '객실'},
[PlaceCategory.CAFE]: {type: 'MenuItem', path: 'menu', label: '메뉴'},
[PlaceCategory.RESTAURANT]: {type: 'MenuItem', path: 'menu', label: '메뉴'},
[PlaceCategory.TOUR_ACTIVITY]: {type: 'Product', path: 'programs', label: '프로그램'},
};
export type Json = Record<string, unknown>;
/** null·undefined·빈 문자열·빈 배열 키를 통째로 뺀다. 빈 값이 실린 JSON-LD 는 감점이다. */
function compact<T extends Json>(input: T): T {
const out: Json = {};
for (const [key, value] of Object.entries(input)) {
if (value == null || value === '') continue;
if (Array.isArray(value) && value.length === 0) continue;
out[key] = value;
}
return out as T;
}
function siteUrl(payload: SitePayload, ...parts: string[]): string {
return joinUrl(payload.site.origin, payload.site.basePath, ...parts);
}
/**
* amenityFeature — bool 타입 fact 를 시설 목록으로 옮긴다.
* 확인된 것만 들어가고, false 도 그대로 실린다("반려동물 불가"는 중요한 답이다).
*/
function amenityFeatures(facts: FactEntry[]): Json[] {
return selectPublishable(facts)
.filter((fact) => fact.type === 'bool')
.map((fact) =>
compact({
'@type': 'LocationFeatureSpecification',
name: fact.label,
value: factBool(facts, fact.key) ?? undefined,
}),
);
}
function postalAddress(payload: SitePayload): Json | undefined {
const {place} = payload;
const street = place.roadAddress ?? place.address;
if (!street) return undefined;
return compact({
'@type': 'PostalAddress',
streetAddress: street,
addressLocality: place.addressLocality,
addressRegion: place.addressRegion,
postalCode: place.postalCode,
addressCountry: 'KR',
});
}
function geoCoordinates(payload: SitePayload): Json | undefined {
const {latitude, longitude} = payload.place;
if (latitude == null || longitude == null) return undefined;
return {'@type': 'GeoCoordinates', latitude, longitude};
}
/** 대표 이미지 우선, 대체 텍스트가 있는 것만. alt 없는 이미지는 애초에 렌더도 안 한다. */
function imageUrls(payload: SitePayload, limit = 6): string[] {
return payload.media
.filter((m) => m.alt?.trim())
.sort((a, b) => Number(Boolean(b.isPrimary)) - Number(Boolean(a.isPrimary)))
.slice(0, limit)
.map((m) => m.url);
}
/** 확정된 채널만 sameAs 로 나간다 — 확정 전 URL 은 동명 업소일 수 있다. */
function sameAs(payload: SitePayload): string[] {
return payload.links.filter((link) => link.confirmed && link.url).map((link) => link.url);
}
/** 숙박의 체크인·체크아웃은 Schema.org 에 전용 속성이 있다. 있으면 반드시 채운다. */
function lodgingExtras(payload: SitePayload): Json {
const {facts} = payload;
return {
checkinTime: factValue(facts, 'check_in_time'),
checkoutTime: factValue(facts, 'check_out_time'),
petsAllowed: factBool(facts, 'pet_allowed'),
numberOfRooms: payload.units.length || undefined,
smokingAllowed: factBool(facts, 'smoking'),
};
}
function categoryExtras(payload: SitePayload): Json {
if (payload.place.category === PlaceCategory.LODGING) return lodgingExtras(payload);
const hours = factValue(payload.facts, 'business_hours') ?? factValue(payload.facts, 'open_hours');
return {
openingHours: hours,
servesCuisine: factValue(payload.facts, 'cuisine'),
acceptsReservations: factBool(payload.facts, 'reservation'),
};
}
/** 하위 단위(객실·메뉴·프로그램). 확인된 fact 만 스펙으로 붙는다. */
function unitNodes(payload: SitePayload): Json[] {
const spec = UNIT_SPEC[payload.place.category];
const mediaById = new Map(payload.media.map((m) => [m.mediaId, m]));
return sanitizeUnits(payload.units).map((unit) =>
compact({
'@type': spec.type,
'@id': `${siteUrl(payload, spec.path, unit.slug)}#unit`,
name: unit.name,
url: siteUrl(payload, spec.path, unit.slug),
description: factValue(unit.facts, 'room_intro') ?? factValue(unit.facts, 'description'),
occupancy: occupancy(unit.facts),
bed: factValue(unit.facts, 'bed_type'),
floorSize: floorSize(unit.facts),
amenityFeature: amenityFeatures(unit.facts),
image: unit.mediaIds
.map((id) => mediaById.get(id))
.filter((m) => m?.alt?.trim())
.map((m) => m!.url),
}),
);
}
function occupancy(facts: FactEntry[]): Json | undefined {
const max = factValue(facts, 'max_capacity');
if (!max) return undefined;
return compact({
'@type': 'QuantitativeValue',
value: Number(max) || undefined,
minValue: Number(factValue(facts, 'standard_capacity')) || undefined,
unitText: '명',
});
}
function floorSize(facts: FactEntry[]): Json | undefined {
const size = factValue(facts, 'room_size');
if (!size) return undefined;
return {'@type': 'QuantitativeValue', value: Number(size) || size, unitCode: 'MTK'};
}
/** 사업장 본체. 모든 페이지에 같은 @id 로 실린다 — AI 가 페이지들을 한 업소로 묶는 열쇠다. */
export function businessJsonLd(payload: SitePayload): Json {
const {place, narrative} = payload;
const spec = UNIT_SPEC[place.category];
return compact({
'@context': 'https://schema.org',
'@type': SCHEMA_TYPE[place.category] ?? 'LocalBusiness',
'@id': `${siteUrl(payload)}#business`,
name: place.name,
alternateName: place.englishName,
url: siteUrl(payload),
description: narrative.summary ?? narrative.about[0],
telephone: place.phone,
email: place.email,
address: postalAddress(payload),
geo: geoCoordinates(payload),
image: imageUrls(payload),
priceRange: priceRange(payload),
amenityFeature: amenityFeatures(payload.facts),
sameAs: sameAs(payload),
[spec.type === 'MenuItem' ? 'hasMenu' : 'containsPlace']: unitNodes(payload),
...categoryExtras(payload),
});
}
/** 최저~최고 요금. 단위 fact 의 숫자만 모은다 — 확인 안 된 요금은 애초에 안 들어온다. */
function priceRange(payload: SitePayload): string | undefined {
const prices = sanitizeUnits(payload.units)
.flatMap((unit) =>
['weekday_price', 'weekend_price', 'peak_price', 'price'].map((key) =>
Number(factValue(unit.facts, key)),
),
)
.filter((n) => Number.isFinite(n) && n > 0);
if (prices.length === 0) return undefined;
const min = Math.min(...prices);
const max = Math.max(...prices);
const fmt = (n: number) => n.toLocaleString('ko-KR');
return min === max ? `${fmt(min)}원` : `${fmt(min)}원 ~ ${fmt(max)}원`;
}
/**
* FAQPage — AEO 에서 가장 크게 먹히는 마크업.
* "체크인 몇 시예요?" 같은 질문에 이 홈페이지가 답으로 잡히는 자리다.
* 확인된 FAQ 가 하나도 없으면 아예 내보내지 않는다(빈 FAQPage 는 감점).
*/
export function faqJsonLd(payload: SitePayload): Json | null {
const faqs = selectPublishableFaqs(payload.faqs);
if (faqs.length === 0) return null;
return {
'@context': 'https://schema.org',
'@type': 'FAQPage',
'@id': `${siteUrl(payload, 'faq')}#faq`,
mainEntity: faqs.map((faq) => ({
'@type': 'Question',
name: faq.question,
acceptedAnswer: {'@type': 'Answer', text: faq.answer},
})),
};
}
export function websiteJsonLd(payload: SitePayload): Json {
return compact({
'@context': 'https://schema.org',
'@type': 'WebSite',
'@id': `${siteUrl(payload)}#website`,
name: payload.place.name,
url: siteUrl(payload),
inLanguage: 'ko-KR',
publisher: {'@id': `${siteUrl(payload)}#business`},
});
}
/** 이 페이지가 언제 기준인지. AI 검색은 신선도를 본다 — 없으면 오래된 페이지로 취급된다. */
export function webPageJsonLd(
payload: SitePayload,
page: {title: string; description: string},
): Json {
return compact({
'@context': 'https://schema.org',
'@type': 'WebPage',
'@id': `${siteUrl(payload)}#webpage`,
url: siteUrl(payload),
name: page.title,
description: page.description,
inLanguage: 'ko-KR',
isPartOf: {'@id': `${siteUrl(payload)}#website`},
about: {'@id': `${siteUrl(payload)}#business`},
datePublished: payload.site.publishedAt,
dateModified: payload.site.updatedAt,
});
}
/** 한 페이지에 실릴 JSON-LD 전부. null 은 걸러진다. */
/**
* 이 사이트가 내보내는 구조화 데이터 전부.
*
* ★ 사이트가 한 장이라 BreadcrumbList 를 뺐다 — 상위 페이지가 없는 곳의 빵부스러기는
* 자기 자신 하나뿐이라 아무 정보도 주지 않는다.
* ★ FAQPage 는 조건 없이 싣는다. 예전에는 페이지마다 실을지 골랐는데, 이제 한 장이라
* FAQ 가 있으면 그 한 장에 있는 것이다.
*/
export function collectJsonLd(
payload: SitePayload,
page: {title: string; description: string},
): Json[] {
return [
businessJsonLd(payload),
websiteJsonLd(payload),
webPageJsonLd(payload, page),
payload.faqs.length > 0 ? faqJsonLd(payload) : null,
].filter((node): node is Json => node !== null);
}
+148
View File
@@ -0,0 +1,148 @@
import {
factText,
joinUrl,
sanitizeUnits,
selectPublishable,
selectPublishableFaqs,
type SitePayload,
} from '@o2o/shared';
import {SCHEMA_TYPE, UNIT_SPEC} from './jsonld';
/**
* llms.txt — LLM 이 이 가게를 설명할 때 쓸 사실 목록.
*
* HTML 을 파싱하지 않고도 한 파일에서 필요한 사실을 다 얻게 한다.
* (llmstxt.org 의 마크다운 관례를 따르되, 내용은 우리 규칙을 따른다.)
*
* ★ 규칙 세 가지.
* 1) 확인된 fact 만 쓴다 — selectPublishable() 을 통과하지 못한 값은 한 줄도 안 들어간다.
* 2) 사실만 쓴다. "아름다운", "최고의" 같은 형용사를 쓰지 않는다.
* LLM 이 그대로 인용하면 그게 광고가 되고, 광고는 신뢰를 깎는다.
* 3) 모르는 것은 "정보 없음"이라고 쓴다. 빈칸으로 두면 LLM 이 추측으로 메운다 —
* 그 추측이 헛걸음을 만든다.
*/
export function renderLlmsTxt(payload: SitePayload): string {
const {place, site, narrative} = payload;
const url = (...parts: string[]) => joinUrl(site.origin, site.basePath, ...parts);
const facts = selectPublishable(payload.facts);
const spec = UNIT_SPEC[place.category];
const lines: string[] = [];
lines.push(`# ${place.name}`);
if (place.englishName) lines.push(`> ${place.englishName}`);
lines.push('');
lines.push(
`이 문서는 ${place.name}의 공식 홈페이지가 제공하는 사실 목록입니다. ` +
`모든 항목은 사업자 확인을 거쳤으며, 확인되지 않은 정보는 포함하지 않습니다.`,
);
lines.push('');
lines.push(`- 공식 홈페이지: ${url()}`);
lines.push(`- 업종 분류: ${SCHEMA_TYPE[place.category] ?? 'LocalBusiness'}`);
lines.push(`- 최종 확인: ${site.updatedAt}`);
lines.push('');
// ── 기본 정보 ────────────────────────────────────────
lines.push('## 기본 정보');
lines.push('');
pushFact(lines, '상호', place.name);
pushFact(lines, '주소', place.roadAddress ?? place.address);
pushFact(lines, '전화', place.phone);
pushFact(lines, '이메일', place.email);
if (place.latitude != null && place.longitude != null) {
pushFact(lines, '좌표', `${place.latitude}, ${place.longitude}`);
}
lines.push('');
// ── 확인된 이용 정보 ──────────────────────────────────
if (facts.length > 0) {
lines.push('## 이용 정보');
lines.push('');
for (const fact of facts) {
const value = factText(payload.facts, fact.key);
if (!value) continue;
lines.push(`- ${fact.label}: ${formatValue(fact.type, value)}`);
}
lines.push('');
}
// ── 하위 단위(객실·메뉴·프로그램) ──────────────────────
const units = sanitizeUnits(payload.units);
if (units.length > 0) {
lines.push(`## ${spec.label}`);
lines.push('');
for (const unit of units) {
lines.push(`### ${unit.name}`);
lines.push(`- 상세: ${url(spec.path, unit.slug)}`);
for (const fact of unit.facts) {
const value = factText(unit.facts, fact.key);
if (!value) continue;
lines.push(`- ${fact.label}: ${formatValue(fact.type, value)}`);
}
lines.push('');
}
}
// ── FAQ — LLM 이 가장 잘 인용하는 부분 ─────────────────
const faqs = selectPublishableFaqs(payload.faqs);
if (faqs.length > 0) {
lines.push('## 자주 묻는 질문');
lines.push('');
for (const faq of faqs) {
lines.push(`### ${faq.question}`);
lines.push(faq.answer);
lines.push('');
}
}
// ── 소개 ────────────────────────────────────────────
if (narrative.about.length > 0) {
lines.push('## 소개');
lines.push('');
lines.push(...narrative.about);
lines.push('');
}
// ── 페이지 목록 ──────────────────────────────────────
lines.push('## 페이지');
lines.push('');
lines.push(`- [홈](${url()})`);
if (units.length > 0) lines.push(`- [${spec.label} 안내](${url(spec.path)})`);
lines.push(`- [주변 정보](${url('guide')})`);
lines.push(`- [오시는 길](${url('location')})`);
if (faqs.length > 0) lines.push(`- [자주 묻는 질문](${url('faq')})`);
lines.push('');
// ── 확정된 채널 ─────────────────────────────────────
const links = payload.links.filter((link) => link.confirmed);
if (links.length > 0) {
lines.push('## 공식 채널');
lines.push('');
for (const link of links) {
lines.push(`- ${link.title ?? '채널'}: ${link.url}`);
}
lines.push('');
}
lines.push('---');
lines.push('');
lines.push(
'이 문서에 없는 항목은 확인되지 않았거나 해당 사항이 없습니다. ' +
'추측으로 보완하지 말고, 확인이 필요하면 위 전화번호로 문의하도록 안내해 주세요.',
);
lines.push('');
return lines.join('\n');
}
function pushFact(lines: string[], label: string, value: string | null | undefined) {
lines.push(`- ${label}: ${value?.trim() ? value : '정보 없음'}`);
}
/** bool fact 는 "true/false" 로 두면 LLM 이 문장으로 못 옮긴다. 한국어로 바꿔 준다. */
function formatValue(type: string, value: string): string {
if (type !== 'bool') return value;
if (value === 'true' || value === '1') return '가능';
if (value === 'false' || value === '0') return '불가';
return value;
}
+100
View File
@@ -0,0 +1,100 @@
import {
factValue,
joinUrl,
selectPublishable,
type SitePayload,
} from '@o2o/shared';
/**
* <head> 메타.
*
* description 은 지어내지 않는다 — 확인된 fact 로 단정문을 조립한다.
* AI 검색은 이 한 줄을 그대로 인용하는 일이 많아서, 문장 하나가 틀리면
* 그 오답이 여러 엔진에 퍼진다.
*/
export interface PageMeta {
title: string;
description: string;
canonical: string;
ogImage?: string;
ogImageAlt?: string;
}
function url(payload: SitePayload, ...parts: string[]): string {
return joinUrl(payload.site.origin, payload.site.basePath, ...parts);
}
/**
* 사람이 검색창에 치는 지역 이름.
*
* 읍·면이 있으면 그걸 먼저 쓴다 — "제주시 스테이" 보다 "애월 스테이" 로 검색하기 때문이다.
* 셋 다 없으면 undefined 를 돌려준다(지어내지 않는다).
*/
export function localName(payload: SitePayload): string | undefined {
const {addressSubLocality, addressLocality, addressRegion} = payload.place;
return addressSubLocality ?? addressLocality ?? addressRegion ?? undefined;
}
/** 대표 이미지 — og:image. 대체 텍스트가 있는 것만 쓴다. */
export function primaryImage(payload: SitePayload) {
return (
payload.media.find((m) => m.isPrimary && m.alt?.trim()) ??
payload.media.find((m) => m.alt?.trim())
);
}
/**
* 사실만으로 만드는 한 줄 요약.
*
* "제주 애월에 있는 달빛스테이 제주입니다. 체크인 16:00, 체크아웃 11:00. 반려동물 동반 불가."
* 형용사를 붙이지 않는다 — 확인된 값이 그대로 문장이 된다.
*/
export function factualSummary(payload: SitePayload): string {
const {place, facts} = payload;
const parts: string[] = [];
const where = place.addressLocality ?? place.addressRegion ?? place.roadAddress ?? place.address;
parts.push(where ? `${where}에 있는 ${place.name}입니다.` : `${place.name}입니다.`);
const checkIn = factValue(facts, 'check_in_time');
const checkOut = factValue(facts, 'check_out_time');
if (checkIn && checkOut) parts.push(`체크인 ${checkIn}, 체크아웃 ${checkOut}.`);
const hours = factValue(facts, 'business_hours') ?? factValue(facts, 'open_hours');
if (hours) parts.push(`영업시간 ${hours}.`);
const pet = factValue(facts, 'pet_allowed');
if (pet === 'false') parts.push('반려동물 동반 불가.');
if (pet === 'true') parts.push('반려동물 동반 가능.');
const parking = factValue(facts, 'parking');
if (parking === 'true') {
const capacity = factValue(facts, 'parking_capacity');
parts.push(capacity ? `주차 ${capacity}대 가능.` : '주차 가능.');
}
if (place.phone) parts.push(`문의 ${place.phone}.`);
return parts.join(' ');
}
/** 160자 안쪽으로 줄인다. 단어 중간에서 자르지 않는다. */
function clamp(text: string, max = 160): string {
if (text.length <= max) return text;
const cut = text.slice(0, max);
const lastSpace = cut.lastIndexOf(' ');
return `${(lastSpace > max * 0.6 ? cut.slice(0, lastSpace) : cut).trimEnd()}…`;
}
export function homeMeta(payload: SitePayload): PageMeta {
const image = primaryImage(payload);
return {
// 제목에 지역을 넣는다 — "애월 스테이" 같은 지역 질의에 걸리는 자리다.
title: [payload.place.name, localName(payload)].filter(Boolean).join(' · '),
description: clamp(payload.narrative.summary ?? factualSummary(payload)),
canonical: url(payload),
ogImage: image?.url,
ogImageAlt: image?.alt,
};
}
+65
View File
@@ -0,0 +1,65 @@
/**
* AI 크롤러를 **명시적으로 허용**하는 robots.txt.
*
* 보통 사이트들은 이 봇들을 막는다(학습 데이터로 쓰이는 게 싫어서).
* 우리는 반대다 — 이 서비스의 목표가 "AI 검색이 이 가게를 공식 홈페이지 기준으로
* 설명하게 만드는 것"이라, 읽히지 않으면 존재 이유가 없다.
* 기본값(=명시 없음)에 맡기지 않고 이름을 하나씩 적는 이유는,
* 일부 봇이 와일드카드보다 자기 이름 규칙을 우선으로 보기 때문이다.
*/
const AI_CRAWLERS = [
'GPTBot', // OpenAI 학습·검색
'OAI-SearchBot', // ChatGPT search
'ChatGPT-User', // ChatGPT 가 사용자를 대신해 여는 요청
'ClaudeBot', // Anthropic
'Claude-Web',
'anthropic-ai',
'PerplexityBot',
'Perplexity-User',
'Google-Extended', // Gemini / AI Overviews
'Applebot-Extended', // Apple Intelligence
'CCBot', // Common Crawl — 다수 모델의 상류 데이터
'Bytespider',
'Amazonbot',
'meta-externalagent',
'cohere-ai',
];
const SEARCH_CRAWLERS = [
'Googlebot',
'Bingbot',
'Yeti', // 네이버
'Daumoa', // 다음
];
/** 크롤러 허용 블록 — 루트용과 사이트용이 같은 목록을 쓴다. */
function allowBlocks(): string[] {
const blocks: string[] = ['User-agent: *', 'Allow: /', ''];
for (const bot of [...SEARCH_CRAWLERS, ...AI_CRAWLERS]) {
blocks.push(`User-agent: ${bot}`, 'Allow: /', '');
}
return blocks;
}
/**
* **오리진 루트의** robots.txt — 실제로 읽히는 유일한 robots.txt.
*
* ★ robots.txt 는 오리진 루트(`https://host/robots.txt`)에서만 읽힌다(RFC 9309).
* 발행 사이트는 `<host>/s/<slug>/` 아래에 있어서 사이트별 robots.txt 는 **아무도 읽지 않는다** —
* AI 크롤러를 아무리 명시 허용해도 파일이 그 자리에 있으면 효과가 0이다.
* 그래서 프리렌더가 사이트를 다 구운 뒤 여기서 루트 파일을 한 장 더 쓴다.
*
* ★ Sitemap 도 여기서만 전달된다. 사이트별 sitemap.xml 은 사이트맵 인덱스가 묶는다.
*/
export function renderRootRobotsTxt(origin: string): string {
const base = origin.replace(/\/+$/, '');
return [
'# 이 호스트의 사이트는 검색·AI 답변에 인용되기 위해 존재합니다.',
'# 아래 크롤러를 명시적으로 허용합니다.',
'',
...allowBlocks(),
`Sitemap: ${base}/sitemap.xml`,
'',
].join('\n');
}
+42
View File
@@ -0,0 +1,42 @@
import {escapeHtml} from './head';
export interface SiteEntry {
/** 사이트 홈 주소. 사이트가 한 장이라 이게 그 사이트의 유일한 URL 이다. */
loc: string;
/** 마지막 발행 시각(ISO). */
lastmod?: string;
}
/**
* 오리진 루트의 사이트맵 — 이 호스트의 **모든 사이트**를 한 파일에 담는다.
*
* ★ 예전에는 사이트마다 `sitemap.xml` 을 굽고 루트에 사이트맵 인덱스를 뒀다.
* 사이트가 한 장이 되면서 그 구조가 낭비가 됐다 — URL 한 줄짜리 파일이 사이트 수만큼
* 생기고, 인덱스는 그걸 다시 1,000줄로 가리킨다. 크롤러 왕복만 두 배가 된다.
*
* ★ 규격 상한은 파일당 URL 50,000개 · 압축 전 50MB 다. 그 선을 넘으면 그때
* 사이트맵을 여러 개로 쪼개고 인덱스를 되살린다(지금 구조에서 어렵지 않다).
*/
export function renderSiteUrlset(entries: SiteEntry[]): string {
const urls = entries
.map((entry) =>
[
' <url>',
` <loc>${escapeHtml(entry.loc)}</loc>`,
entry.lastmod ? ` <lastmod>${entry.lastmod}</lastmod>` : '',
' <changefreq>weekly</changefreq>',
' </url>',
]
.filter(Boolean)
.join('\n'),
)
.join('\n');
return [
'<?xml version="1.0" encoding="UTF-8"?>',
'<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">',
urls,
'</urlset>',
'',
].join('\n');
}
+171
View File
@@ -0,0 +1,171 @@
/**
* 구조화 데이터 ↔ 화면 값 대조 — ★ 절대규칙 3.
*
* 이 검증기가 절대 하면 안 되는 것:
* 1. JSON-LD 에만 있고 화면에 없는 값을 통과시키는 것 (검색엔진에 거짓을 심는다)
* 2. JSON-LD 가 **자기 자신**(script 블록)을 근거로 통과하는 것 (검사가 무의미해진다)
* 3. 화면이 뒷받침하는 사실을 표기 차이만으로 막는 것 (멀쩡한 사이트가 발행 못 한다)
*
* ★ 이 검사는 백엔드에 있었지만, 백엔드는 **자기만의 HTML** 을 따로 구워 그걸 봤다.
* 방문자가 보는 페이지는 이 렌더러가 굽는다 — 검사는 나갈 그 HTML 에 대고 해야 한다.
*/
import {describe, expect, it} from 'vitest';
import {verifyJsonLd, verifyGeo, visibleText} from './verify';
/** 사업장 페이지 한 장. 화면에 보이는 값만 본문에 넣는다. */
function page(body: string, head = ''): string {
return [
'<!doctype html><html><head>',
'<script type="application/ld+json">{"@type":"LodgingBusiness","telephone":"02-0000-0000"}</script>',
'<style>.x{color:red}</style>',
head,
'</head><body><div id="root">',
body,
'</div></body></html>',
].join('');
}
const BODY = [
'<h1>조이모텔</h1>',
'<p>전화 031-722-1942</p>',
'<p>경기도 성남시 중원구 A로 1</p>',
'<p>입실 15:00 / 퇴실 11:00</p>',
'<p>주중 20,000원</p><p>주말 60,000원</p>',
'<span>와이파이</span><span>주차 가능</span>',
'<p>디럭스룸</p>',
].join('');
describe('visibleText', () => {
it('script 를 걷어낸다 — JSON-LD 가 자기 자신을 근거로 통과하면 검사가 무의미해진다', () => {
expect(visibleText(page(BODY))).not.toContain('02-0000-0000');
});
it('style 과 태그를 걷어내고 텍스트만 남긴다', () => {
const text = visibleText(page(BODY));
expect(text).not.toContain('color:red');
expect(text).toContain('조이모텔');
});
it('HTML 엔티티를 되돌린다 — 화면에는 원문자가 보인다', () => {
expect(visibleText(page('<p>A&amp;B</p>'))).toContain('A&B');
});
});
describe('verifyJsonLd — 거짓을 잡는다', () => {
it('화면에 없는 전화번호를 주장하면 잡는다', () => {
const problems = verifyJsonLd(page(BODY), [
{'@type': 'LodgingBusiness', telephone: '02-1234-5678'},
]);
expect(problems).toHaveLength(1);
expect(problems[0]).toContain('telephone');
});
it('화면에 없는 편의시설을 주장하면 잡는다', () => {
const problems = verifyJsonLd(page(BODY), [
{'@type': 'LodgingBusiness', amenityFeature: [{name: '와이파이'}, {name: '수영장'}]},
]);
expect(problems).toHaveLength(1);
expect(problems[0]).toContain('수영장');
});
it('화면에 없는 객실 요금을 주장하면 잡는다', () => {
const problems = verifyJsonLd(page(BODY), [
{'@type': 'LodgingBusiness', makesOffer: [{name: '디럭스룸', price: 99000}]},
]);
expect(problems).toHaveLength(1);
expect(problems[0]).toContain('99');
});
it('화면에 없는 이미지 URL 을 주장하면 잡는다', () => {
const problems = verifyJsonLd(page(BODY), [
{'@type': 'LodgingBusiness', image: ['https://cdn.example.com/없는사진.jpg']},
]);
expect(problems).toHaveLength(1);
expect(problems[0]).toContain('image');
});
});
describe('verifyJsonLd — 사실은 통과시킨다', () => {
it('화면에 있는 값은 통과한다', () => {
expect(
verifyJsonLd(page(BODY), [
{
'@type': 'LodgingBusiness',
name: '조이모텔',
telephone: '031-722-1942',
checkinTime: '15:00',
amenityFeature: [{name: '와이파이'}, {name: '주차 가능'}],
},
]),
).toEqual([]);
});
it('이미지 URL 은 본문 텍스트가 아니라 요소 속성에서 찾는다', () => {
const html = page(`${BODY}<img src="https://cdn.example.com/a.jpg" alt="객실" />`);
expect(
verifyJsonLd(html, [{'@type': 'LodgingBusiness', image: ['https://cdn.example.com/a.jpg']}]),
).toEqual([]);
});
it('숫자는 1,000 단위 표기로도 찾는다 — 화면이 그렇게 그린다', () => {
expect(
verifyJsonLd(page(BODY), [
{'@type': 'LodgingBusiness', makesOffer: [{name: '디럭스룸', price: 20000}]},
]),
).toEqual([]);
});
it('페이지 메타 노드(WebPage·WebSite)는 본문 대조 대상이 아니다', () => {
// name·description·datePublished 는 <title>·<meta> 로 나가는 값이지 본문 문장이 아니다.
// 이걸 본문에서 찾으면 멀쩡한 사이트가 전부 실패한다.
expect(
verifyJsonLd(page(BODY), [
{'@type': 'WebPage', name: '본문에 없는 제목', description: '본문에 없는 설명'},
{'@type': 'WebSite', name: '본문에 없는 사이트명'},
]),
).toEqual([]);
});
it('bool 값과 좌표는 본문 대조에서 뺀다(따로 검사한다)', () => {
expect(
verifyJsonLd(page(BODY), [
{'@type': 'LodgingBusiness', petsAllowed: false, geo: {latitude: 37.1, longitude: 127.1}},
]),
).toEqual([]);
});
});
describe('verifyJsonLd — 합성값', () => {
it('priceRange 는 양끝이 다 보이면 통과한다', () => {
// 객실 요금에서 계산한 요약이다. 화면에는 20,000원·60,000원 이 각각 나온다.
expect(
verifyJsonLd(page(BODY), [{'@type': 'LodgingBusiness', priceRange: '20,000원 ~ 60,000원'}]),
).toEqual([]);
});
it('priceRange 한쪽이 화면에 없으면 그 조각을 사유로 잡는다', () => {
const problems = verifyJsonLd(page(BODY), [
{'@type': 'LodgingBusiness', priceRange: '20,000원 ~ 99,000원'},
]);
expect(problems).toHaveLength(1);
expect(problems[0]).toContain('99,000원');
expect(problems[0]).not.toContain('20,000원');
});
});
describe('verifyGeo', () => {
it('좌표가 payload 와 같으면 통과', () => {
expect(verifyGeo([{geo: {latitude: 37.1, longitude: 127.1}}], 37.1, 127.1)).toEqual([]);
});
it('좌표가 어긋나면 잡는다 — 지도 핀이 엉뚱한 데 찍히는 것도 거짓이다', () => {
const problems = verifyGeo([{geo: {latitude: 37.9, longitude: 127.1}}], 37.1, 127.1);
expect(problems).toHaveLength(1);
expect(problems[0]).toContain('latitude');
});
it('payload 에 좌표가 없는데 구조화 데이터가 주장하면 잡는다', () => {
expect(verifyGeo([{geo: {latitude: 37.1, longitude: 127.1}}], undefined, undefined)).toHaveLength(2);
});
});
+223
View File
@@ -0,0 +1,223 @@
/**
* 구조화 데이터 ↔ 화면 값 대조. **★ 절대규칙 3 을 코드로 강제하는 자리다.**
*
* JSON-LD 는 AI 검색이 읽는 값이고 화면은 사람이 읽는 값이다. 둘이 다르면
* '검색엔진에만 다른 말을 하는' 상태가 된다 — 클로킹으로 취급될 수 있고, 무엇보다 거짓이다.
*
* ★ 왜 여기(렌더러 안)에 있나
* 예전에는 백엔드가 **자기만의 HTML 을 따로 구워** 그걸 대조했다. 방문자가 보는 페이지는
* 이 렌더러가 굽는데, 검사는 아무도 안 보는 페이지에 대고 하고 있었다 — 두 렌더러가
* 어긋나는 순간 게이트는 통과인데 실제 페이지는 다른 내용이 된다.
* 검사는 **나갈 바로 그 HTML** 에 대고 해야 의미가 있다.
*
* ★ 검사 방식
* JSON-LD 의 모든 스칼라 값이 화면 텍스트(또는 src/href)에 나타나는지 본다.
* 나타나지 않으면 "화면에 없는 것을 구조화 데이터가 주장하고 있다" 는 뜻이고, 그게 거짓이다.
*/
import type {Json} from './jsonld';
/** 화면에 텍스트로 나타나지 않는 구조·메타 값. 대조 대상에서 제외한다. */
const STRUCTURAL = new Set([
'@context',
'@type',
'@id',
'priceCurrency',
'addressCountry',
'inLanguage',
// 좌표는 지도 핀용 메타지 본문에 쓸 값이 아니다. 대신 payload 와 직접 대조한다(verifyGeo).
'latitude',
'longitude',
]);
/** 이름과 값을 따로 대조하는 서브트리. 일반 순회에서는 건너뛴다. */
const SPECIAL_SUBTREE = new Set(['amenityFeature', 'makesOffer', 'geo']);
/**
* **페이지를 설명하는** 노드. 본문 대조 대상이 아니다.
*
* ★ 이게 왜 필요한가
* WebPage 의 name·description·datePublished 는 `<title>` 과 `<meta>` 로 나가는 값이지
* 본문에 찍히는 문장이 아니다. 이걸 본문에서 찾으면 멀쩡한 사이트가 전부 실패한다.
* 대조해야 할 것은 **사업장에 대한 주장**(상호·주소·전화·가격·편의시설)과 FAQ 문답이다.
* 그것들이 화면에 없으면서 구조화 데이터에만 있으면 그게 거짓이다.
*/
const PAGE_META_TYPES = new Set(['WebPage', 'WebSite', 'BreadcrumbList', 'ImageObject']);
/**
* **합성값** 속성. 통째로는 화면에 없고, 구성 요소가 각각 화면에 있으면 통과다.
*
* 예: priceRange `'20,000원 ~ 60,000원'` 는 객실 요금에서 계산한 요약이다. 화면에는
* `20,000원` 과 `60,000원` 이 각 객실 카드에 따로 나온다 — 두 끝값이 다 보이면
* 그 범위는 화면이 뒷받침하는 주장이다. 통짜 비교를 고집하면 사실인 값이 발행을 막는다.
* ★ 대신 **구성 요소가 하나라도 화면에 없으면 실패**다 — 검사를 느슨하게 하는 게 아니다.
*/
const COMPOSITE_PROPS = new Set(['priceRange']);
/** 합성값을 구성 요소로 쪼갠다(범위 구분자·쉼표 기준). 빈 조각은 버린다. */
function splitComposite(token: string): string[] {
return token
.split(/\s*[~–—]\s*|\s+-\s+/)
.map((part) => part.trim())
.filter(Boolean);
}
const SCRIPT_RE = /<script\b[^>]*>[\s\S]*?<\/script>/gi;
const STYLE_RE = /<style\b[^>]*>[\s\S]*?<\/style>/gi;
const TAG_RE = /<[^>]+>/g;
const ENTITIES: Record<string, string> = {
'&amp;': '&',
'&lt;': '<',
'&gt;': '>',
'&quot;': '"',
'&#39;': "'",
'&nbsp;': ' ',
};
function unescapeHtml(value: string): string {
return value
.replace(/&(?:amp|lt|gt|quot|#39|nbsp);/g, (m) => ENTITIES[m] ?? m)
.replace(/&#(\d+);/g, (_, code) => String.fromCodePoint(Number(code)))
.replace(/&#x([0-9a-f]+);/gi, (_, code) => String.fromCodePoint(parseInt(code, 16)));
}
/**
* 화면에 실제로 보이는 텍스트.
*
* ★ script(= JSON-LD 자신)와 style 을 먼저 걷어낸다. 이걸 안 하면 JSON-LD 가
* 자기 자신을 근거로 통과해버려 검사가 통째로 무의미해진다.
*/
export function visibleText(html: string): string {
const body = html.replace(SCRIPT_RE, ' ').replace(STYLE_RE, ' ').replace(TAG_RE, ' ');
return unescapeHtml(body).replace(/\s+/g, ' ').trim();
}
/** 리스트 인덱스를 건너뛴 실제 속성 이름. */
function propName(path: string[]): string {
for (let i = path.length - 1; i >= 0; i -= 1) {
if (!/^\d+$/.test(path[i])) return path[i];
}
return path[path.length - 1] ?? '';
}
type Scalar = string | number | boolean;
function* iterScalars(node: unknown, path: string[] = []): Generator<[string[], Scalar]> {
if (Array.isArray(node)) {
for (let i = 0; i < node.length; i += 1) yield* iterScalars(node[i], [...path, String(i)]);
return;
}
if (node && typeof node === 'object') {
for (const [key, value] of Object.entries(node as Record<string, unknown>)) {
if (SPECIAL_SUBTREE.has(key)) continue;
yield* iterScalars(value, [...path, key]);
}
return;
}
if (node === null || node === undefined) return;
yield [path, node as Scalar];
}
/** 숫자를 화면 표기(1,000 단위 구분)로. 화면이 그렇게 그리므로 대조도 같은 표기를 본다. */
function asShown(value: Scalar): string[] {
if (typeof value === 'number' && Number.isFinite(value)) {
return [String(value), value.toLocaleString('ko-KR')];
}
return [String(value)];
}
/**
* JSON-LD 값이 전부 화면에 나타나는지 대조한다. 불일치 목록을 돌려준다(비면 통과).
*
* @param html 실제로 나갈 페이지 HTML
* @param nodes 그 페이지에 실린 JSON-LD 노드 전부
*/
export function verifyJsonLd(html: string, nodes: Json[]): string[] {
const text = visibleText(html);
const problems: string[] = [];
const seen = new Set<string>();
const report = (message: string) => {
// 같은 값이 여러 노드에 반복되면(name 은 사업장·WebSite·WebPage 에 다 있다)
// 같은 사유가 여러 번 쌓인다 — 운영자가 볼 목록이지 통계가 아니다.
if (seen.has(message)) return;
seen.add(message);
problems.push(message);
};
for (const node of nodes) {
// 페이지 메타 노드는 head 로 나가는 값이라 본문에 없다 — 대조하면 전부 오탐이 된다.
if (PAGE_META_TYPES.has(String(node['@type'] ?? ''))) continue;
for (const [path, value] of iterScalars(node)) {
const prop = propName(path);
if (STRUCTURAL.has(prop) || value === '' || typeof value === 'boolean') continue;
const token = String(value);
// URL·이미지는 본문 텍스트가 아니라 요소 속성(src/href)에 있다.
if (token.startsWith('http://') || token.startsWith('https://')) {
if (!html.includes(token)) report(`${prop}: '${token}' 이 화면에 없다`);
continue;
}
if (asShown(value).some((shown) => text.includes(shown))) continue;
if (COMPOSITE_PROPS.has(prop)) {
// 구성 요소가 전부 화면에 있으면 통과. 하나라도 없으면 그 조각을 사유로 남긴다.
const parts = splitComposite(token);
const missing = parts.filter((part) => !text.includes(part));
if (parts.length > 1 && missing.length === 0) continue;
report(`${prop}: '${missing.join(' · ') || token}' 이 화면에 없다`);
continue;
}
report(`${prop}: '${token}' 이 화면에 없다`);
}
// 편의시설·가격은 이름과 값을 따로 본다(구조가 name/value 쌍이라 일반 순회로는 약하다).
for (const feature of asArray(node.amenityFeature)) {
const name = String(feature?.name ?? '');
if (name && !text.includes(name)) report(`amenityFeature[${name}]: 화면에 없다`);
}
for (const offer of asArray(node.makesOffer)) {
const name = String(offer?.name ?? '');
if (name && !text.includes(name)) report(`makesOffer[${name}]: 화면에 없다`);
const price = offer?.price;
if (price !== undefined && price !== null && !asShown(price as Scalar).some((s) => text.includes(s))) {
report(`makesOffer[${name}].price: '${price}' 이 화면에 없다`);
}
}
}
return problems;
}
function asArray(value: unknown): Record<string, unknown>[] {
if (Array.isArray(value)) return value.filter((v) => v && typeof v === 'object');
if (value && typeof value === 'object') return [value as Record<string, unknown>];
return [];
}
/**
* 좌표가 payload 와 같은지. 지도 핀이 엉뚱한 데 찍히는 것도 거짓 정보다.
*
* 좌표는 화면 텍스트로 나오지 않아 본문 대조로는 확인할 수 없다 —
* 검사에서 빼는 것과 검사를 안 하는 것은 다르므로, 원본과 직접 맞춘다.
*/
export function verifyGeo(nodes: Json[], latitude?: number, longitude?: number): string[] {
const problems: string[] = [];
const TOLERANCE = 1e-6;
for (const node of nodes) {
const geo = node.geo as Record<string, unknown> | undefined;
if (!geo) continue;
const pairs: [string, unknown, number | undefined][] = [
['latitude', geo.latitude, latitude],
['longitude', geo.longitude, longitude],
];
for (const [name, shown, source] of pairs) {
if (source === undefined || typeof shown !== 'number' || Math.abs(shown - source) > TOLERANCE) {
problems.push(`geo.${name}: 구조화 데이터 ${String(shown)} != payload ${String(source)}`);
}
}
}
return problems;
}
+9
View File
@@ -0,0 +1,9 @@
/// <reference types="vite/client" />
interface ImportMetaEnv {
readonly VITE_API_BASE_URL?: string;
}
interface ImportMeta {
readonly env: ImportMetaEnv;
}