Files
persionalBrand/apps/admin/src/features/brand/TemplatePreview.tsx
T

169 lines
5.2 KiB
TypeScript

import { useEffect, useMemo, useRef, useState } from "react";
import { Alert, Spin } from "antd";
import type {
BrandProfile,
EditorPreviewFrameMessage,
EditorPreviewHostMessage,
RuntimeWorkspace,
} from "@personal-brand/api-client";
import { templatePreviewUrl } from "../../lib/template-preview.js";
import { ComponentTemplatePreview } from "./ComponentTemplatePreview.js";
import { resolveTemplateRenderer } from "./component-renderers.jsx";
import type { PreviewSelection, PreviewTarget } from "./preview-selection.js";
import "./TemplatePreview.css";
export function TemplatePreview({
brand,
workspace,
page,
offeringId,
targetKey,
selection,
targets,
onTargetSelected,
}: {
brand: BrandProfile;
workspace?: RuntimeWorkspace;
page: string;
offeringId?: string;
targetKey?: string;
selection?: PreviewSelection;
targets: PreviewTarget[];
onTargetSelected: (selection?: PreviewSelection) => void;
}) {
const frame = useRef<HTMLIFrameElement>(null);
const useComponent = Boolean(workspace && resolveTemplateRenderer(workspace));
const [ready, setReady] = useState(false);
const [error, setError] = useState("");
const [reloadKey, setReloadKey] = useState(0);
const url = useMemo(() => {
const value = templatePreviewUrl(
brand.slug,
page,
import.meta.env.VITE_TEMPLATE_PREVIEW_URL || "/template-preview/index.html",
window.location.origin,
`/pages/${encodeURIComponent(page)}/index`,
);
if (!value) return undefined;
const preview = new URL(value);
preview.searchParams.set("refresh", String(reloadKey));
return preview.toString();
}, [brand.slug, page, reloadKey]);
const origin = useMemo(() => (url ? new URL(url).origin : ""), [url]);
const brandDraft = useMemo(
() => ({
name: brand.name,
tagline: brand.tagline,
description: brand.description,
avatarUrl: brand.avatarUrl,
coverUrl: brand.coverUrl,
hours: brand.hours,
address: brand.address,
deliveryNote: brand.deliveryNote,
contactPhone: brand.contactPhone,
contactWechat: brand.contactWechat,
config: brand.config,
}),
[brand],
);
useEffect(() => {
setReady(false);
setError("");
}, [url]);
useEffect(() => {
const onMessage = (event: MessageEvent<EditorPreviewFrameMessage>) => {
if (event.source !== frame.current?.contentWindow || event.origin !== origin) return;
const message = event.data;
if (message?.protocol !== "personal-brand-editor-preview" || message.version !== 1) return;
if (message.type === "ready") setReady(true);
if (message.type === "targetSelected" && message.page === page)
onTargetSelected({ targetKey: message.targetKey });
};
window.addEventListener("message", onMessage);
return () => window.removeEventListener("message", onMessage);
}, [onTargetSelected, origin, page]);
useEffect(() => {
if (!ready || !frame.current?.contentWindow || !origin) return;
const send = (message: EditorPreviewHostMessage) =>
frame.current?.contentWindow?.postMessage(message, origin);
if (workspace) {
send({
protocol: "personal-brand-editor-preview",
version: 1,
type: "workspaceDraft",
workspace,
});
} else {
send({
protocol: "personal-brand-editor-preview",
version: 1,
type: "brandDraft",
brand: brandDraft,
});
}
if (targetKey)
send({
protocol: "personal-brand-editor-preview",
version: 1,
type: "focusTarget",
targetKey,
});
}, [brandDraft, origin, ready, targetKey, workspace]);
useEffect(() => {
const refresh = () => setReloadKey((value) => value + 1);
window.addEventListener("template-preview-refresh", refresh);
return () => window.removeEventListener("template-preview-refresh", refresh);
}, []);
if (!useComponent && !url)
return (
<Alert
type="warning"
showIcon
message="页面预览暂不可用"
description="请确认模板预览资源已构建并发布,或本地预览服务正在运行。"
/>
);
return (
<div className="template-preview">
{workspace && useComponent ? (
<ComponentTemplatePreview
workspace={workspace}
page={page}
{...(offeringId ? { offeringId } : {})}
{...(targetKey ? { targetKey } : {})}
{...(selection ? { selection } : {})}
targets={targets}
onTargetSelected={onTargetSelected}
/>
) : null}
{!useComponent ? (
<>
{!ready && !error ? (
<div className="template-preview__loading">
<Spin tip="正在加载页面预览" />
</div>
) : null}
{error ? (
<Alert type="error" showIcon message="页面预览加载失败" description={error} />
) : null}
<iframe
key={url}
ref={frame}
title="小程序页面预览"
src={url}
referrerPolicy="origin"
onError={() => setError("请检查预览服务地址和网络连接。")}
style={{ opacity: ready ? 1 : 0 }}
/>
</>
) : null}
</div>
);
}