feat: 建立组件化模板预览基线并规划可视化编辑

This commit is contained in:
que01 committed 2026-10-09 12:32:24 +08:00
1 parent c5af790554
commit 0b14b5a814
46 files changed
+1880 -427

No files matched your search

+15 -11
View File
@@ -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,
})),
},
}
: {}),
});
+3 -2
View File
@@ -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 (
+4
View File
@@ -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";
}
+11 -6
View File
@@ -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} />;
}
+31 -9
View File
@@ -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>
);