feat: light app center and iframe refactor

This commit is contained in:
fengxiangdebaozi committed 2026-06-12 15:40:09 +08:00
1 parent 728a4b1170
commit 9d73f27146
35 files changed
+1878 -246

No files matched your search

@@ -0,0 +1,542 @@
/**
* 应用管理页 —— 注册 / 编辑 / 删除轻应用(全局共享,写操作仅 admin)。
*
* 两种类型:
* - window_open:填地址 + 路由参数,列表页以卡片展示、点击新开页跳转。
* - iframe:填地址 + 路由参数 + 选择挂载菜单,注册后动态注入侧边栏对应父菜单下。
*
* 路由参数构造器:参数名(key) + 类型(登录/主题)。登录参数右侧选 accessToken/yUserId/
* userName/其他(自填值),运行时从 localStorage.userInfo 解析;主题参数填 dark-blue/red/blue。
*/
import { useMemo, useState } from "react";
import {
ExternalLink,
Layers,
Pencil,
Plus,
Search,
Trash2,
X,
} from "lucide-react";
import { toast } from "sonner";
import {
Dialog,
DialogContent,
DialogFooter,
DialogHeader,
DialogTitle,
} from "@/components/ui/dialog";
import { Input } from "@/components/ui/input";
import { Button } from "@/components/ui/button";
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from "@/components/ui/select";
import { Switch } from "@/components/ui/switch";
import { Textarea } from "@/components/ui/textarea";
import { useTheme } from "@/contexts/ThemeContext";
import {
useLightAppActions,
useLightApps,
type LightApp,
type LightAppRouteParam,
type LightAppType,
} from "@/strategy-components/api/light-apps";
import {
buildLightAppUrl,
LOGIN_SOURCE_OPTIONS,
MOUNT_OPTIONS,
mountLabel,
THEME_EXAMPLE_OPTIONS,
} from "@/strategy-components/lib/light-app";
interface FormState {
name: string;
description: string;
appType: LightAppType;
url: string;
mountLocation: string;
enabled: boolean;
routeParams: LightAppRouteParam[];
}
const emptyForm = (): FormState => ({
name: "",
description: "",
appType: "window_open",
url: "",
mountLocation: "",
enabled: true,
routeParams: [],
});
const newParam = (): LightAppRouteParam => ({
key: "",
paramType: "login",
source: "accessToken",
customValue: "",
themeValue: "dark-blue",
});
function formFromApp(app: LightApp): FormState {
return {
name: app.name,
description: app.description ?? "",
appType: app.appType,
url: app.url,
mountLocation: app.mountLocation ?? "",
enabled: app.enabled,
routeParams: app.routeParams.map((p) => ({
key: p.key,
paramType: p.paramType,
source: p.source ?? "accessToken",
customValue: p.customValue ?? "",
themeValue: p.themeValue ?? "dark-blue",
})),
};
}
export default function LightAppManagementPage() {
const { theme } = useTheme();
const isDark = theme === "dark";
const [search, setSearch] = useState("");
const { data: apps = [], isLoading } = useLightApps({ search });
const actions = useLightAppActions();
const [dialogOpen, setDialogOpen] = useState(false);
const [editing, setEditing] = useState<LightApp | null>(null);
const [form, setForm] = useState<FormState>(emptyForm);
const saving = actions.create.isPending || actions.update.isPending;
const openCreate = () => {
setEditing(null);
setForm(emptyForm());
setDialogOpen(true);
};
const openEdit = (app: LightApp) => {
setEditing(app);
setForm(formFromApp(app));
setDialogOpen(true);
};
const patchForm = (patch: Partial<FormState>) => setForm((f) => ({ ...f, ...patch }));
const patchParam = (idx: number, patch: Partial<LightAppRouteParam>) =>
setForm((f) => ({
...f,
routeParams: f.routeParams.map((p, i) => (i === idx ? { ...p, ...patch } : p)),
}));
const addParam = () => patchForm({ routeParams: [...form.routeParams, newParam()] });
const removeParam = (idx: number) =>
patchForm({ routeParams: form.routeParams.filter((_, i) => i !== idx) });
const previewUrl = useMemo(() => {
if (!form.url) return "";
try {
return buildLightAppUrl({ url: form.url, routeParams: cleanParams(form.routeParams) });
} catch {
return form.url;
}
}, [form.url, form.routeParams]);
const handleSave = async () => {
const name = form.name.trim();
const url = form.url.trim();
if (!name) return toast.error("请填写应用名称");
if (!url) return toast.error("请填写应用地址");
if (form.appType === "iframe" && !form.mountLocation) return toast.error("iframe 类型请选择挂载菜单");
for (const p of form.routeParams) {
if (!p.key.trim()) return toast.error("路由参数的「参数名」不能为空");
}
const payload = {
name,
description: form.description.trim() || null,
appType: form.appType,
url,
routeParams: cleanParams(form.routeParams),
mountLocation: form.appType === "iframe" ? form.mountLocation : null,
enabled: form.enabled,
};
try {
if (editing) {
await actions.update.mutateAsync({ appId: editing.appId, patch: payload });
toast.success(`已更新「${name}」`);
} else {
await actions.create.mutateAsync(payload);
toast.success(`已注册「${name}」`);
}
setDialogOpen(false);
} catch (err) {
toast.error((err as Error).message || "保存失败");
}
};
const handleDelete = async (app: LightApp) => {
if (!window.confirm(`确定删除应用「${app.name}」吗?`)) return;
try {
await actions.remove.mutateAsync(app.appId);
toast.success(`已删除「${app.name}」`);
} catch (err) {
toast.error((err as Error).message || "删除失败");
}
};
// ── theme classes(与配置管理页一致) ──────────────────────────────────
const shellClass = isDark
? "h-full overflow-y-auto bg-[linear-gradient(180deg,#081322_0%,#0d1d33_42%,#0a1628_100%)] text-slate-100"
: "h-full overflow-y-auto bg-[linear-gradient(180deg,#fffdfd_0%,#fff7f7_42%,#fafafa_100%)] text-[#222222]";
const cardClass = isDark
? "border border-[rgba(67,89,124,0.46)] bg-[rgba(12,29,54,0.94)] shadow-[0_16px_36px_rgba(3,10,22,0.2)]"
: "border border-[#E8E8E8] bg-white shadow-[0_14px_30px_rgba(245,34,45,0.06)]";
const headRowClass = isDark ? "text-slate-400" : "text-[#8C8C8C]";
const rowBorder = isDark ? "border-[rgba(67,89,124,0.32)]" : "border-[#F0F0F0]";
const mutedText = isDark ? "text-slate-500" : "text-[#A6A6A6]";
const typeBadge = (t: LightAppType) =>
t === "iframe"
? isDark
? "bg-[rgba(168,85,247,0.16)] text-[#D6B4FF]"
: "bg-[#F9F0FF] text-[#722ED1]"
: isDark
? "bg-[rgba(77,141,255,0.16)] text-[#9CCBFF]"
: "bg-[#FFF1F0] text-[#CF1322]";
return (
<div className={shellClass}>
<div className="mx-auto flex min-h-full max-w-[1280px] flex-col gap-5 px-6 py-6 lg:px-8">
<div className="flex flex-wrap items-end justify-between gap-3">
<div className="space-y-1">
<h1 className={`text-[26px] font-semibold tracking-[0.02em] ${isDark ? "text-slate-50" : "text-[#222222]"}`}>
应用管理
</h1>
<p className={`text-sm ${isDark ? "text-slate-300/80" : "text-slate-500"}`}>
注册轻应用。window.open 类型在「应用列表」以卡片展示;iframe 类型挂载到所选菜单下并注入侧边栏。
</p>
</div>
<Button onClick={openCreate} className="gap-1.5">
<Plus className="h-4 w-4" />
注册应用
</Button>
</div>
<div className="relative max-w-sm">
<Search className={`pointer-events-none absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 ${mutedText}`} />
<Input
value={search}
onChange={(e) => setSearch(e.target.value)}
placeholder="搜索应用名称 / 描述"
className="pl-9"
/>
</div>
<div className={`overflow-hidden rounded-3xl ${cardClass}`}>
<table className="w-full border-collapse text-sm">
<thead>
<tr className={`text-left text-xs uppercase tracking-widest ${headRowClass}`}>
<th className="px-6 py-4 font-semibold">名称</th>
<th className="px-6 py-4 font-semibold">类型</th>
<th className="px-6 py-4 font-semibold">地址 / 挂载</th>
<th className="px-6 py-4 font-semibold">参数</th>
<th className="px-6 py-4 font-semibold">启用</th>
<th className="px-6 py-4 text-right font-semibold">操作</th>
</tr>
</thead>
<tbody>
{apps.length === 0 ? (
<tr>
<td colSpan={6} className={`px-6 py-12 text-center ${mutedText}`}>
{isLoading ? "加载中…" : "暂无应用,点击右上角「注册应用」开始"}
</td>
</tr>
) : (
apps.map((app) => (
<tr key={app.appId} className={`border-t ${rowBorder}`}>
<td className="px-6 py-4 align-middle">
<div className={`text-[15px] font-semibold ${isDark ? "text-white" : "text-[#222222]"}`}>
{app.name}
</div>
{app.description && (
<div className={`mt-0.5 line-clamp-1 text-xs ${mutedText}`}>{app.description}</div>
)}
</td>
<td className="px-6 py-4 align-middle">
<span className={`inline-flex items-center gap-1 rounded-full px-2 py-0.5 text-[11px] font-medium ${typeBadge(app.appType)}`}>
{app.appType === "iframe" ? <Layers className="h-3 w-3" /> : <ExternalLink className="h-3 w-3" />}
{app.appType === "iframe" ? "iframe 嵌套" : "新页跳转"}
</span>
</td>
<td className="px-6 py-4 align-middle">
<div className="max-w-[320px] truncate font-mono text-xs">{app.url}</div>
{app.appType === "iframe" && app.mountLocation && (
<div className={`mt-0.5 text-xs ${mutedText}`}>挂载:{mountLabel(app.mountLocation)}</div>
)}
</td>
<td className="px-6 py-4 align-middle">
<span className={mutedText}>{app.routeParams.length} 个</span>
</td>
<td className="px-6 py-4 align-middle">
<span className={app.enabled ? "text-emerald-500" : mutedText}>
{app.enabled ? "已启用" : "已停用"}
</span>
</td>
<td className="px-6 py-4 text-right align-middle">
<div className="inline-flex items-center gap-2">
<Button variant="outline" size="sm" className="gap-1" onClick={() => openEdit(app)}>
<Pencil className="h-3.5 w-3.5" />
编辑
</Button>
<Button variant="ghost" size="sm" className="gap-1 text-red-500 hover:text-red-600" onClick={() => handleDelete(app)}>
<Trash2 className="h-3.5 w-3.5" />
删除
</Button>
</div>
</td>
</tr>
))
)}
</tbody>
</table>
</div>
</div>
<Dialog open={dialogOpen} onOpenChange={setDialogOpen}>
<DialogContent className="max-h-[88vh] overflow-y-auto sm:max-w-[640px]">
<DialogHeader>
<DialogTitle>{editing ? "编辑应用" : "注册应用"}</DialogTitle>
</DialogHeader>
<div className="space-y-4 py-2">
{/* 类型 */}
<Field label="应用类型">
<Select value={form.appType} onValueChange={(v) => patchForm({ appType: v as LightAppType })}>
<SelectTrigger>
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value="window_open">新页跳转(window.open)</SelectItem>
<SelectItem value="iframe">iframe 嵌套(挂载到菜单)</SelectItem>
</SelectContent>
</Select>
</Field>
<Field label="应用名称">
<Input value={form.name} onChange={(e) => patchForm({ name: e.target.value })} placeholder="如:舆情看板" />
</Field>
<Field label="应用地址">
<Input
value={form.url}
onChange={(e) => patchForm({ url: e.target.value })}
placeholder="https://example.com/page 或 https://x#/route"
/>
</Field>
{form.appType === "iframe" && (
<Field label="挂载菜单">
<Select value={form.mountLocation || undefined} onValueChange={(v) => patchForm({ mountLocation: v })}>
<SelectTrigger>
<SelectValue placeholder="选择挂载到哪个菜单下" />
</SelectTrigger>
<SelectContent>
{MOUNT_OPTIONS.map((o) => (
<SelectItem key={o.value} value={o.value}>
{o.label}
</SelectItem>
))}
</SelectContent>
</Select>
</Field>
)}
<Field label="应用描述(可选)">
<Textarea
value={form.description}
onChange={(e) => patchForm({ description: e.target.value })}
placeholder="简要说明该应用的用途"
rows={2}
/>
</Field>
{/* 路由参数构造器 */}
<div className="space-y-2">
<div className="flex items-center justify-between">
<span className="text-sm font-medium">路由参数</span>
<Button variant="outline" size="sm" className="gap-1" onClick={addParam}>
<Plus className="h-3.5 w-3.5" />
添加路由参数
</Button>
</div>
{form.routeParams.length === 0 && (
<p className={`text-xs ${mutedText}`}>暂无参数。登录参数运行时从 userInfo 取值,主题参数用固定值。</p>
)}
<div className="space-y-2">
{form.routeParams.map((p, idx) => (
<ParamRow
key={idx}
param={p}
isDark={isDark}
onChange={(patch) => patchParam(idx, patch)}
onRemove={() => removeParam(idx)}
/>
))}
</div>
</div>
{previewUrl && (
<div className={`rounded-lg border px-3 py-2 ${isDark ? "border-[rgba(67,89,124,0.4)] bg-[rgba(8,19,34,0.6)]" : "border-[#F0F0F0] bg-[#FAFAFA]"}`}>
<div className={`text-xs ${mutedText}`}>访问预览(登录参数取自当前 userInfo)</div>
<div className="mt-1 break-all font-mono text-xs">{previewUrl}</div>
</div>
)}
<div className="flex items-center justify-between">
<span className="text-sm font-medium">启用</span>
<Switch checked={form.enabled} onCheckedChange={(v) => patchForm({ enabled: v })} />
</div>
</div>
<DialogFooter>
<Button variant="outline" onClick={() => setDialogOpen(false)} disabled={saving}>
取消
</Button>
<Button onClick={handleSave} disabled={saving}>
{saving ? "保存中…" : editing ? "保存" : "注册"}
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
</div>
);
}
/** 去掉与当前参数类型无关的字段,保持载荷干净。 */
function cleanParams(params: LightAppRouteParam[]): LightAppRouteParam[] {
return params
.filter((p) => p.key.trim())
.map((p) => {
const base: LightAppRouteParam = { key: p.key.trim(), paramType: p.paramType };
if (p.paramType === "login") {
base.source = p.source || "accessToken";
if (base.source === "other") base.customValue = p.customValue ?? "";
} else {
base.themeValue = p.themeValue ?? "";
}
return base;
});
}
function Field({ label, children }: { label: string; children: React.ReactNode }) {
return (
<label className="block space-y-1.5">
<span className="text-sm font-medium">{label}</span>
{children}
</label>
);
}
function ParamRow({
param,
isDark,
onChange,
onRemove,
}: {
param: LightAppRouteParam;
isDark: boolean;
onChange: (patch: Partial<LightAppRouteParam>) => void;
onRemove: () => void;
}) {
const rowClass = isDark
? "border border-[rgba(67,89,124,0.4)] bg-[rgba(8,19,34,0.5)]"
: "border border-[#F0F0F0] bg-[#FAFAFA]";
return (
<div className={`rounded-lg p-2.5 ${rowClass}`}>
<div className="flex flex-wrap items-center gap-2">
<Input
value={param.key}
onChange={(e) => onChange({ key: e.target.value })}
placeholder="参数名 key"
className="h-8 w-[140px]"
/>
<Select value={param.paramType} onValueChange={(v) => onChange({ paramType: v as "login" | "theme" })}>
<SelectTrigger className="h-8 w-[120px]">
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value="login">登录参数</SelectItem>
<SelectItem value="theme">主题参数</SelectItem>
</SelectContent>
</Select>
{param.paramType === "login" ? (
<>
<Select value={param.source || "accessToken"} onValueChange={(v) => onChange({ source: v })}>
<SelectTrigger className="h-8 w-[150px]">
<SelectValue />
</SelectTrigger>
<SelectContent>
{LOGIN_SOURCE_OPTIONS.map((o) => (
<SelectItem key={o.value} value={o.value}>
{o.label}
</SelectItem>
))}
</SelectContent>
</Select>
{param.source === "other" && (
<Input
value={param.customValue ?? ""}
onChange={(e) => onChange({ customValue: e.target.value })}
placeholder="自定义值"
className="h-8 w-[150px]"
/>
)}
</>
) : (
<Input
value={param.themeValue ?? ""}
onChange={(e) => onChange({ themeValue: e.target.value })}
placeholder="主题值,如 dark-blue"
className="h-8 w-[160px]"
/>
)}
<button
type="button"
onClick={onRemove}
className="ml-auto inline-flex h-7 w-7 items-center justify-center rounded-md text-red-500 hover:bg-red-500/10"
title="删除该参数"
>
<X className="h-4 w-4" />
</button>
</div>
{param.paramType === "theme" && (
<div className="mt-1.5 flex flex-wrap items-center gap-1.5 pl-1">
<span className="text-[11px] text-muted-foreground">示例(点击填入,可再修改):</span>
{THEME_EXAMPLE_OPTIONS.map((o) => (
<button
key={o.value}
type="button"
onClick={() => onChange({ themeValue: o.value })}
className={`rounded px-1.5 py-0.5 text-[11px] ${
param.themeValue === o.value
? "bg-primary/15 text-primary"
: "bg-muted text-muted-foreground hover:bg-muted/70"
}`}
>
{o.label}
</button>
))}
</div>
)}
</div>
);
}