feat: 建立组件化模板预览基线并规划可视化编辑
This commit is contained in:
1 parent
c5af790554
commit
0b14b5a814
46 files changed
+1880
-427
No files matched your search
@@ -2,4 +2,4 @@ VITE_APP_BASE_PATH=/admin/
|
||||
VITE_API_BASE_URL=/api
|
||||
VITE_DEV_API_TARGET=http://localhost:3001
|
||||
ADMIN_PORT=3000
|
||||
VITE_TEMPLATE_PREVIEW_URLS={"acheng-campus-food":"http://localhost:3002","linjing-editorial":"http://localhost:3003"}
|
||||
VITE_TEMPLATE_PREVIEW_URL=http://localhost:3002
|
||||
@@ -16,6 +16,10 @@ export function BrandPage() {
|
||||
queryKey: ["admin-workspace"],
|
||||
queryFn: () => client.getAdminWorkspace(),
|
||||
});
|
||||
const previewWorkspace = useQuery({
|
||||
queryKey: ["admin-preview-workspace"],
|
||||
queryFn: () => client.getAdminPreviewWorkspace(),
|
||||
});
|
||||
const template = useQuery({
|
||||
queryKey: ["template", brand.data?.templateKey],
|
||||
queryFn: () => client.getPublicTemplate(brand.data!.templateKey),
|
||||
@@ -145,6 +149,7 @@ export function BrandPage() {
|
||||
</Form>
|
||||
<PresentationEditor
|
||||
templateContent={workspace.data?.templateContent}
|
||||
previewWorkspace={previewWorkspace.data}
|
||||
config={brand.data.config}
|
||||
brand={brand.data}
|
||||
loading={workspace.isLoading}
|
||||
|
||||
@@ -0,0 +1,102 @@
|
||||
.component-template-preview {
|
||||
position: relative;
|
||||
width: 100%;
|
||||
height: min(76vh, 820px);
|
||||
min-height: 620px;
|
||||
padding: 24px 16px;
|
||||
overflow-x: hidden;
|
||||
overflow-y: auto;
|
||||
border: 1px solid #e8e8e8;
|
||||
background: #f3f4f6;
|
||||
}
|
||||
|
||||
.component-template-preview__canvas {
|
||||
container-type: inline-size;
|
||||
width: min(100%, 390px);
|
||||
min-height: calc(100% - 48px);
|
||||
margin: 0 auto;
|
||||
overflow: visible;
|
||||
border-radius: 14px;
|
||||
background: #fff;
|
||||
box-shadow:
|
||||
0 0 0 1px rgba(0, 0, 0, 0.04),
|
||||
0 10px 30px rgba(0, 0, 0, 0.08);
|
||||
}
|
||||
|
||||
.component-template-preview__canvas,
|
||||
.component-template-preview__canvas * {
|
||||
box-sizing: border-box;
|
||||
}
|
||||
|
||||
.component-template-preview__canvas > * {
|
||||
width: 100%;
|
||||
max-width: 100%;
|
||||
}
|
||||
|
||||
:where(.component-template-preview__canvas) button {
|
||||
display: block;
|
||||
width: -webkit-fill-available;
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
border: 0;
|
||||
border-radius: 0;
|
||||
background: transparent;
|
||||
color: inherit;
|
||||
font: inherit;
|
||||
font-size: 4.8cqw;
|
||||
line-height: 2.55555556;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
:where(.component-template-preview__canvas) input {
|
||||
display: block;
|
||||
width: 100%;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.component-template-preview__canvas img {
|
||||
flex-shrink: 0;
|
||||
display: block;
|
||||
max-width: 100%;
|
||||
object-fit: cover;
|
||||
}
|
||||
|
||||
.component-template-preview [data-editor-target] {
|
||||
position: relative;
|
||||
cursor: pointer;
|
||||
outline: 2px solid transparent;
|
||||
outline-offset: 3px;
|
||||
transition:
|
||||
outline-color 120ms ease,
|
||||
background-color 120ms ease,
|
||||
box-shadow 120ms ease;
|
||||
}
|
||||
|
||||
.component-template-preview [data-editor-target]:hover {
|
||||
outline-color: #91caff;
|
||||
background-color: rgba(22, 119, 255, 0.04);
|
||||
}
|
||||
|
||||
.component-template-preview [data-editor-target].editor-target-selected {
|
||||
z-index: 2;
|
||||
outline: 2px solid #1677ff;
|
||||
outline-offset: 4px;
|
||||
background-color: rgba(22, 119, 255, 0.1);
|
||||
box-shadow: 0 0 0 5px rgba(22, 119, 255, 0.14);
|
||||
}
|
||||
|
||||
.component-template-preview [data-editor-target].editor-target-selected::before {
|
||||
position: absolute;
|
||||
top: -10px;
|
||||
left: -2px;
|
||||
z-index: 3;
|
||||
padding: 2px 7px;
|
||||
border-radius: 4px;
|
||||
background: #1677ff;
|
||||
color: #fff;
|
||||
content: attr(data-editor-target);
|
||||
font-size: 11px;
|
||||
line-height: 16px;
|
||||
pointer-events: none;
|
||||
white-space: nowrap;
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
import { useEffect, useRef } from "react";
|
||||
import type { RuntimeWorkspace } from "@personal-brand/api-client";
|
||||
import { resolveTemplateRenderer } from "./component-renderers.jsx";
|
||||
import "../../../../../packages/template-acheng-campus-food/taro/style.css";
|
||||
import "../../../../../packages/template-linjing-editorial/taro/style.css";
|
||||
import "./ComponentTemplatePreview.css";
|
||||
|
||||
type PreviewProps = {
|
||||
workspace: RuntimeWorkspace;
|
||||
page: string;
|
||||
offeringId?: string;
|
||||
targetKey?: string;
|
||||
onTargetSelected: (targetKey: string) => void;
|
||||
};
|
||||
|
||||
export function ComponentTemplatePreview({
|
||||
workspace,
|
||||
page,
|
||||
offeringId,
|
||||
targetKey,
|
||||
onTargetSelected,
|
||||
}: PreviewProps) {
|
||||
const Renderer = resolveTemplateRenderer(workspace);
|
||||
const root = useRef<HTMLDivElement>(null);
|
||||
useEffect(() => {
|
||||
root.current?.querySelectorAll<HTMLElement>("[data-editor-target]").forEach((element) => {
|
||||
element.classList.toggle(
|
||||
"editor-target-selected",
|
||||
element.dataset.editorTarget === targetKey,
|
||||
);
|
||||
});
|
||||
const selected = targetKey
|
||||
? root.current?.querySelector<HTMLElement>(`[data-editor-target="${CSS.escape(targetKey)}"]`)
|
||||
: null;
|
||||
selected?.scrollIntoView({ block: "nearest", behavior: "smooth" });
|
||||
}, [targetKey, workspace, page]);
|
||||
return (
|
||||
<div
|
||||
ref={root}
|
||||
className="component-template-preview"
|
||||
data-active-target={targetKey || undefined}
|
||||
onClickCapture={(event) => {
|
||||
const element =
|
||||
event.target instanceof Element
|
||||
? event.target.closest<HTMLElement>("[data-editor-target]")
|
||||
: null;
|
||||
const key = element?.dataset.editorTarget;
|
||||
if (!key) return;
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
onTargetSelected(key);
|
||||
}}
|
||||
>
|
||||
<div className="component-template-preview__canvas">
|
||||
<Renderer workspace={workspace} page={page} {...(offeringId ? { offeringId } : {})} />
|
||||
</div>
|
||||
{targetKey ? (
|
||||
<div className="component-template-preview__selection" data-selected-target={targetKey} />
|
||||
) : null}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
// @ts-nocheck
|
||||
@@ -19,14 +19,21 @@ import {
|
||||
import { useMutation, useQueryClient } from "@tanstack/react-query";
|
||||
import { useCallback, useEffect, useMemo, useState } from "react";
|
||||
import { useNavigate } from "react-router-dom";
|
||||
import type { AdminTemplateContent, TemplateAdminField } from "@personal-brand/api-client";
|
||||
import type {
|
||||
AdminTemplateContent,
|
||||
RuntimeWorkspace,
|
||||
TemplateAdminField,
|
||||
} from "@personal-brand/api-client";
|
||||
import type { BrandProfile } from "@personal-brand/api-client";
|
||||
import { projectBrandAliases } from "@personal-brand/api-client";
|
||||
import { createApiClient } from "../../lib/api.js";
|
||||
import { ImageUrlField } from "../../components/ImageUrlField.js";
|
||||
import { TemplateListField } from "../../components/TemplateListField.js";
|
||||
import { MutationError } from "../../components/QueryState.js";
|
||||
import { TemplatePreview } from "./TemplatePreview.js";
|
||||
import {
|
||||
applyBrandPreviewValues,
|
||||
applyStandardBrandValues,
|
||||
applyPresentationValues,
|
||||
filterSectionsForPreviewTarget,
|
||||
presentationFieldName,
|
||||
@@ -36,6 +43,7 @@ import {
|
||||
|
||||
interface PresentationEditorProps {
|
||||
templateContent: AdminTemplateContent | null | undefined;
|
||||
previewWorkspace?: RuntimeWorkspace | undefined;
|
||||
config: Record<string, unknown> | null | undefined;
|
||||
brand: BrandProfile;
|
||||
loading?: boolean;
|
||||
@@ -83,6 +91,7 @@ function renderField(field: TemplateAdminField) {
|
||||
|
||||
export function PresentationEditor({
|
||||
templateContent,
|
||||
previewWorkspace,
|
||||
config,
|
||||
brand,
|
||||
loading,
|
||||
@@ -94,6 +103,8 @@ export function PresentationEditor({
|
||||
const breakpoints = Grid.useBreakpoint();
|
||||
const [activePage, setActivePage] = useState<string>();
|
||||
const [activeTarget, setActiveTarget] = useState<string>();
|
||||
const [previewConfig, setPreviewConfig] = useState(config ?? {});
|
||||
const [previewBrandValues, setPreviewBrandValues] = useState<Record<string, unknown>>({});
|
||||
const sections = useMemo(() => {
|
||||
const declaredTemplateFields = (templateContent?.templateFields ?? []).map((field) => ({
|
||||
...field,
|
||||
@@ -113,22 +124,20 @@ export function PresentationEditor({
|
||||
]
|
||||
: []),
|
||||
...(templateContent?.admin.sections ?? []),
|
||||
]
|
||||
.map((section) => ({
|
||||
...section,
|
||||
fields: section.fields.filter(
|
||||
(field) =>
|
||||
field.binding.startsWith("brand.config.") ||
|
||||
[
|
||||
"brand.avatarUrl",
|
||||
"brand.description",
|
||||
"brand.contactPhone",
|
||||
"brand.contactWechat",
|
||||
"brand.address",
|
||||
].includes(field.binding),
|
||||
),
|
||||
}))
|
||||
.filter((section) => section.fields.length > 0);
|
||||
].map((section) => ({
|
||||
...section,
|
||||
fields: section.fields.filter(
|
||||
(field) =>
|
||||
field.binding.startsWith("brand.config.") ||
|
||||
[
|
||||
"brand.avatarUrl",
|
||||
"brand.description",
|
||||
"brand.contactPhone",
|
||||
"brand.contactWechat",
|
||||
"brand.address",
|
||||
].includes(field.binding),
|
||||
),
|
||||
}));
|
||||
}, [templateContent]);
|
||||
const pageOptions = useMemo(() => {
|
||||
const pages = new Map<string, string>();
|
||||
@@ -144,11 +153,23 @@ export function PresentationEditor({
|
||||
? activePage
|
||||
: pageOptions[0]?.value;
|
||||
const visibleSections = sections.filter((section) => section.page === selectedPage);
|
||||
const visibleTargets = visibleSections.flatMap((section) =>
|
||||
(section.previewTargets ?? []).map((target) => ({ ...target, page: section.page })),
|
||||
);
|
||||
const visibleTargets = (templateContent?.admin.sections ?? [])
|
||||
.filter((section) => section.page === selectedPage)
|
||||
.flatMap((section) =>
|
||||
(section.previewTargets ?? []).map((target) => ({
|
||||
...target,
|
||||
page: section.page,
|
||||
source: section.target,
|
||||
})),
|
||||
);
|
||||
const selectedTarget = visibleTargets.find((target) => target.key === activeTarget);
|
||||
const editableSections = filterSectionsForPreviewTarget(visibleSections, selectedTarget?.key);
|
||||
const selectedSection = (templateContent?.admin.sections ?? []).find((section) =>
|
||||
section.previewTargets?.some((target) => target.key === selectedTarget?.key),
|
||||
);
|
||||
const editableSections = filterSectionsForPreviewTarget(
|
||||
visibleSections.filter((section) => section.target === "brand"),
|
||||
selectedTarget?.key,
|
||||
);
|
||||
const handleTargetSelected = useCallback((key: string) => setActiveTarget(key), []);
|
||||
const relatedTargets = [
|
||||
...(templateContent?.admin.sections ?? [])
|
||||
@@ -180,6 +201,12 @@ export function PresentationEditor({
|
||||
},
|
||||
],
|
||||
);
|
||||
const relevantPageLinks = selectedSection
|
||||
? pageLinks.filter((item) => {
|
||||
if (item.target.startsWith("trust:")) return selectedSection.target === "trust";
|
||||
return item.target === selectedSection.target;
|
||||
})
|
||||
: pageLinks;
|
||||
const initialValues = useMemo(() => {
|
||||
const values: PresentationValues = {};
|
||||
for (const section of sections) {
|
||||
@@ -188,6 +215,7 @@ export function PresentationEditor({
|
||||
config,
|
||||
field.binding,
|
||||
field,
|
||||
brand as unknown as Record<string, unknown>,
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -197,7 +225,10 @@ export function PresentationEditor({
|
||||
const save = useMutation({
|
||||
mutationFn: (values: PresentationValues) => {
|
||||
const nextConfig = applyPresentationValues(config, sections, values);
|
||||
return createApiClient().updateAdminBrand({ config: nextConfig });
|
||||
return createApiClient().updateAdminBrand({
|
||||
config: nextConfig,
|
||||
...applyStandardBrandValues(brand as unknown as Record<string, unknown>, sections, values),
|
||||
});
|
||||
},
|
||||
onSuccess: () => {
|
||||
message.success("页面内容已保存为草稿,发布后小程序才会更新");
|
||||
@@ -218,6 +249,27 @@ export function PresentationEditor({
|
||||
setActivePage(pageOptions[0]?.value);
|
||||
}, [activePage, pageOptions]);
|
||||
useEffect(() => setActiveTarget(undefined), [selectedPage]);
|
||||
useEffect(() => {
|
||||
setPreviewConfig(config ?? {});
|
||||
setPreviewBrandValues({});
|
||||
}, [config]);
|
||||
const previewBrand = useMemo(
|
||||
() => ({ ...brand, ...previewBrandValues, config: previewConfig }),
|
||||
[brand, previewBrandValues, previewConfig],
|
||||
);
|
||||
const handleValuesChange = useCallback(
|
||||
(_changed: PresentationValues, allValues: PresentationValues) => {
|
||||
const next = applyBrandPreviewValues(
|
||||
brand as unknown as Record<string, unknown>,
|
||||
config,
|
||||
sections,
|
||||
allValues,
|
||||
);
|
||||
setPreviewConfig((next.config as Record<string, unknown>) ?? {});
|
||||
setPreviewBrandValues(next);
|
||||
},
|
||||
[brand, config, sections],
|
||||
);
|
||||
|
||||
return (
|
||||
<Card
|
||||
@@ -259,9 +311,25 @@ export function PresentationEditor({
|
||||
<Col xs={24} xl={12}>
|
||||
<Typography.Title level={5}>页面预览</Typography.Title>
|
||||
<TemplatePreview
|
||||
brand={brand}
|
||||
brand={previewBrand}
|
||||
{...(previewWorkspace
|
||||
? {
|
||||
workspace: {
|
||||
...previewWorkspace,
|
||||
brand: {
|
||||
...projectBrandAliases(
|
||||
{
|
||||
...previewWorkspace.brand,
|
||||
...(previewBrand as unknown as Record<string, unknown>),
|
||||
config: previewConfig,
|
||||
},
|
||||
previewConfig,
|
||||
),
|
||||
},
|
||||
},
|
||||
}
|
||||
: {})}
|
||||
page={selectedPage ?? "home"}
|
||||
route={`/pages/${encodeURIComponent(selectedPage ?? "home")}/index`}
|
||||
{...(activeTarget ? { targetKey: activeTarget } : {})}
|
||||
onTargetSelected={handleTargetSelected}
|
||||
/>
|
||||
@@ -287,6 +355,7 @@ export function PresentationEditor({
|
||||
form={form}
|
||||
layout="vertical"
|
||||
initialValues={initialValues}
|
||||
onValuesChange={handleValuesChange}
|
||||
onFinish={(values) => save.mutate(values)}
|
||||
style={{ minHeight: 540, display: "flex", flexDirection: "column" }}
|
||||
>
|
||||
@@ -333,7 +402,7 @@ export function PresentationEditor({
|
||||
</Row>
|
||||
</section>
|
||||
))}
|
||||
{pageLinks.length ? (
|
||||
{relevantPageLinks.length ? (
|
||||
<Alert
|
||||
type="info"
|
||||
showIcon
|
||||
@@ -341,7 +410,7 @@ export function PresentationEditor({
|
||||
message="这个页面还有关联内容"
|
||||
description={
|
||||
<Space wrap>
|
||||
{pageLinks.map((item) => (
|
||||
{relevantPageLinks.map((item) => (
|
||||
<Button
|
||||
key={item.target}
|
||||
type="link"
|
||||
@@ -367,11 +436,19 @@ export function PresentationEditor({
|
||||
}
|
||||
/>
|
||||
) : null}
|
||||
{!editableSections.length && !pageLinks.length ? (
|
||||
{!editableSections.some((section) => section.fields.length) &&
|
||||
!relevantPageLinks.length ? (
|
||||
<Typography.Paragraph type="secondary">
|
||||
这个页面没有单独的品牌文案配置。
|
||||
</Typography.Paragraph>
|
||||
) : null}
|
||||
{selectedTarget &&
|
||||
!editableSections.some((section) => section.fields.length) &&
|
||||
relevantPageLinks.length ? (
|
||||
<Typography.Paragraph type="secondary">
|
||||
此区域内容由对应的业务管理页面维护。
|
||||
</Typography.Paragraph>
|
||||
) : null}
|
||||
</div>
|
||||
<Space direction="vertical" style={{ width: "100%", marginTop: 24 }}>
|
||||
<MutationError error={save.error} />
|
||||
|
||||
@@ -4,42 +4,42 @@ import type {
|
||||
BrandProfile,
|
||||
EditorPreviewFrameMessage,
|
||||
EditorPreviewHostMessage,
|
||||
RuntimeWorkspace,
|
||||
} from "@personal-brand/api-client";
|
||||
import { templatePreviewUrl } from "../../lib/template-preview.js";
|
||||
import { ComponentTemplatePreview } from "./ComponentTemplatePreview.js";
|
||||
import "./TemplatePreview.css";
|
||||
|
||||
export function TemplatePreview({
|
||||
brand,
|
||||
workspace,
|
||||
page,
|
||||
targetKey,
|
||||
route,
|
||||
onTargetSelected,
|
||||
}: {
|
||||
brand: BrandProfile;
|
||||
workspace?: RuntimeWorkspace;
|
||||
page: string;
|
||||
targetKey?: string;
|
||||
route: string;
|
||||
onTargetSelected: (key: string) => void;
|
||||
}) {
|
||||
const frame = useRef<HTMLIFrameElement>(null);
|
||||
const [ready, setReady] = useState(false);
|
||||
const [error, setError] = useState("");
|
||||
const [reloadKey, setReloadKey] = useState(0);
|
||||
const config = brand.config ?? {};
|
||||
const templateKey =
|
||||
typeof config.visualTemplateKey === "string" ? config.visualTemplateKey : brand.templateKey;
|
||||
const url = useMemo(
|
||||
() =>
|
||||
templatePreviewUrl(
|
||||
templateKey,
|
||||
brand.slug,
|
||||
page,
|
||||
import.meta.env.VITE_TEMPLATE_PREVIEW_URLS,
|
||||
window.location.origin,
|
||||
route,
|
||||
),
|
||||
[brand.slug, page, reloadKey, route, templateKey],
|
||||
);
|
||||
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(
|
||||
() => ({
|
||||
@@ -80,12 +80,21 @@ export function TemplatePreview({
|
||||
if (!ready || !frame.current?.contentWindow || !origin) return;
|
||||
const send = (message: EditorPreviewHostMessage) =>
|
||||
frame.current?.contentWindow?.postMessage(message, origin);
|
||||
send({
|
||||
protocol: "personal-brand-editor-preview",
|
||||
version: 1,
|
||||
type: "brandDraft",
|
||||
brand: brandDraft,
|
||||
});
|
||||
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",
|
||||
@@ -93,7 +102,7 @@ export function TemplatePreview({
|
||||
type: "focusTarget",
|
||||
targetKey,
|
||||
});
|
||||
}, [brandDraft, origin, ready, targetKey]);
|
||||
}, [brandDraft, origin, ready, targetKey, workspace]);
|
||||
|
||||
useEffect(() => {
|
||||
const refresh = () => setReloadKey((value) => value + 1);
|
||||
@@ -106,30 +115,42 @@ export function TemplatePreview({
|
||||
<Alert
|
||||
type="warning"
|
||||
showIcon
|
||||
message="尚未配置模板预览服务"
|
||||
description="请在 Admin 环境变量 VITE_TEMPLATE_PREVIEW_URLS 中为模板配置 H5 预览地址。"
|
||||
message="页面预览暂不可用"
|
||||
description="请确认模板预览资源已构建并发布,或本地预览服务正在运行。"
|
||||
/>
|
||||
);
|
||||
|
||||
return (
|
||||
<div className="template-preview">
|
||||
{!ready && !error ? (
|
||||
<div className="template-preview__loading">
|
||||
<Spin tip="正在加载页面预览" />
|
||||
</div>
|
||||
{workspace ? (
|
||||
<ComponentTemplatePreview
|
||||
workspace={workspace}
|
||||
page={page}
|
||||
{...(targetKey ? { targetKey } : {})}
|
||||
onTargetSelected={onTargetSelected}
|
||||
/>
|
||||
) : null}
|
||||
{error ? (
|
||||
<Alert type="error" showIcon message="页面预览加载失败" description={error} />
|
||||
{!workspace ? (
|
||||
<>
|
||||
{!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}
|
||||
<iframe
|
||||
key={url}
|
||||
ref={frame}
|
||||
title="小程序页面预览"
|
||||
src={url}
|
||||
referrerPolicy="origin"
|
||||
onError={() => setError("请检查预览服务地址和网络连接。")}
|
||||
style={{ opacity: ready ? 1 : 0 }}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
import type { ComponentType } from "react";
|
||||
import type { RuntimeWorkspace } from "@personal-brand/api-client";
|
||||
|
||||
declare module "./component-renderers.jsx" {
|
||||
export function resolveTemplateRenderer(workspace: RuntimeWorkspace): ComponentType<{
|
||||
workspace: RuntimeWorkspace;
|
||||
page: string;
|
||||
offeringId?: string;
|
||||
}>;
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
import { TemplatePage as FoodTemplatePage } from "../../../../../packages/template-acheng-campus-food/taro/index.tsx";
|
||||
import { TemplatePage as EditorialTemplatePage } from "../../../../../packages/template-linjing-editorial/taro/index.tsx";
|
||||
import React from "react";
|
||||
import { TemplateAssetContext } from "./taro-web-components.jsx";
|
||||
|
||||
function FoodPreview(props) {
|
||||
return (
|
||||
<TemplateAssetContext.Provider value="acheng-campus-food">
|
||||
<FoodTemplatePage {...props} />
|
||||
</TemplateAssetContext.Provider>
|
||||
);
|
||||
}
|
||||
function EditorialPreview(props) {
|
||||
return (
|
||||
<TemplateAssetContext.Provider value="linjing-editorial">
|
||||
<EditorialTemplatePage {...props} />
|
||||
</TemplateAssetContext.Provider>
|
||||
);
|
||||
}
|
||||
|
||||
export function resolveTemplateRenderer(workspace) {
|
||||
const config = workspace?.brand?.config;
|
||||
const key =
|
||||
config && typeof config === "object" && !Array.isArray(config)
|
||||
? config.visualTemplateKey
|
||||
: undefined;
|
||||
return key === "linjing-editorial" ? EditorialPreview : FoodPreview;
|
||||
}
|
||||
@@ -31,11 +31,14 @@ function asObject(value: unknown): Record<string, unknown> {
|
||||
}
|
||||
|
||||
function safePath(binding: string): string[] | null {
|
||||
const prefix = ["brand.config.", "offering.config.", "trust.config."].find((candidate) =>
|
||||
binding.startsWith(candidate),
|
||||
);
|
||||
if (!prefix) return null;
|
||||
const path = binding.slice(prefix.length).split(".");
|
||||
const prefixes = ["brand.config.", "offering.config.", "trust.config."];
|
||||
const prefix = prefixes.find((candidate) => binding.startsWith(candidate));
|
||||
const standardBrandField =
|
||||
/^brand\.(avatarUrl|description|contactPhone|contactWechat|address|hours|deliveryNote)$/.test(
|
||||
binding,
|
||||
);
|
||||
if (!prefix && !standardBrandField) return null;
|
||||
const path = prefix ? binding.slice(prefix.length).split(".") : [binding.slice("brand.".length)];
|
||||
if (path.some((part) => !part || ["__proto__", "prototype", "constructor"].includes(part)))
|
||||
return null;
|
||||
return path;
|
||||
@@ -49,10 +52,15 @@ export function readPresentationValue(
|
||||
config: Record<string, unknown> | null | undefined,
|
||||
binding: string,
|
||||
field?: PresentationField,
|
||||
brand?: Record<string, unknown>,
|
||||
): unknown {
|
||||
const path = safePath(binding);
|
||||
if (!path) return undefined;
|
||||
let value: unknown = asObject(config);
|
||||
const isConfigBinding =
|
||||
binding.startsWith("brand.config.") ||
|
||||
binding.startsWith("offering.config.") ||
|
||||
binding.startsWith("trust.config.");
|
||||
let value: unknown = isConfigBinding ? asObject(config) : asObject(brand);
|
||||
for (const part of path) value = asObject(value)[part];
|
||||
if (field?.input === "list") {
|
||||
if (!Array.isArray(value)) return [];
|
||||
@@ -104,3 +112,33 @@ export function applyPresentationValues(
|
||||
}
|
||||
return nextConfig;
|
||||
}
|
||||
|
||||
export function applyStandardBrandValues(
|
||||
brand: Record<string, unknown>,
|
||||
sections: PresentationSection[],
|
||||
values: PresentationValues,
|
||||
): Record<string, unknown> {
|
||||
const next = { ...brand };
|
||||
for (const section of sections) {
|
||||
for (const field of section.fields) {
|
||||
if (!field.binding.startsWith("brand.") || field.binding.startsWith("brand.config."))
|
||||
continue;
|
||||
const value = values[presentationFieldName(section.key, field.key)];
|
||||
if (value !== undefined) next[field.binding.slice("brand.".length)] = value;
|
||||
}
|
||||
}
|
||||
return next;
|
||||
}
|
||||
|
||||
export function applyBrandPreviewValues(
|
||||
brand: Record<string, unknown>,
|
||||
config: Record<string, unknown> | null | undefined,
|
||||
sections: PresentationSection[],
|
||||
values: PresentationValues,
|
||||
): Record<string, unknown> {
|
||||
const nextBrand = applyStandardBrandValues(brand, sections, values);
|
||||
return {
|
||||
...nextBrand,
|
||||
config: applyPresentationValues(config, sections, values),
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
import React from "react";
|
||||
|
||||
export const TemplateAssetContext = React.createContext("");
|
||||
const templateAssets = import.meta.glob("../../../../../packages/template-*/miniapp/assets/**/*", {
|
||||
eager: true,
|
||||
query: "?url",
|
||||
import: "default",
|
||||
});
|
||||
|
||||
function resolveImageSource(src, templateKey) {
|
||||
if (typeof src !== "string" || !src.startsWith("/assets/")) return src;
|
||||
const relative = src.slice("/assets/".length);
|
||||
for (const [file, url] of Object.entries(templateAssets)) {
|
||||
const parts = file.split("/packages/template-")[1]?.split("/miniapp/assets/");
|
||||
if (!parts) continue;
|
||||
const [key, asset] = parts;
|
||||
if (relative === key + "/" + asset || (key === templateKey && relative === asset)) return url;
|
||||
}
|
||||
return src;
|
||||
}
|
||||
|
||||
const element = (tag) =>
|
||||
React.forwardRef(({ children, className, style, onClick, ...props }, ref) =>
|
||||
React.createElement(tag, { ...props, ref, className, style, onClick }, children),
|
||||
);
|
||||
|
||||
export const View = element("div");
|
||||
export const Text = element("span");
|
||||
export const Button = element("button");
|
||||
export const Input = React.forwardRef((props, ref) =>
|
||||
React.createElement("input", { ...props, ref }),
|
||||
);
|
||||
export const Image = React.forwardRef(({ mode, src, style, ...props }, ref) => {
|
||||
const key = React.useContext(TemplateAssetContext);
|
||||
return React.createElement("img", {
|
||||
...props,
|
||||
ref,
|
||||
src: resolveImageSource(src, key),
|
||||
style: { objectFit: mode === "aspectFit" ? "contain" : "cover", ...style },
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,11 @@
|
||||
const noop = () => Promise.resolve();
|
||||
const Taro = {
|
||||
setStorageSync() {},
|
||||
getStorageSync() {
|
||||
return undefined;
|
||||
},
|
||||
removeStorageSync() {},
|
||||
switchTab: noop,
|
||||
navigateTo: noop,
|
||||
};
|
||||
export default Taro;
|
||||
@@ -1,25 +1,13 @@
|
||||
export function templatePreviewUrl(
|
||||
templateKey: string,
|
||||
brandSlug: string | undefined,
|
||||
page: string,
|
||||
configured: string | undefined,
|
||||
parentOrigin?: string,
|
||||
route?: string,
|
||||
): string | undefined {
|
||||
let urls: Record<string, unknown>;
|
||||
const raw = configured || "http://localhost:3002";
|
||||
try {
|
||||
const parsed: unknown = configured ? JSON.parse(configured) : {};
|
||||
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
|
||||
return undefined;
|
||||
}
|
||||
urls = parsed as Record<string, unknown>;
|
||||
} catch {
|
||||
return undefined;
|
||||
}
|
||||
const raw = urls[templateKey];
|
||||
if (typeof raw !== "string" || !raw) return undefined;
|
||||
try {
|
||||
const url = new URL(raw);
|
||||
const url = new URL(raw, parentOrigin);
|
||||
url.searchParams.set("editor", "1");
|
||||
if (parentOrigin) url.searchParams.set("parentOrigin", parentOrigin);
|
||||
if (brandSlug) url.searchParams.set("brand", brandSlug);
|
||||
|
||||
Vendored
+3
-1
@@ -1,7 +1,9 @@
|
||||
interface ImportMetaEnv {
|
||||
readonly DEV: boolean;
|
||||
readonly PROD: boolean;
|
||||
readonly VITE_API_BASE_URL?: string;
|
||||
readonly VITE_APP_BASE_PATH?: string;
|
||||
readonly VITE_TEMPLATE_PREVIEW_URLS?: string;
|
||||
readonly VITE_TEMPLATE_PREVIEW_URL?: string;
|
||||
}
|
||||
|
||||
interface ImportMeta {
|
||||
|
||||
@@ -0,0 +1,31 @@
|
||||
// 模板 CSS 使用 Taro 的 750 设计宽度,转换到预览容器单位。
|
||||
export function templatePreviewCss() {
|
||||
return {
|
||||
postcssPlugin: "template-preview-css",
|
||||
Once(root) {
|
||||
const file = root.source?.input.file || "";
|
||||
if (!file.includes("/packages/template-") || !file.endsWith("/taro/style.css")) return;
|
||||
root.walkRules((rule) => {
|
||||
rule.selector = rule.selector
|
||||
.split(",")
|
||||
.map(
|
||||
(selector) =>
|
||||
".component-template-preview__canvas " +
|
||||
selector
|
||||
.trim()
|
||||
.replace(
|
||||
/(^|[ >+~])(image|text|view)(?=[ .#:[>+~)]|$)/g,
|
||||
(_, prefix, tag) => prefix + { image: "img", text: "span", view: "div" }[tag],
|
||||
),
|
||||
)
|
||||
.join(", ");
|
||||
});
|
||||
root.walkDecls((declaration) => {
|
||||
declaration.value = declaration.value.replace(
|
||||
/(-?(?:[0-9]*[.])?[0-9]+)px/g,
|
||||
(_, value) => Number((Number(value) / 7.5).toFixed(8)) + "cqw",
|
||||
);
|
||||
});
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
import assert from "node:assert/strict";
|
||||
import {
|
||||
applyPresentationValues,
|
||||
applyBrandPreviewValues,
|
||||
filterSectionsForPreviewTarget,
|
||||
presentationFieldName,
|
||||
readPresentationValue,
|
||||
@@ -124,3 +125,26 @@ const offering = applyPresentationValues(
|
||||
{ [presentationFieldName("offering", "background")]: "新背景" },
|
||||
);
|
||||
assert.deepEqual(offering.details, { background: "新背景", preserve: "保留" });
|
||||
|
||||
const brandDraft = applyBrandPreviewValues(
|
||||
{ description: "旧简介", address: "旧地址", config: { visualPresentation: {} } },
|
||||
{ visualPresentation: {} },
|
||||
[
|
||||
{
|
||||
key: "identity",
|
||||
fields: [
|
||||
{ key: "description", binding: "brand.description" },
|
||||
{ key: "address", binding: "brand.address" },
|
||||
{ key: "headline", binding: "brand.config.visualPresentation.home.title" },
|
||||
],
|
||||
},
|
||||
],
|
||||
{
|
||||
[presentationFieldName("identity", "description")]: "新简介",
|
||||
[presentationFieldName("identity", "address")]: "新地址",
|
||||
[presentationFieldName("identity", "headline")]: "新标题",
|
||||
},
|
||||
);
|
||||
assert.equal(brandDraft.description, "新简介");
|
||||
assert.equal(brandDraft.address, "新地址");
|
||||
assert.equal(brandDraft.config.visualPresentation.home.title, "新标题");
|
||||
@@ -2,12 +2,11 @@ import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
import { templatePreviewUrl } from "../src/lib/template-preview.ts";
|
||||
|
||||
test("template preview URL is resolved from generic deployment configuration", () => {
|
||||
test("template preview URL is resolved from one shared deployment address", () => {
|
||||
const url = templatePreviewUrl(
|
||||
"new-template",
|
||||
"brand-a",
|
||||
"profile",
|
||||
JSON.stringify({ "new-template": "https://preview.example.test/app/" }),
|
||||
"https://preview.example.test/app/",
|
||||
"https://admin.example.test",
|
||||
"/pages/profile/index",
|
||||
);
|
||||
@@ -17,11 +16,18 @@ test("template preview URL is resolved from generic deployment configuration", (
|
||||
);
|
||||
});
|
||||
|
||||
test("missing, malformed or invalid template preview configuration fails closed", () => {
|
||||
assert.equal(templatePreviewUrl("missing", "brand-a", "home", undefined), undefined);
|
||||
assert.equal(templatePreviewUrl("missing", "brand-a", "home", "{"), undefined);
|
||||
test("the shared same-origin preview address is the default", () => {
|
||||
assert.equal(
|
||||
templatePreviewUrl("broken", "brand-a", "home", JSON.stringify({ broken: "not a URL" })),
|
||||
undefined,
|
||||
templatePreviewUrl("brand-a", "home", undefined),
|
||||
"http://localhost:3002/?editor=1&brand=brand-a#/pages/home/index",
|
||||
);
|
||||
assert.equal(templatePreviewUrl("brand-a", "home", "{"), undefined);
|
||||
assert.equal(templatePreviewUrl("brand-a", "home", "not a URL"), undefined);
|
||||
});
|
||||
|
||||
test("same-origin static preview uses its explicit entry document", () => {
|
||||
assert.equal(
|
||||
templatePreviewUrl("brand-a", "home", "/template-preview/index.html", "http://localhost:3005"),
|
||||
"http://localhost:3005/template-preview/index.html?editor=1&parentOrigin=http%3A%2F%2Flocalhost%3A3005&brand=brand-a#/pages/home/index",
|
||||
);
|
||||
});
|
||||
@@ -1,9 +1,22 @@
|
||||
import { defineConfig } from "vite";
|
||||
import react from "@vitejs/plugin-react";
|
||||
import { templatePreviewCss } from "./template-preview-css.mjs";
|
||||
|
||||
export default defineConfig({
|
||||
plugins: [react()],
|
||||
css: { postcss: { plugins: [templatePreviewCss()] } },
|
||||
base: process.env.VITE_APP_BASE_PATH ?? "/",
|
||||
resolve: {
|
||||
alias: {
|
||||
"@tarojs/components": `${process.cwd()}/src/features/brand/taro-web-components.jsx`,
|
||||
"@tarojs/taro": `${process.cwd()}/src/features/brand/taro-web-runtime.jsx`,
|
||||
},
|
||||
},
|
||||
define: {
|
||||
"process.env.TARO_PLATFORM": JSON.stringify("web"),
|
||||
PREVIEW_ALL_TEMPLATES: JSON.stringify(true),
|
||||
TEMPLATE_MANIFEST: JSON.stringify({ navigation: [] }),
|
||||
},
|
||||
server: {
|
||||
host: "0.0.0.0",
|
||||
port: Number(process.env.ADMIN_PORT ?? 3000),
|
||||
|
||||
@@ -36,12 +36,14 @@ import {
|
||||
} from "@personal-brand/config";
|
||||
import { TemplateWorkspaceService } from "./template-workspace.service.js";
|
||||
import { validateFieldSnapshot, validateOfferingConfig } from "@personal-brand/validation";
|
||||
import { PublicWorkspaceService } from "./modules/public/public-workspace.controller.js";
|
||||
|
||||
@Controller("admin/workspace")
|
||||
class AdminWorkspaceController {
|
||||
constructor(
|
||||
private readonly prisma: PrismaService,
|
||||
private readonly templateWorkspace: TemplateWorkspaceService,
|
||||
private readonly publicWorkspace: PublicWorkspaceService,
|
||||
) {}
|
||||
private brandId(): string {
|
||||
return process.env.DEFAULT_BRAND_ID ?? "00000000-0000-0000-0000-000000000001";
|
||||
@@ -194,6 +196,11 @@ class AdminWorkspaceController {
|
||||
: null,
|
||||
};
|
||||
}
|
||||
@Get("preview")
|
||||
async getPreviewWorkspace(@Req() request: FastifyRequest): Promise<unknown> {
|
||||
const { brandId } = this.requireAdmin(request);
|
||||
return this.publicWorkspace.getForBrandId(brandId);
|
||||
}
|
||||
private jsonObject(value: unknown): Record<string, unknown> {
|
||||
return value && typeof value === "object" && !Array.isArray(value)
|
||||
? (value as Record<string, unknown>)
|
||||
|
||||
@@ -7,7 +7,10 @@ import { BookingService } from "./booking.service.js";
|
||||
import { AdminAuthService } from "./admin-auth.service.js";
|
||||
import { ApiExceptionFilter, RequestIdMiddleware } from "./http.js";
|
||||
import { AdminWorkspaceController } from "./admin-workspace.controller.js";
|
||||
import { PublicWorkspaceController } from "./modules/public/public-workspace.controller.js";
|
||||
import {
|
||||
PublicWorkspaceController,
|
||||
PublicWorkspaceService,
|
||||
} from "./modules/public/public-workspace.controller.js";
|
||||
import { PublicBrandContextService } from "./modules/public/public-brand-context.service.js";
|
||||
import { AdminConfigController } from "./modules/admin/admin-config.controller.js";
|
||||
import { PublicOfferingController } from "./modules/public/public-offering.controller.js";
|
||||
@@ -70,6 +73,7 @@ export class HealthController {
|
||||
BrandReleaseService,
|
||||
BrandReleaseApiService,
|
||||
PublicBrandContextService,
|
||||
PublicWorkspaceService,
|
||||
],
|
||||
exports: [PrismaService, WechatAuthService],
|
||||
})
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { Controller, Get, Query } from "@nestjs/common";
|
||||
import { Controller, Get, Injectable, Query } from "@nestjs/common";
|
||||
import { Prisma } from "@prisma/client";
|
||||
import { PrismaService } from "../../prisma.service.js";
|
||||
import { PublicBrandContextService } from "./public-brand-context.service.js";
|
||||
@@ -26,15 +26,11 @@ import {
|
||||
projectTrustPresentation,
|
||||
} from "@personal-brand/types";
|
||||
|
||||
@Controller("public/workspace")
|
||||
export class PublicWorkspaceController {
|
||||
constructor(
|
||||
private readonly prisma: PrismaService,
|
||||
private readonly brandContext: PublicBrandContextService,
|
||||
) {}
|
||||
@Get()
|
||||
async get(@Query("brandSlug") brandSlug?: string): Promise<unknown> {
|
||||
const brandId = await this.brandContext.resolveId(brandSlug);
|
||||
@Injectable()
|
||||
export class PublicWorkspaceService {
|
||||
constructor(private readonly prisma: PrismaService) {}
|
||||
|
||||
async getForBrandId(brandId: string): Promise<unknown> {
|
||||
const release = await this.prisma.brandRelease.findFirst({
|
||||
where: { brandId, status: "published" },
|
||||
orderBy: { version: "desc" },
|
||||
@@ -370,3 +366,17 @@ export class PublicWorkspaceController {
|
||||
return value === "create-booking" || value === "create-quote" ? value : "create-inquiry";
|
||||
}
|
||||
}
|
||||
|
||||
@Controller("public/workspace")
|
||||
export class PublicWorkspaceController {
|
||||
constructor(
|
||||
private readonly brandContext: PublicBrandContextService,
|
||||
private readonly workspaceService: PublicWorkspaceService,
|
||||
) {}
|
||||
|
||||
@Get()
|
||||
async get(@Query("brandSlug") brandSlug?: string): Promise<unknown> {
|
||||
const brandId = await this.brandContext.resolveId(brandSlug);
|
||||
return this.workspaceService.getForBrandId(brandId);
|
||||
}
|
||||
}
|
||||
@@ -1325,6 +1325,28 @@ test("admin can install a template and public workspace exposes enabled configur
|
||||
}
|
||||
});
|
||||
|
||||
test("admin preview workspace is brand-scoped and exposes only the published runtime", async () => {
|
||||
const user = await prisma.adminUser.findUniqueOrThrow({ where: { username: "admin" } });
|
||||
const token = signIdentity({ subject: user.id, brandId, role: "admin" });
|
||||
const unauthorized = await request("/admin/workspace/preview");
|
||||
assert.equal(unauthorized.statusCode, 401);
|
||||
const wrongRole = await request("/admin/workspace/preview", {
|
||||
headers: { authorization: `Bearer ${customerToken}` },
|
||||
});
|
||||
assert.equal(wrongRole.statusCode, 403);
|
||||
const authorized = await request("/admin/workspace/preview", {
|
||||
headers: { authorization: `Bearer ${token}` },
|
||||
});
|
||||
assert.equal(authorized.statusCode, 200);
|
||||
const workspace = JSON.parse(authorized.body);
|
||||
assert.equal(workspace.publication?.status, "published");
|
||||
assert.equal(
|
||||
workspace.brand.slug,
|
||||
(await prisma.brandProfile.findUniqueOrThrow({ where: { id: brandId } })).slug,
|
||||
);
|
||||
assert.equal(workspace.brand.visualTemplateKey, "acheng-campus-food");
|
||||
});
|
||||
|
||||
test("admin can customize workspace fields with brand isolation", async () => {
|
||||
await prisma.brandFieldDefinition.deleteMany({ where: { brandId } });
|
||||
await prisma.brandTemplateInstallation.deleteMany({ where: { brandId } });
|
||||
|
||||
@@ -4,6 +4,7 @@ import fs from "node:fs";
|
||||
|
||||
const root = path.resolve(__dirname, "../../..");
|
||||
const key = process.env.TEMPLATE_KEY || "acheng-campus-food";
|
||||
const previewAllTemplates = process.env.PREVIEW_ALL_TEMPLATES === "true";
|
||||
const templates = fs
|
||||
.readdirSync(path.join(root, "packages"))
|
||||
.filter(
|
||||
@@ -30,20 +31,33 @@ export default defineConfig({
|
||||
designWidth: 750,
|
||||
deviceRatio: { 750: 1 },
|
||||
sourceRoot: "src",
|
||||
outputRoot: `dist/${key}/${process.env.TARO_ENV || "weapp"}`,
|
||||
outputRoot: previewAllTemplates
|
||||
? "dist/template-preview/h5"
|
||||
: `dist/${key}/${process.env.TARO_ENV || "weapp"}`,
|
||||
framework: "react",
|
||||
compiler: { type: "vite" },
|
||||
plugins: [],
|
||||
alias: { "@template": path.join(template, "taro") },
|
||||
alias: {
|
||||
"@template": previewAllTemplates
|
||||
? path.resolve(__dirname, "../src/runtime/template-preview-entry.tsx")
|
||||
: path.join(template, "taro"),
|
||||
},
|
||||
defineConstants: {
|
||||
TEMPLATE_KEY: JSON.stringify(key),
|
||||
BRAND_SLUG: JSON.stringify(brand),
|
||||
API_BASE_URL: JSON.stringify(process.env.API_BASE_URL || "http://localhost:3001"),
|
||||
TEMPLATE_MANIFEST: JSON.stringify(manifest),
|
||||
PREVIEW_ALL_TEMPLATES: JSON.stringify(previewAllTemplates),
|
||||
},
|
||||
copy: {
|
||||
options: {},
|
||||
patterns: [
|
||||
...(previewAllTemplates
|
||||
? templates.map((templateKey) => ({
|
||||
from: path.join(root, "packages", `template-${templateKey}`, "miniapp/assets"),
|
||||
to: `dist/template-preview/h5/assets/${templateKey}`,
|
||||
}))
|
||||
: []),
|
||||
...(process.env.TARO_ENV === "weapp"
|
||||
? [
|
||||
{
|
||||
@@ -52,15 +66,19 @@ export default defineConfig({
|
||||
},
|
||||
]
|
||||
: []),
|
||||
{
|
||||
from: path.join(template, "miniapp/assets"),
|
||||
to: `dist/${key}/${process.env.TARO_ENV || "weapp"}/assets`,
|
||||
},
|
||||
...(!previewAllTemplates
|
||||
? [
|
||||
{
|
||||
from: path.join(template, "miniapp/assets"),
|
||||
to: `dist/${key}/${process.env.TARO_ENV || "weapp"}/assets`,
|
||||
},
|
||||
]
|
||||
: []),
|
||||
],
|
||||
},
|
||||
mini: {},
|
||||
h5: {
|
||||
publicPath: "/",
|
||||
publicPath: process.env.PREVIEW_PUBLIC_PATH || "/",
|
||||
router: { mode: "hash" },
|
||||
devServer: { host: "0.0.0.0", port: Number(process.env.PREVIEW_PORT || 3002) },
|
||||
},
|
||||
|
||||
@@ -3,7 +3,9 @@
|
||||
"private": true,
|
||||
"scripts": {
|
||||
"dev:h5": "taro build --type h5 --watch",
|
||||
"dev:preview": "PREVIEW_ALL_TEMPLATES=true taro build --type h5 --watch",
|
||||
"build:h5": "taro build --type h5",
|
||||
"build:preview": "PREVIEW_ALL_TEMPLATES=true taro build --type h5",
|
||||
"build:weapp": "taro build --type weapp",
|
||||
"typecheck": "tsc --noEmit",
|
||||
"lint": "pnpm --workspace-root exec eslint apps/taro/src apps/taro/config packages/template-acheng-campus-food/taro packages/template-linjing-editorial/taro",
|
||||
|
||||
+15
-11
@@ -21,15 +21,19 @@ export default defineAppConfig({
|
||||
navigationBarBackgroundColor: "#ffffff",
|
||||
navigationBarTextStyle: "black",
|
||||
},
|
||||
tabBar: {
|
||||
color: "#8b8178",
|
||||
selectedColor: "#3b2118",
|
||||
backgroundColor: "#ffffff",
|
||||
list: TEMPLATE_MANIFEST.navigation.map((tab) => ({
|
||||
pagePath: routes[tab.page],
|
||||
text: tab.label,
|
||||
iconPath: tab.iconPath,
|
||||
selectedIconPath: tab.selectedIconPath,
|
||||
})),
|
||||
},
|
||||
...(!PREVIEW_ALL_TEMPLATES
|
||||
? {
|
||||
tabBar: {
|
||||
color: "#8b8178",
|
||||
selectedColor: "#3b2118",
|
||||
backgroundColor: "#ffffff",
|
||||
list: TEMPLATE_MANIFEST.navigation.map((tab) => ({
|
||||
pagePath: routes[tab.page],
|
||||
text: tab.label,
|
||||
iconPath: tab.iconPath,
|
||||
selectedIconPath: tab.selectedIconPath,
|
||||
})),
|
||||
},
|
||||
}
|
||||
: {}),
|
||||
});
|
||||
@@ -9,7 +9,7 @@ import { Inquiry } from "./Inquiry";
|
||||
import { Records } from "./Records";
|
||||
import { Success } from "./Success";
|
||||
export function Page({ page }: { page: PageKey }) {
|
||||
const { workspace, error, loading, reload, setBrandDraft } = useWorkspace();
|
||||
const { workspace, error, loading, reload, setBrandDraft, setWorkspaceDraft } = useWorkspace();
|
||||
const router = useRouter();
|
||||
useEffect(() => {
|
||||
if (process.env.TARO_ENV !== "h5" || window.parent === window) return;
|
||||
@@ -27,6 +27,7 @@ export function Page({ page }: { page: PageKey }) {
|
||||
if (event.source !== window.parent || event.origin !== parentOrigin) return;
|
||||
const message = event.data;
|
||||
if (message?.protocol !== "personal-brand-editor-preview" || message.version !== 1) return;
|
||||
if (message.type === "workspaceDraft") setWorkspaceDraft(message.workspace);
|
||||
if (message.type === "brandDraft") setBrandDraft(message.brand);
|
||||
if (message.type === "focusTarget") {
|
||||
document.querySelectorAll<HTMLElement>("[data-editor-target]").forEach((element) => {
|
||||
@@ -63,7 +64,7 @@ export function Page({ page }: { page: PageKey }) {
|
||||
window.removeEventListener("message", onMessage);
|
||||
document.removeEventListener("click", onClick, true);
|
||||
};
|
||||
}, [setBrandDraft]);
|
||||
}, [setBrandDraft, setWorkspaceDraft]);
|
||||
if (loading) return <View className="runtime-state">正在加载…</View>;
|
||||
if (error || !workspace)
|
||||
return (
|
||||
|
||||
Vendored
+4
@@ -12,7 +12,11 @@ declare const TEMPLATE_MANIFEST: {
|
||||
selectedIconPath: string;
|
||||
}[];
|
||||
};
|
||||
declare const PREVIEW_ALL_TEMPLATES: boolean;
|
||||
declare module "*.css";
|
||||
interface ImportMeta {
|
||||
glob<T = unknown>(pattern: string, options?: { eager?: boolean }): Record<string, T>;
|
||||
}
|
||||
declare module "@template" {
|
||||
export { TemplatePage } from "../../../packages/template-acheng-campus-food/taro";
|
||||
}
|
||||
@@ -7,6 +7,12 @@ export function brandSlug() {
|
||||
}
|
||||
return BRAND_SLUG;
|
||||
}
|
||||
function isEditorPreview() {
|
||||
return (
|
||||
process.env.TARO_ENV === "h5" &&
|
||||
new URLSearchParams(window.location.search).get("editor") === "1"
|
||||
);
|
||||
}
|
||||
export const tokenKey = () => `customerToken:${brandSlug()}`;
|
||||
export function hasSession() {
|
||||
return Boolean(Taro.getStorageSync<string>(tokenKey()));
|
||||
@@ -16,9 +22,10 @@ export async function request<T>(
|
||||
options: { method?: "GET" | "POST"; data?: unknown; customer?: boolean } = {},
|
||||
): Promise<T> {
|
||||
const context = path.startsWith("/public/") || path.startsWith("/customer/session/wechat");
|
||||
const query = context
|
||||
? `${path.includes("?") ? "&" : "?"}brandSlug=${encodeURIComponent(brandSlug())}`
|
||||
: "";
|
||||
const query =
|
||||
context && !(isEditorPreview() && path === "/public/workspace")
|
||||
? `${path.includes("?") ? "&" : "?"}brandSlug=${encodeURIComponent(brandSlug())}`
|
||||
: "";
|
||||
const response = await Taro.request<T & { error?: { message?: string; requestId?: string } }>({
|
||||
url: API_BASE_URL.replace(/\/$/, "") + path + query,
|
||||
method: options.method || "GET",
|
||||
@@ -38,9 +45,7 @@ export async function request<T>(
|
||||
}
|
||||
export async function loadWorkspace() {
|
||||
const data = await request<RuntimeWorkspace>("/public/workspace");
|
||||
const editorPreview =
|
||||
process.env.TARO_ENV === "h5" &&
|
||||
new URLSearchParams(window.location.search).get("editor") === "1";
|
||||
const editorPreview = isEditorPreview();
|
||||
if (!editorPreview && data.publication?.status !== "published") throw new Error("品牌尚未发布");
|
||||
if (!editorPreview && data.brand.visualTemplateKey !== TEMPLATE_KEY)
|
||||
throw new Error("该品牌使用其他模板,请选择匹配的模板预览地址");
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
import type { ComponentType } from "react";
|
||||
import type { TemplateProps } from "./template";
|
||||
|
||||
type TemplateRenderer = ComponentType<TemplateProps>;
|
||||
|
||||
const renderers = import.meta.glob<{
|
||||
TemplatePage: TemplateRenderer;
|
||||
}>("../../../../packages/template-*/taro/index.tsx", { eager: true });
|
||||
|
||||
export function TemplatePage(props: TemplateProps) {
|
||||
const config = props.workspace.brand.config;
|
||||
const visualTemplateKey =
|
||||
config && typeof config === "object" && !Array.isArray(config)
|
||||
? (config as Record<string, unknown>).visualTemplateKey
|
||||
: undefined;
|
||||
const templateKey = typeof visualTemplateKey === "string" ? visualTemplateKey : TEMPLATE_KEY;
|
||||
const suffix = `/template-${templateKey}/taro/index.tsx`;
|
||||
const rendererModule = Object.entries(renderers).find(([path]) => path.endsWith(suffix))?.[1];
|
||||
if (!rendererModule)
|
||||
return <div className="runtime-state">当前模板没有可用的 H5 预览 renderer</div>;
|
||||
const Renderer = rendererModule.TemplatePage;
|
||||
return <Renderer {...props} />;
|
||||
}
|
||||
@@ -8,19 +8,22 @@ const Context = createContext<{
|
||||
error: string;
|
||||
loading: boolean;
|
||||
setBrandDraft: (brand: Partial<RuntimeWorkspace["brand"]>) => void;
|
||||
setWorkspaceDraft: (workspace: RuntimeWorkspace) => void;
|
||||
reload: () => void;
|
||||
}>({ error: "", loading: true, setBrandDraft() {}, reload() {} });
|
||||
}>({ error: "", loading: true, setBrandDraft() {}, setWorkspaceDraft() {}, reload() {} });
|
||||
export function WorkspaceProvider({ children }: PropsWithChildren) {
|
||||
const [baseWorkspace, setBaseWorkspace] = useState<RuntimeWorkspace>();
|
||||
const [brandDraft, setBrandDraft] = useState<Partial<RuntimeWorkspace["brand"]>>({});
|
||||
const workspace = baseWorkspace
|
||||
const [workspaceDraft, setWorkspaceDraft] = useState<RuntimeWorkspace>();
|
||||
const workspace = workspaceDraft ?? baseWorkspace;
|
||||
const resolvedWorkspace = workspace
|
||||
? {
|
||||
...baseWorkspace,
|
||||
...workspace,
|
||||
brand: projectBrandAliases(
|
||||
{ ...baseWorkspace.brand, ...brandDraft },
|
||||
{ ...workspace.brand, ...brandDraft },
|
||||
brandDraft.config && typeof brandDraft.config === "object"
|
||||
? (brandDraft.config as Record<string, unknown>)
|
||||
: ((baseWorkspace.brand.config as Record<string, unknown> | undefined) ?? {}),
|
||||
: ((workspace.brand.config as Record<string, unknown> | undefined) ?? {}),
|
||||
),
|
||||
}
|
||||
: undefined;
|
||||
@@ -29,16 +32,35 @@ export function WorkspaceProvider({ children }: PropsWithChildren) {
|
||||
const reload = useCallback(() => {
|
||||
setLoading(true);
|
||||
setError("");
|
||||
void loadWorkspace()
|
||||
.then(setBaseWorkspace)
|
||||
const editorPreview =
|
||||
process.env.TARO_ENV === "h5" &&
|
||||
new URLSearchParams(window.location.search).get("editor") === "1";
|
||||
const workspacePromise = editorPreview ? Promise.resolve(undefined) : loadWorkspace();
|
||||
void workspacePromise
|
||||
.then((value) => {
|
||||
if (value) setBaseWorkspace(value);
|
||||
})
|
||||
.catch((error: unknown) =>
|
||||
setError(error instanceof Error ? error.message : "加载失败,请重试"),
|
||||
)
|
||||
.finally(() => setLoading(false));
|
||||
.finally(() => setLoading(!editorPreview));
|
||||
}, []);
|
||||
useEffect(reload, [reload]);
|
||||
return (
|
||||
<Context.Provider value={{ workspace, error, loading, setBrandDraft, reload }}>
|
||||
<Context.Provider
|
||||
value={{
|
||||
workspace: resolvedWorkspace,
|
||||
error,
|
||||
loading:
|
||||
process.env.TARO_ENV === "h5" &&
|
||||
new URLSearchParams(window.location.search).get("editor") === "1"
|
||||
? !workspace
|
||||
: loading,
|
||||
setBrandDraft,
|
||||
setWorkspaceDraft,
|
||||
reload,
|
||||
}}
|
||||
>
|
||||
{children}
|
||||
</Context.Provider>
|
||||
);
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { test, expect } from "@playwright/test";
|
||||
|
||||
const adminOrigin = "http://localhost:3011";
|
||||
const adminOrigin = process.env.ADMIN_URL || "http://localhost:3005";
|
||||
const brand = {
|
||||
id: "brand-fixture",
|
||||
slug: "preview-fixture",
|
||||
@@ -8,7 +8,7 @@ const brand = {
|
||||
templateKey: "food",
|
||||
tagline: "校园家常餐",
|
||||
description: "认真做好每一餐",
|
||||
avatarUrl: "",
|
||||
avatarUrl: "/assets/owner/portrait.jpg",
|
||||
coverUrl: "",
|
||||
hours: "每日 17:00",
|
||||
address: "东门附近",
|
||||
@@ -35,7 +35,16 @@ const runtimeWorkspace = {
|
||||
},
|
||||
templateData: {},
|
||||
navigation: { tabs: [] },
|
||||
offerings: [],
|
||||
offerings: [
|
||||
{
|
||||
id: "menu-fixture",
|
||||
name: "家庭聚餐定制",
|
||||
summary: "为同学聚餐、家庭聚会提供常见的私房菜定制。",
|
||||
priceText: "88.88",
|
||||
coverUrl: brand.avatarUrl,
|
||||
presentation: { categoryLabel: "业务提供项", keywords: [], details: [] },
|
||||
},
|
||||
],
|
||||
inquiryForms: [],
|
||||
trustItems: [],
|
||||
trustPresentation: {},
|
||||
@@ -44,7 +53,10 @@ const runtimeWorkspace = {
|
||||
};
|
||||
const templateContent = {
|
||||
displayName: "餐饮模板",
|
||||
navigation: [{ key: "home", page: "home", label: "首页" }],
|
||||
navigation: [
|
||||
{ key: "home", page: "home", label: "首页" },
|
||||
{ key: "offerings", page: "offerings", label: "套餐餐品" },
|
||||
],
|
||||
assetSlots: [],
|
||||
trustContentTypes: [],
|
||||
admin: {
|
||||
@@ -88,6 +100,7 @@ const templateContent = {
|
||||
};
|
||||
|
||||
test("Admin 按通用预览目标筛选字段并同步品牌草稿", async ({ page }) => {
|
||||
await page.setViewportSize({ width: 1920, height: 1000 });
|
||||
await page.route("http://localhost:3001/public/workspace**", (route) =>
|
||||
route.fulfill({ json: runtimeWorkspace }),
|
||||
);
|
||||
@@ -116,6 +129,8 @@ test("Admin 按通用预览目标筛选字段并同步品牌草稿", async ({ pa
|
||||
return route.fulfill({
|
||||
json: { brand, installations: [], fields: [], offerings: [], forms: [], templateContent },
|
||||
});
|
||||
if (url.pathname === "/admin/workspace/preview")
|
||||
return route.fulfill({ json: runtimeWorkspace });
|
||||
if (url.pathname === "/public/templates/food")
|
||||
return route.fulfill({
|
||||
json: { name: "餐饮模板", description: "fixture", serviceCategories: [] },
|
||||
@@ -129,16 +144,75 @@ test("Admin 按通用预览目标筛选字段并同步品牌草稿", async ({ pa
|
||||
await page.getByLabel("密码").fill("fixture-password");
|
||||
await page.locator('button[type="submit"]').click();
|
||||
await expect(page.getByText("小程序页面配置")).toBeVisible();
|
||||
const frame = page.frameLocator('iframe[title="小程序页面预览"]');
|
||||
await expect(frame.locator(".food-home .name")).toContainText("测试主理人");
|
||||
await frame.locator('[data-editor-target="food.home.location"]').click();
|
||||
const preview = page.locator(".component-template-preview");
|
||||
await expect(preview.locator(".food-home .name")).toContainText("测试主理人");
|
||||
const dimensions = await preview.evaluate((element) => {
|
||||
const canvas = element.querySelector(".component-template-preview__canvas")!;
|
||||
const name = element.querySelector(".name")!;
|
||||
const avatar = element.querySelector(".identity img")!;
|
||||
return {
|
||||
width: canvas.getBoundingClientRect().width,
|
||||
font: parseFloat(getComputedStyle(name).fontSize),
|
||||
avatar: avatar.getBoundingClientRect().width,
|
||||
transform: getComputedStyle(canvas.firstElementChild!).transform,
|
||||
};
|
||||
});
|
||||
expect(dimensions.font / dimensions.width).toBeCloseTo(32 / 750, 3);
|
||||
expect(dimensions.avatar / dimensions.width).toBeCloseTo(128 / 750, 3);
|
||||
expect(dimensions.transform).toBe("none");
|
||||
await expect
|
||||
.poll(() =>
|
||||
preview.locator(".identity img").evaluate((image: HTMLImageElement) => image.naturalWidth),
|
||||
)
|
||||
.toBeGreaterThan(0);
|
||||
await preview.screenshot({ path: "../../.codex-tasks/preview-proportion/home.png" });
|
||||
const actionButtons = preview.locator(".food-home .actions button");
|
||||
await expect(actionButtons).toHaveCount(2);
|
||||
const previewBox = await preview.locator(".component-template-preview__canvas").boundingBox();
|
||||
const firstActionBox = await actionButtons.nth(0).boundingBox();
|
||||
const secondActionBox = await actionButtons.nth(1).boundingBox();
|
||||
expect(previewBox && firstActionBox && secondActionBox).toBeTruthy();
|
||||
expect(firstActionBox!.x).toBeGreaterThanOrEqual(previewBox!.x);
|
||||
expect(secondActionBox!.x + secondActionBox!.width).toBeLessThanOrEqual(
|
||||
previewBox!.x + previewBox!.width,
|
||||
);
|
||||
await expect(actionButtons.nth(0)).toContainText("咨询 / 预订");
|
||||
await expect(actionButtons.nth(1)).toContainText("查看餐品");
|
||||
await preview.locator('[data-editor-target="food.home.location"]').click();
|
||||
await expect(page.getByText("出摊信息标题")).toBeVisible();
|
||||
await expect(page.getByText("招牌餐品标题")).toHaveCount(0);
|
||||
await page.getByLabel("出摊信息标题").fill("后台草稿地点");
|
||||
await expect(preview.locator(".notice-title")).toContainText("后台草稿地点");
|
||||
await page.getByRole("button", { name: "保存页面内容" }).click();
|
||||
await expect(page.getByText("页面内容已保存为草稿,发布后小程序才会更新")).toBeVisible();
|
||||
await expect(frame.locator(".notice-title")).toContainText("后台草稿地点");
|
||||
await expect(frame.locator('[data-editor-target="food.home.location"]')).toHaveClass(
|
||||
await expect(preview.locator('[data-editor-target="food.home.location"]')).toHaveClass(
|
||||
/editor-target-selected/,
|
||||
);
|
||||
await page.getByText("套餐餐品", { exact: true }).click();
|
||||
await expect(preview.locator(".offering-card")).toHaveCount(1);
|
||||
await expect
|
||||
.poll(() =>
|
||||
preview.locator(".dish-media img").evaluate((image: HTMLImageElement) => image.naturalWidth),
|
||||
)
|
||||
.toBeGreaterThan(0);
|
||||
for (const width of [390, 320]) {
|
||||
await preview.locator(".component-template-preview__canvas").evaluate((element, size) => {
|
||||
(element as HTMLElement).style.width = size + "px";
|
||||
}, width);
|
||||
const layout = await preview.evaluate((element) => {
|
||||
const canvas = element.querySelector(".component-template-preview__canvas")!;
|
||||
const card = element.querySelector(".offering-card")!;
|
||||
const media = element.querySelector(".dish-media")!;
|
||||
return {
|
||||
canvas: canvas.getBoundingClientRect().width,
|
||||
overflow: card.scrollWidth - card.clientWidth,
|
||||
media: media.getBoundingClientRect().width,
|
||||
};
|
||||
});
|
||||
expect(layout.overflow).toBeLessThanOrEqual(1);
|
||||
expect(layout.media / layout.canvas).toBeCloseTo(224 / 750, 3);
|
||||
await preview.screenshot({
|
||||
path: "../../.codex-tasks/preview-proportion/menu-" + width + ".png",
|
||||
});
|
||||
}
|
||||
});
|
||||
Reference in new issue
Block a user