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

592 lines
17 KiB
TypeScript
Raw Normal View History

2026-11-24 14:49:58 +08:00
import {
ArrowLeft,
ChevronRight,
Menu,
Pencil,
Plus,
Save,
Trash2,
} from "lucide-react";
2026-11-23 11:09:03 +08:00
import { useEffect, useMemo, useState } from "react";
import { apiPost } from "./api";
2026-11-24 14:49:58 +08:00
import { statusLabel } from "./statusLabels";
2026-11-23 11:09:03 +08:00
const SITE_CODE = "SIT0000000000001";
type NavigationSummary = {
navigationCode: string;
navigationName: string;
position: "HEADER" | "FOOTER";
status: "DRAFT" | "PUBLISHED" | "OFFLINE";
items: NavigationItemResponse[];
};
type NavigationItemResponse = {
itemCode: string;
parentItemCode?: string;
itemType: string;
title: string;
targetCode?: string;
url: string;
openType: "CURRENT" | "NEW";
visible: boolean;
sortNo: number;
};
type NavigationItemForm = {
clientKey: string;
parentClientKey: string;
itemType: string;
title: string;
targetCode: string;
url: string;
openType: "CURRENT" | "NEW";
visible: boolean;
sortNo: number;
};
type TargetOption = {
group: string;
type: string;
code: string;
label: string;
url: string;
};
/** 生成仅用于当前编辑会话的菜单项临时键。 */
function createClientKey(): string {
return `menu-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
}
/** 新建一个空白菜单项。 */
function createItem(parentClientKey = "", sortNo = 0): NavigationItemForm {
2026-11-24 14:49:58 +08:00
return {
clientKey: createClientKey(),
parentClientKey,
itemType: "HOME",
title: "",
targetCode: "",
url: "/",
openType: "CURRENT",
visible: true,
sortNo,
};
2026-11-23 11:09:03 +08:00
}
/** 菜单导航列表与独立编辑页。 */
export default function NavigationManager() {
const [list, setList] = useState<NavigationSummary[]>([]);
const [editing, setEditing] = useState(false);
const [navigationCode, setNavigationCode] = useState("");
const [navigationName, setNavigationName] = useState("");
const [position, setPosition] = useState<"HEADER" | "FOOTER">("HEADER");
2026-11-24 14:49:58 +08:00
const [status, setStatus] = useState<"DRAFT" | "PUBLISHED" | "OFFLINE">(
"DRAFT",
);
2026-11-23 11:09:03 +08:00
const [items, setItems] = useState<NavigationItemForm[]>([]);
const [targets, setTargets] = useState<TargetOption[]>([]);
const [message, setMessage] = useState("");
const [saving, setSaving] = useState(false);
/** 读取导航列表。 */
const loadList = async () => {
try {
2026-11-24 14:49:58 +08:00
const result = await apiPost<{ items: NavigationSummary[] }>(
"/navigations/list",
{ siteCode: SITE_CODE },
);
2026-11-23 11:09:03 +08:00
setList(result.items || []);
setMessage("");
} catch (error) {
setMessage(error instanceof Error ? error.message : "导航加载失败");
}
};
2026-11-24 14:49:58 +08:00
useEffect(() => {
void loadList();
}, []);
2026-11-23 11:09:03 +08:00
/** 汇总导航可以跳转的固定页面和业务内容。 */
const loadTargets = async () => {
const options: TargetOption[] = [
{ group: "固定页面", type: "HOME", code: "", label: "首页", url: "/" },
2026-11-24 14:49:58 +08:00
{
group: "固定页面",
type: "PRODUCT_LIST",
code: "",
label: "产品列表页",
url: "/products",
},
{
group: "固定页面",
type: "NEWS_LIST",
code: "",
label: "新闻列表页",
url: "/news",
},
{
group: "固定页面",
type: "CASE_LIST",
code: "",
label: "案例列表页",
url: "/cases",
},
{
group: "固定页面",
type: "HELP_LIST",
code: "",
label: "帮助列表页",
url: "/help",
},
2026-11-23 11:09:03 +08:00
];
const settled = await Promise.allSettled([
apiPost<any>("/pages/list", { siteCode: SITE_CODE }),
apiPost<any>("/products/categories/list", { siteCode: SITE_CODE }),
apiPost<any>("/products/list", { siteCode: SITE_CODE }),
...(["NEWS", "CASE", "HELP"] as const).flatMap((contentType) => [
2026-11-24 14:49:58 +08:00
apiPost<any>("/contents/categories/list", {
siteCode: SITE_CODE,
contentType,
}),
2026-11-23 11:09:03 +08:00
apiPost<any>("/contents/list", { siteCode: SITE_CODE, contentType }),
]),
]);
2026-11-24 14:49:58 +08:00
const value = (index: number) =>
settled[index].status === "fulfilled"
? (settled[index] as PromiseFulfilledResult<any>).value.items || []
: [];
value(0).forEach((page: any) =>
options.push({
group: page.pageType === "CUSTOM_PAGE" ? "自定义页面" : "系统页面",
type: page.pageType === "CUSTOM_PAGE" ? "CUSTOM_PAGE" : "SYSTEM_PAGE",
code: page.pageCode,
label: page.pageName,
url: `/${page.slug}`,
}),
);
value(1).forEach((category: any) =>
options.push({
group: "产品分类",
type: "PRODUCT_CATEGORY",
code: category.categoryCode,
label: category.categoryName,
url: `/products/category/${category.slug}`,
}),
);
value(2).forEach((product: any) =>
options.push({
group: "产品",
type: "PRODUCT",
code: product.productCode,
label: product.productName,
url: `/products/${product.slug}`,
}),
);
const contentMeta = [
{
name: "新闻",
prefix: "news",
categoryType: "NEWS_CATEGORY",
itemType: "NEWS",
},
{
name: "案例",
prefix: "cases",
categoryType: "CASE_CATEGORY",
itemType: "CASE",
},
{
name: "帮助",
prefix: "help",
categoryType: "HELP_CATEGORY",
itemType: "HELP",
},
];
2026-11-23 11:09:03 +08:00
contentMeta.forEach((meta, offset) => {
2026-11-24 14:49:58 +08:00
value(3 + offset * 2).forEach((category: any) =>
options.push({
group: `${meta.name}分类`,
type: meta.categoryType,
code: category.categoryCode,
label: category.categoryName,
url: `/${meta.prefix}/category/${category.slug}`,
}),
);
value(4 + offset * 2).forEach((content: any) =>
options.push({
group: meta.name,
type: meta.itemType,
code: content.contentCode,
label: content.title,
url: `/${meta.prefix}/${content.slug}`,
}),
);
2026-11-23 11:09:03 +08:00
});
setTargets(options);
};
/** 打开新增导航页面。 */
const createNavigation = () => {
2026-11-24 14:49:58 +08:00
setNavigationCode("");
setNavigationName("");
setPosition("HEADER");
setStatus("DRAFT");
setItems([createItem()]);
setEditing(true);
setMessage("");
2026-11-23 11:09:03 +08:00
void loadTargets();
};
/** 打开既有导航编辑页面。 */
const editNavigation = (navigation: NavigationSummary) => {
2026-11-24 14:49:58 +08:00
setNavigationCode(navigation.navigationCode);
setNavigationName(navigation.navigationName);
setPosition(navigation.position);
setStatus(navigation.status);
setItems(
navigation.items.map((item) => ({
clientKey: item.itemCode,
parentClientKey: item.parentItemCode || "",
itemType: item.itemType,
title: item.title,
targetCode: item.targetCode || "",
url: item.url,
openType: item.openType,
visible: item.visible,
sortNo: item.sortNo,
})),
);
setEditing(true);
setMessage("");
void loadTargets();
2026-11-23 11:09:03 +08:00
};
/** 更新指定菜单项。 */
2026-11-24 14:49:58 +08:00
const updateItem = (key: string, patch: Partial<NavigationItemForm>) =>
setItems((current) =>
current.map((item) =>
item.clientKey === key ? { ...item, ...patch } : item,
),
);
2026-11-23 11:09:03 +08:00
/** 选择内部页面或内容作为菜单目标。 */
const selectTarget = (key: string, encoded: string) => {
2026-11-24 14:49:58 +08:00
const option = targets.find(
(item) => `${item.type}|${item.code}|${item.url}` === encoded,
);
if (option)
updateItem(key, {
itemType: option.type,
targetCode: option.code,
url: option.url,
title:
items.find((item) => item.clientKey === key)?.title || option.label,
});
2026-11-23 11:09:03 +08:00
};
/** 删除菜单项及其直接子项。 */
2026-11-24 14:49:58 +08:00
const deleteItem = (key: string) =>
setItems((current) =>
current.filter(
(item) => item.clientKey !== key && item.parentClientKey !== key,
),
);
2026-11-23 11:09:03 +08:00
/** 保存完整导航菜单树。 */
const save = async () => {
2026-11-24 14:49:58 +08:00
if (
!navigationName.trim() ||
items.length === 0 ||
items.some((item) => !item.title.trim() || !item.url.trim())
) {
setMessage("请填写导航名称及全部菜单项的标题和目标");
return;
}
2026-11-23 11:09:03 +08:00
try {
2026-11-24 14:49:58 +08:00
setSaving(true);
setMessage("");
await apiPost("/navigations/save", {
navigationCode: navigationCode || null,
siteCode: SITE_CODE,
navigationName,
position,
status,
items: items.map((item, index) => ({ ...item, sortNo: index })),
});
setEditing(false);
await loadList();
} catch (error) {
setMessage(error instanceof Error ? error.message : "导航保存失败");
} finally {
setSaving(false);
}
2026-11-23 11:09:03 +08:00
};
/** 删除导航。 */
const remove = async (navigation: NavigationSummary) => {
2026-11-24 14:49:58 +08:00
if (!window.confirm(`确认删除导航“${navigation.navigationName}”吗?`))
return;
try {
await apiPost("/navigations/delete", {
siteCode: SITE_CODE,
navigationCode: navigation.navigationCode,
});
await loadList();
} catch (error) {
setMessage(error instanceof Error ? error.message : "导航删除失败");
}
2026-11-23 11:09:03 +08:00
};
2026-11-24 14:49:58 +08:00
const groupedTargets = useMemo(
() => Array.from(new Set(targets.map((item) => item.group))),
[targets],
);
2026-11-23 11:09:03 +08:00
2026-11-24 14:49:58 +08:00
if (!editing)
return (
<div className="navigation-manager">
<header>
<div>
<h1>菜单导航</h1>
<p>配置前台站页头与页脚显示的菜单结构。</p>
</div>
<button className="primary" onClick={createNavigation}>
<Plus size={17} />
添加导航
</button>
</header>
{message && <div className="notice">{message}</div>}
<section className="navigation-list">
<div className="navigation-list-head">
<span>导航</span>
<span>菜单项</span>
<span>位置 / 状态</span>
<span>操作</span>
</div>
{list.length === 0 ? (
<div className="empty">
<Menu size={34} />
<strong>暂无导航配置</strong>
<p>点击“添加导航”创建前台菜单。</p>
</div>
) : (
list.map((navigation) => (
<div
className="navigation-list-row"
key={navigation.navigationCode}
>
<strong>{navigation.navigationName}</strong>
<span>
{navigation.items
.filter((item) => !item.parentItemCode)
.map((item) => item.title)
.join("、") || "--"}
</span>
<span>
{navigation.position === "HEADER" ? "页头" : "页脚"} ·{" "}
{statusLabel(navigation.status)}
</span>
<div>
<button
title="编辑导航"
onClick={() => editNavigation(navigation)}
>
<Pencil size={17} />
</button>
<button
className="danger"
title="删除导航"
onClick={() => void remove(navigation)}
>
<Trash2 size={17} />
</button>
</div>
</div>
))
)}
</section>
</div>
);
2026-11-23 11:09:03 +08:00
2026-11-24 14:49:58 +08:00
return (
<div className="navigation-editor">
<header>
<div className="navigation-editor-title">
<button className="icon-button" onClick={() => setEditing(false)}>
<ArrowLeft size={18} />
</button>
<div>
<h1>{navigationCode ? "编辑导航" : "新增导航"}</h1>
<p>设置菜单层级、跳转目标和打开方式。</p>
</div>
</div>
<div className="header-actions">
<button className="secondary" onClick={() => setEditing(false)}>
取消
</button>
<button
className="primary"
disabled={saving}
onClick={() => void save()}
>
<Save size={17} />
{saving ? "保存中" : "保存"}
</button>
</div>
</header>
{message && <div className="notice">{message}</div>}
<section className="navigation-base">
<label>
<span>导航标题 *</span>
<input
maxLength={100}
value={navigationName}
onChange={(event) => setNavigationName(event.target.value)}
placeholder="例如:主导航"
/>
</label>
<label>
<span>展示位置</span>
<select
value={position}
onChange={(event) =>
setPosition(event.target.value as "HEADER" | "FOOTER")
}
>
<option value="HEADER">页头导航</option>
<option value="FOOTER">页脚导航</option>
</select>
</label>
<label>
<span>发布状态</span>
<select
value={status}
onChange={(event) => setStatus(event.target.value as typeof status)}
>
<option value="DRAFT">草稿</option>
<option value="PUBLISHED">发布</option>
<option value="OFFLINE">下线</option>
</select>
</label>
</section>
<section className="navigation-items">
<div className="navigation-items-heading">
<div>
<h2>菜单项</h2>
<p>菜单项可以指向固定页面、分类、具体内容或自定义地址。</p>
</div>
<button
className="secondary"
onClick={() =>
setItems((current) => [
...current,
createItem("", current.length),
])
}
>
<Plus size={16} />
添加菜单项
</button>
</div>
<div className="navigation-item-head">
<span>菜单标题</span>
<span>页面打开方式</span>
<span>跳转目标</span>
<span>显示</span>
<span>操作</span>
</div>
{items.map((item) => (
<div
className={`navigation-item-row ${item.parentClientKey ? "child" : ""}`}
key={item.clientKey}
>
{item.parentClientKey && (
<ChevronRight className="child-marker" size={16} />
)}
<input
value={item.title}
onChange={(event) =>
updateItem(item.clientKey, { title: event.target.value })
}
placeholder="菜单标题"
/>
<select
value={item.openType}
onChange={(event) =>
updateItem(item.clientKey, {
openType: event.target
.value as NavigationItemForm["openType"],
})
}
>
<option value="CURRENT">当前页面打开</option>
<option value="NEW">新窗口打开</option>
</select>
<select
value={`${item.itemType}|${item.targetCode}|${item.url}`}
onChange={(event) =>
selectTarget(item.clientKey, event.target.value)
}
>
<option value={`${item.itemType}|${item.targetCode}|${item.url}`}>
{targets.length ? "请选择页面或内容" : "正在加载目标..."}
</option>
{groupedTargets.map((group) => (
<optgroup label={group} key={group}>
{targets
.filter((target) => target.group === group)
.map((target) => (
<option
key={`${target.type}-${target.code}-${target.url}`}
value={`${target.type}|${target.code}|${target.url}`}
>
{target.label}
</option>
))}
</optgroup>
))}
</select>
<label className="switch">
<input
type="checkbox"
checked={item.visible}
onChange={(event) =>
updateItem(item.clientKey, { visible: event.target.checked })
}
/>
<span />
</label>
<div className="navigation-row-actions">
{!item.parentClientKey && (
<button
title="添加子菜单"
onClick={() =>
setItems((current) => [
...current,
createItem(item.clientKey, current.length),
])
}
>
<Plus size={17} />
</button>
)}
<button
className="danger"
title="删除菜单项"
onClick={() => deleteItem(item.clientKey)}
>
<Trash2 size={17} />
</button>
</div>
</div>
))}
{items.length === 0 && (
<div className="empty">
<strong>暂无菜单项</strong>
<p>添加至少一个菜单项后才能保存。</p>
</div>
)}
</section>
</div>
);
2026-11-23 11:09:03 +08:00
}