feat: 建立组件化模板预览基线并规划可视化编辑
This commit is contained in:
1 parent
c5af790554
commit
0b14b5a814
46 files changed
+1880
-427
No files matched your search
@@ -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 {
|
||||
|
||||
Reference in new issue
Block a user