Commit c75b40b2 by liimin

视觉优化

1 parent e58bfa56
Pipeline #446 for c75b40b2 failed in 0 seconds
import { useEffect, useReducer, useRef, useState } from 'react'; import { useEffect, useReducer, useRef, useState } from 'react';
import { useLocation, useNavigate } from 'react-router-dom'; import { useLocation, useNavigate } from 'react-router-dom';
import { Button, Empty } from 'antd'; import { Button, Empty } from 'antd';
import { bus, destroyApp, startApp } from 'wujie'; import { bus } from 'wujie';
import { BrandLoader } from '@uj/biz'; import { BrandLoader } from '@uj/biz';
import { busEvents } from '@uj/contracts'; import { busEvents } from '@uj/contracts';
import { entryOf } from './subapps'; import { entryOf } from './subapps';
import { forgetReady, isReady, markReady } from './subapp-handshake'; import { forgetReady, isReady, markReady } from './subapp-handshake';
import { createSubAppProps } from './subapp-props'; import { createSubAppProps } from './subapp-props';
import { logoutEverything } from './subapp-lifecycle'; import { logoutEverything } from './subapp-lifecycle';
import { destroyAppLocked, restartAppLocked, startAppLocked } from './wujie-lifecycle';
/** /**
* 同一宿主元素 + 同一子应用只准启动一次(el -> 已启动的 shortName)。 * 同一宿主元素 + 同一子应用只准启动一次(el -> 已启动的 shortName)。
* *
* HMR / 快速来回切路由会让两个 startApp(同名) 几乎同时进入,第二个 active() * 真正的并发闸在 wujie-lifecycle.ts(按 shortName 串行)。这里这层只挡
* 在第一个 iframe 注入 iframeWindow.__WUJIE 之前就跑 syncUrlToWindow, * 「同一 el 的 effect 重入」,避免 StrictMode 下重复 startApp。
* 读到 undefined 直接 TypeError。用宿主 el 作键挡掉重入。
* *
* 键里必须带 shortName:`<Routes>` 在 /store/* 与 /system/* 之间切换时组件类型没变, * 键里必须带 shortName:`<Routes>` 在 /store/* 与 /system/* 之间切换时组件类型没变,
* React 复用同一实例,hostRef 还是同一个 div;只按 el 记会让第二个子应用永远 * React 复用同一实例,hostRef 还是同一个 div;只按 el 记会让第二个子应用永远
...@@ -22,6 +22,14 @@ import { logoutEverything } from './subapp-lifecycle'; ...@@ -22,6 +22,14 @@ import { logoutEverything } from './subapp-lifecycle';
*/ */
const startedOn = new WeakMap<HTMLElement, string>(); const startedOn = new WeakMap<HTMLElement, string>();
type Phase = 'loading' | 'ready' | 'failed';
function errorText(err: unknown): string {
if (err instanceof Error) return err.message;
if (typeof err === 'string') return err;
return '未知错误';
}
/** /**
* 通用子应用挂载点。 * 通用子应用挂载点。
* *
...@@ -45,75 +53,102 @@ export function MicroApp({ shortName, route }: { shortName: string; route: strin ...@@ -45,75 +53,102 @@ export function MicroApp({ shortName, route }: { shortName: string; route: strin
// 就绪真源是 subapp-handshake 那张表;本地 state 只当「表变了,再渲染一次」的信号。 // 就绪真源是 subapp-handshake 那张表;本地 state 只当「表变了,再渲染一次」的信号。
// 不写成布尔 useState:两个子应用切换时复用同一组件实例,本地布尔会带着上一个的值过来。 // 不写成布尔 useState:两个子应用切换时复用同一组件实例,本地布尔会带着上一个的值过来。
const [, announce] = useReducer((n: number) => n + 1, 0); const [, announce] = useReducer((n: number) => n + 1, 0);
const ready = isReady(shortName); const [phase, setPhase] = useState<Phase>('loading');
const [failed, setFailed] = useState(false); const [message, setMessage] = useState('');
const [attempt, setAttempt] = useState(0); const [attempt, setAttempt] = useState(0);
const failed = phase === 'failed';
// 就绪真源仍是握手表:alive 切回来时表已就绪,不能因为本地 phase 重置就又盖一层 loading。
const ready = isReady(shortName) && !failed;
const retry = () => { const retry = () => {
const el = hostRef.current; const el = hostRef.current;
if (el) startedOn.delete(el); if (el) startedOn.delete(el);
try { // 先排销毁再让 effect 排启动:两者同一把锁,顺序确定,不会撞上 __WUJIE.sync。
destroyApp(shortName); void destroyAppLocked(shortName).catch(() => {});
} catch {
/* 销毁失败不影响重建 */
}
forgetReady(shortName); forgetReady(shortName);
setFailed(false); setMessage('');
setPhase('loading');
setAttempt((n) => n + 1); setAttempt((n) => n + 1);
}; };
useEffect(() => { useEffect(() => {
const el = hostRef.current; const el = hostRef.current;
if (!el) return; if (!el) return;
if (!entry) {
setFailed(true);
return;
}
if (startedOn.get(el) === shortName) return;
let cancelled = false; let cancelled = false;
let retried = false; let retried = false;
let timer = 0;
const launch = () => { /** 失败即终态,只有 retry / 新一次挂载能清掉;避免后来到的 reject 把错误态抹回 loading。 */
const fail = (err: unknown) => {
if (cancelled) return;
window.clearTimeout(timer);
startedOn.delete(el);
forgetReady(shortName);
setMessage(errorText(err));
setPhase('failed');
announce();
void destroyAppLocked(shortName).catch(() => {});
};
const armTimeout = () => {
window.clearTimeout(timer);
timer = window.setTimeout(() => {
// alive 复用时握手表还留着上次会话的 ready,不必等新一次上报。
if (isReady(shortName)) return;
fail(new Error('启动超时(15 秒),子应用未上报就绪。请检查子应用服务与浏览器控制台。'));
}, 15_000);
};
if (!entry) {
fail(new Error('未找到子应用入口。请检查 manifest.json 或 VITE_<SHORT>_SUBAPP_URL 配置。'));
return () => {
cancelled = true;
window.clearTimeout(timer);
};
}
const options = {
name: shortName,
url: entry,
el,
// 全仓唯一的一份请求能力经 props 注入;子应用不打包 axios / PEM / VITE_*。
props: createSubAppProps({ shortName, page: subPath, navigate }),
// 子应用实例由 wujie 缓存管理,路由切走不销毁、切回即激活。
alive: true,
// 主应用 URL 是唯一真源,不把子应用路由写进 query(否则菜单 selectedKey 要重写)。
sync: false,
};
const launch = (fresh: boolean) => {
if (cancelled) return; if (cancelled) return;
startedOn.set(el, shortName); startedOn.set(el, shortName);
setFailed(false); setMessage('');
void startApp({ setPhase('loading');
name: shortName, armTimeout();
url: entry, const task = fresh ? restartAppLocked(options) : startAppLocked(options);
el, void task.catch((err: unknown) => {
// 全仓唯一的一份请求能力经 props 注入;子应用不打包 axios / PEM / VITE_*。 if (cancelled) return;
props: createSubAppProps({ shortName, page: subPath, navigate }),
// 子应用实例由 wujie 缓存管理,路由切走不销毁、切回即激活。
alive: true,
// 主应用 URL 是唯一真源,不把子应用路由写进 query(否则菜单 selectedKey 要重写)。
sync: false,
}).catch((err) => {
console.error(`[wujie] 子应用 ${shortName} 启动失败:`, err); console.error(`[wujie] 子应用 ${shortName} 启动失败:`, err);
startedOn.delete(el); startedOn.delete(el);
forgetReady(shortName); forgetReady(shortName);
announce(); announce();
try { // 清掉可能已毒化的同名 sandbox 后自动重试一次;重试整体进闸,
destroyApp(shortName); // 不再出现 destroy 未落地就 startApp 的 __WUJIE.sync 竞态。
} catch { if (!retried) {
/* 销毁失败不影响后续自愈 */
}
// 清掉可能已毒化的同名 sandbox 后自动重试一次;仅一次,避免坏缓存无限循环。
if (!retried && !cancelled) {
retried = true; retried = true;
launch(); launch(true);
} else if (!cancelled) { } else {
setFailed(true); fail(err);
} }
}); });
}; };
launch(); // 已启动过(alive 切回来)就不重复 startApp;未启动才发。
// 跳过启动也要挂超时:StrictMode 首个 effect 被取消时会清掉自己的计时器,
// startApp 可能既不 resolve 也不 reject(iframe 静默失败),没有计时器用户会永远转圈。 // 否则第二个实例会无限停在 loading。
const timer = window.setTimeout(() => { if (startedOn.get(el) !== shortName) launch(false);
if (!cancelled && !isReady(shortName)) setFailed(true); else armTimeout();
}, 15_000);
return () => { return () => {
cancelled = true; cancelled = true;
...@@ -129,7 +164,8 @@ export function MicroApp({ shortName, route }: { shortName: string; route: strin ...@@ -129,7 +164,8 @@ export function MicroApp({ shortName, route }: { shortName: string; route: strin
// 主应用侧必须用 wujie 模块级导出的 bus:window.$wujie 只存在于子应用 iframe。 // 主应用侧必须用 wujie 模块级导出的 bus:window.$wujie 只存在于子应用 iframe。
const onReady = () => { const onReady = () => {
markReady(shortName); markReady(shortName);
setFailed(false); setMessage('');
setPhase('ready');
announce(); announce();
bus.$emit(events.navigate, subPath); bus.$emit(events.navigate, subPath);
}; };
...@@ -158,9 +194,7 @@ export function MicroApp({ shortName, route }: { shortName: string; route: strin ...@@ -158,9 +194,7 @@ export function MicroApp({ shortName, route }: { shortName: string; route: strin
<div ref={hostRef} style={{ width: '100%', height: '100%' }} /> <div ref={hostRef} style={{ width: '100%', height: '100%' }} />
{!ready && !failed && entry && ( {!ready && !failed && entry && (
<div className="uj-mfe-loading"> <div className="uj-mfe-loading" role="status" aria-live="polite">
{/* 子应用接入是「门店覆盖网络」的延伸,加载图标沿用登录页的基站双环 +
扫描弧 + 青绿脉冲,不再用 antd 通用转圈(见 @uj/biz 的 BrandLoader)。 */}
<div className="uj-mfe-loading__spinner"> <div className="uj-mfe-loading__spinner">
<BrandLoader /> <BrandLoader />
<span className="uj-mfe-loading__label">正在接入…</span> <span className="uj-mfe-loading__label">正在接入…</span>
...@@ -168,15 +202,16 @@ export function MicroApp({ shortName, route }: { shortName: string; route: strin ...@@ -168,15 +202,16 @@ export function MicroApp({ shortName, route }: { shortName: string; route: strin
</div> </div>
)} )}
{(!entry || failed) && ( {failed && (
<div className="uj-mfe-loading"> <div className="uj-mfe-loading uj-mfe-loading--error" role="alert">
<Empty description={entry ? '子应用加载失败' : '未找到子应用入口'} /> <Empty description={entry ? '子应用启动失败' : '未找到子应用入口'} />
<div style={{ marginTop: 12, fontSize: 13, color: '#56697d' }}> <div className="uj-mfe-loading__error-message">{message}</div>
<div className="uj-mfe-loading__hint">
{entry {entry
? '可能是子应用未启动或网络不可用。可以先重试;多次失败请刷新页面。' ? '可先重试;若反复失败,请刷新页面并查看浏览器控制台的子应用报错。'
: `请为 ${shortName} 配置 package.json 的 uj.entry 或运行时 manifest。`} : `请为 ${shortName} 配置 manifest.json 或 package.json 的 uj.entry。`}
</div> </div>
<div style={{ display: 'flex', gap: 8, marginTop: 16 }}> <div className="uj-mfe-loading__actions">
{entry && ( {entry && (
<Button type="primary" onClick={retry}> <Button type="primary" onClick={retry}>
重试 重试
......
/**
* 工作台右下角底图(纯装饰:aria-hidden + pointer-events:none,无状态)。
*
* 视觉语言与登录页 uj-login-coverage 同源——透视纵深点阵、链节点虚线、
* 以基站为心的扫描弧与双层环、青绿脉冲核——配色从登录页的深空反转为
* 浅底上的品牌蓝低透明度水印:贴合登录页主题,又不压过内容卡片,
* 只在右侧与下部的空白处透出来。
* 固定坐标 + 固定种子伪随机(分布一致、非真实数据);脉冲动画尊重
* prefers-reduced-motion(见 design.css 的 .uj-wb-pulse)。
*/
const W = 640;
const H = 520;
const HORIZON = 74; // 远处地平线 y
const NEAR = 498; // 近处地面 y
const VP = { x: 300, y: HORIZON - 6 }; // 消失点
const BASE = { x: 462, y: 428 }; // 近景基站(右下,贴工作台空白区)
const AXIS_TOP = { x: 252, y: 106 }; // 链节点纵深起点
function makeRand(seed: number) {
let s = seed % 233280;
return () => {
s = (s * 9301 + 49297) % 233280;
return s / 233280;
};
}
const rand = makeRand(73);
const lerp = (a: number, b: number, t: number) => a + (b - a) * t;
type Dot = { x: number; y: number; r: number; op: number };
// 透视点阵:4 排 × 8 列,约 55% 保留;越近越大越亮,整体压低做背景层
const DOTS: Dot[] = (() => {
const out: Dot[] = [];
const rows = [0.16, 0.4, 0.64, 0.88];
const cols = [-0.8, -0.58, -0.36, -0.14, 0.1, 0.32, 0.54, 0.76];
for (const t of rows) {
const pp = Math.pow(t, 0.82);
const y = lerp(HORIZON, NEAR, pp);
const spread = lerp(60, 300, pp);
for (const c of cols) {
if (rand() < 0.55) {
out.push({
x: VP.x + c * spread + (rand() - 0.5) * 14,
y: y + (rand() - 0.5) * 8,
r: lerp(0.9, 2.6, t),
op: lerp(0.07, 0.2, t),
});
}
}
}
return out;
})();
// 链节点:沿纵深逐级放大/提亮,末端不重复(那里是基站)
const CHAIN = Array.from({ length: 4 }, (_, i) => {
const pp = Math.pow((i + 1) / 5, 0.82);
return {
x: lerp(AXIS_TOP.x, BASE.x, pp),
y: lerp(AXIS_TOP.y, BASE.y, pp),
r: lerp(1.2, 4, pp),
op: lerp(0.14, 0.4, pp),
};
});
const CHAIN_DASH = [...CHAIN.slice(-2), { x: BASE.x, y: BASE.y }];
// 2 道扫描弧:以基站为心向上展开,两端渐隐由 stroke 渐变承担
const ARCS = [150, 224].map((r) => {
const a0 = Math.PI * 1.05;
const a1 = Math.PI * 1.95;
return {
r,
d: `M ${BASE.x + r * Math.cos(a0)} ${BASE.y + r * Math.sin(a0)} A ${r} ${r} 0 0 1 ${BASE.x + r * Math.cos(a1)} ${BASE.y + r * Math.sin(a1)}`,
};
});
// 2 条极淡经线:从近处地面两侧收向消失点
const MERIDIANS = [-0.62, 0.62].map((lx) => ({
x1: VP.x + lx * 300,
y1: NEAR,
x2: VP.x,
y2: VP.y,
}));
// 上方留白区 6 颗极淡星点
const STARS = Array.from({ length: 6 }, () => ({
x: 40 + rand() * (W - 80),
y: 14 + rand() * (HORIZON * 0.5),
r: 0.7 + rand() * 0.9,
op: 0.08 + rand() * 0.08,
}));
const CORE_R = 4.5; // 青绿脉冲/实心核半径
export function WorkbenchBackdrop() {
return (
<div className="uj-wb-backdrop" aria-hidden="true">
<svg
viewBox={`0 0 ${W} ${H}`}
width="100%"
height="auto"
preserveAspectRatio="xMidYMax meet"
focusable="false"
>
<defs>
{/* 大光场:以基站为心,中心 0.12 → 边缘 0 */}
<radialGradient id="ujWbFocus" cx="50%" cy="50%" r="50%">
<stop offset="0%" stopColor="#2b5ce6" stopOpacity="0.12" />
<stop offset="55%" stopColor="#2b5ce6" stopOpacity="0.05" />
<stop offset="100%" stopColor="#2b5ce6" stopOpacity="0" />
</radialGradient>
{/* 基站中层辉光 */}
<radialGradient id="ujWbGlow" cx="50%" cy="50%" r="50%">
<stop offset="0%" stopColor="#5b8def" stopOpacity="0.18" />
<stop offset="100%" stopColor="#5b8def" stopOpacity="0" />
</radialGradient>
{/* 经线垂直渐隐:远处化掉不形成硬线 */}
<linearGradient id="ujWbMeridian" x1="0" y1="0" x2="0" y2="1">
<stop offset="0%" stopColor="#2b5ce6" stopOpacity="0.1" />
<stop offset="100%" stopColor="#2b5ce6" stopOpacity="0" />
</linearGradient>
</defs>
{/* 明暗底层:以基站为心的大光场 */}
<ellipse cx={BASE.x} cy={BASE.y - 30} rx={330} ry={250} fill="url(#ujWbFocus)" />
{/* 2 道扫描弧(两端渐隐) */}
<g fill="none" stroke="#2b5ce6" strokeWidth="1">
{ARCS.map((arc) => (
<path key={arc.r} d={arc.d} strokeOpacity="0.1" />
))}
</g>
{/* 2 条极淡经线收向消失点 */}
<g fill="none" stroke="url(#ujWbMeridian)" strokeWidth="0.8">
{MERIDIANS.map((m, i) => (
<line key={i} x1={m.x1} y1={m.y1} x2={m.x2} y2={m.y2} />
))}
</g>
{/* 背景点阵:近大远小、近亮远淡 */}
<g fill="#2b5ce6">
{DOTS.map((dot, i) => (
<circle key={i} cx={dot.x} cy={dot.y} r={dot.r} fillOpacity={dot.op} />
))}
</g>
{/* 链节点虚线:末段渐淡接入基站 */}
<g fill="none" stroke="#5b8def" strokeWidth="1.1" strokeDasharray="4 5" strokeLinecap="round">
{CHAIN_DASH.slice(1).map((c, i) => (
<line
key={i}
x1={CHAIN_DASH[i].x}
y1={CHAIN_DASH[i].y}
x2={c.x}
y2={c.y}
strokeOpacity={i === 1 ? 0.12 : 0.2}
/>
))}
</g>
{/* 链节点 */}
<g fill="#5b8def">
{CHAIN.map((c, i) => (
<circle key={i} cx={c.x} cy={c.y} r={c.r} fillOpacity={c.op} />
))}
</g>
{/* 基站:大光场 + 辉光 + 双层环 + 青绿脉冲 + 实心核 */}
<g>
<circle cx={BASE.x} cy={BASE.y} r={96} fill="url(#ujWbGlow)" />
<circle cx={BASE.x} cy={BASE.y} r={44} fill="none" stroke="#2b5ce6" strokeOpacity="0.16" strokeWidth="1.1" />
<circle cx={BASE.x} cy={BASE.y} r={25} fill="none" stroke="#2b5ce6" strokeOpacity="0.26" strokeWidth="1.2" />
<circle
className="uj-wb-pulse"
cx={BASE.x}
cy={BASE.y}
r={CORE_R}
fill="none"
stroke="#2de2c4"
strokeWidth="1.2"
vectorEffect="non-scaling-stroke"
/>
<circle cx={BASE.x} cy={BASE.y} r={CORE_R} fill="#1fe0c8" fillOpacity="0.8" />
</g>
{/* 上方 6 颗极淡星点 */}
<g fill="#2b5ce6">
{STARS.map((star, i) => (
<circle key={i} cx={star.x} cy={star.y} r={star.r} fillOpacity={star.op} />
))}
</g>
</svg>
</div>
);
}
/**
* 工作台扩展项注册表(机制保留,首页当前不渲染)。
*
* 2026-11-16 三次重设计后,工作台按使用者视角重做,只呈现「今天 / 我是谁 /
* 账号能做什么」。「扩展」是工程侧概念,终端用户既不懂也不关心,因此页面上
* 不再出现扩展位与空态卡片。
*
* 本文件保留为后续接入点:若将来确有要在首页面向用户呈现的能力,按
* WorkbenchExtension 登记,并以用户看得懂的命名与文案渲染(如「更多服务」),
* 不要在页面文案里出现「扩展 / 主壳 / 会话」这类词。
*/
import type { ReactNode } from 'react';
export interface WorkbenchExtension {
/** 稳定 key,同时作为列表项标识 */
id: string;
title: string;
description?: string;
icon?: ReactNode;
/** 扩展主体;不提供时只渲染标题与说明 */
content?: ReactNode;
}
/** 只读快照:变更请走 registerWorkbenchExtension,避免页面持有可写数组。 */
const extensions: WorkbenchExtension[] = [];
export function workbenchExtensions(): readonly WorkbenchExtension[] {
return extensions;
}
export function registerWorkbenchExtension(extension: WorkbenchExtension): void {
if (extensions.some((item) => item.id === extension.id)) return;
extensions.push(extension);
}
import { bus, destroyApp } from 'wujie'; import { bus } from 'wujie';
import { busEvents } from '@uj/contracts'; import { busEvents } from '@uj/contracts';
import { collectRouteDefs } from './dynamic-subapps'; import { collectRouteDefs } from './dynamic-subapps';
import { forgetReady, isReady } from './subapp-handshake'; import { forgetReady, isReady } from './subapp-handshake';
import { destroyAppLocked } from './wujie-lifecycle';
import { useAppStore } from '@/store/useAppStore'; import { useAppStore } from '@/store/useAppStore';
import { auth, menu as menuApi } from '@/api'; import { auth, menu as menuApi } from '@/api';
...@@ -36,7 +37,7 @@ export async function logoutEverything(navigate: (path: string) => void): Promis ...@@ -36,7 +37,7 @@ export async function logoutEverything(navigate: (path: string) => void): Promis
if (isReady(s.shortName)) bus.$emit(busEvents(s.shortName).logout); if (isReady(s.shortName)) bus.$emit(busEvents(s.shortName).logout);
forgetReady(s.shortName); forgetReady(s.shortName);
// 不阻塞登出导航:销毁是异步的,子应用尚未启动时失败可忽略。 // 不阻塞登出导航:销毁是异步的,子应用尚未启动时失败可忽略。
destroyApp(s.shortName).catch(() => {}); void destroyAppLocked(s.shortName).catch(() => {});
} }
navigate('/login'); navigate('/login');
......
...@@ -22,3 +22,33 @@ ...@@ -22,3 +22,33 @@
font-size: 12px; font-size: 12px;
letter-spacing: 0.5px; letter-spacing: 0.5px;
} }
/* 失败态:错误信息必须可读、可操作,不能退化成无限 loading。 */
.uj-mfe-loading--error {
gap: 0;
padding: var(--uj-space-6);
text-align: center;
}
.uj-mfe-loading__error-message {
max-width: 640px;
margin-top: var(--uj-space-4);
padding: var(--uj-space-3) var(--uj-space-4);
border: 1px solid var(--uj-error-border, #f8cfd1);
border-radius: var(--uj-radius-md, 6px);
background: var(--uj-error-soft, #fdedee);
color: var(--uj-error, #e5484d);
font-size: var(--uj-font-md, 14px);
line-height: 1.6;
overflow-wrap: anywhere;
}
.uj-mfe-loading__hint {
margin-top: var(--uj-space-3);
color: var(--uj-text-3);
font-size: var(--uj-font-sm, 13px);
line-height: 1.6;
}
.uj-mfe-loading__actions {
display: flex;
gap: var(--uj-space-2);
margin-top: var(--uj-space-5);
}
import { destroyApp, refreshApp, startApp, type startOptions } from 'wujie';
/**
* 同名子应用的 wujie 操作串行闸。
*
* wujie@2.1.0 的 sync.js 里 `iframeWindow.__WUJIE.sync` 是无保护解引用:
* 只要两个 startApp(同名) 并发,或 destroyApp 还没落地就再次 startApp,
* 第二个 active() 就会在沙箱注入 __WUJIE 之前读到 undefined,抛
* `Cannot read properties of undefined (reading 'sync')`。
*
* MicroApp 的宿主 WeakMap 只能挡住「同一个 el 重入」,挡不住:
* - StrictMode / 快速切路由产生的新 el 并发启动同名应用;
* - 失败自愈里 un-await 的 destroyApp 与紧随其后的 startApp。
* 因此把 start / destroy / refresh 统一收进「按 shortName 排队」的闸:
* 同一名字在任意时刻只有一个 wujie 操作在飞,后续操作等前一个 settle 再执行。
*/
const pending = new Map<string, Promise<unknown>>();
/** 把任务接在该名字的队尾;前一个失败不阻断后一个(先吞掉再执行)。 */
function withAppLock<T>(name: string, task: () => Promise<T>): Promise<T> {
const previous = pending.get(name) ?? Promise.resolve();
const next = previous.then(task, task);
pending.set(name, next);
// 清理必须在调用方拿到 reject 之前完成,保证 catch 里发起的重启已排到下一轮。
const release = () => {
if (pending.get(name) === next) pending.delete(name);
};
void next.then(release, release);
return next;
}
/** 首次启动 / alive 复用激活:进闸。 */
export function startAppLocked(options: startOptions): Promise<unknown> {
return withAppLock(options.name, () => startApp(options));
}
/** 正常销毁:进闸,避免与正在进行的启动互相踩踏。 */
export function destroyAppLocked(name: string): Promise<void> {
return withAppLock(name, () => destroyApp(name));
}
/**
* 失败自愈:wujie 自带的 refreshApp 就是「先 destroy 再 start」,
* 放进同一把锁后整段原子执行;拆成两次进闸会让别的路由切换插队再起一次。
*/
export function restartAppLocked(options: startOptions): Promise<unknown> {
return withAppLock(options.name, () => refreshApp(options));
}
import { createClient, createFetchSender, type ResponseOptions } from '@uj/api-core'; import { createClient, createFetchSender, type ResponseOptions } from '@uj/api-core';
import { getLoginSession } from '@/access'; import { getLoginSession } from '@/access';
import { useAppStore } from '@/store/useAppStore';
import { loadUsedcarRemoteConfig, type UsedcarRopBlock } from './config-center'; import { loadUsedcarRemoteConfig, type UsedcarRopBlock } from './config-center';
/** /**
...@@ -158,7 +159,10 @@ function devSessionOverride(): string { ...@@ -158,7 +159,10 @@ function devSessionOverride(): string {
} }
} }
function hostOptions(): Pick<ClientOptions, 'sender' | 'session' | 'errorHandler'> { function hostOptions(): Pick<
ClientOptions,
'sender' | 'session' | 'errorHandler' | 'onLoginRequired'
> {
return { return {
sender: directSender(), sender: directSender(),
/** /**
...@@ -204,6 +208,24 @@ function hostOptions(): Pick<ClientOptions, 'sender' | 'session' | 'errorHandler ...@@ -204,6 +208,24 @@ function hostOptions(): Pick<ClientOptions, 'sender' | 'session' | 'errorHandler
}, },
}, },
errorHandler: (error) => { throw error.cause ?? error; }, errorHandler: (error) => { throw error.cause ?? error; },
/**
* 登录态失效统一出口(GSC / ROP 信封的登出码:20 缺会话、21 登录过期)。
*
* 门面在命中 logoutCodes 时先回调这里,再按 throwOnError 抛错。原先本域没有装配该回调,
* 于是 code=21 只被抛成一个普通 RequestError,React Query 落到 isError 分支,
* 页面把「[21] 登录失效,请重新登录」当成一条列表加载失败来展示,用户停在原页。
*
* 这里复用兼容层 useAppStore.logout():它只广播 <shortName>:logout-host,由主壳
* logoutEverything 双清令牌 / 会话、销毁全部 wujie 实例并 navigate('/login');
* 子应用绝不自己清 token(真源在主壳),与 points 子应用的 onLoginRequired 同一套路。
*
* 并发兜底:同一时刻多条请求都会命中 21,logout() 会置 loggedIn=false;
* 后续回调据此跳过,避免重复广播登出 / 重复导航。重新登录后 loggedIn 恢复为 true。
*/
onLoginRequired: () => {
if (!useAppStore.getState().loggedIn) return;
useAppStore.getState().logout();
},
}; };
} }
......
/* 数据看板时间筛选:分段按钮 + 自定义区间。
色值 / 间距 / 圆角 / 字号全部引用 --uj-* 令牌,与全站主题同一套。 */
.uj-period {
display: inline-flex;
align-items: center;
flex-wrap: wrap;
gap: var(--uj-space-3);
}
/* 分段控件:一条浅底容器把互斥档位收在一起,选中档用主色实底。 */
.uj-period__group {
display: inline-flex;
align-items: center;
padding: var(--uj-space-1);
background: var(--uj-surface-3);
border: 1px solid var(--uj-border);
border-radius: var(--uj-radius-md);
}
.uj-period__item {
appearance: none;
min-height: 28px;
padding: 0 var(--uj-space-3);
border: 1px solid transparent;
border-radius: var(--uj-radius-sm);
background: transparent;
color: var(--uj-text-2);
font-size: var(--uj-font-sm);
line-height: 1.5;
cursor: pointer;
transition: background-color var(--duration-fast, 150ms) var(--easing-standard, ease),
color var(--duration-fast, 150ms) var(--easing-standard, ease);
}
.uj-period__item:hover:not(.is-active):not(:disabled) {
background: var(--uj-surface);
color: var(--uj-text-1);
border-color: var(--uj-border-strong);
}
.uj-period__item.is-active {
background: var(--uj-primary);
color: var(--uj-on-primary);
font-weight: 500;
box-shadow: var(--uj-shadow-card);
}
.uj-period__item:focus-visible {
outline: 2px solid var(--uj-primary);
outline-offset: 2px;
}
.uj-period__item:disabled {
opacity: 0.6;
cursor: not-allowed;
pointer-events: none;
}
.uj-period__range {
width: 240px;
}
@media (max-width: 700px) {
.uj-period {
width: 100%;
}
.uj-period__range {
flex: 1 1 100%;
width: 100%;
}
}
@media (prefers-reduced-motion: reduce) {
.uj-period__item {
transition: none;
}
}
/**
* 数据看板统一时间筛选组件。
*
* 统一「今日 / 昨日 / 本月 / 上月」这组互斥快捷档 + 可选自定义区间,
* 替代原先散落在指标卡筛选行、两张趋势卡表头里的三份裸 <button>:
* 三处各自写一遍 active 判断、各写一套不合规的 CSS,样式与系统主题脱节。
*
* 外观只取 @uj/design-tokens 的 --uj-* 语义令牌,不写死色值。
* 状态矩阵:default / hover / active(aria-pressed) / focus-visible / disabled。
*/
import type { Dayjs } from 'dayjs';
import { UDatePicker } from '@uj/ui';
import './PeriodFilter.css';
export interface PeriodOption<T extends string | number> {
value: T;
label: string;
disabled?: boolean;
}
export interface PeriodFilterProps<T extends string | number> {
/** 当前选中的快捷档;传 null 表示「自定义区间」或尚未选择 */
value: T | null;
options: ReadonlyArray<PeriodOption<T>>;
onChange: (value: T) => void;
/** 自定义区间值;不传则不渲染区间选择器 */
range?: [Dayjs, Dayjs] | null;
onRangeChange?: (range: [Dayjs, Dayjs] | null) => void;
/** 无障碍名称:屏幕阅读器用它区分同页多个筛选组 */
ariaLabel?: string;
}
export function PeriodFilter<T extends string | number>({
value,
options,
onChange,
range,
onRangeChange,
ariaLabel = '时间筛选',
}: PeriodFilterProps<T>) {
const hasRange = Array.isArray(range) && range.length === 2;
const showRange = onRangeChange !== undefined;
function pick(option: PeriodOption<T>): void {
if (option.disabled) return;
// 选中快捷档即让出自定义区间,两条输入互斥。
if (hasRange) onRangeChange?.(null);
onChange(option.value);
}
return (
<div className="uj-period" role="group" aria-label={ariaLabel}>
<div className="uj-period__group">
{options.map((option) => {
const active = !hasRange && value === option.value;
return (
<button
type="button"
key={String(option.value)}
className={`uj-period__item${active ? ' is-active' : ''}`}
aria-pressed={active}
disabled={option.disabled}
onClick={() => pick(option)}
>
{option.label}
</button>
);
})}
</div>
{showRange ? (
<UDatePicker.RangePicker
className="uj-period__range"
placeholder={['开始日期', '结束日期']}
value={range ?? null}
onChange={(next) =>
onRangeChange?.(
next && next[0] && next[1] ? [next[0], next[1]] : null,
)
}
allowClear
/>
) : null}
</div>
);
}
/* 指标卡样式与看板页面同目录,组件只服务本模块;色值全部取 --uj-* 语义令牌。 */
.uc-stat {
display: flex;
flex-direction: column;
gap: var(--uj-space-2);
min-height: 120px;
padding: var(--uj-space-4) var(--uj-space-5);
border: 1px solid var(--uj-border, #e6ebf2);
border-radius: var(--uj-radius-card, 10px);
background: var(--uj-surface-2, #f8fafc);
}
.uc-stat__top {
display: flex;
align-items: center;
gap: var(--uj-space-2);
min-width: 0;
}
.uc-stat__icon {
display: flex;
flex: none;
align-items: center;
justify-content: center;
width: 26px;
height: 26px;
border-radius: var(--uj-radius-sm, 4px);
background: var(--uj-primary-soft, #eef3ff);
color: var(--uj-primary, #2b5ce6);
font-size: var(--uj-font-sm, 13px);
}
.uc-stat__label {
color: var(--uj-text-2, #4a5568);
font-size: var(--uj-font-sm, 13px);
line-height: 1.5;
overflow-wrap: anywhere;
}
.uc-stat__value {
color: var(--uj-text-1, #1d2533);
font-size: var(--uj-font-3xl, 24px);
font-weight: 600;
font-variant-numeric: var(--uj-num, tabular-nums);
line-height: 1.25;
overflow-wrap: anywhere;
}
.uc-stat__rate {
display: inline-flex;
align-self: flex-start;
align-items: center;
gap: var(--uj-space-1);
padding: 2px var(--uj-space-2);
border-radius: var(--uj-radius-pill, 6px);
background: var(--uj-neutral-soft, #f2f4f8);
color: var(--uj-text-2, #4a5568);
font-size: var(--uj-font-xs, 12px);
line-height: 1.6;
}
/* 中文语境:上涨用红、下跌用绿;同时配箭头与文字,不只靠颜色。 */
.uc-stat__rate--up {
background: var(--uj-error-soft, #fdedee);
color: var(--uj-error, #e5484d);
}
.uc-stat__rate--down {
background: var(--uj-success-soft, #e9f7ef);
color: var(--uj-success, #16a34a);
}
import type { ReactNode } from 'react';
import { ArrowDownOutlined, ArrowUpOutlined } from '@ant-design/icons';
import './StatCard.css';
/**
* 数据看板指标卡(模块内组件)。
*
* 只在本看板内复用,不放全局组件库:它的字段契约(主值 + 环比)来自
* dataBoard/index 返回体,不具备跨域通用性。
*
* 设计要点:
* - 每张卡有图标 + 标题 + 主值 + 环比四段结构,不再是纯色方块;
* - 主值用等宽数字令牌,多行不破版;环比用图标 + 文字,不靠颜色单独表意;
* - 涨红跌绿沿用中文语境,语义色成对取 soft / 前景令牌;
* - 缺值统一显示「—」,与加载中 / 接口未返回区分但不伪造数字。
*/
export interface StatCardProps {
label: string;
value: number | string | undefined;
rate: number | string | undefined;
suffix?: string;
icon: ReactNode;
}
type Trend = 'up' | 'down' | 'flat';
function trendOf(rate: number | string | undefined): Trend {
if (rate === undefined || rate === null || rate === '') return 'flat';
const n = Number(rate);
if (!Number.isFinite(n) || n === 0) return 'flat';
return n > 0 ? 'up' : 'down';
}
function valueOf(value: number | string | undefined, suffix?: string): string {
if (value === undefined || value === null || value === '') return '—';
return `${value}${suffix ?? ''}`;
}
function rateOf(rate: number | string | undefined): string {
if (rate === undefined || rate === null || rate === '') return '—';
const n = Number(rate);
return Number.isFinite(n) && n > 0 ? `+${rate}%` : `${rate}%`;
}
export function StatCard({ label, value, rate, suffix, icon }: StatCardProps) {
const trend = trendOf(rate);
const display = valueOf(value, suffix);
return (
<article className="uc-stat" aria-label={`${label}:${display}`}>
<div className="uc-stat__top">
<span className="uc-stat__icon" aria-hidden>
{icon}
</span>
<span className="uc-stat__label">{label}</span>
</div>
<div className="uc-stat__value">{display}</div>
<div className={`uc-stat__rate uc-stat__rate--${trend}`}>
{trend === 'up' ? <ArrowUpOutlined aria-hidden /> : null}
{trend === 'down' ? <ArrowDownOutlined aria-hidden /> : null}
<span>环比 {rateOf(rate)}</span>
</div>
</article>
);
}
/* 趋势数据卡样式与看板页面同目录,组件只服务本模块;色值全部取 --uj-* 语义令牌。 */
.uc-trend {
display: grid;
gap: var(--uj-space-2, 8px);
grid-template-columns: repeat(auto-fit, minmax(104px, 1fr));
margin-top: var(--uj-space-5);
}
.uc-trend__item {
display: flex;
flex-direction: column;
gap: var(--uj-space-2);
min-width: 0;
padding: var(--uj-space-3) var(--uj-space-4);
border: 1px solid var(--uj-border, #e6ebf2);
border-radius: var(--uj-radius-md, 6px);
background: var(--uj-surface-2, #f8fafc);
}
.uc-trend__date {
color: var(--uj-text-3, #8a94a6);
font-size: var(--uj-font-xs, 12px);
line-height: 1.4;
}
.uc-trend__value {
color: var(--uj-text-1, #1d2533);
font-size: var(--uj-font-2xl, 20px);
font-weight: 600;
font-variant-numeric: var(--uj-num, tabular-nums);
line-height: 1.2;
overflow-wrap: anywhere;
}
.uc-trend__value small {
margin-left: 2px;
color: var(--uj-text-3, #8a94a6);
font-size: var(--uj-font-xs, 12px);
font-weight: 400;
}
.uc-trend__empty {
padding: var(--uj-space-8) 0;
color: var(--uj-text-3, #8a94a6);
font-size: var(--uj-font-sm, 13px);
text-align: center;
}
import type { TrendPoint } from '@/api';
import './TrendChart.css';
/**
* 看板趋势数据(模块内组件,只服务本看板)。
*
* 为什么不复用 StatCard:趋势点是 date + count 的时间序列,没有环比字段,
* 套 KPI 卡会显示假的「环比 —」。这里做成「一排带边框的紧凑数据卡」:
* 每张卡 = 日期 + 数值,卡片有明确边界,信息清晰,不放任何柱状/条形图。
*/
export interface TrendChartProps {
data: TrendPoint[];
unit?: string;
loading?: boolean;
}
/** 长日期收敛成短标签:有「时:分」取时间,否则取「月-日」,再否则原样。 */
function shortenDate(date: string): string {
const time = /(\d{1,2}:\d{2})/.exec(date);
if (time) return time[1];
const parts = date.split(/[-/]/);
if (parts.length >= 3) return `${parts[parts.length - 2]}-${parts[parts.length - 1]}`;
return date;
}
function countOf(point: TrendPoint): number {
const n = Number(point.count);
return Number.isFinite(n) ? n : 0;
}
export function TrendChart({ data, unit = '辆', loading = false }: TrendChartProps) {
if (loading) return <div className="uc-trend__empty">正在加载趋势数据…</div>;
if (data.length === 0) return <div className="uc-trend__empty">暂无趋势数据</div>;
return (
<div className="uc-trend" role="list" aria-label={`趋势数据,共 ${data.length} 个数据点`}>
{data.map((point, index) => {
const count = countOf(point);
return (
<div
key={`${point.date}-${index}`}
className="uc-trend__item"
role="listitem"
aria-label={`${point.date}:${count}${unit}`}
title={`${point.date}:${count}${unit}`}
>
<span className="uc-trend__date">{shortenDate(point.date)}</span>
<span className="uc-trend__value">
{count}
<small>{unit}</small>
</span>
</div>
);
})}
</div>
);
}
...@@ -7,7 +7,7 @@ ...@@ -7,7 +7,7 @@
.uc-head { .uc-head {
align-items: center; align-items: center;
display: flex; display: flex;
gap: var(--uj-space-2); gap: var(--uj-space-3);
justify-content: space-between; justify-content: space-between;
} }
.uc-filter { .uc-filter {
...@@ -16,62 +16,36 @@ ...@@ -16,62 +16,36 @@
.uc-filter .ant-select { .uc-filter .ant-select {
width: 245px; width: 245px;
} }
.uc-filter button, /* 时间筛选的分段按钮 / 区间选择器样式收口在 @/features/shared/PeriodFilter.css,
.uc-head button { 这里不再重复裸 button 规则。 */
background: var(--uj-surface);
border: 1px solid var(--uj-border);
color: var(--uj-text-1);
cursor: pointer;
padding: var(--uj-space-2);
}
.uc-filter .active {
background: var(--uj-primary);
color: var(--uj-on-primary);
}
.uc-grid { .uc-grid {
display: grid; display: grid;
gap: var(--uj-space-4); gap: var(--uj-space-4);
grid-template-columns: repeat(5, minmax(0, 1fr)); grid-template-columns: repeat(5, minmax(0, 1fr));
} }
.uc-grid > div { /* 指标卡与筛选行的列数按「这块卡自身的宽度」决定(容器查询),
background: var(--uj-surface-2); 不随浏览器视口折叠——DevTools 停靠、分屏、高 DPI 都不会再把网格挤成 1 列。 */
border-radius: var(--uj-radius-sm); .uc-board {
display: grid; container-type: inline-size;
gap: var(--uj-space-3);
min-height: 120px;
padding: var(--uj-space-5);
}
.uc-grid strong {
font-size: var(--uj-font-3xl);
}
.uc-grid small {
color: var(--uj-text-3);
} }
.uc-trend { /* 单张指标卡的视觉收口在同目录 components/StatCard.css,这里只管网格排布;
display: grid; 趋势图样式在 components/TrendChart.css。 */
gap: var(--uj-space-2); @container (max-width: 1020px) {
grid-template-columns: repeat(auto-fit, minmax(110px, 1fr));
margin-top: var(--uj-space-5);
}
.uc-trend div {
background: var(--uj-surface-2);
padding: var(--uj-space-3);
}
.uc-trend span,
.uc-trend strong {
display: block;
}
@media (max-width: 1000px) {
.uc-grid { .uc-grid {
grid-template-columns: repeat(3, minmax(0, 1fr)); grid-template-columns: repeat(3, minmax(0, 1fr));
} }
} }
@media (max-width: 700px) { @container (max-width: 660px) {
.uc-grid {
grid-template-columns: repeat(2, minmax(0, 1fr));
}
.uc-filter, .uc-filter,
.uc-filter > div { .uc-filter > div {
align-items: flex-start; align-items: flex-start;
flex-direction: column; flex-direction: column;
} }
}
@container (max-width: 460px) {
.uc-grid { .uc-grid {
grid-template-columns: 1fr; grid-template-columns: 1fr;
} }
......
import { useMemo, useState } from 'react'; import { useMemo, useState } from 'react';
import { useQuery } from '@tanstack/react-query'; import { useQuery } from '@tanstack/react-query';
import { type Dayjs } from 'dayjs'; import { type Dayjs } from 'dayjs';
import { UAlert, UButton, UCard, UDatePicker, UEmpty, USelect, UText } from '@uj/ui'; import {
CarOutlined,
DollarOutlined,
ImportOutlined,
LineChartOutlined,
PercentageOutlined,
RetweetOutlined,
RiseOutlined,
ShoppingCartOutlined,
SwapOutlined,
TruckOutlined,
} from '@ant-design/icons';
import { UAlert, UButton, UCard, USelect, UText } from '@uj/ui';
import { PageShell } from '@/components'; import { PageShell } from '@/components';
import { PeriodFilter, type PeriodOption } from '@/features/shared/PeriodFilter';
import { StatCard } from './components/StatCard';
import { TrendChart } from './components/TrendChart';
import { dashboardApi, type TrendPoint } from '@/api'; import { dashboardApi, type TrendPoint } from '@/api';
import { errorDetail } from '@/utils/error'; import { errorDetail } from '@/utils/error';
import './index.css'; import './index.css';
const PERIODS = [
/** 今日 / 昨日 / 本月 / 上月:指标卡与趋势卡共用同一组档位定义。 */
const PERIODS: ReadonlyArray<PeriodOption<number>> = [
{ value: 1, label: '今日' }, { value: 1, label: '今日' },
{ value: 2, label: '昨日' }, { value: 2, label: '昨日' },
{ value: 3, label: '本月' }, { value: 3, label: '本月' },
{ value: 4, label: '上月' }, { value: 4, label: '上月' },
]; ];
/** 指标定义收敛为一份:标签 / 返回字段 / 环比字段 / 单位 / 图标。 */
const STATS = [ const STATS = [
['评估量(辆)', 'appraisalCount', 'appraisalCountChainRatio'], { label: '评估量(辆)', key: 'appraisalCount', rate: 'appraisalCountChainRatio', icon: <CarOutlined /> },
['总毛利(万元)', 'grossProfitTotal', 'grossProfitTotalChainRatio'], { label: '总毛利(万元)', key: 'grossProfitTotal', rate: 'grossProfitTotalChainRatio', icon: <DollarOutlined /> },
['单车毛利(元)', 'grossProfitPerUnit', 'grossProfitPerUnitChainRatio'], {
['平均售价(万元)', 'avgSellingPrice', 'avgSellingPriceChainRatio'], label: '单车毛利(元)',
['新车下定数(辆)', 'newCarOrderCount', 'newCarOrderCountChainRatio'], key: 'grossProfitPerUnit',
['二手车收车成交量(辆)', 'transactionCount', 'transactionCountChainRatio'], rate: 'grossProfitPerUnitChainRatio',
['评估转化率(比)', 'appraisalConversionRate', 'appraisalConversionRateChainRatio', '%'], icon: <RiseOutlined />,
['置换率(比)', 'replacementRate', 'replacementRateChainRatio', '%'], },
['新车交付数(辆)', 'newCarDeliveryCount', 'newCarDeliveryCountChainRatio'], {
['二手车收购交车数(辆)', 'acquisitionDeliveryCount', 'acquisitionDeliveryCountChainRatio'], label: '平均售价(万元)',
] as const; key: 'avgSellingPrice',
rate: 'avgSellingPriceChainRatio',
icon: <LineChartOutlined />,
},
{
label: '新车下定数(辆)',
key: 'newCarOrderCount',
rate: 'newCarOrderCountChainRatio',
icon: <ShoppingCartOutlined />,
},
{
label: '二手车收车成交量(辆)',
key: 'transactionCount',
rate: 'transactionCountChainRatio',
icon: <SwapOutlined />,
},
{
label: '评估转化率(比)',
key: 'appraisalConversionRate',
rate: 'appraisalConversionRateChainRatio',
suffix: '%',
icon: <PercentageOutlined />,
},
{
label: '置换率(比)',
key: 'replacementRate',
rate: 'replacementRateChainRatio',
suffix: '%',
icon: <RetweetOutlined />,
},
{
label: '新车交付数(辆)',
key: 'newCarDeliveryCount',
rate: 'newCarDeliveryCountChainRatio',
icon: <TruckOutlined />,
},
{
label: '二手车收购交车数(辆)',
key: 'acquisitionDeliveryCount',
rate: 'acquisitionDeliveryCountChainRatio',
icon: <ImportOutlined />,
},
];
function storesFromResponse(response: unknown): Array<{ merchantId: string; merchantName: string }> { function storesFromResponse(response: unknown): Array<{ merchantId: string; merchantName: string }> {
function parse(value: unknown): unknown { function parse(value: unknown): unknown {
if (typeof value !== 'string') return value; if (typeof value !== 'string') return value;
...@@ -61,16 +121,15 @@ function Trend({ title, load }: { title: string; load: (type: number) => Promise ...@@ -61,16 +121,15 @@ function Trend({ title, load }: { title: string; load: (type: number) => Promise
const [type, setType] = useState(1); const [type, setType] = useState(1);
const query = useQuery({ queryKey: ['trend', title, type], queryFn: () => load(type) }); const query = useQuery({ queryKey: ['trend', title, type], queryFn: () => load(type) });
return ( return (
<UCard> <UCard variant="outlined">
<div className="uc-head"> <div className="uc-head">
<UText strong>{title}趋势</UText> <UText strong>{title}趋势</UText>
<div> <PeriodFilter
{PERIODS.map((p) => ( value={type}
<button type="button" key={p.value} onClick={() => setType(p.value)}> options={PERIODS}
{p.label} onChange={setType}
</button> ariaLabel={`${title}趋势时间筛选`}
))} />
</div>
</div> </div>
{query.isError ? ( {query.isError ? (
<UAlert <UAlert
...@@ -85,14 +144,7 @@ function Trend({ title, load }: { title: string; load: (type: number) => Promise ...@@ -85,14 +144,7 @@ function Trend({ title, load }: { title: string; load: (type: number) => Promise
} }
/> />
) : ( ) : (
<div className="uc-trend"> <TrendChart data={query.data ?? []} loading={query.isLoading} />
{query.data?.map((p) => (
<div key={p.date}>
<span>{p.date}</span>
<strong>{p.count}辆</strong>
</div>
)) ?? <UEmpty description="正在加载" />}
</div>
)} )}
</UCard> </UCard>
); );
...@@ -127,7 +179,10 @@ export default function Dashboard() { ...@@ -127,7 +179,10 @@ export default function Dashboard() {
return ( return (
<PageShell title="数据看板" description="查看二手车业务的关键指标及趋势。"> <PageShell title="数据看板" description="查看二手车业务的关键指标及趋势。">
<div className="uc-dashboard"> <div className="uc-dashboard">
<UCard> {/* outlined:看板三大块需要清晰边界,borderless 的浅底柔影在白底页面上会隐身;
uc-board 同时是容器查询上下文——指标网格按这块卡的实际宽度定列数,
不随浏览器视口(DevTools 停靠 / 分屏 / 高 DPI)塌列。 */}
<UCard variant="outlined" className="uc-board">
<div className="uc-filter"> <div className="uc-filter">
<div> <div>
<UText>请选择门店:</UText> <UText>请选择门店:</UText>
...@@ -144,22 +199,13 @@ export default function Dashboard() { ...@@ -144,22 +199,13 @@ export default function Dashboard() {
/> />
</div> </div>
<div> <div>
{PERIODS.map((p) => ( <PeriodFilter
<button value={dateType}
type="button" options={PERIODS}
key={p.value} onChange={setDateType}
className={dateType === p.value && !range ? 'active' : ''} range={range}
onClick={() => { onRangeChange={setRange}
setRange(null); ariaLabel="看板指标时间筛选"
setDateType(p.value);
}}
>
{p.label}
</button>
))}
<UDatePicker.RangePicker
placeholder={['开始日期', '结束日期']}
onChange={(value) => setRange(value as [Dayjs, Dayjs] | null)}
/> />
</div> </div>
</div> </div>
...@@ -177,18 +223,15 @@ export default function Dashboard() { ...@@ -177,18 +223,15 @@ export default function Dashboard() {
/> />
) : ( ) : (
<div className="uc-grid"> <div className="uc-grid">
{STATS.map(([label, key, rate, suffix]) => ( {STATS.map((stat) => (
<div key={key}> <StatCard
<span>{label}</span> key={stat.key}
<strong> label={stat.label}
{statistics.data?.[key] === undefined value={statistics.data?.[stat.key]}
? '—' rate={statistics.data?.[stat.rate]}
: `${statistics.data[key]}${suffix ?? ''}`} suffix={stat.suffix}
</strong> icon={stat.icon}
<small> />
环比 {statistics.data?.[rate] === undefined ? '—' : `${statistics.data[rate]}%`}
</small>
</div>
))} ))}
</div> </div>
)} )}
......
...@@ -15,7 +15,7 @@ import type { CSSProperties } from 'react'; ...@@ -15,7 +15,7 @@ import type { CSSProperties } from 'react';
* 组件无状态、无随机数、无定时器,纯 SVG + CSS,尊重 prefers-reduced-motion。 * 组件无状态、无随机数、无定时器,纯 SVG + CSS,尊重 prefers-reduced-motion。
*/ */
export interface TableLoaderProps { export interface TableLoaderProps {
/** 图形宽度,高度按 120:76 等比换算,默认 120 */ /** 图形宽度,高度按 120:76 等比换算,默认 96 */
size?: number; size?: number;
/** 图形下方文案,传空字符串隐藏 */ /** 图形下方文案,传空字符串隐藏 */
label?: string; label?: string;
...@@ -51,7 +51,7 @@ const ROWS = [ ...@@ -51,7 +51,7 @@ const ROWS = [
]; ];
export function TableLoader({ export function TableLoader({
size = 120, size = 96,
label = '正在加载数据…', label = '正在加载数据…',
className, className,
style, style,
......
...@@ -656,7 +656,7 @@ body { ...@@ -656,7 +656,7 @@ body {
flex-direction: column; flex-direction: column;
align-items: center; align-items: center;
gap: 6px; gap: 6px;
width: 120px; width: 96px;
height: auto; height: auto;
color: var(--uj-text-3); color: var(--uj-text-3);
line-height: 1.4; line-height: 1.4;
......
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!