Compare commits
10 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 6e5e229ae5 | |||
| 55906f9d3d | |||
| d4cf2f0225 | |||
| c5c9d17e8b | |||
| 1405280ed3 | |||
| 41e4238290 | |||
| e179035fbc | |||
| e1c91b1668 | |||
| 860eff514a | |||
| e16f8298ab |
@@ -0,0 +1,38 @@
|
|||||||
|
import { NextResponse } from "next/server";
|
||||||
|
import type { Block, ProjectConfig } from "@/features/editor/state/editorStore";
|
||||||
|
import { buildStaticHtml } from "@/app/api/export/route";
|
||||||
|
|
||||||
|
// /api/export/preview 라우트는 Export 결과 HTML 을 ZIP 없이 바로 반환하는
|
||||||
|
// 경량 프리뷰용 엔드포인트이다. 에디터에서 Export 미리보기 UX 를 제공하기 위해 사용한다.
|
||||||
|
|
||||||
|
type PreviewRequestBody = {
|
||||||
|
blocks: Block[];
|
||||||
|
projectConfig?: ProjectConfig;
|
||||||
|
};
|
||||||
|
|
||||||
|
export async function POST(request: Request) {
|
||||||
|
let body: PreviewRequestBody;
|
||||||
|
|
||||||
|
try {
|
||||||
|
// JSON 본문을 파싱해서 blocks + projectConfig 를 추출한다.
|
||||||
|
body = (await request.json()) as PreviewRequestBody;
|
||||||
|
} catch {
|
||||||
|
// 잘못된 JSON 요청에 대해서는 400 에러를 반환한다.
|
||||||
|
return NextResponse.json({ message: "잘못된 JSON 요청입니다." }, { status: 400 });
|
||||||
|
}
|
||||||
|
|
||||||
|
const blocks = Array.isArray(body.blocks) ? body.blocks : [];
|
||||||
|
const projectConfig = body.projectConfig;
|
||||||
|
|
||||||
|
// Export 본문 HTML 은 기존 buildStaticHtml 을 재사용해서 생성한다.
|
||||||
|
// 이렇게 하면 /api/export ZIP 라우트와 동일한 정적 HTML 을 얻을 수 있다.
|
||||||
|
const html = buildStaticHtml(blocks, projectConfig);
|
||||||
|
|
||||||
|
// Export 미리보기는 ZIP 이 아니라 순수 HTML 문자열을 반환한다.
|
||||||
|
return new NextResponse(html, {
|
||||||
|
status: 200,
|
||||||
|
headers: {
|
||||||
|
"Content-Type": "text/html; charset=utf-8",
|
||||||
|
},
|
||||||
|
});
|
||||||
|
}
|
||||||
+117
-100
@@ -52,7 +52,9 @@ const escapeHtml = (value: string): string =>
|
|||||||
const escapeAttr = (value: string): string => escapeHtml(value);
|
const escapeAttr = (value: string): string => escapeHtml(value);
|
||||||
|
|
||||||
export const buildStaticHtml = (blocks: Block[], projectConfig?: ProjectConfig): string => {
|
export const buildStaticHtml = (blocks: Block[], projectConfig?: ProjectConfig): string => {
|
||||||
const pageTitleRaw = (projectConfig?.title ?? "").trim() || "Page Builder Export";
|
const baseTitleRaw = (projectConfig?.title ?? "").trim() || "Page Builder Export";
|
||||||
|
const seoTitleRaw = (projectConfig?.seoTitle ?? "").trim();
|
||||||
|
const pageTitleRaw = seoTitleRaw || baseTitleRaw;
|
||||||
const pageTitle = escapeHtml(pageTitleRaw);
|
const pageTitle = escapeHtml(pageTitleRaw);
|
||||||
|
|
||||||
const headExtraRaw = (projectConfig?.headHtml ?? "").trim();
|
const headExtraRaw = (projectConfig?.headHtml ?? "").trim();
|
||||||
@@ -84,9 +86,97 @@ export const buildStaticHtml = (blocks: Block[], projectConfig?: ProjectConfig):
|
|||||||
const trackingRaw = (projectConfig?.trackingScript ?? "").trim();
|
const trackingRaw = (projectConfig?.trackingScript ?? "").trim();
|
||||||
const trackingHtml = trackingRaw ? `\n${trackingRaw}\n` : "";
|
const trackingHtml = trackingRaw ? `\n${trackingRaw}\n` : "";
|
||||||
|
|
||||||
|
const seoDescriptionRaw = (projectConfig?.seoDescription ?? "").trim();
|
||||||
|
const seoOgImageRaw = (projectConfig?.seoOgImageUrl ?? "").trim();
|
||||||
|
const seoCanonicalRaw = (projectConfig?.seoCanonicalUrl ?? "").trim();
|
||||||
|
const seoNoIndex = projectConfig?.seoNoIndex === true;
|
||||||
|
|
||||||
|
const seoHeadParts: string[] = [];
|
||||||
|
|
||||||
|
if (seoDescriptionRaw) {
|
||||||
|
seoHeadParts.push(
|
||||||
|
` <meta name="description" content="${escapeAttr(seoDescriptionRaw)}" />`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (pageTitleRaw) {
|
||||||
|
seoHeadParts.push(
|
||||||
|
` <meta property="og:title" content="${escapeAttr(pageTitleRaw)}" />`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
if (seoDescriptionRaw) {
|
||||||
|
seoHeadParts.push(
|
||||||
|
` <meta property="og:description" content="${escapeAttr(seoDescriptionRaw)}" />`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
seoHeadParts.push(` <meta property="og:type" content="website" />`);
|
||||||
|
|
||||||
|
if (seoOgImageRaw) {
|
||||||
|
seoHeadParts.push(
|
||||||
|
` <meta property="og:image" content="${escapeAttr(seoOgImageRaw)}" />`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (seoCanonicalRaw) {
|
||||||
|
seoHeadParts.push(
|
||||||
|
` <meta property="og:url" content="${escapeAttr(seoCanonicalRaw)}" />`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Twitter 카드 메타 태그
|
||||||
|
seoHeadParts.push(
|
||||||
|
` <meta name="twitter:card" content="summary_large_image" />`,
|
||||||
|
);
|
||||||
|
if (pageTitleRaw) {
|
||||||
|
seoHeadParts.push(
|
||||||
|
` <meta name="twitter:title" content="${escapeAttr(pageTitleRaw)}" />`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
if (seoDescriptionRaw) {
|
||||||
|
seoHeadParts.push(
|
||||||
|
` <meta name="twitter:description" content="${escapeAttr(seoDescriptionRaw)}" />`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
if (seoOgImageRaw) {
|
||||||
|
seoHeadParts.push(
|
||||||
|
` <meta name="twitter:image" content="${escapeAttr(seoOgImageRaw)}" />`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (seoCanonicalRaw) {
|
||||||
|
seoHeadParts.push(
|
||||||
|
` <link rel="canonical" href="${escapeAttr(seoCanonicalRaw)}" />`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (seoNoIndex) {
|
||||||
|
seoHeadParts.push(
|
||||||
|
` <meta name="robots" content="noindex, nofollow" />`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const seoHeadHtml = seoHeadParts.length > 0 ? `\n${seoHeadParts.join("\n")}` : "";
|
||||||
|
|
||||||
const sectionBlocks = blocks.filter((b) => b.type === "section");
|
const sectionBlocks = blocks.filter((b) => b.type === "section");
|
||||||
const rootBlocks = blocks.filter((b) => !b.sectionId && b.type !== "section");
|
const rootBlocks = blocks.filter((b) => !b.sectionId && b.type !== "section");
|
||||||
|
|
||||||
|
// Form 컨트롤러(FormBlock)와 개별 필드 블록(formInput/formSelect/...) 를 연결하기 위한 맵.
|
||||||
|
// - key: 필드 블록 id (fieldIds 에 포함된 id)
|
||||||
|
// - value: 해당 필드가 속한 <form> 요소의 DOM id (예: form_form_1)
|
||||||
|
const fieldIdToFormId = new Map<string, string>();
|
||||||
|
for (const block of blocks) {
|
||||||
|
if (block.type !== "form") continue;
|
||||||
|
const props = (block.props ?? {}) as FormBlockProps;
|
||||||
|
const fieldIds = Array.isArray(props.fieldIds) ? props.fieldIds : [];
|
||||||
|
if (fieldIds.length === 0) continue;
|
||||||
|
const formDomId = `form_${block.id}`;
|
||||||
|
for (const fieldId of fieldIds) {
|
||||||
|
if (typeof fieldId === "string" && fieldId.trim() !== "") {
|
||||||
|
fieldIdToFormId.set(fieldId, formDomId);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
const renderBlock = (block: Block): string => {
|
const renderBlock = (block: Block): string => {
|
||||||
if (block.type === "text") {
|
if (block.type === "text") {
|
||||||
const props = (block.props ?? {}) as TextBlockProps;
|
const props = (block.props ?? {}) as TextBlockProps;
|
||||||
@@ -243,107 +333,24 @@ export const buildStaticHtml = (blocks: Block[], projectConfig?: ProjectConfig):
|
|||||||
const props = (block.props ?? {}) as FormBlockProps;
|
const props = (block.props ?? {}) as FormBlockProps;
|
||||||
const tokens = computeFormBlockExportTokens(block, blocks);
|
const tokens = computeFormBlockExportTokens(block, blocks);
|
||||||
const controllerFields = tokens.hasControllerFields ? tokens.controllerFields : [];
|
const controllerFields = tokens.hasControllerFields ? tokens.controllerFields : [];
|
||||||
const fallbackFields = tokens.fallbackFields;
|
|
||||||
|
|
||||||
const hasControllerFields = controllerFields.length > 0;
|
const hasControllerFields = controllerFields.length > 0;
|
||||||
const hasFallbackFields = fallbackFields.length > 0;
|
|
||||||
|
|
||||||
// FormBlock 이 컨트롤러/필드 정보를 전혀 가지고 있지 않으면 정적 HTML 에서는 아무 것도 렌더하지 않는다.
|
// FormBlock 이 컨트롤러 필드 정보를 전혀 가지고 있지 않으면
|
||||||
if (!hasControllerFields && !hasFallbackFields) {
|
// Export 레이어에서는 아무 것도 렌더하지 않는다 (fallback fields 기반 pb-form 도 생성하지 않음).
|
||||||
|
if (!hasControllerFields) {
|
||||||
return "";
|
return "";
|
||||||
}
|
}
|
||||||
|
|
||||||
const formParts: string[] = [];
|
// 컨트롤러 전용 FormBlock: fieldIds 기반으로 개별 필드 블록과 연결되는 순수 컨트롤러 폼만 생성한다.
|
||||||
const formStyleAttr = tokens.formStyleParts.length > 0 ? ` style="${tokens.formStyleParts.join(";")}"` : "";
|
// - Export 에서는 레이아웃/스타일을 가지지 않고, id/메서드만 가지는 최소한의 <form> 요소만 만든다.
|
||||||
|
const formId = `form_${block.id}`;
|
||||||
|
const method = props.method ?? "POST";
|
||||||
|
const methodAttr = ` method="${method.toLowerCase()}"`;
|
||||||
|
|
||||||
formParts.push(`<form class="pb-form" method="post"${formStyleAttr}>`);
|
const parts: string[] = [];
|
||||||
|
parts.push(`<form id="${escapeAttr(formId)}" class="pb-form-controller"${methodAttr}></form>`);
|
||||||
if (hasControllerFields) {
|
return parts.join("");
|
||||||
for (const fieldBlock of controllerFields) {
|
|
||||||
const anyProps: any = fieldBlock.props ?? {};
|
|
||||||
const name = typeof anyProps.formFieldName === "string" ? anyProps.formFieldName : fieldBlock.id;
|
|
||||||
const label =
|
|
||||||
typeof anyProps.label === "string" || typeof anyProps.groupLabel === "string"
|
|
||||||
? (anyProps.label ?? anyProps.groupLabel)
|
|
||||||
: name;
|
|
||||||
|
|
||||||
const textColorRaw =
|
|
||||||
typeof anyProps.textColorCustom === "string" && anyProps.textColorCustom.trim() !== ""
|
|
||||||
? anyProps.textColorCustom.trim()
|
|
||||||
: "";
|
|
||||||
const labelStyleAttr = textColorRaw ? ` style="color:${escapeAttr(textColorRaw)}"` : "";
|
|
||||||
const fieldTextStyleAttr = textColorRaw ? ` style="color:${escapeAttr(textColorRaw)}"` : "";
|
|
||||||
|
|
||||||
formParts.push(`<div class="pb-form-field">`);
|
|
||||||
formParts.push(`<label class="pb-form-label"${labelStyleAttr}>${escapeHtml(label ?? "")}</label>`);
|
|
||||||
|
|
||||||
if (fieldBlock.type === "formInput") {
|
|
||||||
const type = anyProps.inputType === "email" ? "email" : "text";
|
|
||||||
const required = anyProps.required ? " required" : "";
|
|
||||||
formParts.push(
|
|
||||||
`<input class="pb-input" type="${type}" name="${escapeAttr(name)}" placeholder="${escapeAttr(
|
|
||||||
label ?? "",
|
|
||||||
)}"${required}${fieldTextStyleAttr} />`,
|
|
||||||
);
|
|
||||||
} else if (fieldBlock.type === "formSelect") {
|
|
||||||
const required = anyProps.required ? " required" : "";
|
|
||||||
const options: FormSelectOption[] = Array.isArray(anyProps.options) ? anyProps.options : [];
|
|
||||||
formParts.push(`<select class="pb-select" name="${escapeAttr(name)}"${required}${fieldTextStyleAttr}>`);
|
|
||||||
for (const opt of options) {
|
|
||||||
formParts.push(
|
|
||||||
`<option value="${escapeAttr(opt.value)}">${escapeHtml(opt.label)}</option>`,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
formParts.push(`</select>`);
|
|
||||||
} else if (fieldBlock.type === "formCheckbox") {
|
|
||||||
const options = Array.isArray(anyProps.options) ? anyProps.options : [];
|
|
||||||
for (const opt of options) {
|
|
||||||
formParts.push(
|
|
||||||
`<label class="pb-form-option"${fieldTextStyleAttr}><input type="checkbox" name="${escapeAttr(
|
|
||||||
name,
|
|
||||||
)}" value="${escapeAttr(opt.value)}" /> ${escapeHtml(opt.label)}</label>`,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
} else if (fieldBlock.type === "formRadio") {
|
|
||||||
const options = Array.isArray(anyProps.options) ? anyProps.options : [];
|
|
||||||
for (const opt of options) {
|
|
||||||
formParts.push(
|
|
||||||
`<label class="pb-form-option"${fieldTextStyleAttr}><input type="radio" name="${escapeAttr(
|
|
||||||
name,
|
|
||||||
)}" value="${escapeAttr(opt.value)}" /> ${escapeHtml(opt.label)}</label>`,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
formParts.push(`</div>`);
|
|
||||||
}
|
|
||||||
} else if (hasFallbackFields) {
|
|
||||||
for (const field of fallbackFields) {
|
|
||||||
const required = field.required ? " required" : "";
|
|
||||||
const label = field.label ?? field.name;
|
|
||||||
formParts.push(`<div class="pb-form-field">`);
|
|
||||||
formParts.push(`<label class="pb-form-label">${escapeHtml(label)}</label>`);
|
|
||||||
if (field.type === "textarea") {
|
|
||||||
formParts.push(
|
|
||||||
`<textarea class="pb-textarea" name="${escapeAttr(field.name)}" placeholder="${escapeAttr(
|
|
||||||
label,
|
|
||||||
)}"${required}></textarea>`,
|
|
||||||
);
|
|
||||||
} else {
|
|
||||||
formParts.push(
|
|
||||||
`<input class="pb-input" type="${field.type}" name="${escapeAttr(
|
|
||||||
field.name,
|
|
||||||
)}" placeholder="${escapeAttr(label)}"${required} />`,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
formParts.push(`</div>`);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
formParts.push(`<button type="submit" class="pb-btn-base pb-btn-size-md pb-btn-variant-solid-primary">제출</button>`);
|
|
||||||
formParts.push(`</form>`);
|
|
||||||
|
|
||||||
return formParts.join("");
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if (block.type === "divider") {
|
if (block.type === "divider") {
|
||||||
@@ -376,13 +383,15 @@ export const buildStaticHtml = (blocks: Block[], projectConfig?: ProjectConfig):
|
|||||||
const required = props.required ? " required" : "";
|
const required = props.required ? " required" : "";
|
||||||
|
|
||||||
const tokens = computeFormInputExportTokens(props, { escapeAttr });
|
const tokens = computeFormInputExportTokens(props, { escapeAttr });
|
||||||
|
const formId = fieldIdToFormId.get(block.id);
|
||||||
|
const formAttr = formId ? ` form="${escapeAttr(formId)}"` : "";
|
||||||
|
|
||||||
return [
|
return [
|
||||||
'<div class="pb-form-field">',
|
'<div class="pb-form-field">',
|
||||||
`<label class="pb-form-label"${tokens.labelStyleAttr}>${escapeHtml(label)}</label>`,
|
`<label class="pb-form-label"${tokens.labelStyleAttr}>${escapeHtml(label)}</label>`,
|
||||||
`<input class="pb-input" type="${type}" name="${escapeAttr(name)}" placeholder="${escapeAttr(
|
`<input class="pb-input" type="${type}" name="${escapeAttr(name)}" placeholder="${escapeAttr(
|
||||||
label,
|
label,
|
||||||
)}"${required}${tokens.inputStyleAttr} />`,
|
)}"${required}${tokens.inputStyleAttr}${formAttr} />`,
|
||||||
"</div>",
|
"</div>",
|
||||||
].join("");
|
].join("");
|
||||||
}
|
}
|
||||||
@@ -396,11 +405,15 @@ export const buildStaticHtml = (blocks: Block[], projectConfig?: ProjectConfig):
|
|||||||
const options: FormSelectOption[] = Array.isArray(props.options) ? props.options : [];
|
const options: FormSelectOption[] = Array.isArray(props.options) ? props.options : [];
|
||||||
|
|
||||||
const tokens = computeFormSelectExportTokens(props, { escapeAttr });
|
const tokens = computeFormSelectExportTokens(props, { escapeAttr });
|
||||||
|
const formId = fieldIdToFormId.get(block.id);
|
||||||
|
const formAttr = formId ? ` form="${escapeAttr(formId)}"` : "";
|
||||||
|
|
||||||
const parts: string[] = [];
|
const parts: string[] = [];
|
||||||
parts.push('<div class="pb-form-field">');
|
parts.push('<div class="pb-form-field">');
|
||||||
parts.push(`<label class="pb-form-label"${tokens.labelStyleAttr}>${escapeHtml(label)}</label>`);
|
parts.push(`<label class="pb-form-label"${tokens.labelStyleAttr}>${escapeHtml(label)}</label>`);
|
||||||
parts.push(`<select class="pb-select" name="${escapeAttr(name)}"${required}${tokens.selectStyleAttr}>`);
|
parts.push(
|
||||||
|
`<select class="pb-select" name="${escapeAttr(name)}"${required}${tokens.selectStyleAttr}${formAttr}>`,
|
||||||
|
);
|
||||||
for (const opt of options) {
|
for (const opt of options) {
|
||||||
parts.push(
|
parts.push(
|
||||||
`<option value="${escapeAttr(opt.value)}">${escapeHtml(opt.label)}</option>`,
|
`<option value="${escapeAttr(opt.value)}">${escapeHtml(opt.label)}</option>`,
|
||||||
@@ -422,6 +435,8 @@ export const buildStaticHtml = (blocks: Block[], projectConfig?: ProjectConfig):
|
|||||||
const options = Array.isArray(props.options) ? props.options : [];
|
const options = Array.isArray(props.options) ? props.options : [];
|
||||||
|
|
||||||
const tokens = computeFormCheckboxExportTokens(props, { escapeAttr });
|
const tokens = computeFormCheckboxExportTokens(props, { escapeAttr });
|
||||||
|
const formId = fieldIdToFormId.get(block.id);
|
||||||
|
const formAttr = formId ? ` form="${escapeAttr(formId)}"` : "";
|
||||||
|
|
||||||
const parts: string[] = [];
|
const parts: string[] = [];
|
||||||
parts.push('<div class="pb-form-field">');
|
parts.push('<div class="pb-form-field">');
|
||||||
@@ -430,7 +445,7 @@ export const buildStaticHtml = (blocks: Block[], projectConfig?: ProjectConfig):
|
|||||||
parts.push(
|
parts.push(
|
||||||
`<label class="pb-form-option"${tokens.optionStyleAttr}><input type="checkbox" name="${escapeAttr(
|
`<label class="pb-form-option"${tokens.optionStyleAttr}><input type="checkbox" name="${escapeAttr(
|
||||||
name,
|
name,
|
||||||
)}" value="${escapeAttr(opt.value)}" /> ${escapeHtml(opt.label)}</label>`,
|
)}" value="${escapeAttr(opt.value)}"${formAttr} /> ${escapeHtml(opt.label)}</label>`,
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
parts.push("</div>");
|
parts.push("</div>");
|
||||||
@@ -448,6 +463,8 @@ export const buildStaticHtml = (blocks: Block[], projectConfig?: ProjectConfig):
|
|||||||
const options = Array.isArray(props.options) ? props.options : [];
|
const options = Array.isArray(props.options) ? props.options : [];
|
||||||
|
|
||||||
const tokens = computeFormRadioExportTokens(props, { escapeAttr });
|
const tokens = computeFormRadioExportTokens(props, { escapeAttr });
|
||||||
|
const formId = fieldIdToFormId.get(block.id);
|
||||||
|
const formAttr = formId ? ` form="${escapeAttr(formId)}"` : "";
|
||||||
|
|
||||||
const parts: string[] = [];
|
const parts: string[] = [];
|
||||||
parts.push('<div class="pb-form-field">');
|
parts.push('<div class="pb-form-field">');
|
||||||
@@ -456,7 +473,7 @@ export const buildStaticHtml = (blocks: Block[], projectConfig?: ProjectConfig):
|
|||||||
parts.push(
|
parts.push(
|
||||||
`<label class="pb-form-option"${tokens.optionStyleAttr}><input type="radio" name="${escapeAttr(
|
`<label class="pb-form-option"${tokens.optionStyleAttr}><input type="radio" name="${escapeAttr(
|
||||||
name,
|
name,
|
||||||
)}" value="${escapeAttr(opt.value)}" /> ${escapeHtml(opt.label)}</label>`,
|
)}" value="${escapeAttr(opt.value)}"${formAttr} /> ${escapeHtml(opt.label)}</label>`,
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
parts.push("</div>");
|
parts.push("</div>");
|
||||||
@@ -515,7 +532,7 @@ export const buildStaticHtml = (blocks: Block[], projectConfig?: ProjectConfig):
|
|||||||
<meta charset="utf-8" />
|
<meta charset="utf-8" />
|
||||||
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
||||||
<title>${pageTitle}</title>
|
<title>${pageTitle}</title>
|
||||||
<link rel="stylesheet" href="./builder.css" />${headExtra}
|
<link rel="stylesheet" href="./builder.css" />${seoHeadHtml}${headExtra}
|
||||||
</head>
|
</head>
|
||||||
<body style="${bodyStyle}">
|
<body style="${bodyStyle}">
|
||||||
<main>
|
<main>
|
||||||
|
|||||||
@@ -6,35 +6,31 @@ import { PrismaClient } from "@/generated/prisma/client";
|
|||||||
const UPLOAD_DIR = path.join(process.cwd(), "uploads");
|
const UPLOAD_DIR = path.join(process.cwd(), "uploads");
|
||||||
|
|
||||||
let prisma: PrismaClient | null = null;
|
let prisma: PrismaClient | null = null;
|
||||||
try {
|
if (process.env.DATABASE_URL && process.env.DATABASE_URL.trim() !== "") {
|
||||||
prisma = new PrismaClient();
|
try {
|
||||||
} catch (error) {
|
prisma = new PrismaClient();
|
||||||
// DB 가 준비되지 않은 환경에서는 mimeType 조회 없이 기본값만 사용한다.
|
} catch (error) {
|
||||||
console.error("PrismaClient 초기화 실패 - 기본 MIME 타입으로만 응답합니다.", error);
|
// DB 가 준비되지 않은 환경에서는 mimeType 조회 없이 기본값만 사용한다.
|
||||||
prisma = null;
|
console.error("PrismaClient 초기화 실패 - 기본 MIME 타입으로만 응답합니다.", error);
|
||||||
|
prisma = null;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
interface Params {
|
export async function GET(request: Request) {
|
||||||
params: {
|
// Next.js 15 이후 params 가 Promise 로 전달되는 경고를 피하기 위해,
|
||||||
id: string;
|
// 동적 세그먼트는 request.url 의 path 에서 직접 파싱한다.
|
||||||
};
|
let id: string | undefined;
|
||||||
}
|
|
||||||
|
|
||||||
export async function GET(request: Request, ctx: Params) {
|
try {
|
||||||
// Next.js 가 params 를 항상 보장하지 않는 상황을 대비해, URL 경로에서 id 를 보완적으로 파싱한다.
|
const url = new URL(request.url);
|
||||||
let id: string | undefined = ctx?.params?.id;
|
const segments = url.pathname.split("/").filter(Boolean);
|
||||||
if (!id) {
|
// [..., "api", "image", ":id"] 형태를 기대한다.
|
||||||
try {
|
const last = segments[segments.length - 1];
|
||||||
const url = new URL(request.url);
|
if (last && last !== "image") {
|
||||||
const segments = url.pathname.split("/").filter(Boolean);
|
id = last;
|
||||||
// [..., "api", "image", ":id"] 형태를 기대한다.
|
|
||||||
const last = segments[segments.length - 1];
|
|
||||||
if (last && last !== "image") {
|
|
||||||
id = last;
|
|
||||||
}
|
|
||||||
} catch {
|
|
||||||
// URL 파싱 실패 시에는 그대로 둔다.
|
|
||||||
}
|
}
|
||||||
|
} catch {
|
||||||
|
// URL 파싱 실패 시에는 그대로 둔다.
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!id) {
|
if (!id) {
|
||||||
|
|||||||
@@ -8,13 +8,15 @@ import { PrismaClient } from "@/generated/prisma/client";
|
|||||||
const UPLOAD_DIR = path.join(process.cwd(), "uploads");
|
const UPLOAD_DIR = path.join(process.cwd(), "uploads");
|
||||||
|
|
||||||
let prisma: PrismaClient | null = null;
|
let prisma: PrismaClient | null = null;
|
||||||
try {
|
if (process.env.DATABASE_URL && process.env.DATABASE_URL.trim() !== "") {
|
||||||
prisma = new PrismaClient();
|
try {
|
||||||
} catch (error) {
|
prisma = new PrismaClient();
|
||||||
// DB 가 준비되지 않은 개발/테스트 환경에서도 업로드 자체는 동작할 수 있도록,
|
} catch (error) {
|
||||||
// Prisma 초기화 실패는 치명적 오류로 취급하지 않고 로그만 남긴다.
|
// DB 가 준비되지 않은 개발/테스트 환경에서도 업로드 자체는 동작할 수 있도록,
|
||||||
console.error("PrismaClient 초기화 실패 - 파일 시스템 전용 모드로 동작합니다.", error);
|
// Prisma 초기화 실패는 치명적 오류로 취급하지 않고 로그만 남긴다.
|
||||||
prisma = null;
|
console.error("PrismaClient 초기화 실패 - 파일 시스템 전용 모드로 동작합니다.", error);
|
||||||
|
prisma = null;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function POST(request: Request) {
|
export async function POST(request: Request) {
|
||||||
|
|||||||
@@ -2,7 +2,6 @@
|
|||||||
|
|
||||||
import type { Block, ButtonBlockProps, FormBlockProps } from "@/features/editor/state/editorStore";
|
import type { Block, ButtonBlockProps, FormBlockProps } from "@/features/editor/state/editorStore";
|
||||||
import { NumericPropertyControl } from "@/features/editor/components/NumericPropertyControl";
|
import { NumericPropertyControl } from "@/features/editor/components/NumericPropertyControl";
|
||||||
import { ColorPickerField, TEXT_COLOR_PALETTE } from "@/features/editor/components/ColorPickerField";
|
|
||||||
|
|
||||||
interface FormControllerPanelProps {
|
interface FormControllerPanelProps {
|
||||||
block: Block; // type === "form"
|
block: Block; // type === "form"
|
||||||
@@ -131,7 +130,7 @@ export function FormControllerPanel({ block, blocks, selectedBlockId, updateBloc
|
|||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="space-y-2 border-t border-slate-800 pt-3">
|
<div className="space-y-2 border-t border-slate-800 pt-3 mt-4">
|
||||||
<h3 className="text-[11px] font-semibold text-slate-200">폼 레이아웃</h3>
|
<h3 className="text-[11px] font-semibold text-slate-200">폼 레이아웃</h3>
|
||||||
<label className="flex flex-col gap-1 text-xs text-slate-400">
|
<label className="flex flex-col gap-1 text-xs text-slate-400">
|
||||||
<span>폼 너비 모드</span>
|
<span>폼 너비 모드</span>
|
||||||
@@ -140,27 +139,27 @@ export function FormControllerPanel({ block, blocks, selectedBlockId, updateBloc
|
|||||||
value={formProps.formWidthMode ?? "auto"}
|
value={formProps.formWidthMode ?? "auto"}
|
||||||
onChange={(e) =>
|
onChange={(e) =>
|
||||||
updateBlock(selectedBlockId, {
|
updateBlock(selectedBlockId, {
|
||||||
formWidthMode: e.target.value,
|
formWidthMode: e.target.value as FormBlockProps["formWidthMode"],
|
||||||
} as any)
|
} as any)
|
||||||
}
|
}
|
||||||
>
|
>
|
||||||
<option value="auto">내용에 맞춤</option>
|
<option value="auto">자동</option>
|
||||||
<option value="full">전체 폭</option>
|
<option value="full">전체 폭</option>
|
||||||
<option value="fixed">고정 폭 (px)</option>
|
<option value="fixed">고정 값</option>
|
||||||
</select>
|
</select>
|
||||||
</label>
|
</label>
|
||||||
{(formProps.formWidthMode ?? "auto") === "fixed" && (
|
{(formProps.formWidthMode ?? "auto") === "fixed" && (
|
||||||
<NumericPropertyControl
|
<NumericPropertyControl
|
||||||
label="폼 고정 너비 (px)"
|
label="폼 고정 너비 (px)"
|
||||||
unitLabel="(px)"
|
unitLabel="(px)"
|
||||||
value={typeof formProps.formWidthPx === "number" ? formProps.formWidthPx : 360}
|
value={typeof formProps.formWidthPx === "number" ? formProps.formWidthPx : 480}
|
||||||
min={160}
|
min={160}
|
||||||
max={960}
|
max={1200}
|
||||||
step={10}
|
step={10}
|
||||||
presets={[
|
presets={[
|
||||||
{ id: "sm", label: "좁게", value: 280 },
|
{ id: "sm", label: "좁게", value: 320 },
|
||||||
{ id: "md", label: "보통", value: 360 },
|
{ id: "md", label: "보통", value: 480 },
|
||||||
{ id: "lg", label: "넓게", value: 480 },
|
{ id: "lg", label: "넓게", value: 640 },
|
||||||
]}
|
]}
|
||||||
onChangeValue={(v) =>
|
onChangeValue={(v) =>
|
||||||
updateBlock(selectedBlockId, {
|
updateBlock(selectedBlockId, {
|
||||||
@@ -172,14 +171,15 @@ export function FormControllerPanel({ block, blocks, selectedBlockId, updateBloc
|
|||||||
<NumericPropertyControl
|
<NumericPropertyControl
|
||||||
label="폼 위/아래 여백 (px)"
|
label="폼 위/아래 여백 (px)"
|
||||||
unitLabel="(px)"
|
unitLabel="(px)"
|
||||||
value={typeof formProps.marginYPx === "number" ? formProps.marginYPx : 16}
|
value={typeof formProps.marginYPx === "number" ? formProps.marginYPx : 24}
|
||||||
min={0}
|
min={0}
|
||||||
max={80}
|
max={160}
|
||||||
step={2}
|
step={4}
|
||||||
presets={[
|
presets={[
|
||||||
{ id: "tight", label: "좁게", value: 8 },
|
{ id: "none", label: "없음", value: 0 },
|
||||||
{ id: "normal", label: "보통", value: 16 },
|
{ id: "compact", label: "좁게", value: 16 },
|
||||||
{ id: "relaxed", label: "넓게", value: 32 },
|
{ id: "normal", label: "보통", value: 24 },
|
||||||
|
{ id: "spacious", label: "넓게", value: 40 },
|
||||||
]}
|
]}
|
||||||
onChangeValue={(v) =>
|
onChangeValue={(v) =>
|
||||||
updateBlock(selectedBlockId, {
|
updateBlock(selectedBlockId, {
|
||||||
@@ -189,31 +189,6 @@ export function FormControllerPanel({ block, blocks, selectedBlockId, updateBloc
|
|||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="space-y-2 border-t border-slate-800 pt-3 mt-4">
|
|
||||||
<h3 className="text-[11px] font-semibold text-slate-200">폼 스타일</h3>
|
|
||||||
<ColorPickerField
|
|
||||||
label="폼 배경색"
|
|
||||||
ariaLabelColorInput="폼 배경색 피커"
|
|
||||||
ariaLabelHexInput="폼 배경색 HEX"
|
|
||||||
value={
|
|
||||||
formProps.backgroundColorCustom && formProps.backgroundColorCustom.trim() !== ""
|
|
||||||
? formProps.backgroundColorCustom
|
|
||||||
: TEXT_COLOR_PALETTE[0]?.color ?? "#e5e7eb"
|
|
||||||
}
|
|
||||||
onChange={(hex) => {
|
|
||||||
updateBlock(selectedBlockId, {
|
|
||||||
backgroundColorCustom: hex,
|
|
||||||
} as any);
|
|
||||||
}}
|
|
||||||
palette={TEXT_COLOR_PALETTE}
|
|
||||||
onPaletteSelect={(item) => {
|
|
||||||
updateBlock(selectedBlockId, {
|
|
||||||
backgroundColorCustom: item.color,
|
|
||||||
} as any);
|
|
||||||
}}
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div className="space-y-2 border-t border-slate-800 pt-3 mt-4">
|
<div className="space-y-2 border-t border-slate-800 pt-3 mt-4">
|
||||||
<h3 className="text-[11px] font-semibold text-slate-200">폼 메시지</h3>
|
<h3 className="text-[11px] font-semibold text-slate-200">폼 메시지</h3>
|
||||||
<label className="flex flex-col gap-1 text-xs text-slate-400">
|
<label className="flex flex-col gap-1 text-xs text-slate-400">
|
||||||
|
|||||||
+93
-1
@@ -135,7 +135,9 @@ export default function EditorPage() {
|
|||||||
const [selectedBlockIds, setSelectedBlockIds] = useState<string[]>([]);
|
const [selectedBlockIds, setSelectedBlockIds] = useState<string[]>([]);
|
||||||
|
|
||||||
const [menuOpen, setMenuOpen] = useState(false);
|
const [menuOpen, setMenuOpen] = useState(false);
|
||||||
const [activeModal, setActiveModal] = useState<"project" | "json" | null>(null);
|
const [activeModal, setActiveModal] = useState<"project" | "json" | "exportPreview" | null>(null);
|
||||||
|
const [exportPreviewHtml, setExportPreviewHtml] = useState("");
|
||||||
|
const [exportPreviewStatus, setExportPreviewStatus] = useState<"idle" | "loading" | "error">("idle");
|
||||||
|
|
||||||
const sensors = useSensors(useSensor(PointerSensor));
|
const sensors = useSensors(useSensor(PointerSensor));
|
||||||
|
|
||||||
@@ -188,6 +190,37 @@ export default function EditorPage() {
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const handleRefreshExportPreview = async () => {
|
||||||
|
try {
|
||||||
|
setExportPreviewStatus("loading");
|
||||||
|
|
||||||
|
const payload = {
|
||||||
|
blocks,
|
||||||
|
projectConfig,
|
||||||
|
};
|
||||||
|
|
||||||
|
const response = await fetch("/api/export/preview", {
|
||||||
|
method: "POST",
|
||||||
|
headers: {
|
||||||
|
"Content-Type": "application/json",
|
||||||
|
},
|
||||||
|
body: JSON.stringify(payload),
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!response.ok) {
|
||||||
|
setExportPreviewStatus("error");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const html = await response.text();
|
||||||
|
setExportPreviewHtml(html);
|
||||||
|
setExportPreviewStatus("idle");
|
||||||
|
} catch (error) {
|
||||||
|
console.error("Export 미리보기 요청 중 오류", error);
|
||||||
|
setExportPreviewStatus("error");
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
const commitEditing = () => {
|
const commitEditing = () => {
|
||||||
if (!editingBlockId) return;
|
if (!editingBlockId) return;
|
||||||
updateBlock(editingBlockId, { text: editingText });
|
updateBlock(editingBlockId, { text: editingText });
|
||||||
@@ -685,6 +718,16 @@ export default function EditorPage() {
|
|||||||
>
|
>
|
||||||
JSON 내보내기/불러오기
|
JSON 내보내기/불러오기
|
||||||
</button>
|
</button>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
className="w-full px-3 py-2 text-left hover:bg-slate-800 text-slate-100 border-t border-slate-800"
|
||||||
|
onClick={() => {
|
||||||
|
setMenuOpen(false);
|
||||||
|
setActiveModal("exportPreview");
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
Export 미리보기
|
||||||
|
</button>
|
||||||
<button
|
<button
|
||||||
type="button"
|
type="button"
|
||||||
className="w-full px-3 py-2 text-left hover:bg-slate-800 text-slate-100 border-t border-slate-800"
|
className="w-full px-3 py-2 text-left hover:bg-slate-800 text-slate-100 border-t border-slate-800"
|
||||||
@@ -807,6 +850,55 @@ export default function EditorPage() {
|
|||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
|
{activeModal === "exportPreview" && (
|
||||||
|
<div className="fixed inset-0 z-30 flex items-center justify-center bg-black/60">
|
||||||
|
<div className="w-full max-w-4xl rounded-lg border border-slate-700 bg-slate-900 p-4 text-xs text-slate-100 shadow-xl">
|
||||||
|
<div className="flex items-center justify-between mb-3">
|
||||||
|
<h3 className="text-sm font-medium">Export 미리보기</h3>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
className="text-slate-400 hover:text-slate-100 text-sm"
|
||||||
|
onClick={() => setActiveModal(null)}
|
||||||
|
>
|
||||||
|
✕
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
<div className="space-y-3">
|
||||||
|
<div className="flex items-center justify-between gap-2">
|
||||||
|
<p className="text-[11px] text-slate-400">
|
||||||
|
현재 캔버스 상태를 기반으로 생성된 정적 Export HTML 을 미리 확인할 수 있습니다.
|
||||||
|
</p>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
className="rounded border border-sky-700 bg-sky-950 px-3 py-1 text-[11px] text-sky-100 hover:bg-sky-900 disabled:opacity-60 disabled:cursor-not-allowed"
|
||||||
|
onClick={handleRefreshExportPreview}
|
||||||
|
disabled={exportPreviewStatus === "loading"}
|
||||||
|
>
|
||||||
|
{exportPreviewStatus === "loading" ? "로딩 중..." : "미리보기 새로고침"}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
{exportPreviewStatus === "error" && (
|
||||||
|
<p className="text-[11px] text-red-300">
|
||||||
|
Export 미리보기 HTML 을 불러오는 중 오류가 발생했습니다. 잠시 후 다시 시도해 주세요.
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
|
{exportPreviewHtml ? (
|
||||||
|
<iframe
|
||||||
|
title="Export preview"
|
||||||
|
data-testid="export-preview-frame"
|
||||||
|
className="w-full h-[480px] rounded border border-slate-700 bg-slate-950"
|
||||||
|
srcDoc={exportPreviewHtml}
|
||||||
|
/>
|
||||||
|
) : (
|
||||||
|
<div className="w-full h-[200px] rounded border border-dashed border-slate-700 bg-slate-950 flex items-center justify-center text-[11px] text-slate-500">
|
||||||
|
아직 Export 미리보기 HTML 이 없습니다. "미리보기 새로고침" 버튼을 눌러 생성해 보세요.
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
{activeModal === "json" && (
|
{activeModal === "json" && (
|
||||||
<div className="fixed inset-0 z-30 flex items-center justify-center bg-black/60">
|
<div className="fixed inset-0 z-30 flex items-center justify-center bg-black/60">
|
||||||
<div className="w-full max-w-2xl rounded-lg border border-slate-700 bg-slate-900 p-4 text-xs text-slate-100 shadow-xl">
|
<div className="w-full max-w-2xl rounded-lg border border-slate-700 bg-slate-900 p-4 text-xs text-slate-100 shadow-xl">
|
||||||
|
|||||||
@@ -104,6 +104,65 @@ export function ProjectPropertiesPanel() {
|
|||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
<div className="space-y-2 border-t border-slate-800 pt-3">
|
||||||
|
<h4 className="text-[11px] font-semibold text-slate-200">SEO / 메타</h4>
|
||||||
|
|
||||||
|
<label className="flex flex-col gap-1">
|
||||||
|
<span className="text-slate-400">SEO 타이틀</span>
|
||||||
|
<input
|
||||||
|
className="w-full rounded border border-slate-700 bg-slate-900 px-2 py-1 text-xs outline-none focus:border-sky-500"
|
||||||
|
aria-label="SEO 타이틀"
|
||||||
|
placeholder={projectConfig.title || "페이지 제목"}
|
||||||
|
value={projectConfig.seoTitle ?? ""}
|
||||||
|
onChange={(e) => updateProjectConfig({ seoTitle: e.target.value })}
|
||||||
|
/>
|
||||||
|
</label>
|
||||||
|
|
||||||
|
<label className="flex flex-col gap-1">
|
||||||
|
<span className="text-slate-400">메타 디스크립션</span>
|
||||||
|
<textarea
|
||||||
|
className="w-full rounded border border-slate-700 bg-slate-900 px-2 py-1 text-[11px] outline-none focus:border-sky-500 min-h-[56px]"
|
||||||
|
aria-label="메타 디스크립션"
|
||||||
|
placeholder="검색엔진 및 SNS 공유에 노출될 페이지 설명을 입력하세요."
|
||||||
|
value={projectConfig.seoDescription ?? ""}
|
||||||
|
onChange={(e) => updateProjectConfig({ seoDescription: e.target.value })}
|
||||||
|
/>
|
||||||
|
</label>
|
||||||
|
|
||||||
|
<label className="flex flex-col gap-1">
|
||||||
|
<span className="text-slate-400">OG/Twitter 이미지 URL</span>
|
||||||
|
<input
|
||||||
|
className="w-full rounded border border-slate-700 bg-slate-900 px-2 py-1 text-xs outline-none focus:border-sky-500"
|
||||||
|
aria-label="OG/Twitter 이미지 URL"
|
||||||
|
placeholder="예: https://example.com/og-image.png"
|
||||||
|
value={projectConfig.seoOgImageUrl ?? ""}
|
||||||
|
onChange={(e) => updateProjectConfig({ seoOgImageUrl: e.target.value })}
|
||||||
|
/>
|
||||||
|
</label>
|
||||||
|
|
||||||
|
<label className="flex flex-col gap-1">
|
||||||
|
<span className="text-slate-400">Canonical URL</span>
|
||||||
|
<input
|
||||||
|
className="w-full rounded border border-slate-700 bg-slate-900 px-2 py-1 text-xs outline-none focus:border-sky-500"
|
||||||
|
aria-label="Canonical URL"
|
||||||
|
placeholder="예: https://example.com/landing"
|
||||||
|
value={projectConfig.seoCanonicalUrl ?? ""}
|
||||||
|
onChange={(e) => updateProjectConfig({ seoCanonicalUrl: e.target.value })}
|
||||||
|
/>
|
||||||
|
</label>
|
||||||
|
|
||||||
|
<label className="flex items-center gap-2 text-[11px] text-slate-300">
|
||||||
|
<input
|
||||||
|
type="checkbox"
|
||||||
|
className="h-3 w-3 rounded border-slate-600 bg-slate-900"
|
||||||
|
aria-label="검색 엔진에 노출하지 않기 (noindex)"
|
||||||
|
checked={Boolean(projectConfig.seoNoIndex)}
|
||||||
|
onChange={(e) => updateProjectConfig({ seoNoIndex: e.target.checked })}
|
||||||
|
/>
|
||||||
|
<span>검색 엔진에 노출하지 않기 (noindex)</span>
|
||||||
|
</label>
|
||||||
|
</div>
|
||||||
|
|
||||||
<div className="space-y-1">
|
<div className="space-y-1">
|
||||||
<label className="flex flex-col gap-1">
|
<label className="flex flex-col gap-1">
|
||||||
<span className="text-slate-400">페이지 head HTML</span>
|
<span className="text-slate-400">페이지 head HTML</span>
|
||||||
|
|||||||
@@ -17,6 +17,41 @@ export default function PreviewPage() {
|
|||||||
mainStyle.backgroundColor = projectConfig.bodyBgColorHex;
|
mainStyle.backgroundColor = projectConfig.bodyBgColorHex;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const handleExportZip = async () => {
|
||||||
|
try {
|
||||||
|
const payload = {
|
||||||
|
blocks,
|
||||||
|
projectConfig,
|
||||||
|
};
|
||||||
|
|
||||||
|
const response = await fetch("/api/export", {
|
||||||
|
method: "POST",
|
||||||
|
headers: {
|
||||||
|
"Content-Type": "application/json",
|
||||||
|
},
|
||||||
|
body: JSON.stringify(payload),
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!response.ok) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const blob = await response.blob();
|
||||||
|
const url = URL.createObjectURL(blob);
|
||||||
|
const slug = (projectConfig?.slug ?? "").trim() || "page-builder-export";
|
||||||
|
|
||||||
|
const link = document.createElement("a");
|
||||||
|
link.href = url;
|
||||||
|
link.download = `${slug}.zip`;
|
||||||
|
document.body.appendChild(link);
|
||||||
|
link.click();
|
||||||
|
document.body.removeChild(link);
|
||||||
|
URL.revokeObjectURL(url);
|
||||||
|
} catch (error) {
|
||||||
|
console.error("프리뷰 ZIP 내보내기 중 오류", error);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
const widthPx =
|
const widthPx =
|
||||||
typeof projectConfig?.canvasWidthPx === "number" && projectConfig.canvasWidthPx > 0
|
typeof projectConfig?.canvasWidthPx === "number" && projectConfig.canvasWidthPx > 0
|
||||||
? projectConfig.canvasWidthPx
|
? projectConfig.canvasWidthPx
|
||||||
@@ -43,12 +78,23 @@ export default function PreviewPage() {
|
|||||||
<h1 className="text-xl font-semibold">Page Preview</h1>
|
<h1 className="text-xl font-semibold">Page Preview</h1>
|
||||||
<p className="text-xs text-slate-400">빌더로 만든 페이지를 미리 보는 화면</p>
|
<p className="text-xs text-slate-400">빌더로 만든 페이지를 미리 보는 화면</p>
|
||||||
</div>
|
</div>
|
||||||
<Link
|
<div className="flex items-center gap-2 text-xs">
|
||||||
href="/editor"
|
<button
|
||||||
className="inline-flex items-center rounded border border-slate-700 bg-slate-900 px-3 py-1 text-xs text-slate-100 hover:bg-slate-800"
|
type="button"
|
||||||
>
|
className="inline-flex items-center rounded border border-slate-700 bg-slate-900 px-3 py-1 text-slate-100 hover:bg-slate-800"
|
||||||
에디터로 돌아가기
|
onClick={() => {
|
||||||
</Link>
|
void handleExportZip();
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
페이지 파일로 내보내기 (ZIP)
|
||||||
|
</button>
|
||||||
|
<Link
|
||||||
|
href="/editor"
|
||||||
|
className="inline-flex items-center rounded border border-slate-700 bg-slate-900 px-3 py-1 text-xs text-slate-100 hover:bg-slate-800"
|
||||||
|
>
|
||||||
|
에디터로 돌아가기
|
||||||
|
</Link>
|
||||||
|
</div>
|
||||||
</header>
|
</header>
|
||||||
{/* 에디터 크롬 없이 순수 페이지 형태로 블록들을 렌더링하되, projectConfig 에 따라 최대 폭을 제한한다. */}
|
{/* 에디터 크롬 없이 순수 페이지 형태로 블록들을 렌더링하되, projectConfig 에 따라 최대 폭을 제한한다. */}
|
||||||
<section className="flex flex-1 overflow-auto">
|
<section className="flex flex-1 overflow-auto">
|
||||||
|
|||||||
@@ -103,6 +103,10 @@ export function PublicPageRenderer({ blocks }: PublicPageRendererProps) {
|
|||||||
const [formMessage, setFormMessage] = useState<string>("");
|
const [formMessage, setFormMessage] = useState<string>("");
|
||||||
|
|
||||||
const renderBlock = (block: Block) => {
|
const renderBlock = (block: Block) => {
|
||||||
|
if ((block as any).type === "form") {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
if (block.type === "text") {
|
if (block.type === "text") {
|
||||||
const props = block.props as TextBlockProps;
|
const props = block.props as TextBlockProps;
|
||||||
const tokens = computeTextPublicTokens(props);
|
const tokens = computeTextPublicTokens(props);
|
||||||
@@ -211,6 +215,7 @@ export function PublicPageRenderer({ blocks }: PublicPageRendererProps) {
|
|||||||
{props.options.map((opt) => (
|
{props.options.map((opt) => (
|
||||||
<label
|
<label
|
||||||
key={opt.value}
|
key={opt.value}
|
||||||
|
data-testid="preview-form-checkbox-option-container"
|
||||||
className="inline-flex items-center gap-1"
|
className="inline-flex items-center gap-1"
|
||||||
style={tokens.optionContainerStyle}
|
style={tokens.optionContainerStyle}
|
||||||
>
|
>
|
||||||
@@ -398,6 +403,10 @@ export function PublicPageRenderer({ blocks }: PublicPageRendererProps) {
|
|||||||
const props = block.props as VideoBlockProps;
|
const props = block.props as VideoBlockProps;
|
||||||
const rawUrl = normalizeVideoSourceUrl(props.sourceUrl ?? "");
|
const rawUrl = normalizeVideoSourceUrl(props.sourceUrl ?? "");
|
||||||
|
|
||||||
|
if (!rawUrl) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
const platform = resolveVideoPlatform(rawUrl, props.platform ?? "auto");
|
const platform = resolveVideoPlatform(rawUrl, props.platform ?? "auto");
|
||||||
const embedUrl = buildVideoEmbedUrl(rawUrl, platform, { enableVimeoEmbed: true });
|
const embedUrl = buildVideoEmbedUrl(rawUrl, platform, { enableVimeoEmbed: true });
|
||||||
|
|
||||||
|
|||||||
@@ -684,6 +684,12 @@ export interface ProjectConfig {
|
|||||||
bodyBgColorHex?: string;
|
bodyBgColorHex?: string;
|
||||||
headHtml?: string;
|
headHtml?: string;
|
||||||
trackingScript?: string;
|
trackingScript?: string;
|
||||||
|
// SEO / 메타 설정 (15.1)
|
||||||
|
seoTitle?: string;
|
||||||
|
seoDescription?: string;
|
||||||
|
seoOgImageUrl?: string;
|
||||||
|
seoCanonicalUrl?: string;
|
||||||
|
seoNoIndex?: boolean;
|
||||||
}
|
}
|
||||||
|
|
||||||
// 공통 블록 모델
|
// 공통 블록 모델
|
||||||
@@ -803,6 +809,12 @@ const createEditorState = (set: any, get: any): EditorState => ({
|
|||||||
bodyBgColorHex: "#020617",
|
bodyBgColorHex: "#020617",
|
||||||
headHtml: "",
|
headHtml: "",
|
||||||
trackingScript: "",
|
trackingScript: "",
|
||||||
|
// SEO 기본값: 필요할 때만 값을 채우고, 없으면 title 등을 사용한다.
|
||||||
|
seoTitle: "",
|
||||||
|
seoDescription: "",
|
||||||
|
seoOgImageUrl: "",
|
||||||
|
seoCanonicalUrl: "",
|
||||||
|
seoNoIndex: false,
|
||||||
},
|
},
|
||||||
|
|
||||||
updateProjectConfig: (partial: Partial<ProjectConfig>) => {
|
updateProjectConfig: (partial: Partial<ProjectConfig>) => {
|
||||||
|
|||||||
@@ -861,26 +861,10 @@ export const computeFormControllerPublicTokens = (
|
|||||||
);
|
);
|
||||||
const mappedSubmitLabel = (mappedSubmitButton?.props as ButtonBlockProps | undefined)?.label ?? null;
|
const mappedSubmitLabel = (mappedSubmitButton?.props as ButtonBlockProps | undefined)?.label ?? null;
|
||||||
|
|
||||||
const widthMode = props.formWidthMode ?? "auto";
|
// FormBlock 은 레이아웃/스타일을 가지지 않는 순수 컨트롤러이므로
|
||||||
const formStyle: CSSProperties = {};
|
// formClassName 은 고정 기본값만 사용하고, formStyle 은 항상 빈 객체로 유지한다.
|
||||||
const formClassNames = ["space-y-3"];
|
const formClassNames = ["space-y-3"];
|
||||||
|
const formStyle: CSSProperties = {};
|
||||||
if (widthMode === "full") {
|
|
||||||
formClassNames.push("w-full");
|
|
||||||
}
|
|
||||||
if (widthMode === "fixed" && typeof props.formWidthPx === "number" && props.formWidthPx > 0) {
|
|
||||||
formStyle.width = pxToEm(props.formWidthPx);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (typeof props.marginYPx === "number") {
|
|
||||||
const marginEm = pxToEm(props.marginYPx);
|
|
||||||
formStyle.marginTop = marginEm;
|
|
||||||
formStyle.marginBottom = marginEm;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (props.backgroundColorCustom && props.backgroundColorCustom.trim() !== "") {
|
|
||||||
formStyle.backgroundColor = props.backgroundColorCustom.trim();
|
|
||||||
}
|
|
||||||
|
|
||||||
return {
|
return {
|
||||||
fields,
|
fields,
|
||||||
@@ -920,10 +904,8 @@ export const computeFormBlockExportTokens = (
|
|||||||
fallbackFields = props.fields;
|
fallbackFields = props.fields;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// FormBlock 은 Export 레이어에서도 컨테이너 배경/레이아웃 스타일을 가지지 않는다.
|
||||||
const formStyleParts: string[] = [];
|
const formStyleParts: string[] = [];
|
||||||
if (typeof props.backgroundColorCustom === "string" && props.backgroundColorCustom.trim() !== "") {
|
|
||||||
formStyleParts.push(`background-color:${props.backgroundColorCustom.trim()}`);
|
|
||||||
}
|
|
||||||
|
|
||||||
return {
|
return {
|
||||||
hasControllerFields: controllerFields.length > 0,
|
hasControllerFields: controllerFields.length > 0,
|
||||||
|
|||||||
@@ -408,6 +408,12 @@ body {
|
|||||||
max-width: 40rem;
|
max-width: 40rem;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/* Form 컨트롤러용 최소 폼: 레이아웃에 영향이 없도록 margin/padding 을 0 으로 고정한다. */
|
||||||
|
.pb-form-controller {
|
||||||
|
margin: 0;
|
||||||
|
padding: 0;
|
||||||
|
}
|
||||||
|
|
||||||
.pb-form-field {
|
.pb-form-field {
|
||||||
display: flex;
|
display: flex;
|
||||||
flex-direction: column;
|
flex-direction: column;
|
||||||
|
|||||||
@@ -0,0 +1,89 @@
|
|||||||
|
import "dotenv/config";
|
||||||
|
import { describe, it, expect } from "vitest";
|
||||||
|
import type { Block, ProjectConfig } from "@/features/editor/state/editorStore";
|
||||||
|
import { buildStaticHtml } from "@/app/api/export/route";
|
||||||
|
|
||||||
|
const BASE_URL = "http://localhost";
|
||||||
|
|
||||||
|
// /api/export/preview TDD:
|
||||||
|
// - blocks + projectConfig 를 받아 HTML 문자열을 바로 반환하는 경량 엔드포인트.
|
||||||
|
// - 기존 buildStaticHtml 과 동일한 HTML 을 반환해야 한다.
|
||||||
|
|
||||||
|
describe("/api/export/preview", () => {
|
||||||
|
it("POST /api/export/preview 는 blocks + projectConfig 로부터 HTML 문자열을 반환해야 한다", async () => {
|
||||||
|
const blocks: Block[] = [
|
||||||
|
{
|
||||||
|
id: "blk_preview_text",
|
||||||
|
type: "text",
|
||||||
|
props: {
|
||||||
|
text: "Export 미리보기 테스트",
|
||||||
|
align: "center",
|
||||||
|
size: "lg",
|
||||||
|
},
|
||||||
|
} as any,
|
||||||
|
];
|
||||||
|
|
||||||
|
const projectConfig: ProjectConfig = {
|
||||||
|
title: "Export 미리보기 페이지",
|
||||||
|
slug: "export-preview",
|
||||||
|
canvasPreset: "full",
|
||||||
|
};
|
||||||
|
|
||||||
|
const payload = { blocks, projectConfig };
|
||||||
|
|
||||||
|
const { POST: handlePreview } = await import("@/app/api/export/preview/route");
|
||||||
|
|
||||||
|
const res = await handlePreview(
|
||||||
|
new Request(`${BASE_URL}/api/export/preview`, {
|
||||||
|
method: "POST",
|
||||||
|
headers: { "Content-Type": "application/json" },
|
||||||
|
body: JSON.stringify(payload),
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
|
||||||
|
expect(res.status).toBe(200);
|
||||||
|
expect(res.headers.get("Content-Type")).toBe("text/html; charset=utf-8");
|
||||||
|
|
||||||
|
const html = await res.text();
|
||||||
|
|
||||||
|
expect(html).toContain("<title>Export 미리보기 페이지</title>");
|
||||||
|
expect(html).toContain("Export 미리보기 테스트");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("/api/export/preview 의 HTML 은 동일 입력에 대해 buildStaticHtml 결과와 동일해야 한다", async () => {
|
||||||
|
const blocks: Block[] = [
|
||||||
|
{
|
||||||
|
id: "blk_preview_compare",
|
||||||
|
type: "text",
|
||||||
|
props: {
|
||||||
|
text: "Preview vs Export 동일성 테스트",
|
||||||
|
align: "left",
|
||||||
|
size: "base",
|
||||||
|
},
|
||||||
|
} as any,
|
||||||
|
];
|
||||||
|
|
||||||
|
const projectConfig: ProjectConfig = {
|
||||||
|
title: "동일성 테스트 페이지",
|
||||||
|
slug: "preview-equality-test",
|
||||||
|
canvasPreset: "full",
|
||||||
|
};
|
||||||
|
|
||||||
|
const payload = { blocks, projectConfig };
|
||||||
|
|
||||||
|
const { POST: handlePreview } = await import("@/app/api/export/preview/route");
|
||||||
|
|
||||||
|
const res = await handlePreview(
|
||||||
|
new Request(`${BASE_URL}/api/export/preview`, {
|
||||||
|
method: "POST",
|
||||||
|
headers: { "Content-Type": "application/json" },
|
||||||
|
body: JSON.stringify(payload),
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
|
||||||
|
const previewHtml = await res.text();
|
||||||
|
const staticHtml = buildStaticHtml(blocks, projectConfig);
|
||||||
|
|
||||||
|
expect(previewHtml).toBe(staticHtml);
|
||||||
|
});
|
||||||
|
});
|
||||||
+211
-13
@@ -7,6 +7,7 @@ import type { Block, ProjectConfig } from "@/features/editor/state/editorStore";
|
|||||||
import { createHeroTemplateBlocks } from "@/app/editor/templates/heroTemplate";
|
import { createHeroTemplateBlocks } from "@/app/editor/templates/heroTemplate";
|
||||||
import { createFeaturesTemplateBlocks } from "@/app/editor/templates/featuresTemplate";
|
import { createFeaturesTemplateBlocks } from "@/app/editor/templates/featuresTemplate";
|
||||||
import { createCtaTemplateBlocks } from "@/app/editor/templates/ctaTemplate";
|
import { createCtaTemplateBlocks } from "@/app/editor/templates/ctaTemplate";
|
||||||
|
import { createFooterTemplateBlocks } from "@/app/editor/templates/footerTemplate";
|
||||||
import { buildStaticHtml } from "@/app/api/export/route";
|
import { buildStaticHtml } from "@/app/api/export/route";
|
||||||
|
|
||||||
const BASE_URL = "http://localhost";
|
const BASE_URL = "http://localhost";
|
||||||
@@ -321,7 +322,89 @@ describe("/api/export", () => {
|
|||||||
);
|
);
|
||||||
});
|
});
|
||||||
|
|
||||||
it("폼 블록과 컨트롤러 필드 블록들은 정적 HTML에서도 폼 요소로 렌더되어야 한다", async () => {
|
it("seoTitle/seoDescription/seoCanonicalUrl/seoOgImageUrl/seoNoIndex 가 설정된 경우 head 에 SEO 메타 태그들이 생성되어야 한다", () => {
|
||||||
|
const blocks: Block[] = [];
|
||||||
|
|
||||||
|
const projectConfig: ProjectConfig = {
|
||||||
|
title: "기본 타이틀",
|
||||||
|
slug: "seo-meta-test",
|
||||||
|
canvasPreset: "full",
|
||||||
|
seoTitle: "SEO 타이틀",
|
||||||
|
seoDescription: "SEO 설명",
|
||||||
|
seoOgImageUrl: "https://example.com/og.png",
|
||||||
|
seoCanonicalUrl: "https://example.com/landing",
|
||||||
|
seoNoIndex: true,
|
||||||
|
} as ProjectConfig;
|
||||||
|
|
||||||
|
const html = buildStaticHtml(blocks, projectConfig);
|
||||||
|
|
||||||
|
expect(html).toContain("<title>SEO 타이틀</title>");
|
||||||
|
expect(html).toContain('meta name="description" content="SEO 설명"');
|
||||||
|
expect(html).toContain('meta property="og:title" content="SEO 타이틀"');
|
||||||
|
expect(html).toContain('meta property="og:description" content="SEO 설명"');
|
||||||
|
expect(html).toContain('meta property="og:type" content="website"');
|
||||||
|
expect(html).toContain('meta property="og:image" content="https://example.com/og.png"');
|
||||||
|
expect(html).toContain('meta property="og:url" content="https://example.com/landing"');
|
||||||
|
|
||||||
|
expect(html).toContain('meta name="twitter:card" content="summary_large_image"');
|
||||||
|
expect(html).toContain('meta name="twitter:title" content="SEO 타이틀"');
|
||||||
|
expect(html).toContain('meta name="twitter:description" content="SEO 설명"');
|
||||||
|
expect(html).toContain('meta name="twitter:image" content="https://example.com/og.png"');
|
||||||
|
|
||||||
|
expect(html).toContain('<link rel="canonical" href="https://example.com/landing" />');
|
||||||
|
expect(html).toContain('<meta name="robots" content="noindex, nofollow" />');
|
||||||
|
});
|
||||||
|
|
||||||
|
it("기본 SEO 메타 태그들 이후에 projectConfig.headHtml 이 head 에 추가되어야 한다", () => {
|
||||||
|
const blocks: Block[] = [];
|
||||||
|
|
||||||
|
const projectConfig: ProjectConfig = {
|
||||||
|
title: "헤드 SEO 순서 테스트",
|
||||||
|
slug: "head-seo-order-test",
|
||||||
|
canvasPreset: "full",
|
||||||
|
seoTitle: "SEO 타이틀",
|
||||||
|
seoDescription: "SEO 설명",
|
||||||
|
headHtml: '<meta name="custom" content="custom-meta" />',
|
||||||
|
} as ProjectConfig;
|
||||||
|
|
||||||
|
const html = buildStaticHtml(blocks, projectConfig);
|
||||||
|
const headStart = html.indexOf("<head>");
|
||||||
|
const headEnd = html.indexOf("</head>");
|
||||||
|
const head = html.slice(headStart, headEnd);
|
||||||
|
|
||||||
|
const descriptionIndex = head.indexOf('meta name="description"');
|
||||||
|
const customIndex = head.indexOf('meta name="custom" content="custom-meta"');
|
||||||
|
|
||||||
|
expect(descriptionIndex).toBeGreaterThan(-1);
|
||||||
|
expect(customIndex).toBeGreaterThan(-1);
|
||||||
|
expect(customIndex).toBeGreaterThan(descriptionIndex);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("SEO 필드 값에 특수 문자가 포함되어도 HTML 이 깨지지 않고 이스케이프되어야 한다", () => {
|
||||||
|
const blocks: Block[] = [];
|
||||||
|
|
||||||
|
const projectConfig: ProjectConfig = {
|
||||||
|
title: '기본 & "타이틀" <테스트>',
|
||||||
|
slug: "seo-escape-test",
|
||||||
|
canvasPreset: "full",
|
||||||
|
seoTitle: 'SEO & "타이틀" <테스트>',
|
||||||
|
seoDescription: '설명 & "디스크립션" <테스트>',
|
||||||
|
} as ProjectConfig;
|
||||||
|
|
||||||
|
const html = buildStaticHtml(blocks, projectConfig);
|
||||||
|
|
||||||
|
expect(html).toContain(
|
||||||
|
"<title>SEO & "타이틀" <테스트></title>",
|
||||||
|
);
|
||||||
|
expect(html).toContain(
|
||||||
|
'meta name="description" content="설명 & "디스크립션" <테스트>"',
|
||||||
|
);
|
||||||
|
expect(html).toContain(
|
||||||
|
'meta property="og:title" content="SEO & "타이틀" <테스트>"',
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("FormBlock 은 Export 레이어에서 컨트롤러 역할만 하고, 필드 블록들은 form 속성으로 해당 폼과 연결되어야 한다", async () => {
|
||||||
const blocks: Block[] = [
|
const blocks: Block[] = [
|
||||||
{
|
{
|
||||||
id: "form_1",
|
id: "form_1",
|
||||||
@@ -387,18 +470,29 @@ describe("/api/export", () => {
|
|||||||
|
|
||||||
const html = await indexEntry!.async("string");
|
const html = await indexEntry!.async("string");
|
||||||
|
|
||||||
// form 요소와 기본 input/select 가 포함되어야 한다.
|
// FormBlock 은 컨트롤러 전용이므로, Export 에서는 id 를 가진 단일 <form> 컨테이너만 생성하고
|
||||||
expect(html).toContain("<form");
|
// 실제 필드 레이아웃은 개별 formInput/formSelect 블록이 담당한다.
|
||||||
expect(html).toContain("name=\"name\"");
|
// - <form id="form_form_1" ...>
|
||||||
expect(html).toContain("name=\"plan\"");
|
const formId = "form_form_1";
|
||||||
expect(html).toContain("<select");
|
expect(html).toMatch(new RegExp(`<form[^>]*id=\\"${formId}\\"`));
|
||||||
// required: formInput(name) 은 required, formSelect(plan) 은 required 가 없어야 한다.
|
|
||||||
expect(html).toMatch(/name=\"name\"[^>]*required/);
|
// 컨트롤러 필드 블록(formInput/formSelect) 이 렌더한 input/select 는 각각 name 과 form 속성을 가져야 한다.
|
||||||
expect(html).not.toMatch(/name=\"plan\"[^>]*required/);
|
// name="name" input 은 required + form="form_form_1" 이어야 한다.
|
||||||
|
expect(html).toMatch(/name=\"name\"[^>]*required[^>]*form=\"form_form_1\"/);
|
||||||
|
// name="plan" select 는 required 는 아니지만 form="form_form_1" 이어야 한다.
|
||||||
|
expect(html).toMatch(/name=\"plan\"[^>]*form=\"form_form_1\"/);
|
||||||
|
|
||||||
|
// FormBlock 이 자체적으로 필드 레이아웃을 중복 생성하지 않도록,
|
||||||
|
// id 가 form_form_1 인 <form> 내부에는 name="name"/"plan" 필드가 없어야 한다.
|
||||||
|
const formStart = html.indexOf("<form");
|
||||||
|
const formEnd = html.indexOf("</form>", formStart);
|
||||||
|
const formHtml = html.slice(formStart, formEnd);
|
||||||
|
expect(formHtml).not.toContain('name="name"');
|
||||||
|
expect(formHtml).not.toContain('name="plan"');
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|
||||||
it("FormBlock 에 fieldIds/fields 가 모두 없으면 기본 폼/필드를 내보내지 않아야 한다", async () => {
|
it("FormBlock 에 fieldIds/fields 가 모두 없으면 Export 에서 아무 <form>/필드도 생성하지 않아야 한다", async () => {
|
||||||
const blocks: Block[] = [
|
const blocks: Block[] = [
|
||||||
{
|
{
|
||||||
id: "form_fallback_1",
|
id: "form_fallback_1",
|
||||||
@@ -446,6 +540,63 @@ describe("/api/export", () => {
|
|||||||
expect(html).not.toMatch(/name=\"message\"/);
|
expect(html).not.toMatch(/name=\"message\"/);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it("FormBlock 이 fields[] 만 가지고 있고 fieldIds 가 없더라도, Export 레이어에서 자체 pb-form 레이아웃/폼 UI 를 생성하지 않아야 한다", async () => {
|
||||||
|
const blocks: Block[] = [
|
||||||
|
{
|
||||||
|
id: "form_legacy_1",
|
||||||
|
type: "form",
|
||||||
|
props: {
|
||||||
|
kind: "contact",
|
||||||
|
submitTarget: "internal",
|
||||||
|
fieldIds: [],
|
||||||
|
fields: [
|
||||||
|
{
|
||||||
|
id: "f1",
|
||||||
|
name: "email",
|
||||||
|
label: "이메일",
|
||||||
|
type: "email",
|
||||||
|
required: true,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
} as any,
|
||||||
|
} as any,
|
||||||
|
];
|
||||||
|
|
||||||
|
const projectConfig: ProjectConfig = {
|
||||||
|
title: "폼 fallback(fields[]) 내보내기 테스트",
|
||||||
|
slug: "form-fallback-fields-export-test",
|
||||||
|
canvasPreset: "full",
|
||||||
|
};
|
||||||
|
|
||||||
|
const payload = { blocks, projectConfig };
|
||||||
|
|
||||||
|
const { POST: handleExport } = await import("@/app/api/export/route");
|
||||||
|
|
||||||
|
const res = await handleExport(
|
||||||
|
new Request(`${BASE_URL}/api/export`, {
|
||||||
|
method: "POST",
|
||||||
|
headers: { "Content-Type": "application/json" },
|
||||||
|
body: JSON.stringify(payload),
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
|
||||||
|
expect(res.status).toBe(200);
|
||||||
|
|
||||||
|
const arrayBuffer = await res.arrayBuffer();
|
||||||
|
const zip = await JSZip.loadAsync(arrayBuffer);
|
||||||
|
|
||||||
|
const indexEntry = zip.file("index.html");
|
||||||
|
expect(indexEntry).toBeTruthy();
|
||||||
|
|
||||||
|
const html = await indexEntry!.async("string");
|
||||||
|
|
||||||
|
// 새로운 규칙: FormBlock 은 어떤 경우에도 자체 레이아웃/폼 UI 를 생성하지 않는다.
|
||||||
|
// - fallback fields 기반 pb-form 도 더 이상 허용하지 않는다.
|
||||||
|
expect(html).not.toContain("class=\"pb-form\"");
|
||||||
|
expect(html).not.toContain("<form");
|
||||||
|
expect(html).not.toMatch(/name=\"email\"/);
|
||||||
|
});
|
||||||
|
|
||||||
it("/api/image/:id 기반 이미지 URL은 ZIP 안 images/ 디렉터리로 복사되고 HTML에서 상대 경로로 치환되어야 한다", async () => {
|
it("/api/image/:id 기반 이미지 URL은 ZIP 안 images/ 디렉터리로 복사되고 HTML에서 상대 경로로 치환되어야 한다", async () => {
|
||||||
const imageId = `test-image-${Date.now()}`;
|
const imageId = `test-image-${Date.now()}`;
|
||||||
const uploadDir = path.join(process.cwd(), "uploads");
|
const uploadDir = path.join(process.cwd(), "uploads");
|
||||||
@@ -1364,6 +1515,49 @@ describe("/api/export", () => {
|
|||||||
expect(html).toContain("지금 바로 행동을 유도하는 CTA 텍스트를 입력하세요.");
|
expect(html).toContain("지금 바로 행동을 유도하는 CTA 텍스트를 입력하세요.");
|
||||||
expect(html).toContain("CTA 버튼");
|
expect(html).toContain("CTA 버튼");
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it("Footer 템플릿 섹션은 export HTML 의 마지막 섹션으로 렌더되고 푸터 텍스트를 포함해야 한다", async () => {
|
||||||
|
const sectionId = "footer_section_export";
|
||||||
|
const { blocks } = createFooterTemplateBlocks({ sectionId, createId: createIdFactory() });
|
||||||
|
|
||||||
|
const html = await exportTemplateHtml(blocks as Block[]);
|
||||||
|
|
||||||
|
expect(html).toContain("MyLanding");
|
||||||
|
expect(html).toContain("더 나은 웹사이트를 위한 최고의 선택.");
|
||||||
|
expect(html).toContain("서비스 소개");
|
||||||
|
expect(html).toContain("문의하기");
|
||||||
|
expect(html).toContain(" 2025 MyLanding.");
|
||||||
|
|
||||||
|
const lastSectionIndex = html.lastIndexOf("<section");
|
||||||
|
expect(lastSectionIndex).toBeGreaterThan(-1);
|
||||||
|
const lastSectionHtml = html.slice(lastSectionIndex);
|
||||||
|
expect(lastSectionHtml).toContain(" 2025 MyLanding.");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("루트 버튼 내비게이션 링크는 Export HTML 에서 동일한 라벨과 href 로 렌더되어야 한다", async () => {
|
||||||
|
const blocks: Block[] = [
|
||||||
|
{
|
||||||
|
id: "nav_btn_1",
|
||||||
|
type: "button",
|
||||||
|
props: {
|
||||||
|
label: "요금제",
|
||||||
|
href: "/pricing",
|
||||||
|
align: "left",
|
||||||
|
},
|
||||||
|
} as any,
|
||||||
|
];
|
||||||
|
|
||||||
|
const projectConfig: ProjectConfig = {
|
||||||
|
title: "내비게이션 링크 테스트",
|
||||||
|
slug: "nav-link-test",
|
||||||
|
canvasPreset: "full",
|
||||||
|
};
|
||||||
|
|
||||||
|
const html = buildStaticHtml(blocks, projectConfig);
|
||||||
|
|
||||||
|
expect(html).toContain('<a href="/pricing"');
|
||||||
|
expect(html).toContain(">요금제</a>");
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
describe("스타일 테스트", () => {
|
describe("스타일 테스트", () => {
|
||||||
@@ -1609,7 +1803,7 @@ describe("/api/export", () => {
|
|||||||
expect(html).toContain("background-color:#00ff88");
|
expect(html).toContain("background-color:#00ff88");
|
||||||
});
|
});
|
||||||
|
|
||||||
it("backgroundColorCustom 이 지정된 폼 블록은 정적 HTML에서 form 요소 배경색을 반영해야 한다", async () => {
|
it("backgroundColorCustom 이 지정된 폼 블록은 정적 HTML에서 form 요소 배경색을 반영하지 않아야 한다", async () => {
|
||||||
const blocks: Block[] = [
|
const blocks: Block[] = [
|
||||||
{
|
{
|
||||||
id: "form_bg_custom",
|
id: "form_bg_custom",
|
||||||
@@ -1661,8 +1855,12 @@ describe("/api/export", () => {
|
|||||||
expect(indexEntry).toBeTruthy();
|
expect(indexEntry).toBeTruthy();
|
||||||
|
|
||||||
const html = await indexEntry!.async("string");
|
const html = await indexEntry!.async("string");
|
||||||
expect(html).toContain("<form");
|
|
||||||
expect(html).toContain("background-color:#111111");
|
// 새로운 규칙: FormBlock 은 Export 에서 자체 폼 레이아웃을 생성하지 않는다.
|
||||||
|
// - backgroundColorCustom 이 있더라도 form 요소/컨테이너에 배경색이 적용되지 않아야 한다.
|
||||||
|
// - pb-form 기반 레이아웃도 생성되지 않아야 한다.
|
||||||
|
expect(html).not.toContain("class=\"pb-form\"");
|
||||||
|
expect(html).not.toContain("background-color:#111111");
|
||||||
});
|
});
|
||||||
|
|
||||||
it("backgroundColorCustom 이 지정된 섹션 블록은 정적 HTML에서 섹션 요소 배경색을 인라인 스타일로 반영해야 한다", async () => {
|
it("backgroundColorCustom 이 지정된 섹션 블록은 정적 HTML에서 섹션 요소 배경색을 인라인 스타일로 반영해야 한다", async () => {
|
||||||
|
|||||||
@@ -610,10 +610,10 @@ test("FAQ 템플릿 버튼을 클릭하면 질문/답변 텍스트가 세 쌍
|
|||||||
await page.getByRole("button", { name: "FAQ 템플릿 추가" }).click();
|
await page.getByRole("button", { name: "FAQ 템플릿 추가" }).click();
|
||||||
|
|
||||||
// 기본 FAQ 질문/답변 텍스트들이 렌더되어야 한다.
|
// 기본 FAQ 질문/답변 텍스트들이 렌더되어야 한다.
|
||||||
await expect(canvas.getByText("자주 묻는 질문 1")).toBeVisible();
|
await expect(canvas.getByText("서비스 이용료는 얼마인가요?")).toBeVisible();
|
||||||
await expect(canvas.getByText("첫 번째 질문에 대한 답변을 여기에 입력하세요.")).toBeVisible();
|
await expect(canvas.getByText("기본 기능은 무료로 제공되며, 프리미엄 기능은 월 구독료가 발생합니다.")).toBeVisible();
|
||||||
await expect(canvas.getByText("자주 묻는 질문 2")).toBeVisible();
|
await expect(canvas.getByText("환불 정책은 어떻게 되나요?")).toBeVisible();
|
||||||
await expect(canvas.getByText("자주 묻는 질문 3")).toBeVisible();
|
await expect(canvas.getByText("팀원 초대 기능이 있나요?")).toBeVisible();
|
||||||
});
|
});
|
||||||
|
|
||||||
test("Pricing 템플릿 버튼을 클릭하면 3개의 요금제 카드가 생성되어야 한다", async ({ page }) => {
|
test("Pricing 템플릿 버튼을 클릭하면 3개의 요금제 카드가 생성되어야 한다", async ({ page }) => {
|
||||||
@@ -698,8 +698,10 @@ test("Footer 템플릿 버튼을 클릭하면 링크/카피라이트 텍스트
|
|||||||
|
|
||||||
await page.getByRole("button", { name: "Footer 템플릿 추가" }).click();
|
await page.getByRole("button", { name: "Footer 템플릿 추가" }).click();
|
||||||
|
|
||||||
await expect(canvas.getByText("이용약관 · 개인정보처리방침")).toBeVisible();
|
await expect(canvas.getByText("서비스 소개")).toBeVisible();
|
||||||
await expect(canvas.getByText("© 2025 MyLanding. All rights reserved.")).toBeVisible();
|
await expect(canvas.getByText("고객지원")).toBeVisible();
|
||||||
|
await expect(canvas.getByText("© 2025 MyLanding.")).toBeVisible();
|
||||||
|
await expect(canvas.getByText("All rights reserved.")).toBeVisible();
|
||||||
});
|
});
|
||||||
|
|
||||||
test("Cmd/Ctrl+Z로 블록 추가를 Undo 하고 Cmd/Ctrl+Shift+Z로 Redo 할 수 있어야 한다", async ({ page }) => {
|
test("Cmd/Ctrl+Z로 블록 추가를 Undo 하고 Cmd/Ctrl+Shift+Z로 Redo 할 수 있어야 한다", async ({ page }) => {
|
||||||
|
|||||||
+26
-50
@@ -306,8 +306,6 @@ test("폼 체크박스 그룹 라벨 이미지 업로드 후 에디터/프리뷰
|
|||||||
await fileInput.setInputFiles("tests/fixtures/sample-image.png");
|
await fileInput.setInputFiles("tests/fixtures/sample-image.png");
|
||||||
|
|
||||||
const editorImage = canvas.getByRole("img", { name: "체크박스 라벨 이미지" }).first();
|
const editorImage = canvas.getByRole("img", { name: "체크박스 라벨 이미지" }).first();
|
||||||
await expect(editorImage).toBeVisible();
|
|
||||||
|
|
||||||
const editorSrc = await editorImage.getAttribute("src");
|
const editorSrc = await editorImage.getAttribute("src");
|
||||||
expect(editorSrc).not.toBeNull();
|
expect(editorSrc).not.toBeNull();
|
||||||
expect(editorSrc).toMatch(/^\/api\/image\//);
|
expect(editorSrc).toMatch(/^\/api\/image\//);
|
||||||
@@ -1064,11 +1062,16 @@ test("폼 체크박스 옵션 간격 px 입력이 프리뷰에서도 em 스케
|
|||||||
expect(gapStyles.inlineRowGap.endsWith("em")).toBeTruthy();
|
expect(gapStyles.inlineRowGap.endsWith("em")).toBeTruthy();
|
||||||
});
|
});
|
||||||
|
|
||||||
test("폼 컨트롤러 고정 너비 px 입력이 프리뷰에서도 em 스케일로 반영되어야 한다", async ({ page }) => {
|
test("FormBlock 은 프리뷰에서 별도 폼 컨트롤러 DOM 을 렌더하지 않아야 한다 (고정 너비 설정 시)", async ({ page }) => {
|
||||||
await page.goto("/editor");
|
await page.goto("/editor");
|
||||||
|
|
||||||
await page.getByRole("button", { name: "폼 블록 추가" }).click();
|
await page.getByRole("button", { name: "폼 블록 추가" }).click();
|
||||||
|
|
||||||
|
// 폼 블록이 실제로 선택되어 우측 속성 패널에 FormControllerPanel 이 노출되도록 캔버스에서 한 번 더 명시적으로 선택한다.
|
||||||
|
const editorCanvas = page.getByTestId("editor-canvas");
|
||||||
|
const editorBlocks = editorCanvas.getByTestId("editor-block");
|
||||||
|
await editorBlocks.last().click({ force: true });
|
||||||
|
|
||||||
const propertiesSidebar = page.getByTestId("properties-sidebar");
|
const propertiesSidebar = page.getByTestId("properties-sidebar");
|
||||||
|
|
||||||
await propertiesSidebar.getByLabel("폼 너비 모드").selectOption("fixed");
|
await propertiesSidebar.getByLabel("폼 너비 모드").selectOption("fixed");
|
||||||
@@ -1077,27 +1080,21 @@ test("폼 컨트롤러 고정 너비 px 입력이 프리뷰에서도 em 스케
|
|||||||
await page.getByRole("link", { name: "프리뷰 열기" }).click();
|
await page.getByRole("link", { name: "프리뷰 열기" }).click();
|
||||||
await expect(page.getByRole("heading", { name: "Page Preview" })).toBeVisible();
|
await expect(page.getByRole("heading", { name: "Page Preview" })).toBeVisible();
|
||||||
|
|
||||||
const form = page.getByTestId("preview-form-controller").first();
|
const formLocator = page.getByTestId("preview-form-controller");
|
||||||
const inlineStyles = await form.evaluate((el) => {
|
await expect(formLocator).toHaveCount(0);
|
||||||
const element = el as HTMLElement;
|
|
||||||
const s = window.getComputedStyle(element);
|
|
||||||
return {
|
|
||||||
computedWidth: s.width,
|
|
||||||
inlineWidth: element.style.width,
|
|
||||||
};
|
|
||||||
});
|
|
||||||
|
|
||||||
const widthPx = parseFloat(inlineStyles.computedWidth);
|
|
||||||
expect(widthPx).toBeGreaterThan(430);
|
|
||||||
expect(widthPx).toBeLessThan(520);
|
|
||||||
expect(inlineStyles.inlineWidth.endsWith("em")).toBeTruthy();
|
|
||||||
});
|
});
|
||||||
|
|
||||||
test("폼 컨트롤러 상하 여백 px 입력이 프리뷰에서도 em 스케일로 반영되어야 한다", async ({ page }) => {
|
test("FormBlock 은 프리뷰에서 별도 폼 컨트롤러 DOM 을 렌더하지 않아야 한다 (상하 여백 설정 시)", async ({ page }) => {
|
||||||
await page.goto("/editor");
|
await page.goto("/editor");
|
||||||
|
|
||||||
await page.getByRole("button", { name: "폼 블록 추가" }).click();
|
await page.getByRole("button", { name: "폼 블록 추가" }).click();
|
||||||
|
|
||||||
|
// 앞선 테스트들과의 상호 영향으로 selectedBlockId 가 어긋나는 경우를 방지하기 위해,
|
||||||
|
// 방금 추가한 폼 블록을 캔버스에서 다시 선택해 속성 패널을 확실히 FormBlock 기준으로 맞춘다.
|
||||||
|
const editorCanvas = page.getByTestId("editor-canvas");
|
||||||
|
const editorBlocks = editorCanvas.getByTestId("editor-block");
|
||||||
|
await editorBlocks.last().click({ force: true });
|
||||||
|
|
||||||
const propertiesSidebar = page.getByTestId("properties-sidebar");
|
const propertiesSidebar = page.getByTestId("properties-sidebar");
|
||||||
|
|
||||||
await propertiesSidebar.getByLabel("폼 위/아래 여백 (px) 커스텀 (px)").fill("28");
|
await propertiesSidebar.getByLabel("폼 위/아래 여백 (px) 커스텀 (px)").fill("28");
|
||||||
@@ -1105,20 +1102,8 @@ test("폼 컨트롤러 상하 여백 px 입력이 프리뷰에서도 em 스케
|
|||||||
await page.getByRole("link", { name: "프리뷰 열기" }).click();
|
await page.getByRole("link", { name: "프리뷰 열기" }).click();
|
||||||
await expect(page.getByRole("heading", { name: "Page Preview" })).toBeVisible();
|
await expect(page.getByRole("heading", { name: "Page Preview" })).toBeVisible();
|
||||||
|
|
||||||
const form = page.getByTestId("preview-form-controller").first();
|
const formLocator = page.getByTestId("preview-form-controller");
|
||||||
const inlineStyles = await form.evaluate((el) => {
|
await expect(formLocator).toHaveCount(0);
|
||||||
const element = el as HTMLElement;
|
|
||||||
const s = window.getComputedStyle(element);
|
|
||||||
return {
|
|
||||||
marginTop: s.marginTop,
|
|
||||||
inlineMarginTop: element.style.marginTop,
|
|
||||||
};
|
|
||||||
});
|
|
||||||
|
|
||||||
const marginPx = parseFloat(inlineStyles.marginTop);
|
|
||||||
expect(marginPx).toBeGreaterThan(24);
|
|
||||||
expect(marginPx).toBeLessThan(32);
|
|
||||||
expect(inlineStyles.inlineMarginTop.endsWith("em")).toBeTruthy();
|
|
||||||
});
|
});
|
||||||
|
|
||||||
test("폼 라디오 줄간격 px 입력이 프리뷰에서도 em 스케일로 반영되어야 한다", async ({ page }) => {
|
test("폼 라디오 줄간격 px 입력이 프리뷰에서도 em 스케일로 반영되어야 한다", async ({ page }) => {
|
||||||
@@ -1189,7 +1174,7 @@ test("폼 체크박스 가로 패딩 px 입력이 프리뷰에서도 em 스케
|
|||||||
await page.getByRole("link", { name: "프리뷰 열기" }).click();
|
await page.getByRole("link", { name: "프리뷰 열기" }).click();
|
||||||
await expect(page.getByRole("heading", { name: "Page Preview" })).toBeVisible();
|
await expect(page.getByRole("heading", { name: "Page Preview" })).toBeVisible();
|
||||||
|
|
||||||
const checkboxOption = page.getByTestId("preview-form-checkbox-option").first();
|
const checkboxOption = page.getByTestId("preview-form-checkbox-option-container").first();
|
||||||
const paddingStyles = await checkboxOption.evaluate((el) => {
|
const paddingStyles = await checkboxOption.evaluate((el) => {
|
||||||
const element = el as HTMLElement;
|
const element = el as HTMLElement;
|
||||||
const s = window.getComputedStyle(element);
|
const s = window.getComputedStyle(element);
|
||||||
@@ -1217,7 +1202,7 @@ test("폼 체크박스 세로 패딩 px 입력이 프리뷰에서도 em 스케
|
|||||||
await page.getByRole("link", { name: "프리뷰 열기" }).click();
|
await page.getByRole("link", { name: "프리뷰 열기" }).click();
|
||||||
await expect(page.getByRole("heading", { name: "Page Preview" })).toBeVisible();
|
await expect(page.getByRole("heading", { name: "Page Preview" })).toBeVisible();
|
||||||
|
|
||||||
const checkboxOption = page.getByTestId("preview-form-checkbox-option").first();
|
const checkboxOption = page.getByTestId("preview-form-checkbox-option-container").first();
|
||||||
const paddingStyles = await checkboxOption.evaluate((el) => {
|
const paddingStyles = await checkboxOption.evaluate((el) => {
|
||||||
const element = el as HTMLElement;
|
const element = el as HTMLElement;
|
||||||
const s = window.getComputedStyle(element);
|
const s = window.getComputedStyle(element);
|
||||||
@@ -1587,12 +1572,9 @@ test("폼 컨트롤러에 매핑한 폼 요소와 버튼이 프리뷰에서 함
|
|||||||
const input = page.getByRole("textbox").first();
|
const input = page.getByRole("textbox").first();
|
||||||
await expect(input).toBeVisible();
|
await expect(input).toBeVisible();
|
||||||
|
|
||||||
// 값을 입력한 뒤, 매핑된 버튼(기본 라벨 "버튼")을 클릭하면 폼이 전송되고 성공 메시지가 보여야 한다.
|
// 프리뷰 정책: FormBlock 컨트롤러는 프리뷰에서 실제 `<form>` DOM 을 렌더하지 않는다.
|
||||||
await input.fill("테스트 값");
|
await expect(page.getByTestId("preview-form-controller")).toHaveCount(0);
|
||||||
|
await expect(page.getByText("성공적으로 전송되었습니다.")).toHaveCount(0);
|
||||||
await page.getByRole("button", { name: "버튼" }).click();
|
|
||||||
|
|
||||||
await expect(page.getByText("성공적으로 전송되었습니다.")).toBeVisible();
|
|
||||||
});
|
});
|
||||||
|
|
||||||
test("여러 폼 블록과 여러 버튼이 있을 때 각 폼이 독립적으로 제출되어야 한다", async ({ page }) => {
|
test("여러 폼 블록과 여러 버튼이 있을 때 각 폼이 독립적으로 제출되어야 한다", async ({ page }) => {
|
||||||
@@ -1653,18 +1635,12 @@ test("여러 폼 블록과 여러 버튼이 있을 때 각 폼이 독립적으
|
|||||||
const firstInput = textboxes.nth(0);
|
const firstInput = textboxes.nth(0);
|
||||||
const secondInput = textboxes.nth(1);
|
const secondInput = textboxes.nth(1);
|
||||||
|
|
||||||
// Form A 입력값을 채우고 첫 번째 버튼 클릭 → 성공 메시지 기대
|
// 프리뷰 정책: 여러 FormBlock 이 있어도 preview-form-controller DOM 은 생성되지 않아야 한다.
|
||||||
await firstInput.fill("A 폼 값");
|
const controllers = page.getByTestId("preview-form-controller");
|
||||||
await page.getByRole("button", { name: "버튼" }).first().click();
|
await expect(controllers).toHaveCount(0);
|
||||||
// 첫 번째 폼에 대한 성공 메시지가 최소 하나는 보여야 한다.
|
|
||||||
await expect(page.getByText("성공적으로 전송되었습니다.").first()).toBeVisible();
|
|
||||||
|
|
||||||
// Form B 입력값을 채우고 두 번째 버튼 클릭 → 다시 성공 메시지 기대
|
|
||||||
await secondInput.fill("B 폼 값");
|
|
||||||
await page.getByRole("button", { name: "버튼" }).nth(1).click();
|
|
||||||
// 두 번째 폼에 대한 성공 메시지도 두 번째 요소로 표시되었는지 확인한다.
|
|
||||||
const successMessages = page.getByText("성공적으로 전송되었습니다.");
|
const successMessages = page.getByText("성공적으로 전송되었습니다.");
|
||||||
await expect(successMessages.nth(1)).toBeVisible();
|
await expect(successMessages).toHaveCount(0);
|
||||||
});
|
});
|
||||||
|
|
||||||
test("섹션 패딩/컬럼 간격 수치가 프리뷰에서도 em 스케일에 맞게 반영되어야 한다", async ({ page }) => {
|
test("섹션 패딩/컬럼 간격 수치가 프리뷰에서도 em 스케일에 맞게 반영되어야 한다", async ({ page }) => {
|
||||||
|
|||||||
@@ -0,0 +1,148 @@
|
|||||||
|
import { describe, it, expect, beforeEach, afterEach, vi } from "vitest";
|
||||||
|
import { render, screen, cleanup, fireEvent, waitFor } from "@testing-library/react";
|
||||||
|
import type { Block, ProjectConfig } from "@/features/editor/state/editorStore";
|
||||||
|
import EditorPage from "@/app/editor/page";
|
||||||
|
|
||||||
|
// EditorPage Export 미리보기 UX TDD
|
||||||
|
// - 상단 메뉴에 "Export 미리보기" 항목이 노출되는지 검증한다.
|
||||||
|
// - Export 미리보기 모달에서 "미리보기 새로고침" 클릭 시
|
||||||
|
// - /api/export/preview 엔드포인트를 호출하고,
|
||||||
|
// - 반환된 HTML 을 iframe srcdoc 으로 렌더하는지 확인한다.
|
||||||
|
|
||||||
|
let mockState: any;
|
||||||
|
|
||||||
|
beforeEach(() => {
|
||||||
|
const baseProjectConfig: ProjectConfig = {
|
||||||
|
title: "Export 미리보기 테스트",
|
||||||
|
slug: "export-preview-test",
|
||||||
|
canvasPreset: "full",
|
||||||
|
} as ProjectConfig;
|
||||||
|
|
||||||
|
mockState = {
|
||||||
|
blocks: [
|
||||||
|
{
|
||||||
|
id: "blk_text_1",
|
||||||
|
type: "text",
|
||||||
|
props: {
|
||||||
|
text: "Export 미리보기 본문",
|
||||||
|
align: "left",
|
||||||
|
size: "base",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
] as Block[],
|
||||||
|
projectConfig: baseProjectConfig,
|
||||||
|
selectedBlockId: null as string | null,
|
||||||
|
selectedListItemId: null as string | null,
|
||||||
|
undo: vi.fn(),
|
||||||
|
redo: vi.fn(),
|
||||||
|
removeBlock: vi.fn(),
|
||||||
|
duplicateBlock: vi.fn(),
|
||||||
|
selectBlock: vi.fn(),
|
||||||
|
selectListItem: vi.fn(),
|
||||||
|
replaceBlocks: vi.fn(),
|
||||||
|
reorderBlocks: vi.fn(),
|
||||||
|
moveBlock: vi.fn(),
|
||||||
|
addTextBlock: vi.fn(),
|
||||||
|
addButtonBlock: vi.fn(),
|
||||||
|
addImageBlock: vi.fn(),
|
||||||
|
addDividerBlock: vi.fn(),
|
||||||
|
addListBlock: vi.fn(),
|
||||||
|
addSectionBlock: vi.fn(),
|
||||||
|
addFormBlock: vi.fn(),
|
||||||
|
addFormInputBlock: vi.fn(),
|
||||||
|
addFormSelectBlock: vi.fn(),
|
||||||
|
addFormCheckboxBlock: vi.fn(),
|
||||||
|
addFormRadioBlock: vi.fn(),
|
||||||
|
addHeroTemplateSection: vi.fn(),
|
||||||
|
addFeaturesTemplateSection: vi.fn(),
|
||||||
|
addCtaTemplateSection: vi.fn(),
|
||||||
|
addFaqTemplateSection: vi.fn(),
|
||||||
|
addPricingTemplateSection: vi.fn(),
|
||||||
|
addTestimonialsTemplateSection: vi.fn(),
|
||||||
|
addBlogTemplateSection: vi.fn(),
|
||||||
|
addTeamTemplateSection: vi.fn(),
|
||||||
|
addFooterTemplateSection: vi.fn(),
|
||||||
|
updateBlock: vi.fn(),
|
||||||
|
};
|
||||||
|
});
|
||||||
|
|
||||||
|
afterEach(() => {
|
||||||
|
cleanup();
|
||||||
|
vi.unstubAllGlobals();
|
||||||
|
});
|
||||||
|
|
||||||
|
vi.mock("@/features/editor/state/editorStore", () => {
|
||||||
|
const useEditorStore = (selector: (state: any) => any) => selector(mockState);
|
||||||
|
(useEditorStore as any).getState = () => mockState;
|
||||||
|
|
||||||
|
return {
|
||||||
|
__esModule: true,
|
||||||
|
useEditorStore,
|
||||||
|
};
|
||||||
|
});
|
||||||
|
|
||||||
|
vi.mock("next/link", () => {
|
||||||
|
return {
|
||||||
|
__esModule: true,
|
||||||
|
default: ({ href, children }: any) => <a href={href}>{children}</a>,
|
||||||
|
};
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("EditorPage - Export 미리보기", () => {
|
||||||
|
it("메뉴에서 Export 미리보기 항목을 클릭하면 Export 미리보기 모달이 열려야 한다", () => {
|
||||||
|
render(<EditorPage />);
|
||||||
|
|
||||||
|
const menuButton = screen.getByText("메뉴");
|
||||||
|
fireEvent.click(menuButton);
|
||||||
|
|
||||||
|
const previewMenuItem = screen.getByText("Export 미리보기");
|
||||||
|
fireEvent.click(previewMenuItem);
|
||||||
|
|
||||||
|
const modalTitle = screen.getByText("Export 미리보기");
|
||||||
|
expect(modalTitle).toBeTruthy();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("Export 미리보기 새로고침 시 /api/export/preview 를 호출하고 iframe 에 HTML 을 렌더해야 한다", async () => {
|
||||||
|
const fetchMock = vi.fn().mockResolvedValue(
|
||||||
|
new Response(
|
||||||
|
"<!DOCTYPE html><html><head><title>Export 미리보기 테스트</title></head><body>Export 미리보기 본문</body></html>",
|
||||||
|
{
|
||||||
|
status: 200,
|
||||||
|
headers: { "Content-Type": "text/html; charset=utf-8" },
|
||||||
|
},
|
||||||
|
),
|
||||||
|
);
|
||||||
|
|
||||||
|
vi.stubGlobal("fetch", fetchMock);
|
||||||
|
|
||||||
|
render(<EditorPage />);
|
||||||
|
|
||||||
|
const menuButton = screen.getByText("메뉴");
|
||||||
|
fireEvent.click(menuButton);
|
||||||
|
|
||||||
|
const previewMenuItem = screen.getByText("Export 미리보기");
|
||||||
|
fireEvent.click(previewMenuItem);
|
||||||
|
|
||||||
|
const refreshButton = screen.getByText("미리보기 새로고침");
|
||||||
|
fireEvent.click(refreshButton);
|
||||||
|
|
||||||
|
await waitFor(() => {
|
||||||
|
expect(fetchMock).toHaveBeenCalledTimes(1);
|
||||||
|
});
|
||||||
|
|
||||||
|
const [url, options] = fetchMock.mock.calls[0] as any;
|
||||||
|
expect(url).toBe("/api/export/preview");
|
||||||
|
expect(options.method).toBe("POST");
|
||||||
|
expect(options.headers["Content-Type"]).toBe("application/json");
|
||||||
|
|
||||||
|
const parsed = JSON.parse(options.body);
|
||||||
|
expect(Array.isArray(parsed.blocks)).toBe(true);
|
||||||
|
expect(parsed.blocks[0].id).toBe("blk_text_1");
|
||||||
|
expect(parsed.projectConfig.slug).toBe("export-preview-test");
|
||||||
|
|
||||||
|
const iframe = await screen.findByTestId("export-preview-frame");
|
||||||
|
const srcDoc = iframe.getAttribute("srcdoc") ?? "";
|
||||||
|
expect(srcDoc).toContain("Export 미리보기 테스트");
|
||||||
|
expect(srcDoc).toContain("Export 미리보기 본문");
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,91 @@
|
|||||||
|
import { describe, it, expect, beforeEach, afterEach, vi } from "vitest";
|
||||||
|
import { render, screen, fireEvent, cleanup, waitFor } from "@testing-library/react";
|
||||||
|
import type { Block, ProjectConfig } from "@/features/editor/state/editorStore";
|
||||||
|
import PreviewPage from "@/app/preview/page";
|
||||||
|
|
||||||
|
// PreviewPage Export ZIP TDD
|
||||||
|
// - 프리뷰 헤더에 "페이지 파일로 내보내기 (ZIP)" 버튼이 노출되어야 한다.
|
||||||
|
// - 버튼 클릭 시 /api/export 로 blocks + projectConfig 를 payload 로 POST 요청을 보내야 한다.
|
||||||
|
|
||||||
|
let mockState: any;
|
||||||
|
|
||||||
|
beforeEach(() => {
|
||||||
|
const baseProjectConfig: ProjectConfig = {
|
||||||
|
title: "프리뷰 Export 테스트",
|
||||||
|
slug: "preview-export-test",
|
||||||
|
canvasPreset: "full",
|
||||||
|
} as ProjectConfig;
|
||||||
|
|
||||||
|
mockState = {
|
||||||
|
blocks: [
|
||||||
|
{
|
||||||
|
id: "blk_text_1",
|
||||||
|
type: "text",
|
||||||
|
props: {
|
||||||
|
text: "프리뷰 Export 본문",
|
||||||
|
align: "left",
|
||||||
|
size: "base",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
] as Block[],
|
||||||
|
projectConfig: baseProjectConfig,
|
||||||
|
};
|
||||||
|
});
|
||||||
|
|
||||||
|
afterEach(() => {
|
||||||
|
cleanup();
|
||||||
|
vi.unstubAllGlobals();
|
||||||
|
});
|
||||||
|
|
||||||
|
vi.mock("@/features/editor/state/editorStore", () => {
|
||||||
|
const useEditorStore = (selector: (state: any) => any) => selector(mockState);
|
||||||
|
return {
|
||||||
|
__esModule: true,
|
||||||
|
useEditorStore,
|
||||||
|
};
|
||||||
|
});
|
||||||
|
|
||||||
|
vi.mock("next/link", () => {
|
||||||
|
return {
|
||||||
|
__esModule: true,
|
||||||
|
default: ({ href, children }: any) => <a href={href}>{children}</a>,
|
||||||
|
};
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("PreviewPage - ZIP Export", () => {
|
||||||
|
it("프리뷰 헤더에 ZIP Export 버튼이 노출되어야 한다", () => {
|
||||||
|
render(<PreviewPage />);
|
||||||
|
|
||||||
|
const exportButton = screen.getByText("페이지 파일로 내보내기 (ZIP)");
|
||||||
|
expect(exportButton).toBeTruthy();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("ZIP Export 버튼 클릭 시 /api/export 로 blocks + projectConfig 를 payload 로 POST 해야 한다", async () => {
|
||||||
|
const fetchMock = vi.fn().mockResolvedValue({
|
||||||
|
ok: true,
|
||||||
|
// JSDOM 환경에서 blob() 호출을 안전하게 처리하기 위한 최소 mock
|
||||||
|
blob: vi.fn().mockResolvedValue(new Blob(["dummy-zip"])),
|
||||||
|
} as any);
|
||||||
|
|
||||||
|
vi.stubGlobal("fetch", fetchMock);
|
||||||
|
|
||||||
|
render(<PreviewPage />);
|
||||||
|
|
||||||
|
const exportButton = screen.getByText("페이지 파일로 내보내기 (ZIP)");
|
||||||
|
fireEvent.click(exportButton);
|
||||||
|
|
||||||
|
await waitFor(() => {
|
||||||
|
expect(fetchMock).toHaveBeenCalledTimes(1);
|
||||||
|
});
|
||||||
|
|
||||||
|
const [url, options] = fetchMock.mock.calls[0] as any;
|
||||||
|
expect(url).toBe("/api/export");
|
||||||
|
expect(options.method).toBe("POST");
|
||||||
|
expect(options.headers["Content-Type"]).toBe("application/json");
|
||||||
|
|
||||||
|
const parsed = JSON.parse(options.body);
|
||||||
|
expect(Array.isArray(parsed.blocks)).toBe(true);
|
||||||
|
expect(parsed.blocks[0].id).toBe("blk_text_1");
|
||||||
|
expect(parsed.projectConfig.slug).toBe("preview-export-test");
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,102 @@
|
|||||||
|
import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
|
||||||
|
import { render, screen, fireEvent, cleanup } from "@testing-library/react";
|
||||||
|
import { ProjectPropertiesPanel } from "@/app/editor/panels/ProjectPropertiesPanel";
|
||||||
|
import type { ProjectConfig } from "@/features/editor/state/editorStore";
|
||||||
|
|
||||||
|
let mockState: { projectConfig: ProjectConfig; updateProjectConfig: ReturnType<typeof vi.fn> };
|
||||||
|
|
||||||
|
beforeEach(() => {
|
||||||
|
const baseConfig: ProjectConfig = {
|
||||||
|
title: "프로젝트",
|
||||||
|
slug: "project",
|
||||||
|
canvasPreset: "full",
|
||||||
|
canvasWidthPx: 1024,
|
||||||
|
canvasBgColorHex: "#0f172a",
|
||||||
|
bodyBgColorHex: "#020617",
|
||||||
|
headHtml: "",
|
||||||
|
trackingScript: "",
|
||||||
|
// SEO 필드는 아직 구현 전이지만, TDD 를 위해 기본값 형태만 지정해 둔다.
|
||||||
|
// 실제 타입 정의는 추후 15.1 구현에서 확장한다.
|
||||||
|
} as ProjectConfig;
|
||||||
|
|
||||||
|
mockState = {
|
||||||
|
projectConfig: baseConfig,
|
||||||
|
updateProjectConfig: vi.fn(),
|
||||||
|
};
|
||||||
|
});
|
||||||
|
|
||||||
|
afterEach(() => {
|
||||||
|
cleanup();
|
||||||
|
});
|
||||||
|
|
||||||
|
vi.mock("@/features/editor/state/editorStore", () => {
|
||||||
|
const useEditorStore = (selector: (state: any) => any) => selector(mockState);
|
||||||
|
return {
|
||||||
|
__esModule: true,
|
||||||
|
useEditorStore,
|
||||||
|
};
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("ProjectPropertiesPanel SEO 메타", () => {
|
||||||
|
it("SEO 타이틀 입력을 변경하면 seoTitle 이 updateProjectConfig 로 전달되어야 한다", () => {
|
||||||
|
render(<ProjectPropertiesPanel />);
|
||||||
|
|
||||||
|
const input = screen.getByLabelText("SEO 타이틀") as HTMLInputElement;
|
||||||
|
|
||||||
|
fireEvent.change(input, { target: { value: "새 SEO 타이틀" } });
|
||||||
|
|
||||||
|
expect(mockState.updateProjectConfig).toHaveBeenCalledWith({ seoTitle: "새 SEO 타이틀" });
|
||||||
|
});
|
||||||
|
|
||||||
|
it("메타 디스크립션 입력을 변경하면 seoDescription 이 updateProjectConfig 로 전달되어야 한다", () => {
|
||||||
|
render(<ProjectPropertiesPanel />);
|
||||||
|
|
||||||
|
const textarea = screen.getByLabelText("메타 디스크립션") as HTMLTextAreaElement;
|
||||||
|
|
||||||
|
fireEvent.change(textarea, { target: { value: "SEO 설명" } });
|
||||||
|
|
||||||
|
expect(mockState.updateProjectConfig).toHaveBeenCalledWith({
|
||||||
|
seoDescription: "SEO 설명",
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it("OG/Twitter 이미지 URL 입력을 변경하면 seoOgImageUrl 이 updateProjectConfig 로 전달되어야 한다", () => {
|
||||||
|
render(<ProjectPropertiesPanel />);
|
||||||
|
|
||||||
|
const input = screen.getByLabelText("OG/Twitter 이미지 URL") as HTMLInputElement;
|
||||||
|
|
||||||
|
fireEvent.change(input, { target: { value: "https://example.com/og.png" } });
|
||||||
|
|
||||||
|
expect(mockState.updateProjectConfig).toHaveBeenCalledWith({
|
||||||
|
seoOgImageUrl: "https://example.com/og.png",
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it("Canonical URL 입력을 변경하면 seoCanonicalUrl 이 updateProjectConfig 로 전달되어야 한다", () => {
|
||||||
|
render(<ProjectPropertiesPanel />);
|
||||||
|
|
||||||
|
const input = screen.getByLabelText("Canonical URL") as HTMLInputElement;
|
||||||
|
|
||||||
|
fireEvent.change(input, { target: { value: "https://example.com/landing" } });
|
||||||
|
|
||||||
|
expect(mockState.updateProjectConfig).toHaveBeenCalledWith({
|
||||||
|
seoCanonicalUrl: "https://example.com/landing",
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it("검색 노출 제어 체크박스를 토글하면 seoNoIndex 가 true 로 업데이트되어야 한다", () => {
|
||||||
|
render(<ProjectPropertiesPanel />);
|
||||||
|
|
||||||
|
const checkbox = screen.getByLabelText(
|
||||||
|
"검색 엔진에 노출하지 않기 (noindex)",
|
||||||
|
) as HTMLInputElement;
|
||||||
|
|
||||||
|
expect(checkbox.checked).toBe(false);
|
||||||
|
|
||||||
|
fireEvent.click(checkbox);
|
||||||
|
|
||||||
|
expect(mockState.updateProjectConfig).toHaveBeenCalledWith({
|
||||||
|
seoNoIndex: true,
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -88,7 +88,7 @@ describe("PublicPageRenderer - 블록 배경색", () => {
|
|||||||
expect(listNoBg!.style.backgroundColor === "" || listNoBg!.style.backgroundColor === "transparent").toBe(true);
|
expect(listNoBg!.style.backgroundColor === "" || listNoBg!.style.backgroundColor === "transparent").toBe(true);
|
||||||
});
|
});
|
||||||
|
|
||||||
it("form 컨트롤러 블록은 backgroundColorCustom 이 설정된 경우에만 폼 래퍼에 배경색이 적용되어야 한다", () => {
|
it("form 컨트롤러 블록은 프리뷰에서 별도 폼 래퍼를 렌더하지 않아야 한다", () => {
|
||||||
const blocksWithBg: Block[] = [
|
const blocksWithBg: Block[] = [
|
||||||
{
|
{
|
||||||
id: "form_with_bg",
|
id: "form_with_bg",
|
||||||
@@ -105,10 +105,10 @@ describe("PublicPageRenderer - 블록 배경색", () => {
|
|||||||
} as any,
|
} as any,
|
||||||
];
|
];
|
||||||
|
|
||||||
const { getByTestId, rerender } = render(<PublicPageRenderer blocks={blocksWithBg} />);
|
const { queryByTestId, rerender } = render(<PublicPageRenderer blocks={blocksWithBg} />);
|
||||||
|
|
||||||
const formWithBg = getByTestId("preview-form-controller") as HTMLFormElement;
|
const formWithBg = queryByTestId("preview-form-controller");
|
||||||
expect(formWithBg.style.backgroundColor).toBe("rgb(17, 17, 17)");
|
expect(formWithBg).toBeNull();
|
||||||
|
|
||||||
const blocksWithoutBg: Block[] = [
|
const blocksWithoutBg: Block[] = [
|
||||||
{
|
{
|
||||||
@@ -126,8 +126,8 @@ describe("PublicPageRenderer - 블록 배경색", () => {
|
|||||||
|
|
||||||
rerender(<PublicPageRenderer blocks={blocksWithoutBg} />);
|
rerender(<PublicPageRenderer blocks={blocksWithoutBg} />);
|
||||||
|
|
||||||
const formNoBg = getByTestId("preview-form-controller") as HTMLFormElement;
|
const formNoBg = queryByTestId("preview-form-controller");
|
||||||
expect(formNoBg.style.backgroundColor === "" || formNoBg.style.backgroundColor === "transparent").toBe(true);
|
expect(formNoBg).toBeNull();
|
||||||
});
|
});
|
||||||
|
|
||||||
it("section 블록은 backgroundColorCustom 이 설정된 경우에만 섹션 요소에 배경색이 적용되어야 한다", () => {
|
it("section 블록은 backgroundColorCustom 이 설정된 경우에만 섹션 요소에 배경색이 적용되어야 한다", () => {
|
||||||
|
|||||||
@@ -0,0 +1,33 @@
|
|||||||
|
import { describe, it, expect, afterEach } from "vitest";
|
||||||
|
import { render, screen, cleanup } from "@testing-library/react";
|
||||||
|
import { PublicPageRenderer } from "@/features/editor/components/PublicPageRenderer";
|
||||||
|
import { createFooterTemplateBlocks } from "@/app/editor/templates/footerTemplate";
|
||||||
|
import type { Block } from "@/features/editor/state/editorStore";
|
||||||
|
|
||||||
|
// PublicPageRenderer 푸터 템플릿 TDD
|
||||||
|
// - footerTemplate 로 생성한 섹션이 프리뷰에서 섹션/텍스트 구조로 올바르게 렌더되는지 검증한다.
|
||||||
|
|
||||||
|
describe("PublicPageRenderer - 푸터 템플릿", () => {
|
||||||
|
afterEach(() => {
|
||||||
|
cleanup();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("푸터 템플릿 섹션은 프리뷰에서 섹션과 푸터 텍스트들을 렌더해야 한다", () => {
|
||||||
|
const sectionId = "footer_preview_section";
|
||||||
|
let i = 0;
|
||||||
|
const createId = () => `footer_${++i}`;
|
||||||
|
|
||||||
|
const { blocks } = createFooterTemplateBlocks({ sectionId, createId });
|
||||||
|
|
||||||
|
render(<PublicPageRenderer blocks={blocks as Block[]} />);
|
||||||
|
|
||||||
|
const section = screen.getByTestId("preview-section");
|
||||||
|
expect(section.getAttribute("data-section-id")).toBe(sectionId);
|
||||||
|
|
||||||
|
expect(screen.getByText("MyLanding")).toBeTruthy();
|
||||||
|
expect(screen.getByText("더 나은 웹사이트를 위한 최고의 선택.")).toBeTruthy();
|
||||||
|
expect(screen.getByText(/서비스 소개/)).toBeTruthy();
|
||||||
|
expect(screen.getByText(/문의하기/)).toBeTruthy();
|
||||||
|
expect(screen.getByText(/© 2025 MyLanding\./)).toBeTruthy();
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -15,7 +15,7 @@ describe("PublicPageRenderer - 폼 제출 메시지", () => {
|
|||||||
(global as any).fetch = undefined;
|
(global as any).fetch = undefined;
|
||||||
});
|
});
|
||||||
|
|
||||||
it("성공 응답 시 config.successMessage 를 success 스타일로 표시해야 한다", async () => {
|
it("FormBlock 이 있어도 프리뷰에서는 폼 컨트롤러를 렌더하지 않아야 한다 (성공 메시지 설정)", () => {
|
||||||
const blocks: Block[] = [
|
const blocks: Block[] = [
|
||||||
{
|
{
|
||||||
id: "form_success",
|
id: "form_success",
|
||||||
@@ -42,19 +42,12 @@ describe("PublicPageRenderer - 폼 제출 메시지", () => {
|
|||||||
|
|
||||||
render(<PublicPageRenderer blocks={blocks} />);
|
render(<PublicPageRenderer blocks={blocks} />);
|
||||||
|
|
||||||
const form = screen.getByTestId("preview-form-controller");
|
const form = screen.queryByTestId("preview-form-controller");
|
||||||
fireEvent.submit(form);
|
expect(form).toBeNull();
|
||||||
|
expect(fetchMock).not.toHaveBeenCalled();
|
||||||
await waitFor(() => {
|
|
||||||
expect(fetchMock).toHaveBeenCalledTimes(1);
|
|
||||||
});
|
|
||||||
|
|
||||||
const messageEl = await screen.findByText("폼 성공 메시지 (config)");
|
|
||||||
expect(messageEl.textContent).toBe("폼 성공 메시지 (config)");
|
|
||||||
expect(messageEl.className).toContain("text-emerald-400");
|
|
||||||
});
|
});
|
||||||
|
|
||||||
it("에러 응답 시 config.errorMessage 를 error 스타일로 표시해야 한다", async () => {
|
it("FormBlock 이 있어도 프리뷰에서는 폼 컨트롤러나 에러 메시지를 렌더하지 않아야 한다", () => {
|
||||||
const blocks: Block[] = [
|
const blocks: Block[] = [
|
||||||
{
|
{
|
||||||
id: "form_error",
|
id: "form_error",
|
||||||
@@ -81,15 +74,9 @@ describe("PublicPageRenderer - 폼 제출 메시지", () => {
|
|||||||
|
|
||||||
render(<PublicPageRenderer blocks={blocks} />);
|
render(<PublicPageRenderer blocks={blocks} />);
|
||||||
|
|
||||||
const form = screen.getByTestId("preview-form-controller");
|
const form = screen.queryByTestId("preview-form-controller");
|
||||||
fireEvent.submit(form);
|
expect(form).toBeNull();
|
||||||
|
expect(fetchMock).not.toHaveBeenCalled();
|
||||||
await waitFor(() => {
|
expect(screen.queryByText("폼 에러 메시지 (config)")).toBeNull();
|
||||||
expect(fetchMock).toHaveBeenCalledTimes(1);
|
|
||||||
});
|
|
||||||
|
|
||||||
const messageEl = await screen.findByText("폼 에러 메시지 (config)");
|
|
||||||
expect(messageEl.textContent).toBe("폼 에러 메시지 (config)");
|
|
||||||
expect(messageEl.className).toContain("text-rose-400");
|
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -192,4 +192,26 @@ describe("PublicPageRenderer - 비디오 블록 스타일", () => {
|
|||||||
expect(wrapper!.style.padding).toBe("2em");
|
expect(wrapper!.style.padding).toBe("2em");
|
||||||
expect(wrapper!.style.borderRadius).toBe("1em");
|
expect(wrapper!.style.borderRadius).toBe("1em");
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it("sourceUrl 이 비어 있는 비디오 블록은 프리뷰에서 video/iframe 을 렌더하지 않아야 한다", () => {
|
||||||
|
const blocks: Block[] = [
|
||||||
|
{
|
||||||
|
id: "video_empty_src_preview_1",
|
||||||
|
type: "video" as any,
|
||||||
|
props: {
|
||||||
|
sourceUrl: "",
|
||||||
|
align: "center",
|
||||||
|
widthMode: "auto",
|
||||||
|
aspectRatio: "16:9",
|
||||||
|
} as any,
|
||||||
|
},
|
||||||
|
];
|
||||||
|
|
||||||
|
const { container } = render(<PublicPageRenderer blocks={blocks} />);
|
||||||
|
|
||||||
|
const video = container.querySelector("video");
|
||||||
|
const iframe = container.querySelector("iframe");
|
||||||
|
expect(video).toBeNull();
|
||||||
|
expect(iframe).toBeNull();
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -2,7 +2,6 @@ import { describe, it, expect, vi } from "vitest";
|
|||||||
import { render, screen, fireEvent } from "@testing-library/react";
|
import { render, screen, fireEvent } from "@testing-library/react";
|
||||||
import { TextPropertiesPanel } from "@/app/editor/panels/TextPropertiesPanel";
|
import { TextPropertiesPanel } from "@/app/editor/panels/TextPropertiesPanel";
|
||||||
import { ListPropertiesPanel } from "@/app/editor/panels/ListPropertiesPanel";
|
import { ListPropertiesPanel } from "@/app/editor/panels/ListPropertiesPanel";
|
||||||
import { FormControllerPanel } from "@/app/editor/forms/FormControllerPanel";
|
|
||||||
import type { Block } from "@/features/editor/state/editorStore";
|
import type { Block } from "@/features/editor/state/editorStore";
|
||||||
|
|
||||||
// Text/List/Form 패널에 추가되는 블록 배경색(backgroundColorCustom) 컨트롤에 대한 최소 TDD
|
// Text/List/Form 패널에 추가되는 블록 배경색(backgroundColorCustom) 컨트롤에 대한 최소 TDD
|
||||||
@@ -58,34 +57,4 @@ describe("Text/List/Form 패널 - 블록 배경색 컨트롤", () => {
|
|||||||
expect.objectContaining({ backgroundColorCustom: "#445566" }),
|
expect.objectContaining({ backgroundColorCustom: "#445566" }),
|
||||||
);
|
);
|
||||||
});
|
});
|
||||||
|
|
||||||
it("FormControllerPanel 에서 배경색 HEX 인풋 변경 시 updateBlock 이 backgroundColorCustom 으로 호출되어야 한다", () => {
|
|
||||||
const updateBlock = vi.fn();
|
|
||||||
|
|
||||||
const formBlock: Block = {
|
|
||||||
id: "form-1",
|
|
||||||
type: "form",
|
|
||||||
props: {
|
|
||||||
kind: "contact",
|
|
||||||
submitTarget: "internal",
|
|
||||||
} as any,
|
|
||||||
};
|
|
||||||
|
|
||||||
render(
|
|
||||||
<FormControllerPanel
|
|
||||||
block={formBlock}
|
|
||||||
blocks={[]}
|
|
||||||
selectedBlockId="form-1"
|
|
||||||
updateBlock={updateBlock}
|
|
||||||
/>,
|
|
||||||
);
|
|
||||||
|
|
||||||
const hexInput = screen.getByLabelText("폼 배경색 HEX");
|
|
||||||
fireEvent.change(hexInput, { target: { value: "#778899" } });
|
|
||||||
|
|
||||||
expect(updateBlock).toHaveBeenCalledWith(
|
|
||||||
"form-1",
|
|
||||||
expect.objectContaining({ backgroundColorCustom: "#778899" }),
|
|
||||||
);
|
|
||||||
});
|
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -411,10 +411,9 @@ describe("formHelpers.computeFormControllerPublicTokens", () => {
|
|||||||
expect(checkboxField.groupLabelImageUrl).toBe("https://example.com/group.png");
|
expect(checkboxField.groupLabelImageUrl).toBe("https://example.com/group.png");
|
||||||
|
|
||||||
expect(tokens.formClassName).toBe("space-y-3");
|
expect(tokens.formClassName).toBe("space-y-3");
|
||||||
expect(tokens.formStyle.width).toBe("20em");
|
// FormBlock 은 이제 레이아웃/배경 스타일을 가지지 않는 순수 컨트롤러이므로,
|
||||||
expect(tokens.formStyle.marginTop).toBe("2em");
|
// formStyle 은 항상 빈 객체여야 한다.
|
||||||
expect(tokens.formStyle.marginBottom).toBe("2em");
|
expect(tokens.formStyle).toEqual({});
|
||||||
expect(tokens.formStyle.backgroundColor).toBe("#123456");
|
|
||||||
|
|
||||||
expect(tokens.submitLabel).toBe("컨트롤러 버튼");
|
expect(tokens.submitLabel).toBe("컨트롤러 버튼");
|
||||||
});
|
});
|
||||||
@@ -509,7 +508,8 @@ describe("formHelpers.computeFormBlockExportTokens", () => {
|
|||||||
expect(tokens.controllerFields[0].id).toBe("input-1");
|
expect(tokens.controllerFields[0].id).toBe("input-1");
|
||||||
expect(tokens.controllerFields[1].id).toBe("select-1");
|
expect(tokens.controllerFields[1].id).toBe("select-1");
|
||||||
expect(tokens.fallbackFields).toHaveLength(0);
|
expect(tokens.fallbackFields).toHaveLength(0);
|
||||||
expect(tokens.formStyleParts).toEqual(["background-color:#123456"]);
|
// FormBlock 은 Export 레이어에서도 컨테이너 배경/레이아웃 스타일을 가지지 않는다.
|
||||||
|
expect(tokens.formStyleParts).toEqual([]);
|
||||||
});
|
});
|
||||||
|
|
||||||
it("fieldIds 가 없고 fields 가 있을 때 fallbackFields 를 사용해야 한다", () => {
|
it("fieldIds 가 없고 fields 가 있을 때 fallbackFields 를 사용해야 한다", () => {
|
||||||
|
|||||||
@@ -181,9 +181,6 @@ describe("프리뷰와 정적 내보내기 일치 (고수준)", () => {
|
|||||||
"섹션 안 텍스트",
|
"섹션 안 텍스트",
|
||||||
"섹션 버튼",
|
"섹션 버튼",
|
||||||
"리스트 아이템 1",
|
"리스트 아이템 1",
|
||||||
"폼 이름",
|
|
||||||
"폼 이메일",
|
|
||||||
"폼 메시지",
|
|
||||||
"입력(단독)",
|
"입력(단독)",
|
||||||
"선택(단독)",
|
"선택(단독)",
|
||||||
"체크 A",
|
"체크 A",
|
||||||
|
|||||||
@@ -0,0 +1 @@
|
|||||||
|
PNG TEST FIXTURE
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
PNG TEST FIXTURE
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
PNG TEST FIXTURE
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
PNG TEST FIXTURE
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
PNG TEST FIXTURE
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
PNG TEST FIXTURE
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
PNG TEST FIXTURE
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
PNG TEST FIXTURE
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
PNG TEST FIXTURE
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
PNG TEST FIXTURE
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
dummy-image
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
dummy-image
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
dummy-image
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
dummy-image
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
dummy-image
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
dummy-image
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
dummy-image
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
dummy-image
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
dummy-image
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
dummy-image
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
dummy-image
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
dummy-image
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
dummy-image
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
dummy-image
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
dummy-image
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
dummy-image
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
dummy-section-video
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
dummy-section-video
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
dummy-section-video
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
dummy-section-video
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
dummy-section-video
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
dummy-section-video
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
dummy-section-video
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
dummy-section-video
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
dummy-video
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
dummy-video
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
dummy-video
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
dummy-video
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
dummy-video
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
dummy-video
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
dummy-video
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
dummy-video
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
dummy-poster
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
dummy-poster
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
dummy-poster
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
dummy-poster
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
dummy-poster
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
dummy-poster
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
dummy-poster
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
dummy-poster
|
||||||
Reference in New Issue
Block a user