Files
shoplix/web-admin/src/DecorationEditor.tsx
T

745 lines
21 KiB
TypeScript
Raw Normal View History

2026-11-21 14:09:59 +08:00
import { useEffect, useMemo, useState } from "react";
2026-11-24 14:49:58 +08:00
import {
ChevronDown,
ChevronUp,
Copy,
Eye,
EyeOff,
GripVertical,
Monitor,
Plus,
Redo2,
Save,
Smartphone,
Tablet,
Trash2,
Undo2,
X,
ExternalLink,
} from "lucide-react";
2026-11-22 10:14:44 +08:00
import { API } from "./api";
2026-11-24 14:49:58 +08:00
import { statusLabel } from "./statusLabels";
2026-11-21 14:09:59 +08:00
const SITE = "SIT0000000000001";
type Viewport = "desktop" | "tablet" | "mobile";
2026-11-24 14:49:58 +08:00
type SectionType =
| "ANNOUNCEMENT"
| "HEADER"
| "HERO"
| "RICH_TEXT"
| "PRODUCTS"
| "CONTENT"
| "INQUIRY"
| "FOOTER";
type Section = {
id: string;
type: SectionType;
title: string;
subtitle: string;
imageUrl: string;
buttonText: string;
buttonUrl: string;
sourceType: string;
limit: number;
visible: boolean;
background: string;
textColor: string;
};
type Schema = {
global: {
primaryColor: string;
backgroundColor: string;
textColor: string;
fontFamily: string;
contentWidth: number;
};
sections: Section[];
};
const labels: Record<SectionType, string> = {
ANNOUNCEMENT: "公告栏",
HEADER: "导航栏",
HERO: "轮播横幅",
RICH_TEXT: "富文本",
PRODUCTS: "产品展示",
CONTENT: "内容展示",
INQUIRY: "询盘表单",
FOOTER: "页脚",
};
const initialSchema: Schema = {
global: {
primaryColor: "#176b5d",
backgroundColor: "#ffffff",
textColor: "#17211f",
fontFamily: "Inter",
contentWidth: 1200,
},
sections: [],
};
const pageOptions = [
{ value: "HOME", label: "首页", path: "/" },
{ value: "PRODUCT_CATEGORY", label: "产品分类页", path: "/products" },
{ value: "PRODUCT_DETAIL", label: "产品详情页", path: "/products" },
{ value: "NEWS_CATEGORY", label: "新闻分类页", path: "/news" },
{ value: "NEWS_DETAIL", label: "新闻详情页", path: "/news" },
{ value: "CASE_CATEGORY", label: "案例分类页", path: "/cases" },
{ value: "CASE_DETAIL", label: "案例详情页", path: "/cases" },
{ value: "HELP_CATEGORY", label: "帮助分类页", path: "/help" },
{ value: "HELP_DETAIL", label: "帮助详情页", path: "/help" },
{ value: "ABOUT_US", label: "关于我们", path: "/about-us" },
{ value: "CUSTOM_PAGE", label: "自定义页面", path: "/custom-page" },
];
async function post(path: string, body: unknown) {
const response = await fetch(API + path, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(body),
});
if (!response.ok)
throw new Error((await response.json()).message || "请求失败");
return response.json();
}
function createSection(type: SectionType): Section {
return {
id: `${type.toLowerCase()}-${Date.now()}`,
type,
title:
type === "HERO"
? "Reliable equipment for demanding operations."
: labels[type],
subtitle:
type === "HERO"
? "Industrial products and project-proven solutions for global B2B customers."
: "",
imageUrl: "",
buttonText: type === "HERO" ? "Explore Products" : "",
buttonUrl: type === "HERO" ? "/products" : "",
sourceType: type === "CONTENT" ? "CASE" : "",
limit: 3,
visible: true,
background: type === "HEADER" || type === "FOOTER" ? "#101a25" : "#ffffff",
textColor: type === "HEADER" || type === "FOOTER" ? "#ffffff" : "#17211f",
};
}
2026-11-21 14:09:59 +08:00
export default function DecorationEditor({ onBack }: { onBack: () => void }) {
const [pageType, setPageType] = useState("HOME");
2026-11-24 14:49:58 +08:00
const [schema, setSchema] = useState<Schema>(initialSchema);
const [history, setHistory] = useState<Schema[]>([]);
const [future, setFuture] = useState<Schema[]>([]);
const [selected, setSelected] = useState<string | null>(null);
const [globalMode, setGlobalMode] = useState(false);
const [viewport, setViewport] = useState<Viewport>("desktop");
const [notice, setNotice] = useState("");
const [status, setStatus] = useState("DRAFT");
const [version, setVersion] = useState(0);
useEffect(() => {
setSelected(null);
setGlobalMode(false);
setHistory([]);
setFuture([]);
post("/decorations/detail", { siteCode: SITE, pageType })
.then((data) => {
setSchema(JSON.parse(data.schema));
setStatus(data.status);
setVersion(data.publishedVersion);
})
.catch((error) => setNotice(error.message));
}, [pageType]);
const commit = (next: Schema) => {
setHistory((items) => [...items.slice(-19), schema]);
setFuture([]);
setSchema(next);
};
const updateSection = (id: string, patch: Partial<Section>) =>
commit({
...schema,
sections: schema.sections.map((item) =>
item.id === id ? { ...item, ...patch } : item,
),
});
const active = schema.sections.find((item) => item.id === selected);
const add = (type: SectionType) => {
const item = createSection(type);
commit({ ...schema, sections: [...schema.sections, item] });
setSelected(item.id);
setGlobalMode(false);
};
const move = (index: number, offset: number) => {
const target = index + offset;
if (target < 0 || target >= schema.sections.length) return;
const sections = [...schema.sections];
[sections[index], sections[target]] = [sections[target], sections[index]];
commit({ ...schema, sections });
};
const undo = () => {
const previous = history.at(-1);
if (!previous) return;
setFuture((items) => [schema, ...items]);
setSchema(previous);
setHistory((items) => items.slice(0, -1));
};
const redo = () => {
const next = future[0];
if (!next) return;
setHistory((items) => [...items, schema]);
setSchema(next);
setFuture((items) => items.slice(1));
};
const save = async () => {
await post("/decorations/save", {
siteCode: SITE,
pageType,
schema: JSON.stringify(schema),
});
setNotice("装修草稿已保存");
};
const publish = async () => {
await save();
await post("/decorations/publish", { siteCode: SITE, pageType });
setStatus("PUBLISHED");
setVersion((value) => value + 1);
setNotice("已发布到英文前台站");
};
const preview = () => {
const target =
pageOptions.find((item) => item.value === pageType) || pageOptions[0];
window.open(
`http://localhost:5174${target.path}?previewPage=${pageType}`,
"_blank",
"noopener,noreferrer",
);
};
const previewWidth = useMemo(
() =>
viewport === "desktop"
? "100%"
: viewport === "tablet"
? "820px"
: "390px",
[viewport],
);
return (
<div className="decorator">
<div className="decorator-top">
<button className="icon" onClick={onBack} title="返回">
<X size={19} />
</button>
<strong>
{pageOptions.find((item) => item.value === pageType)?.label ||
"页面装修"}
</strong>
<span className={`status ${status.toLowerCase()}`}>
{statusLabel(status)}
{status === "PUBLISHED" ? ` V${version}` : ""}
</span>
<select
className="decorator-page-select"
value={pageType}
onChange={(event) => setPageType(event.target.value)}
>
{pageOptions.map((item) => (
<option key={item.value} value={item.value}>
{item.label}
</option>
))}
</select>
<button
className="icon"
onClick={undo}
disabled={!history.length}
title="撤销"
>
<Undo2 size={18} />
</button>
<button
className="icon"
onClick={redo}
disabled={!future.length}
title="重做"
>
<Redo2 size={18} />
</button>
<div className="viewport-switch">
<button
className={viewport === "desktop" ? "active" : ""}
onClick={() => setViewport("desktop")}
title="桌面"
>
<Monitor size={18} />
</button>
<button
className={viewport === "tablet" ? "active" : ""}
onClick={() => setViewport("tablet")}
title="平板"
>
<Tablet size={18} />
</button>
<button
className={viewport === "mobile" ? "active" : ""}
onClick={() => setViewport("mobile")}
title="手机"
>
<Smartphone size={18} />
</button>
</div>
<button className="secondary" onClick={preview}>
<ExternalLink size={16} />
预览
</button>
<button className="secondary" onClick={save}>
<Save size={16} />
保存草稿
</button>
<button className="primary" onClick={publish}>
发布
</button>
</div>
{notice && <div className="decorator-notice">{notice}</div>}
<div className="decorator-body">
<aside className="decorator-tree">
<div className="decorator-tabs">
<button
className={!globalMode ? "active" : ""}
onClick={() => setGlobalMode(false)}
>
装修组件
</button>
<button
className={globalMode ? "active" : ""}
onClick={() => {
setGlobalMode(true);
setSelected(null);
}}
>
全局设置
</button>
</div>
{!globalMode && (
<>
<div className="section-tree">
{schema.sections.map((item, index) => (
<button
key={item.id}
className={selected === item.id ? "selected" : ""}
onClick={() => setSelected(item.id)}
>
<GripVertical size={15} />
<span>
{labels[item.type]}
<small>{item.title}</small>
</span>
<i
onClick={(event) => {
event.stopPropagation();
updateSection(item.id, { visible: !item.visible });
}}
>
{item.visible ? <Eye size={15} /> : <EyeOff size={15} />}
</i>
<i
onClick={(event) => {
event.stopPropagation();
move(index, -1);
}}
>
<ChevronUp size={14} />
</i>
<i
onClick={(event) => {
event.stopPropagation();
move(index, 1);
}}
>
<ChevronDown size={14} />
</i>
</button>
))}
</div>
<div className="component-palette">
<h3>添加组件</h3>
{(Object.keys(labels) as SectionType[]).map((type) => (
<button key={type} onClick={() => add(type)}>
<Plus size={15} />
{labels[type]}
</button>
))}
</div>
</>
)}
</aside>
<div className="decorator-stage">
<div
className="preview-frame"
style={{
width: previewWidth,
background: schema.global.backgroundColor,
color: schema.global.textColor,
fontFamily: schema.global.fontFamily,
}}
>
{schema.sections.filter((item) => item.visible).length ? (
schema.sections
.filter((item) => item.visible)
.map((item) => (
<PreviewSection
key={item.id}
item={item}
primary={schema.global.primaryColor}
selected={selected === item.id}
onSelect={() => {
setSelected(item.id);
setGlobalMode(false);
}}
/>
))
) : (
<div className="preview-empty">
<Panels />
<h2>开始装修首页</h2>
<p>从左侧添加轮播横幅、产品、案例或询盘表单等组件。</p>
</div>
)}
</div>
</div>
<aside className="decorator-settings">
{globalMode ? (
<GlobalSettings
schema={schema}
onChange={(global) => commit({ ...schema, global })}
/>
) : active ? (
<SectionSettings
item={active}
onChange={(patch) => updateSection(active.id, patch)}
onDuplicate={() => {
const copy = {
...active,
id: `${active.type.toLowerCase()}-${Date.now()}`,
};
commit({ ...schema, sections: [...schema.sections, copy] });
setSelected(copy.id);
}}
onDelete={() => {
commit({
...schema,
sections: schema.sections.filter(
(item) => item.id !== active.id,
),
});
setSelected(null);
}}
/>
) : (
<div className="settings-empty">
<h3>组件设置</h3>
<p>在左侧组件树或中间预览中选择一个组件进行编辑。</p>
</div>
)}
</aside>
</div>
</div>
);
2026-11-21 14:09:59 +08:00
}
2026-11-24 14:49:58 +08:00
function Panels() {
return (
<div className="empty-panels">
<span />
<span />
<span />
</div>
);
}
function PreviewSection({
item,
primary,
selected,
onSelect,
}: {
item: Section;
primary: string;
selected: boolean;
onSelect: () => void;
}) {
const style = {
background: item.background,
color: item.textColor,
outline: selected ? `2px solid ${primary}` : undefined,
};
if (item.type === "ANNOUNCEMENT")
return (
<section className="pv-announcement" style={style} onClick={onSelect}>
{item.title || "Free consultation for your next industrial project"}
</section>
);
if (item.type === "HEADER")
return (
<section className="pv-header" style={style} onClick={onSelect}>
<b>SHOPLIX</b>
<nav>Products Solutions News About Us Contact</nav>
<button style={{ background: primary }}>Get a quote</button>
</section>
);
if (item.type === "HERO")
return (
<section
className="pv-hero"
style={{
...style,
backgroundImage: item.imageUrl
? `linear-gradient(90deg,rgba(0,0,0,.65),rgba(0,0,0,.1)),url(${item.imageUrl})`
: undefined,
}}
onClick={onSelect}
>
<div>
<span>ENGINEERED FOR INDUSTRY</span>
<h1>{item.title}</h1>
<p>{item.subtitle}</p>
{item.buttonText && (
<button style={{ background: primary }}>{item.buttonText}</button>
)}
</div>
</section>
);
if (item.type === "RICH_TEXT")
return (
<section className="pv-rich" style={style} onClick={onSelect}>
<h2>{item.title}</h2>
<p>
{item.subtitle ||
"Add your English introduction, advantages or service description here."}
</p>
</section>
);
if (item.type === "PRODUCTS" || item.type === "CONTENT")
return (
<section className="pv-collection" style={style} onClick={onSelect}>
<p>FEATURED</p>
<h2>{item.title}</h2>
<div>
{Array.from({ length: Math.min(item.limit, 4) }, (_, i) => (
<article key={i}>
<span>
{item.type === "PRODUCTS"
? "PRODUCT"
: item.sourceType || "CONTENT"}
</span>
<b>
{item.type === "PRODUCTS"
? `Industrial product ${i + 1}`
: `Project story ${i + 1}`}
</b>
</article>
))}
</div>
</section>
);
if (item.type === "INQUIRY")
return (
<section className="pv-inquiry" style={style} onClick={onSelect}>
<div>
<h2>{item.title}</h2>
<p>{item.subtitle}</p>
</div>
<form>
<input placeholder="Your name" />
<input placeholder="Business email" />
<textarea placeholder="Project requirements" />
<button type="button" style={{ background: primary }}>
Submit Inquiry
</button>
</form>
</section>
);
return (
<section className="pv-footer" style={style} onClick={onSelect}>
<b>SHOPLIX</b>
<div>
Products
<br />
Solutions
<br />
Case Studies
</div>
<div>
About Us
<br />
Contact Us
<br />
Privacy Policy
</div>
<small>
{item.subtitle || "Copyright © 2026. All rights reserved."}
</small>
</section>
);
}
function Field({
label,
children,
}: {
label: string;
children: React.ReactNode;
}) {
return (
<label className="decor-field">
<span>{label}</span>
{children}
</label>
);
}
function GlobalSettings({
schema,
onChange,
}: {
schema: Schema;
onChange: (global: Schema["global"]) => void;
}) {
const g = schema.global;
return (
<div>
<h3>全局设置</h3>
<p>统一控制整站装修的基础视觉。</p>
<Field label="品牌主色">
<input
type="color"
value={g.primaryColor}
onChange={(e) => onChange({ ...g, primaryColor: e.target.value })}
/>
</Field>
<Field label="页面背景">
<input
type="color"
value={g.backgroundColor}
onChange={(e) => onChange({ ...g, backgroundColor: e.target.value })}
/>
</Field>
<Field label="正文颜色">
<input
type="color"
value={g.textColor}
onChange={(e) => onChange({ ...g, textColor: e.target.value })}
/>
</Field>
<Field label="英文字体">
<select
value={g.fontFamily}
onChange={(e) => onChange({ ...g, fontFamily: e.target.value })}
>
<option>Inter</option>
<option>Arial</option>
<option>Georgia</option>
</select>
</Field>
<Field label="内容最大宽度">
<input
type="number"
min="960"
max="1600"
value={g.contentWidth}
onChange={(e) =>
onChange({ ...g, contentWidth: Number(e.target.value) })
}
/>
</Field>
</div>
);
}
function SectionSettings({
item,
onChange,
onDuplicate,
onDelete,
}: {
item: Section;
onChange: (patch: Partial<Section>) => void;
onDuplicate: () => void;
onDelete: () => void;
}) {
return (
<div>
<h3>{labels[item.type]}设置</h3>
<Field label="英文标题">
<input
value={item.title}
onChange={(e) => onChange({ title: e.target.value })}
/>
</Field>
<Field label="英文副标题/内容">
<textarea
rows={4}
value={item.subtitle}
onChange={(e) => onChange({ subtitle: e.target.value })}
/>
</Field>
{item.type === "HERO" && (
<>
<Field label="背景图片 URL">
<input
value={item.imageUrl}
onChange={(e) => onChange({ imageUrl: e.target.value })}
/>
</Field>
<Field label="按钮文案">
<input
value={item.buttonText}
onChange={(e) => onChange({ buttonText: e.target.value })}
/>
</Field>
<Field label="按钮链接">
<input
value={item.buttonUrl}
onChange={(e) => onChange({ buttonUrl: e.target.value })}
/>
</Field>
</>
)}
{item.type === "CONTENT" && (
<Field label="内容来源">
<select
value={item.sourceType}
onChange={(e) => onChange({ sourceType: e.target.value })}
>
<option value="CASE">案例</option>
<option value="NEWS">新闻</option>
<option value="HELP">帮助</option>
</select>
</Field>
)}
{["PRODUCTS", "CONTENT"].includes(item.type) && (
<Field label="展示数量">
<input
type="number"
min="1"
max="12"
value={item.limit}
onChange={(e) => onChange({ limit: Number(e.target.value) })}
/>
</Field>
)}
<Field label="区块背景">
<input
type="color"
value={item.background}
onChange={(e) => onChange({ background: e.target.value })}
/>
</Field>
<Field label="文字颜色">
<input
type="color"
value={item.textColor}
onChange={(e) => onChange({ textColor: e.target.value })}
/>
</Field>
<div className="section-actions">
<button onClick={onDuplicate}>
<Copy size={15} />
复制组件
</button>
<button className="danger" onClick={onDelete}>
<Trash2 size={15} />
删除组件
</button>
</div>
</div>
);
2026-11-21 14:09:59 +08:00
}