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

+5
View File
@@ -0,0 +1,5 @@
# 构建时确定模板,品牌可在 Web 中通过 ?brand=linjing-doors 选择。
TEMPLATE_KEY=acheng-campus-food
BRAND_SLUG=default-brand
API_BASE_URL=http://localhost:3001
PREVIEW_PORT=3002
+59
View File
@@ -0,0 +1,59 @@
# Taro 模板双端工程
本目录在独立迁移分支提供 Web 和微信小程序共用的 React 页面。后台、Prisma 和发布 API 不变;当前原生模板构建仍保留。
## 启动 Web
在仓库根目录执行:
```sh
pnpm install
pnpm --filter @personal-brand/types build
pnpm --filter @personal-brand/taro dev:h5
```
默认餐饮模板、default-brand、API http://localhost:3001,Web http://localhost:3002。
林境模板:
```sh
TEMPLATE_KEY=linjing-editorial PREVIEW_PORT=3003 pnpm --filter @personal-brand/taro dev:h5
```
API 地址通过 `API_BASE_URL` 设置,品牌通过 `BRAND_SLUG` 设置。H5 也可在地址查询参数使用 `?brand=linjing-doors`,但必须与构建模板匹配。环境变量通过命令环境传入;`.env.example` 是参数说明,不自动加载真实密钥。
## 构建
```sh
pnpm --filter @personal-brand/taro build:h5
pnpm --filter @personal-brand/taro build:weapp
TEMPLATE_KEY=linjing-editorial pnpm --filter @personal-brand/taro build:h5
TEMPLATE_KEY=linjing-editorial pnpm --filter @personal-brand/taro build:weapp
```
输出 `apps/taro/dist/<templateKey>/h5` 和 `weapp`。微信开发者工具导入对应 weapp 目录;正式登录需在项目配置里设置与 API 相匹配的 AppID,配置请求合法域名。默认 touristappid 仅用于浏览,不含密钥。
页面结构和样式以 React 原型为参考,当前原生小程序用于校对字段、结构化来源、认证与提交行为。模板实现位于各 package 的 `taro/`;公共请求、表单、记录和状态位于此目录。新模板须提供 manifest、Taro 实现和验收用例,不新增全局 seed。
## 使用边界
Web 支持真实已发布内容、导航、餐品搜索/分类、咨询表单填写和校验。未接入 Web 身份登录,因此没有微信会话时不会提交,不生成假咨询或伪造成功。微信小程序采用 Taro.login 和原 customer/session/wechat 接口。令牌按品牌隔离;请求失败保留表单输入,401 清理会话。
Web 与小程序来自同一套源码,H5 排版检查不等同微信原生验收。原生微信登录、拨号、剪贴板及真机排版须在微信环境最终核验。
## 验证
```sh
pnpm --filter @personal-brand/taro typecheck
pnpm --filter @personal-brand/taro lint
pnpm --filter @personal-brand/taro test
pnpm --filter @personal-brand/taro test:browser
```
浏览器测试需要先启动 API 和餐饮 H5 预览。`PREVIEW_URL` 指定预览地址,`CHROMIUM_PATH` 指定本机 Chromium;测试只读取开发库,模拟错误响应用于失败路径,不写入真实数据。
## 回滚与切换
所有工作在 feat/taro-template-preview 独立 worktree。用户确认前不合并、不切换主工作区、不修改开发数据库或原 dist/miniapp。确认后另行切换默认构建;旧 template:dev 始终可用。
Taro 4.3 官方依赖树含部分旧依赖 deprecation 和 punycode 提示,跟进负责人为框架维护者;本项目固定版本并检查双端产物。Admin React 19 与 Taro React 18 在各 workspace 依赖边界独立,避免跨端插件 peer mismatch。
+67
View File
@@ -0,0 +1,67 @@
import { defineConfig } from "@tarojs/cli";
import path from "node:path";
import fs from "node:fs";
const root = path.resolve(__dirname, "../../..");
const key = process.env.TEMPLATE_KEY || "acheng-campus-food";
const templates = fs
.readdirSync(path.join(root, "packages"))
.filter(
(directory) =>
directory.startsWith("template-") &&
fs.existsSync(path.join(root, "packages", directory, "taro/index.tsx")) &&
fs.existsSync(path.join(root, "packages", directory, "template.json")),
)
.map((directory) => directory.slice("template-".length));
if (!templates.includes(key)) throw new Error(`Unsupported Taro template: ${key}`);
const template = path.join(root, "packages", `template-${key}`);
const manifest = JSON.parse(fs.readFileSync(path.join(template, "template.json"), "utf8")) as {
packageKey: string;
defaultBrandSlug?: string;
};
if (manifest.packageKey !== key) throw new Error(`Template key mismatch: ${key}`);
const brand = process.env.BRAND_SLUG || manifest.defaultBrandSlug || "default-brand";
fs.cpSync(path.join(template, "miniapp/assets"), path.resolve(__dirname, "../src/assets"), {
recursive: true,
});
export default defineConfig({
projectName: "personal-brand-taro",
date: "2026-10-08",
designWidth: 750,
deviceRatio: { 750: 1 },
sourceRoot: "src",
outputRoot: `dist/${key}/${process.env.TARO_ENV || "weapp"}`,
framework: "react",
compiler: { type: "vite" },
plugins: [],
alias: { "@template": path.join(template, "taro") },
defineConstants: {
TEMPLATE_KEY: JSON.stringify(key),
BRAND_SLUG: JSON.stringify(brand),
API_BASE_URL: JSON.stringify(process.env.API_BASE_URL || "http://localhost:3001"),
TEMPLATE_MANIFEST: JSON.stringify(manifest),
},
copy: {
options: {},
patterns: [
...(process.env.TARO_ENV === "weapp"
? [
{
from: path.resolve(__dirname, "../project.config.json"),
to: `dist/${key}/weapp/project.config.json`,
},
]
: []),
{
from: path.join(template, "miniapp/assets"),
to: `dist/${key}/${process.env.TARO_ENV || "weapp"}/assets`,
},
],
},
mini: {},
h5: {
publicPath: "/",
router: { mode: "hash" },
devServer: { host: "0.0.0.0", port: Number(process.env.PREVIEW_PORT || 3002) },
},
});
+39
View File
@@ -0,0 +1,39 @@
{
"name": "@personal-brand/taro",
"private": true,
"scripts": {
"dev:h5": "taro build --type h5 --watch",
"build:h5": "taro build --type h5",
"build:weapp": "taro build --type weapp",
"typecheck": "tsc --noEmit",
"lint": "pnpm --workspace-root exec eslint apps/taro/src apps/taro/config packages/template-acheng-campus-food/taro packages/template-linjing-editorial/taro",
"test": "node --experimental-strip-types --test test/*.test.mjs",
"test:browser": "playwright test"
},
"dependencies": {
"@personal-brand/types": "workspace:*",
"@tarojs/components": "4.3.0",
"@tarojs/helper": "4.3.0",
"@tarojs/plugin-framework-react": "4.3.0",
"@tarojs/plugin-platform-h5": "4.3.0",
"@tarojs/plugin-platform-weapp": "4.3.0",
"@tarojs/react": "4.3.0",
"@tarojs/runtime": "4.3.0",
"@tarojs/shared": "4.3.0",
"@tarojs/taro": "4.3.0",
"react": "18.3.1",
"react-dom": "18.3.1"
},
"devDependencies": {
"@tarojs/cli": "4.3.0",
"@tarojs/vite-runner": "4.3.0",
"@types/react": "18.3.18",
"@types/react-dom": "18.3.5",
"@vitejs/plugin-react": "4.7.0",
"vite": "4.5.14",
"@types/node": "^22.10.0",
"@babel/plugin-proposal-decorators": "^7.25.9",
"@babel/plugin-transform-class-properties": "^7.25.9",
"@playwright/test": "1.58.2"
}
}
+18
View File
@@ -0,0 +1,18 @@
import { defineConfig } from "@playwright/test";
export default defineConfig({
testDir: "./test/browser",
timeout: 30000,
use: {
baseURL: process.env.PREVIEW_URL || "http://localhost:3002",
viewport: { width: 375, height: 812 },
screenshot: "only-on-failure",
launchOptions: {
executablePath:
process.env.CHROMIUM_PATH ||
"/home/que01/.cache/ms-playwright/chromium-1228/chrome-linux64/chrome",
args: ["--no-sandbox"],
},
},
reporter: [["list"]],
outputDir: "../../.codex-tasks/taro-migration/raw/browser",
});
+7
View File
@@ -0,0 +1,7 @@
{
"appid": "touristappid",
"projectname": "personal-brand-taro-preview",
"compileType": "miniprogram",
"setting": { "es6": false, "minified": true, "urlCheck": true },
"description": "独立迁移分支的 Taro 小程序产物;正式登录需配置实际 AppID。"
}
+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);
+81
View File
@@ -0,0 +1,81 @@
import { test, expect } from "@playwright/test";
test("真实 API 驱动首页、出摊和主理人视觉槽位", async ({ page }) => {
const errors: string[] = [];
page.on("pageerror", (error) => errors.push(error.message));
await page.goto("/");
await expect(page.locator(".food-home .name")).toContainText("阿成");
const widths = await page.locator(".scene").evaluate((element) => ({
image: element.getBoundingClientRect().width,
parent: element.parentElement!.getBoundingClientRect().width,
}));
expect(Math.abs(widths.image - widths.parent)).toBeLessThan(2);
await page.getByText("出摊服务", { exact: true }).click();
await expect(page.locator(".schedule")).toHaveCount(2);
await expect(page.locator(".delivery-item")).toHaveCount(2);
await expect(page.locator(".step")).toHaveCount(4);
await page.screenshot({
path: "../../.codex-tasks/taro-migration/raw/food-service.png",
fullPage: true,
});
await page.getByText("主理人", { exact: true }).click();
await expect(page.locator(".standard")).toHaveCount(3);
await expect(page.locator(".case-row")).toHaveCount(3);
await expect(page.locator(".commitment")).toHaveCount(2);
await page.screenshot({
path: "../../.codex-tasks/taro-migration/raw/food-profile.png",
fullPage: true,
});
expect(errors).toEqual([]);
});
test("餐品搜索、详情和咨询目标传递", async ({ page }) => {
await page.goto("/#/pages/offerings/index");
await expect(page.locator(".offering-card").first()).toBeVisible();
await page.locator("input").fill("不存在的餐品名称");
await expect(page.getByText("没有找到相关餐品,换个词试试")).toBeVisible();
await page.locator("input").fill("");
const name = await page.locator(".dish-name").first().textContent();
await page.locator(".offering-card").first().click();
await expect(page.locator(".hero-copy")).toContainText(name!);
await page.locator(".bar taro-button-core").click();
await expect(page.locator(".inquiry-form")).toBeVisible();
await expect(page.locator(".half-field")).toHaveCount(4);
});
test("失败和未登录不清空表单,不伪造提交成功", async ({ page }) => {
await page.goto("/#/pages/inquiry/index");
await expect(page.locator(".inquiry-form")).toBeVisible();
await page.locator(".submit-button").click();
await expect(page.locator(".form-error")).toContainText("请填写");
const input = page.locator("input:not([type=hidden])").last();
await input.fill("13800138000");
await page.locator(".submit-button").click();
await expect(input).toHaveValue("13800138000");
await expect(page).not.toHaveURL(/success/);
});
test("加载失败提供重试", async ({ page }) => {
await page.route("**/public/workspace**", (route) =>
route.fulfill({
status: 503,
contentType: "application/json",
body: JSON.stringify({ error: { message: "测试服务暂不可用" } }),
}),
);
await page.goto("/");
await expect(page.getByText("测试服务暂不可用")).toBeVisible();
await expect(page.getByText("重试")).toBeVisible();
});
test("林境模板使用真实品牌数据与独立路由", async ({ page }) => {
const errors: string[] = [];
page.on("pageerror", (error) => errors.push(error.message));
await page.goto("http://localhost:3003/");
await expect(page.locator(".founder-name")).toContainText("林");
await expect(page.locator(".stat-value")).toHaveCount(4);
await page.getByText("主理人与我", { exact: true }).click();
await expect(page.locator(".editorial-profile .founder")).toBeVisible();
await expect(page.locator(".trust-card").first()).toBeVisible();
await page.screenshot({
path: "../../.codex-tasks/taro-migration/raw/linjing-profile.png",
fullPage: true,
});
expect(errors).toEqual([]);
});
+24
View File
@@ -0,0 +1,24 @@
import { test } from "node:test";
import assert from "node:assert/strict";
import fs from "node:fs";
import path from "node:path";
const root = path.resolve(import.meta.dirname, "../../..");
for (const key of ["acheng-campus-food", "linjing-editorial"])
test(`${key} 两端产物有真实入口及模板导航`, () => {
const manifest = JSON.parse(
fs.readFileSync(path.join(root, `packages/template-${key}/template.json`)),
);
const base = path.join(root, `apps/taro/dist/${key}`);
const config = JSON.parse(fs.readFileSync(path.join(base, "weapp/app.json")));
assert.equal(config.pages.length, 8);
assert.deepEqual(
config.tabBar.list.map((item) => item.text),
manifest.navigation.map((item) => item.label),
);
for (const page of config.pages)
for (const ext of ["js", "wxml", "json"])
assert.ok(fs.existsSync(path.join(base, "weapp", `${page}.${ext}`)), `${page}.${ext}`);
assert.ok(fs.readFileSync(path.join(base, "h5/index.html"), "utf8").includes('type="module"'));
assert.ok(fs.existsSync(path.join(base, "weapp/project.config.json")));
assert.ok(fs.readFileSync(path.join(base, "weapp/common.wxss"), "utf8").length > 1000);
});
+44
View File
@@ -0,0 +1,44 @@
import { test } from "node:test";
import assert from "node:assert/strict";
import { missingField, visibleFields, slot, offering } from "../src/runtime/content.ts";
test("条件字段与空数组校验使用实际显示字段", () => {
const fields = [
{ key: "type", type: "select", label: "类型", required: true },
{
key: "choices",
type: "checkbox",
label: "选项",
required: true,
visibleWhen: [{ field: "type", operator: "equals", value: "group" }],
},
];
assert.equal(visibleFields(fields, { type: "daily" }).length, 1);
assert.equal(missingField(fields, { type: "group", choices: [] }).key, "choices");
assert.equal(missingField(fields, { type: "group", choices: ["a"] }), undefined);
});
test("结构化来源优先,详情使用公开投影", () => {
const item = slot(
{
trustItems: [
{ type: "credential", config: {}, content: "old" },
{ type: "credential", config: { standards: [] }, content: "edited" },
],
},
"credential",
);
assert.equal(item.content, "edited");
const data = offering({
id: "a",
summary: "摘要",
coverUrl: "cover",
priceText: "报价",
presentation: {
categoryLabel: "套餐",
heroImage: "hero",
keywords: [],
details: { background: "实际餐品说明" },
},
});
assert.equal(data.image, "hero");
assert.equal(data.details.background, "实际餐品说明");
});
+22
View File
@@ -0,0 +1,22 @@
{
"compilerOptions": {
"target": "ES2020",
"module": "ESNext",
"moduleResolution": "Bundler",
"jsx": "react-jsx",
"strict": true,
"esModuleInterop": true,
"resolveJsonModule": true,
"skipLibCheck": true,
"noEmit": true,
"types": ["node", "@tarojs/taro"],
"baseUrl": "."
},
"include": [
"src",
"config",
"../../packages/template-*/taro",
"playwright.config.ts",
"test/browser"
]
}