feat: 增加可视化模板页面编辑器

This commit is contained in:
que01 committed 2026-10-08 18:00:36 +08:00
1 parent 9d2038cc93
commit c5af790554
24 files changed
+773 -129

No files matched your search

+5
View File
@@ -28,6 +28,11 @@ button::after {
image {
display: block;
}
.editor-target-selected {
outline: 3px solid #1677ff;
outline-offset: -3px;
cursor: pointer;
}
.runtime-state {
min-height: 70vh;
padding: 80px 32px;
+56 -1
View File
@@ -1,14 +1,69 @@
import { View, Button } from "@tarojs/components";
import { useRouter } from "@tarojs/taro";
import { useEffect } from "react";
import { TemplatePage } from "@template";
import { useWorkspace } from "../runtime/workspace";
import type { EditorPreviewFrameMessage, EditorPreviewHostMessage } from "@personal-brand/types";
import type { PageKey } from "../runtime/navigation";
import { Inquiry } from "./Inquiry";
import { Records } from "./Records";
import { Success } from "./Success";
export function Page({ page }: { page: PageKey }) {
const { workspace, error, loading, reload } = useWorkspace();
const { workspace, error, loading, reload, setBrandDraft } = useWorkspace();
const router = useRouter();
useEffect(() => {
if (process.env.TARO_ENV !== "h5" || window.parent === window) return;
const params = new URLSearchParams(window.location.search);
if (params.get("editor") !== "1") return;
const parentOrigin = params.get("parentOrigin") || "";
try {
if (!parentOrigin || new URL(parentOrigin).origin !== parentOrigin) return;
} catch {
return;
}
const send = (message: EditorPreviewFrameMessage) =>
window.parent.postMessage(message, parentOrigin);
const onMessage = (event: MessageEvent<EditorPreviewHostMessage>) => {
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 === "brandDraft") setBrandDraft(message.brand);
if (message.type === "focusTarget") {
document.querySelectorAll<HTMLElement>("[data-editor-target]").forEach((element) => {
element.classList.toggle(
"editor-target-selected",
element.dataset.editorTarget === message.targetKey,
);
});
}
};
const onClick = (event: MouseEvent) => {
const target =
event.target instanceof Element
? event.target.closest<HTMLElement>("[data-editor-target]")
: null;
if (!target?.dataset.editorTarget) return;
event.preventDefault();
event.stopPropagation();
document.querySelectorAll<HTMLElement>("[data-editor-target]").forEach((element) => {
element.classList.toggle("editor-target-selected", element === target);
});
send({
protocol: "personal-brand-editor-preview",
version: 1,
type: "targetSelected",
targetKey: target.dataset.editorTarget,
page: window.location.hash.match(/pages\/([^/]+)/)?.[1] || "home",
});
};
window.addEventListener("message", onMessage);
document.addEventListener("click", onClick, true);
send({ protocol: "personal-brand-editor-preview", version: 1, type: "ready" });
return () => {
window.removeEventListener("message", onMessage);
document.removeEventListener("click", onClick, true);
};
}, [setBrandDraft]);
if (loading) return <View className="runtime-state">正在加载…</View>;
if (error || !workspace)
return (
+16 -3
View File
@@ -38,10 +38,23 @@ export async function request<T>(
}
export async function loadWorkspace() {
const data = await request<RuntimeWorkspace>("/public/workspace");
if (data.publication?.status !== "published") throw new Error("品牌尚未发布");
if (data.brand.visualTemplateKey !== TEMPLATE_KEY)
const editorPreview =
process.env.TARO_ENV === "h5" &&
new URLSearchParams(window.location.search).get("editor") === "1";
if (!editorPreview && data.publication?.status !== "published") throw new Error("品牌尚未发布");
if (!editorPreview && data.brand.visualTemplateKey !== TEMPLATE_KEY)
throw new Error("该品牌使用其他模板,请选择匹配的模板预览地址");
return data;
return {
...data,
brand: data.brand ?? {},
templateData: data.templateData ?? {},
offerings: data.offerings ?? [],
inquiryForms: data.inquiryForms ?? [],
trustItems: data.trustItems ?? [],
trustPresentation: data.trustPresentation ?? {},
capabilities: data.capabilities ?? [],
theme: data.theme ?? { colors: {} },
};
}
export async function ensureSession() {
if (hasSession()) return;
+20 -4
View File
@@ -1,22 +1,36 @@
import { createContext, useCallback, useContext, useEffect, useState } from "react";
import type { PropsWithChildren } from "react";
import type { RuntimeWorkspace } from "@personal-brand/types";
import { projectBrandAliases } from "@personal-brand/types";
import { loadWorkspace } from "./api";
const Context = createContext<{
workspace?: RuntimeWorkspace;
error: string;
loading: boolean;
setBrandDraft: (brand: Partial<RuntimeWorkspace["brand"]>) => void;
reload: () => void;
}>({ error: "", loading: true, reload() {} });
}>({ error: "", loading: true, setBrandDraft() {}, reload() {} });
export function WorkspaceProvider({ children }: PropsWithChildren) {
const [workspace, setWorkspace] = useState<RuntimeWorkspace>();
const [baseWorkspace, setBaseWorkspace] = useState<RuntimeWorkspace>();
const [brandDraft, setBrandDraft] = useState<Partial<RuntimeWorkspace["brand"]>>({});
const workspace = baseWorkspace
? {
...baseWorkspace,
brand: projectBrandAliases(
{ ...baseWorkspace.brand, ...brandDraft },
brandDraft.config && typeof brandDraft.config === "object"
? (brandDraft.config as Record<string, unknown>)
: ((baseWorkspace.brand.config as Record<string, unknown> | undefined) ?? {}),
),
}
: undefined;
const [error, setError] = useState("");
const [loading, setLoading] = useState(true);
const reload = useCallback(() => {
setLoading(true);
setError("");
void loadWorkspace()
.then(setWorkspace)
.then(setBaseWorkspace)
.catch((error: unknown) =>
setError(error instanceof Error ? error.message : "加载失败,请重试"),
)
@@ -24,7 +38,9 @@ export function WorkspaceProvider({ children }: PropsWithChildren) {
}, []);
useEffect(reload, [reload]);
return (
<Context.Provider value={{ workspace, error, loading, reload }}>{children}</Context.Provider>
<Context.Provider value={{ workspace, error, loading, setBrandDraft, reload }}>
{children}
</Context.Provider>
);
}
export const useWorkspace = () => useContext(Context);