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

+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;
}