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,228 @@
/**
* 轻应用中心(应用管理 / 应用列表)API 客户端 + React Query hooks。
*
* 后端:`/api/light-apps`(见 app/gateway/routers/light_apps.py)。
* 全局共享、无用户隔离;读对所有登录用户开放,写仅 admin。
* snake_case ⇄ camelCase 在此边界收敛;路由参数项本身用 camelCase
* (key/paramType/source/customValue/themeValue),与后端 RouteParam 字段一致,原样透传。
*/
import {
keepPreviousData,
useMutation,
useQuery,
useQueryClient,
} from "@tanstack/react-query";
import { apiFetch } from "@/core/api/fetch-client";
import { getBackendBaseURL } from "@/core/config";
export type LightAppType = "window_open" | "iframe";
export type RouteParamType = "login" | "theme";
/** 路由参数项。登录参数运行时从 localStorage.userInfo 解析;主题参数用 themeValue。 */
export interface LightAppRouteParam {
key: string;
paramType: RouteParamType;
/** 登录参数:accessToken / yUserId / userName / "other"。 */
source?: string | null;
/** 登录参数且 source==="other" 时的字面值。 */
customValue?: string | null;
/** 主题参数的值(dark-blue / red / blue,可改)。 */
themeValue?: string | null;
}
export interface LightApp {
appId: string;
name: string;
description: string | null;
appType: LightAppType;
url: string;
routeParams: LightAppRouteParam[];
/** iframe 挂载的父菜单 id(window_open 为 null)。 */
mountLocation: string | null;
icon: string | null;
enabled: boolean;
sortOrder: number;
createdAt: string | null;
updatedAt: string | null;
}
export interface LightAppInput {
name: string;
description?: string | null;
appType: LightAppType;
url: string;
routeParams: LightAppRouteParam[];
mountLocation?: string | null;
icon?: string | null;
enabled?: boolean;
sortOrder?: number;
}
export interface ListLightAppsParams {
appType?: LightAppType;
mountLocation?: string;
enabledOnly?: boolean;
search?: string;
}
const BASE = () => `${getBackendBaseURL()}/api/light-apps`;
interface ServerRouteParam {
key: string;
paramType: RouteParamType;
source?: string | null;
customValue?: string | null;
themeValue?: string | null;
}
interface ServerApp {
app_id: string;
name: string;
description: string | null;
app_type: LightAppType;
url: string;
route_params: ServerRouteParam[];
mount_location: string | null;
icon: string | null;
enabled: boolean;
sort_order: number;
created_at: string | null;
updated_at: string | null;
}
function toApp(s: ServerApp): LightApp {
return {
appId: s.app_id,
name: s.name,
description: s.description ?? null,
appType: s.app_type,
url: s.url,
routeParams: (s.route_params ?? []).map((p) => ({
key: p.key,
paramType: p.paramType,
source: p.source ?? null,
customValue: p.customValue ?? null,
themeValue: p.themeValue ?? null,
})),
mountLocation: s.mount_location ?? null,
icon: s.icon ?? null,
enabled: s.enabled ?? true,
sortOrder: s.sort_order ?? 0,
createdAt: s.created_at ?? null,
updatedAt: s.updated_at ?? null,
};
}
function toBody(input: Partial<LightAppInput>): Record<string, unknown> {
const body: Record<string, unknown> = {};
if (input.name !== undefined) body.name = input.name;
if (input.description !== undefined) body.description = input.description;
if (input.appType !== undefined) body.app_type = input.appType;
if (input.url !== undefined) body.url = input.url;
if (input.routeParams !== undefined) body.route_params = input.routeParams;
if (input.mountLocation !== undefined) body.mount_location = input.mountLocation;
if (input.icon !== undefined) body.icon = input.icon;
if (input.enabled !== undefined) body.enabled = input.enabled;
if (input.sortOrder !== undefined) body.sort_order = input.sortOrder;
return body;
}
async function readJson<T>(res: Response, ctx: string): Promise<T> {
if (!res.ok) {
const data = await res.json().catch(() => null as unknown);
const detail =
data && typeof data === "object" && "detail" in data
? String((data as { detail: unknown }).detail)
: `${ctx} failed (${res.status})`;
throw new Error(detail);
}
return (await res.json()) as T;
}
export async function listLightApps(params: ListLightAppsParams = {}): Promise<LightApp[]> {
const qs = new URLSearchParams();
if (params.appType) qs.set("app_type", params.appType);
if (params.mountLocation) qs.set("mount_location", params.mountLocation);
if (params.enabledOnly) qs.set("enabled_only", "true");
if (params.search) qs.set("search", params.search);
const query = qs.toString();
const res = await apiFetch(`${BASE()}${query ? `?${query}` : ""}`, { method: "GET" });
const data = await readJson<{ apps: ServerApp[] }>(res, "list light apps");
return (data.apps ?? []).map(toApp);
}
export async function getLightApp(appId: string): Promise<LightApp> {
const res = await apiFetch(`${BASE()}/${encodeURIComponent(appId)}`, { method: "GET" });
return toApp(await readJson<ServerApp>(res, "get light app"));
}
export async function createLightApp(input: LightAppInput): Promise<LightApp> {
const res = await apiFetch(BASE(), {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(toBody(input)),
});
return toApp(await readJson<ServerApp>(res, "create light app"));
}
export async function updateLightApp(
appId: string,
patch: Partial<LightAppInput>,
): Promise<LightApp> {
const res = await apiFetch(`${BASE()}/${encodeURIComponent(appId)}`, {
method: "PUT",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(toBody(patch)),
});
return toApp(await readJson<ServerApp>(res, "update light app"));
}
export async function deleteLightApp(appId: string): Promise<void> {
const res = await apiFetch(`${BASE()}/${encodeURIComponent(appId)}`, { method: "DELETE" });
await readJson<{ success: boolean }>(res, "delete light app");
}
// ── React Query hooks(管理页 / 列表页 / 侧边栏共用缓存) ───────────────────
const LIGHT_APPS_KEY = "light-apps";
export function useLightApps(params: ListLightAppsParams = {}) {
return useQuery({
queryKey: [
LIGHT_APPS_KEY,
"list",
params.appType ?? "",
params.mountLocation ?? "",
params.enabledOnly ?? false,
params.search ?? "",
],
queryFn: () => listLightApps(params),
placeholderData: keepPreviousData,
refetchOnWindowFocus: false,
});
}
export function useLightApp(appId: string | undefined) {
return useQuery({
queryKey: [LIGHT_APPS_KEY, "detail", appId ?? ""],
queryFn: () => getLightApp(appId as string),
enabled: !!appId,
refetchOnWindowFocus: false,
});
}
export function useLightAppActions() {
const queryClient = useQueryClient();
const invalidate = () => queryClient.invalidateQueries({ queryKey: [LIGHT_APPS_KEY] });
return {
create: useMutation({ mutationFn: createLightApp, onSuccess: invalidate }),
update: useMutation({
mutationFn: ({ appId, patch }: { appId: string; patch: Partial<LightAppInput> }) =>
updateLightApp(appId, patch),
onSuccess: invalidate,
}),
remove: useMutation({ mutationFn: deleteLightApp, onSuccess: invalidate }),
};
}
@@ -0,0 +1,43 @@
/**
* 统一的外部 iframe 嵌套页渲染组件。
*
* XK / PG / TY 任务、资源管理等所有「把外部系统嵌进来」的页面共用此组件,
* 只负责把已构造好的 `src` 稳健地渲染出来。URL 构造逻辑收敛在
* `@/core/strategy/external-links`,各业务页只做薄封装。
*
* 关键点 —— `key={src}`:当地址变化(如 XK 在菜单间切换 gopath,只改 hash 片段)时,
* 强制 React 重挂载一个全新的 iframe,触发完整加载,避免「只改 hash 时浏览器不重载、
* 内嵌 SPA 来不及切换路由」导致的页面没变化问题。
*/
import { useTheme } from "@/contexts/ThemeContext";
import "../task-components/css/iframe.css";
interface ExternalIframePageProps {
/** 已构造好的完整地址;为空时展示加载占位(异步取址场景)。 */
src: string;
title?: string;
loadingText?: string;
}
export default function ExternalIframePage({
src,
title,
loadingText = "加载中…",
}: ExternalIframePageProps) {
const { theme } = useTheme();
const isDark = theme === "dark";
if (!src) {
return (
<div className={`flex h-full w-full items-center justify-center text-sm ${isDark ? "text-slate-400" : "text-slate-500"}`}>
{loadingText}
</div>
);
}
return (
<div className="iframe-container">
<iframe key={src} src={src} title={title} className="full-size-iframe" />
</div>
);
}
@@ -5,11 +5,12 @@ import {
getKnowledgeIframeSkin,
} from "@/core/strategy/external-links";
import { requestCrudService } from "@/service/request-axios-service";
import "@/strategy-components/components/task-components/css/strategy-data.css";
import ExternalIframePage from "../common/ExternalIframePage";
const service = requestCrudService;
const KnowledgeBaseResourceManagement: React.FC = () => {
// 知识库地址需异步调接口换取(区别于其它 env 直拼的 iframe 页)。
const [iframeUrl, setIframeUrl] = useState("");
useEffect(() => {
@@ -40,11 +41,7 @@ const KnowledgeBaseResourceManagement: React.FC = () => {
void initIframeUrl();
}, []);
return (
<div className="strategy-data iframe-container">
<iframe src={iframeUrl} className="full-size-iframe" title="知识库资源管理" />
</div>
);
return <ExternalIframePage src={iframeUrl} title="知识库资源管理" />;
};
export default KnowledgeBaseResourceManagement;
@@ -1,20 +1,11 @@
import React, { useEffect, useState } from "react";
import React, { useMemo } from "react";
import { getNetworkActorIframeUrl } from "@/core/strategy/external-links";
import "@/strategy-components/components/task-components/css/strategy-data.css";
import ExternalIframePage from "../common/ExternalIframePage";
const NetworkActorResourceManagement: React.FC = () => {
const [iframeUrl, setIframeUrl] = useState("");
useEffect(() => {
setIframeUrl(getNetworkActorIframeUrl());
}, []);
return (
<div className="strategy-data iframe-container">
<iframe src={iframeUrl} className="full-size-iframe" title="网络xwt资源管理" />
</div>
);
const src = useMemo(() => getNetworkActorIframeUrl(), []);
return <ExternalIframePage src={src} title="网络xwt资源管理" />;
};
export default NetworkActorResourceManagement;
@@ -1,27 +0,0 @@
import React, { useEffect, useState } from "react";
import "./css/iframe.css";
import { useTheme } from "@/contexts/ThemeContext";
const TYURL = import.meta.env.VITE_AIPI_B2ACTOR_URL || "";
const FanganTyPage: React.FC = () => {
const { theme } = useTheme();
const isDark = theme === "dark";
const [iframeUrl, setIframeUrl] = useState("");
useEffect(() => {
initIframeUrl();
}, []);
const initIframeUrl = () => {
const url = `${TYURL}/fromB/toPage?defaultPage=iframeFaty`;
console.log({ iframeUrl: url });
setIframeUrl(url);
};
return (
<div className="iframe-container">
<iframe src={iframeUrl} className="full-size-iframe"></iframe>
</div>
);
};
export default FanganTyPage;
@@ -1,24 +1,16 @@
import { Outlet, useNavigate } from 'react-router-dom';
import React, { useState, useEffect, useRef } from 'react';
import { useSearchParams } from 'react-router-dom';
import React, { useMemo } from "react";
import { getPgIframeUrl } from "@/core/strategy/external-links";
import ExternalIframePage from "../common/ExternalIframePage";
const userInfo = localStorage.getItem('userInfo');
const pgLinkUrl = import.meta.env.VITE_AIPI_PGLINKTO_URL;
interface TaskPgFromProps {
gopath: string
gopath: string;
}
const TaskPgFrom: React.FC<TaskPgFromProps> = ({gopath}) => {
const [pgUrl, setPgUrl] = useState(pgLinkUrl);
useEffect(() => {
if(userInfo) {
const userData = JSON.parse(userInfo);
setPgUrl(`${pgUrl}?access_token=${userData.accessToken}&goPath=${gopath}`);
}
}, [gopath]);
return (
<div className="h-full flex flex-col">
<iframe className="h-[calc(100vh-92px)]" src={pgUrl}></iframe>
</div>
);
}
export default TaskPgFrom
const TaskPgFrom: React.FC<TaskPgFromProps> = ({ gopath }) => {
// 每次从 base 重建(修复原先用状态做模板导致查询串累加的 bug);key={src} 强制重载。
const src = useMemo(() => getPgIframeUrl(gopath), [gopath]);
return <ExternalIframePage src={src} title="PG中任务" />;
};
export default TaskPgFrom;
@@ -0,0 +1,18 @@
import React, { useMemo } from "react";
import { getTyIframeUrl } from "@/core/strategy/external-links";
import ExternalIframePage from "../common/ExternalIframePage";
interface TaskTyFromProps {
/** TY 系统页标识:iframeXdty(行动)/ iframeFaty(方案)/ iframeSysystem(综合)。 */
defaultPage: string;
title?: string;
}
/** TY 中任务统一入口(原 XingdongTy / FanganTy / XXTy 合并)。 */
const TaskTyFrom: React.FC<TaskTyFromProps> = ({ defaultPage, title }) => {
const src = useMemo(() => getTyIframeUrl(defaultPage), [defaultPage]);
return <ExternalIframePage src={src} title={title} />;
};
export default TaskTyFrom;
@@ -1,23 +1,16 @@
import { Outlet, useNavigate } from 'react-router-dom';
import React, { useState, useEffect, useRef } from 'react';
import { useSearchParams } from 'react-router-dom';
const userInfo = localStorage.getItem('userInfo');
const xkLinkUrl = import.meta.env.VITE_AIPI_XKLINKTO_URL;
interface TaskPgFromProps {
gopath: string
import React, { useMemo } from "react";
import { getXkIframeUrl } from "@/core/strategy/external-links";
import ExternalIframePage from "../common/ExternalIframePage";
interface TaskXkFromProps {
gopath: string;
}
const TaskXkFrom: React.FC<TaskPgFromProps> = ({gopath}) => {
const [xkUrl, setXkUrl] = useState(xkLinkUrl);
useEffect(() => {
if(userInfo) {
const userData: any = JSON.parse(userInfo);
setXkUrl(`${xkLinkUrl}${gopath}?accessToken=${userData.accessToken}`);
}
}, [gopath]);
return (
<div className="h-full flex flex-col">
<iframe className="h-[calc(100vh-92px)]" src={xkUrl}></iframe>
</div>
);
}
export default TaskXkFrom
const TaskXkFrom: React.FC<TaskXkFromProps> = ({ gopath }) => {
// gopath 变化(菜单切换)时从 base 重建地址;ExternalIframePage 的 key={src} 会强制重载。
const src = useMemo(() => getXkIframeUrl(gopath), [gopath]);
return <ExternalIframePage src={src} title="XK中任务" />;
};
export default TaskXkFrom;
@@ -1,27 +0,0 @@
import React, { useEffect, useState } from "react";
import "./css/iframe.css";
import { useTheme } from "@/contexts/ThemeContext";
const TYURL = import.meta.env.VITE_AIPI_B2ACTOR_URL || "";
const XXTyPage: React.FC = () => {
const { theme } = useTheme();
const isDark = theme === "dark";
const [iframeUrl, setIframeUrl] = useState("");
useEffect(() => {
initIframeUrl();
}, []);
const initIframeUrl = () => {
const url = `${TYURL}/fromB/toPage?defaultPage=iframeSysystem`;
console.log({ iframeUrl: url });
setIframeUrl(url);
};
return (
<div className="iframe-container">
<iframe src={iframeUrl} className="full-size-iframe"></iframe>
</div>
);
};
export default XXTyPage;
@@ -1,27 +0,0 @@
import React, { useEffect, useState } from "react";
import "./css/iframe.css";
import { useTheme } from "@/contexts/ThemeContext";
const TYURL = import.meta.env.VITE_AIPI_B2ACTOR_URL || "";
const XingdongTyPage: React.FC = () => {
const { theme } = useTheme();
const isDark = theme === "dark";
const [iframeUrl, setIframeUrl] = useState("");
useEffect(() => {
initIframeUrl();
}, []);
const initIframeUrl = () => {
const url = `${TYURL}/fromB/toPage?defaultPage=iframeXdty`;
console.log({ iframeUrl: url });
setIframeUrl(url);
};
return (
<div className="iframe-container">
<iframe src={iframeUrl} className="full-size-iframe"></iframe>
</div>
);
};
export default XingdongTyPage;
@@ -0,0 +1,84 @@
/**
* 轻应用共享常量 + 运行时 URL 构造(管理页预览 / 列表页跳转 / iframe 宿主共用)。
*
* 登录参数运行时从 `localStorage.getItem("userInfo")`(JSON) 解析;主题参数用配置值。
*/
import type { LightApp, LightAppRouteParam } from "@/strategy-components/api/light-apps";
/** iframe 可挂载的父菜单(取自 core/page-layout/sidebar-menu.ts 的现有菜单 id)。 */
export const MOUNT_OPTIONS: { label: string; value: string }[] = [
{ label: "XK中任务", value: "xk-center-task" },
{ label: "PG中任务", value: "pg-center-task" },
{ label: "TY中任务", value: "ty-center-task" },
{ label: "资源管理", value: "resource-management" },
];
export function mountLabel(value: string | null | undefined): string {
if (!value) return "";
return MOUNT_OPTIONS.find((o) => o.value === value)?.label ?? value;
}
/** 登录参数可选来源;值均可在 userInfo 中取到,"other" 表示自填。 */
export const LOGIN_SOURCE_OPTIONS: { label: string; value: string }[] = [
{ label: "accessToken", value: "accessToken" },
{ label: "yUserId", value: "yUserId" },
{ label: "userName", value: "userName" },
{ label: "其他(自定义值)", value: "other" },
];
/** 主题参数示例值(深蓝 / 红 / 蓝),可改。 */
export const THEME_EXAMPLE_OPTIONS: { label: string; value: string }[] = [
{ label: "深蓝色 dark-blue", value: "dark-blue" },
{ label: "红色 red", value: "red" },
{ label: "蓝色 blue", value: "blue" },
];
/** 读取并解析 localStorage 中的 userInfo。 */
export function readUserInfo(): Record<string, unknown> {
try {
const raw = localStorage.getItem("userInfo");
if (!raw) return {};
const parsed = JSON.parse(raw);
return parsed && typeof parsed === "object" ? (parsed as Record<string, unknown>) : {};
} catch {
return {};
}
}
/** 解析单个路由参数在运行时的取值。 */
export function resolveRouteParamValue(
param: LightAppRouteParam,
userInfo: Record<string, unknown> = readUserInfo(),
): string {
if (param.paramType === "theme") {
return param.themeValue ?? "";
}
// login
if (param.source === "other") {
return param.customValue ?? "";
}
if (param.source) {
const value = userInfo[param.source];
return value == null ? "" : String(value);
}
return "";
}
/**
* 构造应用的最终访问 URL:在 `app.url` 上追加解析后的路由参数查询串。
*
* 兼容 hash 路由地址(如 `https://x#/route`)—— 管理员粘贴完整地址,参数自动追加在末尾,
* 落在 hash 路由的 query 上(与现有 XK/PG 页面 `?accessToken=` 拼接方式一致)。
*/
export function buildLightAppUrl(
app: Pick<LightApp, "url" | "routeParams">,
userInfo: Record<string, unknown> = readUserInfo(),
): string {
const pairs = (app.routeParams ?? [])
.filter((p) => p.key)
.map((p) => `${encodeURIComponent(p.key)}=${encodeURIComponent(resolveRouteParamValue(p, userInfo))}`);
if (pairs.length === 0) return app.url;
const sep = app.url.includes("?") ? "&" : "?";
return `${app.url}${sep}${pairs.join("&")}`;
}