feat: 新增 Taro 模板双端运行与独立 Web 预览

This commit is contained in:
que01 committed 2026-10-08 15:28:26 +08:00
1 parent f4061a24bd
commit 7e8fc01fba
48 files changed
+11576 -12

No files matched your search

+35
View File
@@ -0,0 +1,35 @@
const routes: Record<string, string> = {
home: "pages/home/index",
offerings: "pages/offerings/index",
service: "pages/service/index",
profile: "pages/profile/index",
inquiry: "pages/inquiry/index",
};
export default defineAppConfig({
pages: [
"pages/home/index",
"pages/offerings/index",
"pages/service/index",
"pages/profile/index",
"pages/inquiry/index",
"pages/detail/index",
"pages/success/index",
"pages/records/index",
],
window: {
navigationBarTitleText: TEMPLATE_MANIFEST.displayName,
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,
})),
},
});
+55
View File
@@ -0,0 +1,55 @@
page {
background: #fafaf9;
}
body {
margin: 0;
}
view,
text,
image,
input,
textarea,
button {
box-sizing: border-box;
}
button::after {
border: 0;
}
image {
display: block;
}
.runtime-state {
min-height: 70vh;
padding: 80px 32px;
color: #78716c;
font-size: 28px;
text-align: center;
}
.runtime-state button {
margin-top: 24px;
}
.preview-context {
padding: 12px 32px;
color: #78716c;
background: #fff;
border-bottom: 1px solid #eee;
font-size: 22px;
}
@media (min-width: 600px) {
body {
max-width: 430px;
margin: 0 auto;
background: #e7e5e4;
}
#app {
min-height: 100vh;
background: #fafaf9;
}
}
/* postcss-pxtransform disable */
@media (min-width: 600px) {
html {
font-size: 22.933333px !important;
}
}
/* postcss-pxtransform enable */
+6
View File
@@ -0,0 +1,6 @@
import type { PropsWithChildren } from "react";
import { WorkspaceProvider } from "./runtime/workspace";
import "./app.css";
export default function App({ children }: PropsWithChildren) {
return <WorkspaceProvider>{children}</WorkspaceProvider>;
}
+206
View File
@@ -0,0 +1,206 @@
import { useEffect, useRef, useState } from "react";
import {
View,
Text,
Button,
Input,
Textarea,
Picker,
Checkbox,
CheckboxGroup,
Label,
} from "@tarojs/components";
import Taro, { useDidShow, useRouter } from "@tarojs/taro";
import type { RuntimeWorkspace, RuntimeInquiryForm } from "@personal-brand/types";
import { missingField, visibleFields, presentation } from "../runtime/content";
import type { Values } from "../runtime/content";
import { ensureSession, request, brandSlug } from "../runtime/api";
import { takeQuery, navigate } from "../runtime/navigation";
import "./forms.css";
export function Inquiry({ workspace }: { workspace: RuntimeWorkspace }) {
const router = useRouter();
const [offeringId, setOfferingId] = useState(router.params.offeringId || "");
const form: RuntimeInquiryForm | undefined =
workspace.inquiryForms.find((form) => offeringId && form.targetId === offeringId) ||
workspace.inquiryForms.find((form) => form.target === "brand");
const [values, setValues] = useState<Values>({});
const [error, setError] = useState("");
const [sending, setSending] = useState(false);
const busy = useRef(false);
const p = presentation(workspace, "inquiry");
const food = TEMPLATE_KEY === "acheng-campus-food";
useDidShow(() => {
const query = takeQuery("inquiry");
if (query.offeringId) setOfferingId(query.offeringId);
});
useEffect(() => {
setValues({});
setError("");
}, [form?.key]);
const setValue = (key: string, value: string | string[]) =>
setValues((current) => ({ ...current, [key]: value }));
async function submit() {
if (busy.current) return;
if (!form) {
setError("咨询表单暂不可用,请稍后重试");
return;
}
const missing = missingField(form.fields, values);
if (missing) {
setError("请填写" + missing.label);
return;
}
busy.current = true;
setSending(true);
setError("");
try {
await ensureSession();
const valid = Object.fromEntries(
visibleFields(form.fields, values)
.filter((field) => values[field.key] !== undefined)
.map((field) => [field.key, values[field.key]]),
);
const result = await request<{ id: string }>("/customer/inquiry-submissions", {
method: "POST",
customer: true,
data: { formId: form.key, values: valid },
});
Taro.setStorageSync(`latestInquiry:${brandSlug()}`, result);
navigate("success");
} catch (error) {
setError(error instanceof Error ? error.message : "提交失败,请重试");
} finally {
setSending(false);
busy.current = false;
}
}
return (
<View className={`inquiry-page ${food ? "food-inquiry" : "editorial-inquiry"}`}>
<View className="form-intro">
<Text className="eyebrow">{p.eyebrow}</Text>
<Text className="form-title">{p.title || "提交咨询"}</Text>
<Text className="form-subtitle">{p.subtitle}</Text>
</View>
{!form ? (
<View className="form-error">尚未配置可用的咨询表单</View>
) : (
<View className="inquiry-form">
<View className="field-grid">
{visibleFields(form.fields, values).map((field) => {
const options = field.options || [];
const value = values[field.key];
const stringValue = typeof value === "string" ? value : "";
const chips =
food && field.key === "type" && ["select", "radio"].includes(field.type);
return (
<View
className={`form-field ${food && ["people", "date", "budget", "delivery"].includes(field.key) ? "half-field" : ""}`}
key={field.key}
>
<Text className="field-label">
{field.label}
{field.required && <Text className="required"> *</Text>}
</Text>
{chips ? (
<View className="option-grid">
{options.map((option) => (
<Button
className={value === option.value ? "choice selected" : "choice"}
key={option.value}
onClick={() => setValue(field.key, option.value)}
>
{option.label}
</Button>
))}
</View>
) : field.type === "checkbox" ? (
<CheckboxGroup onChange={(event) => setValue(field.key, event.detail.value)}>
<View className="checkbox-options">
{options.map((option) => (
<Label className="checkbox-option" key={option.value}>
<Checkbox
value={option.value}
checked={Array.isArray(value) && value.includes(option.value)}
/>
<Text>{option.label}</Text>
</Label>
))}
</View>
</CheckboxGroup>
) : ["select", "radio"].includes(field.type) ? (
<Picker
mode="selector"
range={options.map((option) => option.label)}
value={Math.max(
0,
options.findIndex((option) => option.value === stringValue),
)}
onChange={(event) => {
const option = options[Number(event.detail.value)];
if (option) setValue(field.key, option.value);
}}
>
<View className="field-input picker-input">
{options.find((option) => option.value === stringValue)?.label || "请选择"}
<Text>⌄</Text>
</View>
</Picker>
) : field.type === "date" ? (
<Picker
mode="date"
value={stringValue}
onChange={(event) => setValue(field.key, event.detail.value)}
>
<View className="field-input picker-input">
{stringValue || "请选择日期"}
<Text>⌄</Text>
</View>
</Picker>
) : field.type === "textarea" ? (
<Textarea
className="field-input field-textarea"
value={stringValue}
placeholder={"请填写" + field.label}
onInput={(event) => setValue(field.key, event.detail.value)}
maxlength={2000}
/>
) : (
<Input
className="field-input"
type={
field.type === "number"
? "number"
: field.type === "tel"
? "number"
: "text"
}
value={stringValue}
placeholder={"请填写" + field.label}
onInput={(event) => setValue(field.key, event.detail.value)}
/>
)}
</View>
);
})}
</View>
{error && (
<View className="form-error" role="alert">
{error}
</View>
)}
<Button
className="submit-button"
disabled={sending}
loading={sending}
onClick={() => void submit()}
>
{p.submitLabel || "提交需求"}
</Button>
</View>
)}
<View className="history-link" onClick={() => navigate("records")}>
查看我的咨询记录 ›
</View>
</View>
);
}
+33
View File
@@ -0,0 +1,33 @@
import { View, Button } from "@tarojs/components";
import { useRouter } from "@tarojs/taro";
import { TemplatePage } from "@template";
import { useWorkspace } from "../runtime/workspace";
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 router = useRouter();
if (loading) return <View className="runtime-state">正在加载…</View>;
if (error || !workspace)
return (
<View className="runtime-state">
{error || "暂时无法加载"}
<Button onClick={reload}>重试</Button>
</View>
);
const children =
page === "inquiry" ? (
<Inquiry workspace={workspace} />
) : page === "records" ? (
<Records workspace={workspace} />
) : page === "success" ? (
<Success workspace={workspace} />
) : null;
return (
<TemplatePage workspace={workspace} page={page} offeringId={router.params.id}>
{children}
</TemplatePage>
);
}
+130
View File
@@ -0,0 +1,130 @@
import { useCallback, useState } from "react";
import { View, Text, Button } from "@tarojs/components";
import { useDidShow } from "@tarojs/taro";
import type { RuntimeWorkspace } from "@personal-brand/types";
import { ensureSession, hasSession, request } from "../runtime/api";
import { navigate } from "../runtime/navigation";
import { presentation } from "../runtime/content";
import "./forms.css";
type RecordItem = {
id: string;
status: string;
createdAt: string;
replyNote?: string;
inquiryForm?: { name: string };
offering?: { name: string };
fieldsSnapshot?: { key: string; label: string; options?: { label: string; value: string }[] }[];
values: Record<string, string | string[]>;
statusHistory?: { toStatus: string; createdAt: string }[];
};
const labels: Record<string, string> = {
new: "待处理",
reviewing: "沟通中",
replied: "已回复",
qualified: "已确认",
converted: "已转化",
closed: "已关闭",
};
export function Records({ workspace }: { workspace: RuntimeWorkspace }) {
const [records, setRecords] = useState<RecordItem[]>([]);
const [error, setError] = useState("");
const [loading, setLoading] = useState(false);
const [authenticated, setAuthenticated] = useState(hasSession());
const p = presentation(workspace, "records");
const load = useCallback(() => {
if (!hasSession()) {
setAuthenticated(false);
setRecords([]);
return;
}
setLoading(true);
setError("");
void request<RecordItem[]>("/customer/inquiry-submissions", { customer: true })
.then(setRecords)
.catch((error: unknown) => {
setError(error instanceof Error ? error.message : "加载失败");
setAuthenticated(hasSession());
})
.finally(() => setLoading(false));
}, []);
useDidShow(load);
return (
<View className="records-page">
<Text className="form-title">{p.title || "我的咨询记录"}</Text>
<Button onClick={() => navigate("inquiry")}>{p.createAction || "新增咨询"}</Button>
{loading ? (
<View className="runtime-state">正在加载…</View>
) : error ? (
<View className="form-error">
{error}
<Button onClick={load}>重试</Button>
</View>
) : !authenticated ? (
<View className="records-empty">
<Text>登录后查看你的咨询及处理进度</Text>
{process.env.TARO_ENV === "weapp" ? (
<Button
onClick={() =>
void ensureSession()
.then(() => {
setAuthenticated(true);
load();
})
.catch((error: unknown) =>
setError(error instanceof Error ? error.message : "登录失败"),
)
}
>
微信登录
</Button>
) : (
<Text className="form-subtitle">
请在微信小程序内登录查看。Web 预览不显示其他用户的记录。
</Text>
)}
</View>
) : !records.length ? (
<View className="records-empty">
<Text>{p.emptyTitle || "还没有咨询记录"}</Text>
<Text className="form-subtitle">{p.emptyDescription}</Text>
<Button onClick={() => navigate("inquiry")}>{p.emptyAction || "开始咨询"}</Button>
</View>
) : (
records.map((item) => (
<View className="record-card" key={item.id}>
<View className="record-head">
<Text>{item.inquiryForm?.name || "品牌咨询"}</Text>
<Text className="record-status">{labels[item.status] || item.status}</Text>
</View>
{item.offering && <Text className="form-subtitle">{item.offering.name}</Text>}
<Text className="record-date">{new Date(item.createdAt).toLocaleString("zh-CN")}</Text>
{(item.fieldsSnapshot || [])
.filter((field) => item.values[field.key] !== undefined)
.map((field) => {
const raw = item.values[field.key];
const value = (Array.isArray(raw) ? raw : [raw])
.map(
(value) =>
field.options?.find((option) => option.value === value)?.label || value,
)
.join("、");
return (
<View className="record-value" key={field.key}>
<Text>{field.label}</Text>
<Text>{value}</Text>
</View>
);
})}
{item.replyNote && <View className="reply-note">主理人回复:{item.replyNote}</View>}
{item.statusHistory?.map((entry, index) => (
<View className="record-history" key={index}>
{labels[entry.toStatus] || entry.toStatus} ·{" "}
{new Date(entry.createdAt).toLocaleString("zh-CN")}
</View>
))}
</View>
))
)}
</View>
);
}
+28
View File
@@ -0,0 +1,28 @@
import { View, Text, Button } from "@tarojs/components";
import Taro from "@tarojs/taro";
import type { RuntimeWorkspace } from "@personal-brand/types";
import { presentation, object, text } from "../runtime/content";
import { brandSlug } from "../runtime/api";
import { navigate } from "../runtime/navigation";
export function Success({ workspace }: { workspace: RuntimeWorkspace }) {
const p = presentation(workspace, "success");
const result = object(Taro.getStorageSync<unknown>(`latestInquiry:${brandSlug()}`));
if (!text(result.id))
return (
<View className="runtime-state">
尚未提交咨询<Button onClick={() => navigate("inquiry")}>填写需求</Button>
</View>
);
return (
<View className="success-page">
<Text className="success-symbol">✓</Text>
<Text className="eyebrow">{p.eyebrow}</Text>
<Text className="form-title">{p.title || "已收到你的需求"}</Text>
<Text className="form-subtitle">{p.intro}</Text>
<Button className="submit-button" onClick={() => navigate("records")}>
{p.recordsAction || "查看咨询记录"}
</Button>
<Button onClick={() => navigate("home")}>{p.homeAction || "返回首页"}</Button>
</View>
);
}
+205
View File
@@ -0,0 +1,205 @@
.inquiry-page,
.records-page,
.success-page {
padding: 32px;
min-height: 100vh;
background: #fafaf9;
color: #292524;
}
.form-intro {
margin: 16px 0 32px;
}
.eyebrow {
display: block;
color: #c2410c;
font-size: 20px;
letter-spacing: 3px;
}
.form-title {
display: block;
font-size: 36px;
font-weight: 700;
line-height: 1.4;
margin-top: 12px;
}
.form-subtitle {
display: block;
font-size: 24px;
line-height: 1.7;
color: #78716c;
margin-top: 12px;
}
.inquiry-form {
background: #fff;
padding: 32px;
border: 1px solid #f5f5f4;
border-radius: 36px;
}
.field-grid {
display: flex;
flex-wrap: wrap;
gap: 24px 20px;
}
.form-field {
width: 100%;
min-width: 0;
}
.half-field {
width: calc(50% - 10px);
}
.field-label {
display: block;
margin-bottom: 12px;
font-size: 24px;
font-weight: 600;
}
.required {
color: #ea580c;
}
.field-input {
display: block;
width: 100%;
height: 84px;
padding: 20px;
border: 1px solid #e7e5e4;
border-radius: 24px;
background: #fafaf9;
font-size: 24px;
}
.field-textarea {
height: 180px;
}
.picker-input {
display: flex;
align-items: center;
justify-content: space-between;
}
.option-grid {
display: grid;
grid-template-columns: repeat(2, minmax(0, 1fr));
gap: 16px;
}
.choice {
margin: 0;
padding: 12px 8px;
line-height: 1.6;
background: #fafaf9;
border: 1px solid #e7e5e4;
border-radius: 24px;
font-size: 24px;
}
.choice.selected {
background: #fff7ed;
border-color: #fb923c;
color: #c2410c;
}
.checkbox-options {
display: flex;
flex-direction: column;
gap: 16px;
}
.checkbox-option {
display: flex;
align-items: center;
font-size: 24px;
}
.submit-button {
margin: 32px 0 0;
background: #f97316;
color: #fff;
border-radius: 24px;
font-size: 28px;
}
.form-error {
margin: 24px 0;
padding: 20px;
background: #fff1f2;
color: #be123c;
font-size: 24px;
line-height: 1.6;
border-radius: 16px;
}
.history-link {
text-align: center;
color: #78716c;
font-size: 24px;
margin-top: 28px;
}
.record-card {
margin-top: 24px;
padding: 28px;
background: #fff;
border-radius: 28px;
}
.record-head {
display: flex;
justify-content: space-between;
gap: 12px;
font-weight: 700;
font-size: 26px;
}
.record-status {
color: #c2410c;
font-size: 22px;
}
.record-date,
.record-history {
display: block;
color: #78716c;
font-size: 22px;
margin-top: 16px;
}
.record-value {
display: flex;
justify-content: space-between;
gap: 20px;
padding-top: 16px;
font-size: 24px;
}
.record-value text:last-child {
white-space: pre-wrap;
text-align: right;
}
.reply-note {
margin-top: 20px;
padding: 20px;
background: #fffbeb;
font-size: 24px;
line-height: 1.6;
}
.records-empty {
text-align: center;
padding: 80px 16px;
font-size: 28px;
}
.records-empty button {
margin-top: 24px;
}
.success-page {
text-align: center;
padding-top: 120px;
}
.success-symbol {
display: block;
color: #16a34a;
font-size: 80px;
margin-bottom: 24px;
}
.success-page button {
margin-top: 28px;
}
.editorial-inquiry .submit-button,
.editorial-forms .submit-button {
background: #202221;
}
.editorial-inquiry,
.editorial-forms .records-page,
.editorial-forms .success-page {
background: #f7f5f1;
}
.editorial-inquiry .eyebrow {
color: #8a6846;
}
.editorial-inquiry .form-title {
font-family: serif;
}
+18
View File
@@ -0,0 +1,18 @@
declare const TEMPLATE_KEY: string;
declare const BRAND_SLUG: string;
declare const API_BASE_URL: string;
declare const TEMPLATE_MANIFEST: {
packageKey: string;
displayName: string;
navigation: {
key: string;
label: string;
page: string;
iconPath: string;
selectedIconPath: string;
}[];
};
declare module "*.css";
declare module "@template" {
export { TemplatePage } from "../../../packages/template-acheng-campus-food/taro";
}
+16
View File
@@ -0,0 +1,16 @@
<!doctype html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8" />
<meta
name="viewport"
content="width=device-width,initial-scale=1,maximum-scale=1,viewport-fit=cover"
/>
<title>品牌模板预览</title>
</head>
<body>
<div id="app"></div>
<!-- prettier-ignore -->
<script><%= htmlWebpackPlugin.options.script %></script>
</body>
</html>
+4
View File
@@ -0,0 +1,4 @@
import { Page } from "../../components/Page";
export default function Screen() {
return <Page page="detail" />;
}
+4
View File
@@ -0,0 +1,4 @@
import { Page } from "../../components/Page";
export default function Screen() {
return <Page page="home" />;
}
+4
View File
@@ -0,0 +1,4 @@
import { Page } from "../../components/Page";
export default function Screen() {
return <Page page="inquiry" />;
}
+4
View File
@@ -0,0 +1,4 @@
import { Page } from "../../components/Page";
export default function Screen() {
return <Page page="offerings" />;
}
+4
View File
@@ -0,0 +1,4 @@
import { Page } from "../../components/Page";
export default function Screen() {
return <Page page="profile" />;
}
+4
View File
@@ -0,0 +1,4 @@
import { Page } from "../../components/Page";
export default function Screen() {
return <Page page="records" />;
}
+4
View File
@@ -0,0 +1,4 @@
import { Page } from "../../components/Page";
export default function Screen() {
return <Page page="service" />;
}
+4
View File
@@ -0,0 +1,4 @@
import { Page } from "../../components/Page";
export default function Screen() {
return <Page page="success" />;
}
+56
View File
@@ -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);
}
+90
View File
@@ -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())),
);
}
+30
View File
@@ -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;
}
+8
View File
@@ -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;
};
+30
View File
@@ -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);