feat: 新增 Taro 模板双端运行与独立 Web 预览
This commit is contained in:
1 parent
f4061a24bd
commit
7e8fc01fba
48 files changed
+11576
-12
No files matched your search
@@ -0,0 +1,56 @@
|
||||
import Taro from "@tarojs/taro";
|
||||
import type { RuntimeWorkspace } from "@personal-brand/types";
|
||||
export function brandSlug() {
|
||||
if (process.env.TARO_ENV === "h5") {
|
||||
const search = new URLSearchParams(window.location.search);
|
||||
return search.get("brand") || BRAND_SLUG;
|
||||
}
|
||||
return BRAND_SLUG;
|
||||
}
|
||||
export const tokenKey = () => `customerToken:${brandSlug()}`;
|
||||
export function hasSession() {
|
||||
return Boolean(Taro.getStorageSync<string>(tokenKey()));
|
||||
}
|
||||
export async function request<T>(
|
||||
path: string,
|
||||
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 response = await Taro.request<T & { error?: { message?: string; requestId?: string } }>({
|
||||
url: API_BASE_URL.replace(/\/$/, "") + path + query,
|
||||
method: options.method || "GET",
|
||||
data: options.data,
|
||||
header: {
|
||||
accept: "application/json",
|
||||
...(options.customer
|
||||
? { Authorization: `Bearer ${Taro.getStorageSync<string>(tokenKey()) || ""}` }
|
||||
: {}),
|
||||
},
|
||||
});
|
||||
if (response.statusCode < 200 || response.statusCode >= 300) {
|
||||
if (options.customer && response.statusCode === 401) Taro.removeStorageSync(tokenKey());
|
||||
throw new Error(response.data?.error?.message || `请求失败(${response.statusCode})`);
|
||||
}
|
||||
return response.data;
|
||||
}
|
||||
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)
|
||||
throw new Error("该品牌使用其他模板,请选择匹配的模板预览地址");
|
||||
return data;
|
||||
}
|
||||
export async function ensureSession() {
|
||||
if (hasSession()) return;
|
||||
if (process.env.TARO_ENV === "h5")
|
||||
throw new Error("请在微信小程序中登录后提交;Web 预览可填写表单,尚未接入 Web 登录。");
|
||||
const login = await Taro.login();
|
||||
const session = await request<{ token: string }>("/customer/session/wechat", {
|
||||
method: "POST",
|
||||
data: { code: login.code },
|
||||
});
|
||||
Taro.setStorageSync(tokenKey(), session.token);
|
||||
}
|
||||
@@ -0,0 +1,90 @@
|
||||
import type {
|
||||
RuntimeOffering,
|
||||
RuntimeWorkspace,
|
||||
RuntimeTrustItem,
|
||||
RuntimeInquiryField,
|
||||
} from "@personal-brand/types";
|
||||
export type Presentation = Record<string, string>;
|
||||
export function text(value: unknown): string {
|
||||
return typeof value === "string" ? value : "";
|
||||
}
|
||||
export function object(value: unknown): Record<string, unknown> {
|
||||
return value && typeof value === "object" && !Array.isArray(value)
|
||||
? (value as Record<string, unknown>)
|
||||
: {};
|
||||
}
|
||||
export function rows(value: unknown): Record<string, string>[] {
|
||||
return Array.isArray(value)
|
||||
? value
|
||||
.filter(
|
||||
(item): item is Record<string, string> =>
|
||||
Boolean(item) && typeof item === "object" && !Array.isArray(item),
|
||||
)
|
||||
.map((item) =>
|
||||
Object.fromEntries(Object.entries(item).map(([key, value]) => [key, text(value)])),
|
||||
)
|
||||
: [];
|
||||
}
|
||||
export function brandText(workspace: RuntimeWorkspace, key: string) {
|
||||
return text(workspace.brand[key]);
|
||||
}
|
||||
export function presentation(workspace: RuntimeWorkspace, page: string): Presentation {
|
||||
return object(object(workspace.brand.visualPresentation)[page]) as Presentation;
|
||||
}
|
||||
export function slot(workspace: RuntimeWorkspace, type: string): RuntimeTrustItem | undefined {
|
||||
const items = workspace.trustItems.filter((item) => item.type === type);
|
||||
return items.find((item) => Object.keys(item.config).length > 0) || items[0];
|
||||
}
|
||||
export type Offering = RuntimeOffering & {
|
||||
image: string;
|
||||
desc: string;
|
||||
priceRange: string;
|
||||
category: string;
|
||||
area: string;
|
||||
series: string;
|
||||
keywords: string[];
|
||||
details: RuntimeOffering["presentation"]["details"];
|
||||
};
|
||||
export function offering(item: RuntimeOffering): Offering {
|
||||
return {
|
||||
...item,
|
||||
image: item.presentation.heroImage || item.coverUrl || "",
|
||||
desc: item.summary || "",
|
||||
priceRange: item.priceText || "沟通报价",
|
||||
category: item.presentation.categoryLabel,
|
||||
area: text(item.presentation.area),
|
||||
series: text(item.presentation.series),
|
||||
keywords: item.presentation.keywords,
|
||||
details: item.presentation.details,
|
||||
};
|
||||
}
|
||||
export type Values = Record<string, string | string[]>;
|
||||
export function visibleFields(fields: RuntimeInquiryField[], values: Values) {
|
||||
return fields.filter((field) =>
|
||||
(field.visibleWhen || []).every((rule) => {
|
||||
const value = values[rule.field];
|
||||
switch (rule.operator) {
|
||||
case "exists":
|
||||
return Array.isArray(value) ? value.length > 0 : Boolean(value);
|
||||
case "equals":
|
||||
return value === rule.value;
|
||||
case "not-equals":
|
||||
return value !== rule.value;
|
||||
case "in":
|
||||
return (
|
||||
Array.isArray(rule.value) && typeof value === "string" && rule.value.includes(value)
|
||||
);
|
||||
}
|
||||
}),
|
||||
);
|
||||
}
|
||||
export function missingField(fields: RuntimeInquiryField[], values: Values) {
|
||||
return visibleFields(fields, values).find(
|
||||
(field) =>
|
||||
field.required &&
|
||||
(!values[field.key] ||
|
||||
(Array.isArray(values[field.key])
|
||||
? values[field.key].length === 0
|
||||
: !(values[field.key] as string).trim())),
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
import Taro from "@tarojs/taro";
|
||||
export const routes = {
|
||||
home: "/pages/home/index",
|
||||
offerings: "/pages/offerings/index",
|
||||
service: "/pages/service/index",
|
||||
profile: "/pages/profile/index",
|
||||
inquiry: "/pages/inquiry/index",
|
||||
detail: "/pages/detail/index",
|
||||
success: "/pages/success/index",
|
||||
records: "/pages/records/index",
|
||||
};
|
||||
export type PageKey = keyof typeof routes;
|
||||
export function navigate(page: PageKey, params: Record<string, string> = {}) {
|
||||
const isTab = TEMPLATE_MANIFEST.navigation.some((tab) => tab.page === page);
|
||||
if (isTab) {
|
||||
Taro.setStorageSync(`routeQuery:${page}`, params);
|
||||
void Taro.switchTab({ url: routes[page] });
|
||||
} else {
|
||||
const query = Object.entries(params)
|
||||
.map(([key, value]) => `${encodeURIComponent(key)}=${encodeURIComponent(value)}`)
|
||||
.join("&");
|
||||
void Taro.navigateTo({ url: routes[page] + (query ? "?" + query : "") });
|
||||
}
|
||||
}
|
||||
export function takeQuery(page: PageKey): Record<string, string> {
|
||||
const key = `routeQuery:${page}`;
|
||||
const value = Taro.getStorageSync<Record<string, string>>(key) || {};
|
||||
Taro.removeStorageSync(key);
|
||||
return value;
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
import type { RuntimeWorkspace } from "@personal-brand/types";
|
||||
import type { PageKey } from "./navigation";
|
||||
export type TemplateProps = {
|
||||
workspace: RuntimeWorkspace;
|
||||
page: PageKey;
|
||||
children?: React.ReactNode;
|
||||
offeringId?: string;
|
||||
};
|
||||
@@ -0,0 +1,30 @@
|
||||
import { createContext, useCallback, useContext, useEffect, useState } from "react";
|
||||
import type { PropsWithChildren } from "react";
|
||||
import type { RuntimeWorkspace } from "@personal-brand/types";
|
||||
import { loadWorkspace } from "./api";
|
||||
const Context = createContext<{
|
||||
workspace?: RuntimeWorkspace;
|
||||
error: string;
|
||||
loading: boolean;
|
||||
reload: () => void;
|
||||
}>({ error: "", loading: true, reload() {} });
|
||||
export function WorkspaceProvider({ children }: PropsWithChildren) {
|
||||
const [workspace, setWorkspace] = useState<RuntimeWorkspace>();
|
||||
const [error, setError] = useState("");
|
||||
const [loading, setLoading] = useState(true);
|
||||
const reload = useCallback(() => {
|
||||
setLoading(true);
|
||||
setError("");
|
||||
void loadWorkspace()
|
||||
.then(setWorkspace)
|
||||
.catch((error: unknown) =>
|
||||
setError(error instanceof Error ? error.message : "加载失败,请重试"),
|
||||
)
|
||||
.finally(() => setLoading(false));
|
||||
}, []);
|
||||
useEffect(reload, [reload]);
|
||||
return (
|
||||
<Context.Provider value={{ workspace, error, loading, reload }}>{children}</Context.Provider>
|
||||
);
|
||||
}
|
||||
export const useWorkspace = () => useContext(Context);
|
||||
Reference in new issue
Block a user