에디터에서 본 화면과 발행된 화면이 달랐다. 렌더러를 두 벌 들고 있었기 때문이다 —
캔버스는 `builder/canvas/variants/*` 25종, 발행본은 `site/src/sections/*`.
Playwright 로 재 보니 아예 다른 물건이었다(2026-09-09, 1024px):
발행본 15섹션 · 에디터 12섹션 · 겹치는 건 4개뿐, 이름도 달랐다
(gallery↔photos · location↔map · guide↔local)
겹치는 4개조차 높이가 달랐다(info 488↔535 · booking 242↔487 · itinerary 881↔383)
소스를 하나로 모은다. 편집·미리보기 둘 다 발행본 렌더러가 그린다.
**데이터도 한 벌** — `GET /v1/place/{id}/site/preview` 가 발행이 굽는 것과 **같은 함수**
(`build_snapshot` → `to_site_payload`)로 payload 를 만든다. DB 도 파일도 건드리지 않는다.
**왜 iframe 인가** — 컴포넌트만 같게 해서는 안 됐다. 미디어 쿼리는 창 폭을 보는데 실제
사이트 폭은 그 안의 프레임이라, 그리드 컬럼 수가 어긋나 섹션이 두 배씩 길어졌다
(festival 2560→6027 · guide 1168→2168). iframe 은 자체 뷰포트를 가져 발행본과 같은 폭을 본다.
폭만이 아니라 **높이도** 준다 — 히어로가 `clamp(24rem, 62vh, 36rem)` 이라 낮은 iframe 에서는
하한에 걸렸다(384 ↔ 발행본 576). 자리에 안 들어가면 transform 으로 줄인다: 크기는 그대로,
그림만 줄여야 미디어 쿼리가 안 흔들린다.
**색·서체도 한 벌** — `themeVars(payload)` · `fontHref(payload)`. 셸에는 발행본 `<head>` 의
폰트 링크가 없어 글자만 기본 산세리프로 떨어졌다(지오메트리는 같은데 픽셀 차이 92%).
**에디터가 저장된 템플릿을 안 읽던 것** — `applyTheme` 이 섹션·색팔레트는 되살리는데
templateId 를 빠뜨렸다. templateId 는 theme JSON 이 아니라 `sites.template_id` **컬럼**이라
저장 경로가 다른데 읽는 쪽이 theme 만 봤다. 사장님이 '옛 항구' 를 골라 발행해도 다시
들어오면 편집 화면만 흰 바탕·고딕이었다.
**고르기는 iframe 안에서** — 같은 오리진이라 안쪽 문서에 직접 리스너를 건다. 어느 섹션인지는
`data-editor-id` 로 안다(화면 id `gallery` ↔ 설정 id `photos`; `display:contents` 라 레이아웃
무영향). 표시는 outline 이다 — 상자 크기를 바꾸지 않아 발행본과 픽셀이 그대로다.
곁들여 정리한 것
- 켤 수 없는 섹션 둘(`pricing`·`planner`)을 뗐다 — 기본표에도 [+섹션 추가]에도 없고 DB 참조 0건.
- 반대로 `event`(소식)는 기본표가 켜서 **발행되는데** 채울 UI 가 없었다. 명세를 넣는다.
이 아이템만 프롬프트가 "찾아라" 가 아니라 **"옮겨 적어라"** 다 — 이 가게에서 지금 하는
일이라 모델이 알 수 없고, 지어내면 손님이 없는 행사를 보고 찾아온다.
- 예약 버튼이 "네이버 예약 예약" 이었다. `{bookingLabel} 예약` 을 13개 파일에서 각자 이어
붙이고 있었다 — `bookingActionLabel()` 하나로 모은다.
- `solution/site` 의 별칭을 `@` → `@site` 로 옮겼다(60파일 195건). 두 앱이 '@' 를 각자 자기
src 로 두면 발행본 컴포넌트를 빌더에서 부를 때 **조용히 다른 파일을 잡는다.**
검증(Playwright, 같은 사업장·1024px):
섹션 15 = 15 · 순서 일치 · **한쪽에만 있는 섹션 0개**
15개 전부 높이·글자 수·제목이 정확히 같다
편집·미리보기·발행본 셋 다 --tpl-bg #e4dac0 · Gugi
`/preview` ↔ 발행본 문서 높이 9029 = 9029, 픽셀 차이 2.88%(축제 카드 지연 로딩 타이밍)
tsc -b 통과 · eslint 통과.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
216 lines
9.6 KiB
TypeScript
216 lines
9.6 KiB
TypeScript
import {deriveSurfaces, type SitePayload} from '@o2o/shared';
|
|
import {collectJsonLd} from './jsonld';
|
|
import type {PageMeta} from './meta';
|
|
|
|
/**
|
|
* <head> 를 문자열로 만든다.
|
|
*
|
|
* 리액트 컴포넌트가 아니라 문자열인 이유: 프리렌더가 정적 HTML 파일을 직접 쓰기 때문이다.
|
|
* 헬멧류 라이브러리를 끼우면 하이드레이션 이후에 head 가 바뀌는데,
|
|
* 그 시점엔 크롤러가 이미 원본 HTML 을 읽고 떠난 뒤다.
|
|
*/
|
|
|
|
const ESCAPE_MAP: Record<string, string> = {
|
|
'&': '&',
|
|
'<': '<',
|
|
'>': '>',
|
|
'"': '"',
|
|
"'": ''',
|
|
};
|
|
|
|
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 변수로. 사장님이 고른 색이 여기서 실제 페이지 색이 된다. */
|
|
/**
|
|
* 템플릿 토큰을 <head> 에 심는다.
|
|
*
|
|
* ★ 색만 내려보내던 자리다. 그래서 사장님이 레트로(간판체·2px 테두리·갱지)를 골라도
|
|
* 발행 페이지는 늘 같은 고딕으로 나갔다 — 캔버스와 발행본이 다르게 보이는 가장 큰 이유였다.
|
|
* 이제 `theme.look` 의 서체·모서리·테두리·여백까지 같이 심는다.
|
|
* ★ 면 토큰(surface/-alt/inverse/border)은 캔버스와 **같은 식**으로 유도한다(shared/lib/color).
|
|
* 식이 두 벌이면 미리보기와 발행본의 바탕색이 갈린다.
|
|
*/
|
|
/**
|
|
* 템플릿 토큰 — **값**으로 돌려준다.
|
|
*
|
|
* ★ 발행본은 이걸 `<head>` 의 `:root` 에 굽고(themeStyle), 빌더 미리보기는 같은 값을
|
|
* 미리보기 요소의 inline style 로 얹는다(`builder/SitePreview`). 두 곳이 각자 만들면
|
|
* 에디터에서 본 색·서체와 발행된 색·서체가 조용히 갈라진다 — 실제로 그 자리였다.
|
|
*/
|
|
export function themeVars(payload: SitePayload): Record<string, string> {
|
|
const {colors, look} = payload.theme;
|
|
const surfaces = deriveSurfaces(colors);
|
|
const vars: Record<string, string> = {
|
|
'--tpl-primary': colors.primary,
|
|
'--tpl-secondary': colors.secondary,
|
|
'--tpl-bg': colors.bg,
|
|
'--tpl-card': colors.card,
|
|
'--tpl-text': colors.text,
|
|
'--tpl-accent': colors.accent,
|
|
'--tpl-surface': surfaces.surface,
|
|
'--tpl-surface-alt': surfaces.surfaceAlt,
|
|
'--tpl-inverse': surfaces.inverse,
|
|
'--tpl-border': surfaces.border,
|
|
};
|
|
if (look) {
|
|
// ★ 값은 그대로 CSS 에 들어간다. `<`·`}` 이 섞이면 <style> 을 깨뜨릴 수 있어 걸러 낸다 —
|
|
// 서버가 해석하지 않고 실어 보내는 값이라 여기서 한 번은 봐야 한다.
|
|
const safe = (value?: string) => (value && !/[<>{};]/.test(value) ? value : undefined);
|
|
const pairs: [string, string | undefined][] = [
|
|
['--tpl-font-heading', safe(look.fontHeading)],
|
|
['--tpl-font-body', safe(look.fontBody)],
|
|
['--tpl-heading-tracking', safe(look.headingTracking)],
|
|
['--tpl-heading-weight', safe(look.headingWeight)],
|
|
['--tpl-section-space', safe(look.sectionSpace)],
|
|
['--tpl-border-width', safe(look.borderWidth)],
|
|
['--tpl-radius', safe(look.radius)],
|
|
['--tpl-shadow', safe(look.shadow)],
|
|
// ★ 종이 질감. `.paper` 가 이 값을 읽는다 — 없으면 섹션 바탕이 평평한 색면으로만 남는다.
|
|
// 토큰이 비어 있으면 아무것도 깔지 않는다(질감을 원하지 않는 템플릿이 있다).
|
|
['--tpl-texture', safe(look.texture)],
|
|
];
|
|
for (const [name, value] of pairs) if (value) vars[name] = value;
|
|
}
|
|
return vars;
|
|
}
|
|
|
|
export function themeStyle(payload: SitePayload): string {
|
|
const lines = Object.entries(themeVars(payload)).map(([name, value]) => `${name}: ${value};`);
|
|
return [' <style>', ' :root {', ...lines.map((line) => ` ${line}`), ' }', ' </style>'].join('\n');
|
|
}
|
|
|
|
/**
|
|
* 템플릿이 요구하는 웹폰트만 골라 한 번에 받아 온다.
|
|
*
|
|
* ★ 서체 스택 문자열에서 이름을 훑어 아는 것만 붙인다. 전부 항상 실으면 쓰지도 않는 서체가
|
|
* 모든 발행 사이트의 첫 렌더를 늦춘다 — 서체 하나가 그럴 이유가 없다.
|
|
*/
|
|
const WEB_FONTS: [RegExp, string][] = [
|
|
[/Noto Sans KR/i, 'family=Noto+Sans+KR:wght@300..900'],
|
|
[/Noto Serif KR/i, 'family=Noto+Serif+KR:wght@300..700'],
|
|
[/Gugi/i, 'family=Gugi'],
|
|
[/Gowun Batang/i, 'family=Gowun+Batang:wght@400;700'],
|
|
[/Nanum Pen Script/i, 'family=Nanum+Pen+Script'],
|
|
];
|
|
|
|
/** 템플릿이 요구하는 웹폰트 주소. 발행본 <head> 와 빌더 미리보기가 같은 것을 쓴다. */
|
|
export function fontHref(payload: SitePayload): string {
|
|
const stacks = [
|
|
'Noto Sans KR',
|
|
'Noto Serif KR',
|
|
payload.theme.look?.fontHeading ?? '',
|
|
payload.theme.look?.fontBody ?? '',
|
|
].join(' ');
|
|
const families = WEB_FONTS.filter(([pattern]) => pattern.test(stacks)).map(([, param]) => param);
|
|
return `https://fonts.googleapis.com/css2?${families.join('&')}&display=swap`;
|
|
}
|
|
|
|
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="${escapeHtml(fontHref(payload))}" 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');
|
|
}
|