feat: init ai-platform - 源码 + 配置
This commit is contained in:
@@ -0,0 +1,89 @@
|
||||
import { useMemo, useState } from 'react';
|
||||
import { countNodes } from '../core/fingerprint.js';
|
||||
import BomTree from './BomTree';
|
||||
|
||||
export default function BomBrowser({ products }: any) {
|
||||
const [search, setSearch] = useState('');
|
||||
const [selectedId, setSelectedId] = useState<any>(null);
|
||||
const [collapsed, setCollapsed] = useState(new Set<any>());
|
||||
|
||||
const groups = useMemo(() => {
|
||||
const g: Record<string, any[]> = {};
|
||||
for (const p of products) {
|
||||
(g[p.series] = g[p.series] || []).push(p);
|
||||
}
|
||||
return g;
|
||||
}, [products]);
|
||||
|
||||
const selected = products.find((p: any) => p.id === selectedId) || null;
|
||||
const lower = search.toLowerCase();
|
||||
|
||||
function toggleGroup(seriesName: any) {
|
||||
setCollapsed(prev => {
|
||||
const next = new Set(prev);
|
||||
if (next.has(seriesName)) next.delete(seriesName);
|
||||
else next.add(seriesName);
|
||||
return next;
|
||||
});
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="two-panel">
|
||||
<div className="panel-left">
|
||||
<div className="search-box">
|
||||
<input
|
||||
type="text"
|
||||
placeholder="搜索产品编码或名称..."
|
||||
value={search}
|
||||
onChange={(e) => setSearch(e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
{Object.entries(groups).map(([seriesName, list]) => {
|
||||
const filtered = list.filter((p: any) =>
|
||||
!search || p.id.toLowerCase().includes(lower) || p.name.toLowerCase().includes(lower)
|
||||
);
|
||||
if (filtered.length === 0) return null;
|
||||
// 搜索时强制展开
|
||||
const isCollapsed = !search && collapsed.has(seriesName);
|
||||
return (
|
||||
<div key={seriesName} className="product-group">
|
||||
<div
|
||||
className={`product-group-title ${isCollapsed ? 'collapsed' : ''}`}
|
||||
onClick={() => !search && toggleGroup(seriesName)}
|
||||
>
|
||||
<span className="product-group-arrow">{isCollapsed ? '▸' : '▾'}</span>
|
||||
<span className="product-group-name">{seriesName}</span>
|
||||
<span className="product-group-count">{filtered.length}</span>
|
||||
</div>
|
||||
{!isCollapsed && filtered.map((p: any) => (
|
||||
<div
|
||||
key={p.id}
|
||||
className={`product-item ${selectedId === p.id ? 'active' : ''}`}
|
||||
onClick={() => setSelectedId(p.id)}
|
||||
>
|
||||
<span>{p.id}</span>
|
||||
<span className="product-meta">{countNodes(p.bom)}节点</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
<div className="panel-right">
|
||||
{selected ? (
|
||||
<>
|
||||
<div style={{ marginBottom: 12, fontWeight: 600, fontSize: 15 }}>{selected.name}</div>
|
||||
<BomTree root={selected.bom} />
|
||||
</>
|
||||
) : (
|
||||
<div className="empty-state">
|
||||
<div className="empty-state-icon">📦</div>
|
||||
<div className="empty-state-text">请从左侧选择一个产品查看 BOM</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
import { useState } from 'react';
|
||||
import { computeFingerprint } from '../core/fingerprint.js';
|
||||
|
||||
function getHighlightSet(highlightFingerprint: any, highlightSet: any) {
|
||||
if (highlightSet) return highlightSet;
|
||||
if (highlightFingerprint) return new Set([highlightFingerprint]);
|
||||
return null;
|
||||
}
|
||||
|
||||
function nodeFp(node: any) { return computeFingerprint(node); }
|
||||
|
||||
function containsHighlight(node: any, set: any) {
|
||||
if (set.has(nodeFp(node))) return true;
|
||||
if (node.children) return node.children.some((c: any) => containsHighlight(c, set));
|
||||
return false;
|
||||
}
|
||||
|
||||
function TreeNode({ node, set, focus }: any) {
|
||||
const [collapsed, setCollapsed] = useState(() => {
|
||||
if (focus && set && set.size) return !containsHighlight(node, set);
|
||||
return false;
|
||||
});
|
||||
|
||||
const hasChildren = node.children && node.children.length > 0;
|
||||
const isHighlighted = set.has(nodeFp(node));
|
||||
|
||||
return (
|
||||
<div className="tree-node">
|
||||
<div className={`tree-node-row ${isHighlighted ? 'highlight-reuse' : ''}`}>
|
||||
{hasChildren ? (
|
||||
<span className="tree-toggle" onClick={() => setCollapsed(!collapsed)}>
|
||||
{collapsed ? '\u25B6' : '\u25BC'}
|
||||
</span>
|
||||
) : (
|
||||
<span className="tree-toggle" style={{ visibility: 'hidden' }}>{'\u25B6'}</span>
|
||||
)}
|
||||
<span className="tree-col tree-col-code">{node.part.code}</span>
|
||||
<span className="tree-col tree-col-name">
|
||||
{node.part.name}
|
||||
{isHighlighted && <span className="badge badge-reuse">命中</span>}
|
||||
</span>
|
||||
<span className="tree-col tree-col-spec">{node.part.spec || ''}</span>
|
||||
<span className="tree-col tree-col-qty">{node.qty}</span>
|
||||
<span className="tree-col tree-col-unit">{node.part.unit || ''}</span>
|
||||
</div>
|
||||
{hasChildren && !collapsed && (
|
||||
<div className="tree-children">
|
||||
{node.children.map((child: any, i: number) => (
|
||||
<TreeNode key={i} node={child} set={set} focus={focus} />
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default function BomTree({ root, highlightFingerprint = null, highlightSet = null, showSpec = true, focus = false, height = null }: any) {
|
||||
const set = getHighlightSet(highlightFingerprint, highlightSet) || new Set<any>();
|
||||
return (
|
||||
<div className="tree-scroll" style={height ? { maxHeight: height } : undefined}>
|
||||
<div className="bom-tree">
|
||||
<div className="tree-header">
|
||||
<span style={{ width: 18 }}></span>
|
||||
<span className="tree-col tree-col-code">物料编码</span>
|
||||
<span className="tree-col tree-col-name">名称</span>
|
||||
{showSpec && <span className="tree-col tree-col-spec">规格</span>}
|
||||
<span className="tree-col tree-col-qty">数量</span>
|
||||
<span className="tree-col tree-col-unit">单位</span>
|
||||
</div>
|
||||
<TreeNode node={root} set={set} focus={focus} />
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
import { useEffect } from 'react';
|
||||
|
||||
export default function ConfirmModal({ open, title, message, confirmText = '确定', danger = true, onConfirm, onCancel }: any) {
|
||||
useEffect(() => {
|
||||
const onKey = (e: KeyboardEvent) => { if (e.key === 'Escape') onCancel(); };
|
||||
if (open) window.addEventListener('keydown', onKey);
|
||||
return () => window.removeEventListener('keydown', onKey);
|
||||
}, [open, onCancel]);
|
||||
|
||||
if (!open) return null;
|
||||
|
||||
return (
|
||||
<div className="confirm-modal-overlay" onClick={(e) => { if (e.target === e.currentTarget) onCancel(); }}>
|
||||
<div className="confirm-modal">
|
||||
<div className="confirm-modal-icon">{danger ? '\u26A0' : '\u2139'}</div>
|
||||
<div className="confirm-modal-title">{title}</div>
|
||||
<div className="confirm-modal-message">{message}</div>
|
||||
<div className="confirm-modal-actions">
|
||||
<button className="btn" onClick={onCancel}>取消</button>
|
||||
<button className={`btn ${danger ? 'btn-danger' : 'btn-primary'}`} onClick={onConfirm}>{confirmText}</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
import { useEffect } from 'react';
|
||||
import { createPortal } from 'react-dom';
|
||||
import { IconX } from './Icons';
|
||||
|
||||
// 使用 Portal 渲染到 body,避免被父级层叠上下文/导航条遮挡
|
||||
export default function Drawer({ open, title, onClose, children, width = 540 }: any) {
|
||||
useEffect(() => {
|
||||
if (!open) return;
|
||||
const onKey = (e: KeyboardEvent) => { if (e.key === 'Escape') onClose(); };
|
||||
window.addEventListener('keydown', onKey);
|
||||
return () => window.removeEventListener('keydown', onKey);
|
||||
}, [open, onClose]);
|
||||
|
||||
return createPortal(
|
||||
<>
|
||||
{/* 遮罩:覆盖全屏(含导航条),点击任意非抽屉区域关闭 */}
|
||||
{open && <div className="drawer-overlay" onClick={onClose} />}
|
||||
|
||||
<div
|
||||
className={`drawer ${open ? 'drawer-open' : 'drawer-closed'}`}
|
||||
style={{ width }}
|
||||
aria-hidden={!open}
|
||||
>
|
||||
<div className="drawer-header">
|
||||
<span className="drawer-title">{title}</span>
|
||||
<button type="button" className="drawer-close" onClick={onClose} aria-label="关闭" title="关闭">
|
||||
<IconX />
|
||||
</button>
|
||||
</div>
|
||||
<div className="drawer-content">{children}</div>
|
||||
</div>
|
||||
</>,
|
||||
document.body
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
// Icons.tsx - SVG 图标系统(stroke 风格,1.5px 线宽)
|
||||
const base = {
|
||||
fill: 'none',
|
||||
stroke: 'currentColor',
|
||||
strokeWidth: 1.5,
|
||||
strokeLinecap: 'round',
|
||||
strokeLinejoin: 'round',
|
||||
width: '1em',
|
||||
height: '1em',
|
||||
} as const;
|
||||
|
||||
export const IconBox = (p: any) => (
|
||||
<svg {...base} viewBox="0 0 24 24" {...p}><path d="M21 8l-9-5-9 5 9 5 9-5z"/><path d="M3 8v8l9 5 9-5V8"/><path d="M12 13v8"/></svg>
|
||||
);
|
||||
export const IconSearch = (p: any) => (
|
||||
<svg {...base} viewBox="0 0 24 24" {...p}><circle cx="11" cy="11" r="7"/><path d="M21 21l-4.3-4.3"/></svg>
|
||||
);
|
||||
export const IconNetwork = (p: any) => (
|
||||
<svg {...base} viewBox="0 0 24 24" {...p}><circle cx="12" cy="5" r="2.5"/><circle cx="5" cy="19" r="2.5"/><circle cx="19" cy="19" r="2.5"/><path d="M12 7.5v4M12 11.5l-5.5 5M12 11.5l5.5 5"/></svg>
|
||||
);
|
||||
export const IconCompare = (p: any) => (
|
||||
<svg {...base} viewBox="0 0 24 24" {...p}><path d="M8 3v18M16 3v18"/><path d="M3 8h5M3 16h5M16 8h5M16 12h5"/></svg>
|
||||
);
|
||||
export const IconLayers = (p: any) => (
|
||||
<svg {...base} viewBox="0 0 24 24" {...p}><path d="M12 2l10 6-10 6L2 8l10-6z"/><path d="M2 13l10 6 10-6"/><path d="M2 17l10 6 10-6"/></svg>
|
||||
);
|
||||
export const IconRefresh = (p: any) => (
|
||||
<svg {...base} viewBox="0 0 24 24" {...p}><path d="M21 12a9 9 0 1 1-2.6-6.4"/><path d="M21 3v6h-6"/></svg>
|
||||
);
|
||||
export const IconChevronDown = (p: any) => (
|
||||
<svg {...base} viewBox="0 0 24 24" {...p}><path d="M6 9l6 6 6-6"/></svg>
|
||||
);
|
||||
export const IconChevronRight = (p: any) => (
|
||||
<svg {...base} viewBox="0 0 24 24" {...p}><path d="M9 6l6 6-6 6"/></svg>
|
||||
);
|
||||
export const IconCheck = (p: any) => (
|
||||
<svg {...base} viewBox="0 0 24 24" {...p}><path d="M20 6L9 17l-5-5"/></svg>
|
||||
);
|
||||
export const IconX = (p: any) => (
|
||||
<svg {...base} viewBox="0 0 24 24" {...p}><path d="M18 6L6 18M6 6l12 12"/></svg>
|
||||
);
|
||||
export const IconTrash = (p: any) => (
|
||||
<svg {...base} viewBox="0 0 24 24" {...p}><path d="M3 6h18M8 6V4h8v2M19 6l-1 14H6L5 6"/><path d="M10 11v6M14 11v6"/></svg>
|
||||
);
|
||||
export const IconPlus = (p: any) => (
|
||||
<svg {...base} viewBox="0 0 24 24" {...p}><path d="M12 5v14M5 12h14"/></svg>
|
||||
);
|
||||
export const IconAlert = (p: any) => (
|
||||
<svg {...base} viewBox="0 0 24 24" {...p}><path d="M12 3l10 18H2L12 3z"/><path d="M12 10v5M12 18.5v.5"/></svg>
|
||||
);
|
||||
export const IconInfo = (p: any) => (
|
||||
<svg {...base} viewBox="0 0 24 24" {...p}><circle cx="12" cy="12" r="9"/><path d="M12 11v6M12 7.5v.5"/></svg>
|
||||
);
|
||||
export const IconEye = (p: any) => (
|
||||
<svg {...base} viewBox="0 0 24 24" {...p}><path d="M2 12s3.5-7 10-7 10 7 10 7-3.5 7-10 7-10-7-10-7z"/><circle cx="12" cy="12" r="3"/></svg>
|
||||
);
|
||||
export const IconTarget = (p: any) => (
|
||||
<svg {...base} viewBox="0 0 24 24" {...p}><circle cx="12" cy="12" r="9"/><circle cx="12" cy="12" r="5"/><circle cx="12" cy="12" r="1"/></svg>
|
||||
);
|
||||
export const IconSparkle = (p: any) => (
|
||||
<svg {...base} viewBox="0 0 24 24" {...p}><path d="M12 3l1.9 5.6L19.5 10l-5.6 1.9L12 17.5l-1.9-5.6L4.5 10l5.6-1.9L12 3z"/></svg>
|
||||
);
|
||||
@@ -0,0 +1,136 @@
|
||||
import { useEffect, useRef, useState } from 'react';
|
||||
import { IconBox } from './Icons';
|
||||
|
||||
// 默认加载阶段定义(向后兼容)
|
||||
const DEFAULT_STAGES = [
|
||||
{ key: 'download', label: '下载数据', icon: '↓' },
|
||||
{ key: 'parse', label: '解析 JSON', icon: '{}' },
|
||||
{ key: 'fingerprint',label: '指纹计算', icon: '#' },
|
||||
{ key: 'filter', label: '阈值过滤', icon: '⚙' },
|
||||
{ key: 'dedup', label: '子路径去重', icon: '⊕' },
|
||||
];
|
||||
|
||||
function fmtBytes(bytes: number) {
|
||||
if (bytes < 1024) return bytes + ' B';
|
||||
if (bytes < 1024 * 1024) return (bytes / 1024).toFixed(0) + ' KB';
|
||||
return (bytes / 1024 / 1024).toFixed(1) + ' MB';
|
||||
}
|
||||
|
||||
function fmtTime(ms: number) {
|
||||
if (ms < 1000) return ms.toFixed(0) + 'ms';
|
||||
return (ms / 1000).toFixed(1) + 's';
|
||||
}
|
||||
|
||||
function StageRow({ stage, index, currentStage, stageStatus, stageDetail }: any) {
|
||||
const status = stageStatus[stage.key];
|
||||
const isCurrent = currentStage === stage.key;
|
||||
const isPast = status === 'done';
|
||||
const isPending = !status && !isCurrent;
|
||||
|
||||
return (
|
||||
<div className={`load-stage-row ${isCurrent ? 'active' : ''} ${isPast ? 'done' : ''} ${isPending ? 'pending' : ''}`}>
|
||||
<div className="load-stage-icon">
|
||||
{isPast ? (
|
||||
<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round">
|
||||
<path d="M20 6L9 17l-5-5" />
|
||||
</svg>
|
||||
) : isCurrent ? (
|
||||
<span className="load-stage-spinner" />
|
||||
) : (
|
||||
<span className="load-stage-index">{index + 1}</span>
|
||||
)}
|
||||
</div>
|
||||
<div className="load-stage-info">
|
||||
<span className="load-stage-label">{stage.label}</span>
|
||||
{stageDetail[stage.key] && (
|
||||
<span className="load-stage-detail">{stageDetail[stage.key]}</span>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default function LoadingScreen({ phase, stageStatus, stageDetail, progress, totalBytes, error, onRetry, fadingOut, stages }: any) {
|
||||
const STAGES = stages || DEFAULT_STAGES;
|
||||
const [elapsed, setElapsed] = useState(0);
|
||||
const startTime = useRef(performance.now());
|
||||
|
||||
useEffect(() => {
|
||||
if (error) return;
|
||||
const timer = setInterval(() => {
|
||||
setElapsed(performance.now() - startTime.current);
|
||||
}, 100);
|
||||
return () => clearInterval(timer);
|
||||
}, [error]);
|
||||
|
||||
// 计算总体进度
|
||||
const stagesDone = Object.values(stageStatus).filter((s: any) => s === 'done').length;
|
||||
const overallPct = error
|
||||
? 0
|
||||
: progress > 0
|
||||
? Math.min((stagesDone / STAGES.length) * 100 + (progress / STAGES.length), 99.5)
|
||||
: (stagesDone / STAGES.length) * 100;
|
||||
|
||||
if (error) {
|
||||
return (
|
||||
<div className={`loading-screen ${fadingOut ? 'fading-out' : ''}`}>
|
||||
<div className="loading-card">
|
||||
<div className="loading-error-icon">
|
||||
<svg width="40" height="40" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round">
|
||||
<circle cx="12" cy="12" r="10" />
|
||||
<path d="M12 8v4M12 16v.5" />
|
||||
</svg>
|
||||
</div>
|
||||
<div className="loading-error-title">数据加载失败</div>
|
||||
<div className="loading-error-msg">{error}</div>
|
||||
<button className="btn btn-primary loading-retry-btn" onClick={onRetry}>
|
||||
重试
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className={`loading-screen ${fadingOut ? 'fading-out' : ''}`}>
|
||||
<div className="loading-card">
|
||||
{/* 标题 */}
|
||||
<div className="loading-header">
|
||||
<span className="loading-logo"><IconBox /></span>
|
||||
<span className="loading-title">BOM 可复用组件挖掘分析</span>
|
||||
</div>
|
||||
|
||||
{/* 阶段列表 */}
|
||||
<div className="load-stage-list">
|
||||
{STAGES.map((stage: any, i: number) => (
|
||||
<StageRow
|
||||
key={stage.key}
|
||||
stage={stage}
|
||||
index={i}
|
||||
currentStage={phase}
|
||||
stageStatus={stageStatus}
|
||||
stageDetail={stageDetail}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
|
||||
{/* 总体进度条 */}
|
||||
<div className="load-progress-section">
|
||||
<div className="load-progress-bar-track">
|
||||
<div
|
||||
className="load-progress-bar-fill"
|
||||
style={{ width: `${overallPct}%` }}
|
||||
/>
|
||||
</div>
|
||||
<div className="load-progress-meta">
|
||||
<span>{overallPct.toFixed(0)}%</span>
|
||||
<span className="load-elapsed">
|
||||
{totalBytes > 0 && `${fmtBytes(totalBytes)} · `}
|
||||
已耗时 {fmtTime(elapsed)}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,226 @@
|
||||
import { useMemo, useState, useRef, useCallback } from 'react';
|
||||
import { getScarcityLevel, getWeightedValue } from '../core/mining.js';
|
||||
import { adoptComponent, adoptComponents, getStandardComponents } from '../core/store.js';
|
||||
import { openSidePanel } from './SidePanel';
|
||||
import { toast } from './Toast';
|
||||
import { IconNetwork } from './Icons';
|
||||
import BomTree from './BomTree';
|
||||
|
||||
function SubTree({ node, depth = 0 }: any) {
|
||||
return (
|
||||
<div style={{ fontFamily: 'var(--font-mono)', fontSize: 12, lineHeight: 1.9, paddingLeft: depth * 16 }}>
|
||||
<span style={{ color: 'var(--accent-primary)', fontWeight: 500 }}>{node.part.code}</span>{' '}
|
||||
{node.part.name} <span className="text-muted">x{node.qty}</span>
|
||||
{node.children && node.children.map((c: any, i: number) => <SubTree key={i} node={c} depth={depth + 1} />)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function ScarcityBadge({ productCount, totalProducts }: any) {
|
||||
const s = getScarcityLevel(productCount, totalProducts);
|
||||
return (
|
||||
<span className="scarcity-badge" style={{
|
||||
fontSize: 10, padding: '2px 7px', borderRadius: 6,
|
||||
background: s.color + '1a', color: s.color, border: `1px solid ${s.color}33`,
|
||||
fontWeight: 600, whiteSpace: 'nowrap',
|
||||
}}>
|
||||
{s.level}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
export default function MiningView({ products, miningResult, setMiningResult, thresholds, setThresholds }: any) {
|
||||
const minCoveragePct = thresholds.minCoveragePct;
|
||||
const minNodes = thresholds.minNodes;
|
||||
const results = miningResult;
|
||||
const [status, setStatus] = useState('');
|
||||
const [mining, setMining] = useState(false);
|
||||
const [expanded, setExpanded] = useState<any>({});
|
||||
const [checked, setChecked] = useState<any>({});
|
||||
const workerRef = useRef<Worker | null>(null);
|
||||
|
||||
const standardFps = useMemo(() => new Set<any>(getStandardComponents().map((c: any) => c.fingerprint)), [results]);
|
||||
|
||||
const minProductCount = Math.max(2, Math.round(products.length * minCoveragePct / 100));
|
||||
|
||||
const runMining = useCallback(() => {
|
||||
// 终止已有 worker
|
||||
if (workerRef.current) workerRef.current.terminate();
|
||||
|
||||
setMining(true);
|
||||
setStatus('后台计算中...');
|
||||
|
||||
const worker = new Worker(new URL('../core/mining-worker.js', import.meta.url), { type: 'module' });
|
||||
workerRef.current = worker;
|
||||
|
||||
worker.onmessage = (e: MessageEvent) => {
|
||||
if (e.data.type === 'done') {
|
||||
const r = e.data.result;
|
||||
setMiningResult(r);
|
||||
setStatus(`完成,共 ${r.length} 个组件`);
|
||||
setMining(false);
|
||||
worker.terminate();
|
||||
workerRef.current = null;
|
||||
} else if (e.data.type === 'error') {
|
||||
setStatus('计算失败: ' + e.data.error);
|
||||
setMining(false);
|
||||
worker.terminate();
|
||||
workerRef.current = null;
|
||||
}
|
||||
};
|
||||
|
||||
worker.postMessage({ products, options: { minProductCount, minNodeCount: minNodes } });
|
||||
}, [products, minProductCount, minNodes, setMiningResult]);
|
||||
|
||||
// 组件卸载时清理 worker
|
||||
useState(() => () => { if (workerRef.current) workerRef.current.terminate(); });
|
||||
|
||||
const totalNodes = results.reduce((s: number, r: any) => s + r.nodeCount, 0);
|
||||
const checkedList = results.filter((r: any) => checked[r.fingerprint]);
|
||||
|
||||
function openContext(productId: any, path: any, comp: any) {
|
||||
const product = products.find((p: any) => p.id === productId);
|
||||
if (!product) return;
|
||||
let currentNode = product.bom;
|
||||
const breadcrumbs = [{ code: product.bom.part.code }];
|
||||
for (let i = 0; i < path.length - 1; i++) {
|
||||
currentNode = currentNode.children[path[i]];
|
||||
breadcrumbs.push({ code: currentNode.part.code });
|
||||
}
|
||||
const componentNode = currentNode.children[path[path.length - 1]];
|
||||
|
||||
openSidePanel(
|
||||
comp.template.part.name + ' @ ' + productId,
|
||||
<>
|
||||
<div style={{ marginBottom: 14, fontSize: 12, display: 'flex', flexWrap: 'wrap', gap: 4, alignItems: 'center' }}>
|
||||
<strong>{product.name}</strong>
|
||||
<span className="text-secondary" style={{ marginLeft: 6 }}>中位置:</span>
|
||||
{breadcrumbs.map((b: any, i: number) => (
|
||||
<span key={i}>
|
||||
{i > 0 && <span style={{ color: 'var(--text-3)', margin: '0 2px' }}>→</span>}
|
||||
<span style={{ fontFamily: 'var(--font-mono)', fontSize: 11 }}>{b.code}</span>
|
||||
</span>
|
||||
))}
|
||||
<span style={{ color: 'var(--text-3)', margin: '0 2px' }}>→</span>
|
||||
<span style={{ color: 'var(--green)', fontWeight: 600, fontFamily: 'var(--font-mono)', fontSize: 11 }}>{componentNode.part.code}</span>
|
||||
</div>
|
||||
<div style={{ border: '1px solid var(--line-1)', borderRadius: 12, padding: 14 }}>
|
||||
<div style={{ fontWeight: 600, fontSize: 13, marginBottom: 10 }}>产品 BOM 树(绿色=当前组件)</div>
|
||||
<BomTree key={product.id + comp.fingerprint} root={product.bom} highlightFingerprint={comp.fingerprint} showSpec={false} focus height="70vh" />
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
<div className="card">
|
||||
<div className="card-title"><span className="title-icon"><IconNetwork /></span>挖掘参数</div>
|
||||
<div className="control-row">
|
||||
<span className="control-label">最少覆盖产品:</span>
|
||||
<input
|
||||
type="number"
|
||||
value={minCoveragePct}
|
||||
min="0.1"
|
||||
max="100"
|
||||
step="0.1"
|
||||
style={{ width: 72 }}
|
||||
disabled={mining}
|
||||
onChange={e => setThresholds({ ...thresholds, minCoveragePct: +e.target.value })}
|
||||
/>
|
||||
<span className="control-label" style={{ marginLeft: 0 }}>%</span>
|
||||
<span className="text-muted text-xs" style={{ whiteSpace: 'nowrap' }}>({minProductCount} 个产品)</span>
|
||||
<span className="control-label" style={{ marginLeft: 20 }}>最小节点数:</span>
|
||||
<input type="number" value={minNodes} min="1" max="20" style={{ width: 72 }} disabled={mining} onChange={e => setThresholds({ ...thresholds, minNodes: +e.target.value })} />
|
||||
<button className="btn btn-primary" onClick={runMining} disabled={mining}>
|
||||
{mining ? <><span className="loading-spinner" style={{ width: 14, height: 14, borderWidth: 2, marginRight: 6, display: 'inline-block', verticalAlign: 'middle' }} />计算中</> : '开始挖掘'}
|
||||
</button>
|
||||
<span className="text-secondary text-sm">{status}</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{results.length > 0 && (
|
||||
<div className="stats-bar">
|
||||
<div className="stat-item"><span className="stat-value">{results.length}</span><span className="stat-label">公共组件数</span></div>
|
||||
<div className="stat-item"><span className="stat-value">{totalNodes}</span><span className="stat-label">总节点数</span></div>
|
||||
<div className="stat-item"><span className="stat-value">{(results.reduce((s: number, r: any) => s + r.productCount, 0) / results.length).toFixed(0)}</span><span className="stat-label">平均覆盖产品数</span></div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="flex justify-between items-center mb-8">
|
||||
<div className="card-title" style={{ margin: 0 }}>挖掘结果</div>
|
||||
<button
|
||||
className="btn btn-success"
|
||||
disabled={checkedList.length === 0 || mining}
|
||||
onClick={() => { adoptComponents(checkedList); toast('已批量采纳 ' + checkedList.length + ' 个标准组件'); setChecked({}); setMiningResult([...results]); }}
|
||||
>批量采纳选中项 ({checkedList.length})</button>
|
||||
</div>
|
||||
|
||||
{results.length === 0 ? (
|
||||
<div className="empty-state">
|
||||
<div className="empty-state-icon">🔍</div>
|
||||
<div className="empty-state-text">{mining ? '后台计算中,请稍候...' : '调整参数后点击"开始挖掘"'}</div>
|
||||
{!mining && <div className="empty-state-hint">系统将从 {products.length} 个产品中识别可复用的公共组件</div>}
|
||||
</div>
|
||||
) : (
|
||||
results.map((comp: any, idx: number) => {
|
||||
const isAdopted = standardFps.has(comp.fingerprint);
|
||||
const isOpen = !!expanded[idx];
|
||||
const scarcity = getScarcityLevel(comp.productCount, products.length);
|
||||
const weighted = getWeightedValue(comp.nodeCount, comp.productCount);
|
||||
return (
|
||||
<div className="mining-result-item" key={comp.fingerprint}>
|
||||
<div className="mining-result-header" onClick={() => setExpanded({ ...expanded, [idx]: !isOpen })}>
|
||||
<label className="checkbox-label" onClick={e => e.stopPropagation()}>
|
||||
<input
|
||||
type="checkbox"
|
||||
disabled={isAdopted}
|
||||
checked={isAdopted || !!checked[comp.fingerprint]}
|
||||
onChange={e => setChecked({ ...checked, [comp.fingerprint]: e.target.checked })}
|
||||
/>
|
||||
</label>
|
||||
<span style={{ fontWeight: 600, flex: 1 }}>{comp.template.part.name}</span>
|
||||
<ScarcityBadge productCount={comp.productCount} totalProducts={products.length} />
|
||||
<span className="mining-stat">节点 <strong>{comp.nodeCount}</strong></span>
|
||||
<span className="mining-stat">产品 <strong>{comp.productCount}</strong></span>
|
||||
<span className="mining-stat">价值 <strong>{comp.productCount * comp.nodeCount}</strong></span>
|
||||
{isAdopted && <span className="badge badge-reuse">已入库</span>}
|
||||
<span className="tree-toggle" style={{ width: 'auto', fontSize: 12 }}>{isOpen ? '收起 \u25B2' : '展开 \u25BC'}</span>
|
||||
</div>
|
||||
{isOpen && (
|
||||
<div className="mining-result-body expanded">
|
||||
<div style={{ display: 'flex', gap: 20 }}>
|
||||
<div style={{ flex: 1, minWidth: 0 }}>
|
||||
<div style={{ display: 'flex', gap: 8, marginBottom: 8, flexWrap: 'wrap' }}>
|
||||
<span className="mining-stat">节点 <strong>{comp.nodeCount}</strong></span>
|
||||
<span className="mining-stat">产品 <strong>{comp.productCount}</strong></span>
|
||||
<span className="mining-stat">覆盖率 <strong>{(comp.productCount / products.length * 100).toFixed(1)}%</strong></span>
|
||||
<span className="mining-stat">稀缺度 <strong style={{ color: scarcity.color }}>{scarcity.level}</strong></span>
|
||||
<span className="mining-stat">加权价值 <strong>{weighted}</strong></span>
|
||||
</div>
|
||||
<strong>组件结构({comp.nodeCount} 节点):</strong>
|
||||
<div className="card" style={{ marginTop: 8, padding: 12 }}><SubTree node={comp.template} /></div>
|
||||
{!isAdopted && (
|
||||
<div style={{ marginTop: 12 }}>
|
||||
<button className="btn btn-success btn-sm" onClick={() => { adoptComponent(comp); toast('已采纳「' + comp.template.part.name + '」为标准组件'); setMiningResult([...results]); }}>采纳为标准组件</button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
<div style={{ flex: 1.2, minWidth: 0 }}>
|
||||
<strong>引用产品({comp.productCount} 个)— 点击查看上下文:</strong>
|
||||
<div style={{ marginTop: 8, display: 'flex', flexWrap: 'wrap', gap: 6 }}>
|
||||
{comp.products.map((p: any) => (
|
||||
<button key={p.id} className="btn btn-sm" style={{ fontSize: 11 }} onClick={() => openContext(p.id, p.path, comp)}>{p.id}</button>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
})
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,132 @@
|
||||
import { useState } from 'react';
|
||||
import { computeAllFingerprints } from '../core/fingerprint.js';
|
||||
import { getStandardComponents } from '../core/store.js';
|
||||
import BomTree from './BomTree';
|
||||
import { IconTarget, IconSparkle } from './Icons';
|
||||
|
||||
export default function ReuseSearch({ newRequirements }: any) {
|
||||
const [selectedId, setSelectedId] = useState('');
|
||||
const [result, setResult] = useState<any>(null);
|
||||
|
||||
function search() {
|
||||
const req = newRequirements.find((r: any) => r.id === selectedId);
|
||||
if (!req) return;
|
||||
const standard = getStandardComponents();
|
||||
if (standard.length === 0) { setResult({ empty: true }); return; }
|
||||
|
||||
const standardFpMap = new Map(standard.map((c: any) => [c.fingerprint, c]));
|
||||
const fpMap = computeAllFingerprints(req.bom);
|
||||
|
||||
const allPaths: any[] = [];
|
||||
(function collect(node: any, path: any[]) {
|
||||
allPaths.push(path.join(','));
|
||||
if (node.children) node.children.forEach((c: any, i: number) => collect(c, [...path, i]));
|
||||
})(req.bom, []);
|
||||
|
||||
const hits: any[] = [];
|
||||
for (const [fp] of fpMap) {
|
||||
const sc = standardFpMap.get(fp);
|
||||
if (sc) hits.push({ comp: sc, fingerprint: fp });
|
||||
}
|
||||
|
||||
const covered = new Set<any>();
|
||||
for (const hit of hits) {
|
||||
for (const entry of fpMap.get(hit.fingerprint)) {
|
||||
(function mark(node: any, path: any[]) {
|
||||
covered.add(path.join(','));
|
||||
if (node.children) node.children.forEach((c: any, i: number) => mark(c, [...path, i]));
|
||||
})(entry.node, entry.path);
|
||||
}
|
||||
}
|
||||
|
||||
// 未覆盖叶子零件
|
||||
const uncovered: any[] = [];
|
||||
(function walk(node: any, path: any[]) {
|
||||
const isCovered = covered.has(path.join(','));
|
||||
if (!isCovered && (!node.children || node.children.length === 0)) {
|
||||
uncovered.push(node.part);
|
||||
}
|
||||
if (node.children) node.children.forEach((c: any, i: number) => walk(c, [...path, i]));
|
||||
})(req.bom, []);
|
||||
|
||||
setResult({
|
||||
req,
|
||||
hits,
|
||||
highlightSet: new Set(hits.map((h: any) => h.fingerprint)),
|
||||
totalNodes: allPaths.length,
|
||||
covered: covered.size,
|
||||
coverage: allPaths.length > 0 ? ((covered.size / allPaths.length) * 100).toFixed(1) : 0,
|
||||
uncovered,
|
||||
});
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
<div className="card">
|
||||
<div className="card-title"><span className="title-icon"><IconTarget /></span>选择新客户需求</div>
|
||||
<div className="control-row">
|
||||
<select value={selectedId} style={{ width: 400 }} onChange={e => setSelectedId(e.target.value)}>
|
||||
<option value="">-- 请选择新需求样例 --</option>
|
||||
{newRequirements.map((r: any) => <option key={r.id} value={r.id}>{r.id} - {r.name}</option>)}
|
||||
</select>
|
||||
<button className="btn btn-primary" disabled={!selectedId} onClick={search}><IconSparkle /> 检索复用</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{result && result.empty && (
|
||||
<div className="empty-state"><div className="empty-state-text">标准组件库为空,请先采纳标准组件</div></div>
|
||||
)}
|
||||
|
||||
{result && !result.empty && (
|
||||
<div className="reuse-layout">
|
||||
{/* 左:摘要 */}
|
||||
<div className="reuse-left">
|
||||
<div className="stats-bar" style={{ gridTemplateColumns: 'repeat(3, 1fr)', marginBottom: 14 }}>
|
||||
<div className="stat-item"><span className="stat-value">{result.hits.length}</span><span className="stat-label">命中标组件</span></div>
|
||||
<div className="stat-item"><span className="stat-value">{result.coverage}%</span><span className="stat-label">复用覆盖率</span></div>
|
||||
<div className="stat-item"><span className="stat-value">{result.covered}/{result.totalNodes}</span><span className="stat-label">覆盖/总节点</span></div>
|
||||
</div>
|
||||
|
||||
<div className="card" style={{ marginBottom: 14 }}>
|
||||
<div className="card-title" style={{ marginBottom: 8 }}>覆盖率</div>
|
||||
<div className="coverage-bar" style={{ height: 26, margin: 0 }}>
|
||||
<div className="coverage-fill" style={{ width: `${result.coverage}%` }}>{result.coverage}%</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="card" style={{ marginBottom: 14 }}>
|
||||
<div className="card-title" style={{ marginBottom: 8 }}>命中的标准组件({result.hits.length})</div>
|
||||
{result.hits.map((h: any) => (
|
||||
<div key={h.fingerprint} className="hit-item">
|
||||
<span className="badge badge-reuse">命中</span>
|
||||
<strong>{h.comp.template.part.name}</strong>
|
||||
<span className="text-muted text-sm" style={{ marginLeft: 'auto' }}>{h.comp.nodeCount} 节点</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
|
||||
<div className="card">
|
||||
<div className="card-title" style={{ marginBottom: 8 }}>需新设计零件({result.uncovered.length})</div>
|
||||
<div style={{ display: 'flex', flexWrap: 'wrap', gap: 6 }}>
|
||||
{result.uncovered.map((p: any, i: number) => (
|
||||
<span key={i} className="uncovered-tag" title={p.spec}>{p.name}</span>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* 右:BOM 树(绿色=命中) */}
|
||||
<div className="reuse-right">
|
||||
<div className="card" style={{ marginBottom: 0, height: '100%', display: 'flex', flexDirection: 'column' }}>
|
||||
<div className="card-title" style={{ marginBottom: 10 }}>
|
||||
新需求 BOM(绿色=命中)
|
||||
<span className="text-muted text-sm" style={{ marginLeft: 'auto' }}>{result.req.name}</span>
|
||||
</div>
|
||||
<BomTree root={result.req.bom} highlightSet={result.highlightSet} focus height="calc(100vh - 250px)" />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
import { useEffect, useState, useCallback } from 'react';
|
||||
import { IconX } from './Icons';
|
||||
|
||||
// 全局左右分栏侧面板:打开时内容区自动收缩,实现左右联动
|
||||
let api: { open: (t: string, b: any) => void; close: () => void } | null = null;
|
||||
|
||||
export function openSidePanel(title: string, body: any) {
|
||||
if (api) api.open(title, body);
|
||||
}
|
||||
|
||||
export function closeSidePanel() {
|
||||
if (api) api.close();
|
||||
}
|
||||
|
||||
export default function SidePanelHost({ width = 480 }: any) {
|
||||
const [open, setOpen] = useState(false);
|
||||
const [title, setTitle] = useState('');
|
||||
const [body, setBody] = useState<any>(null);
|
||||
|
||||
const openFn = useCallback((t: string, b: any) => { setTitle(t); setBody(b); setOpen(true); }, []);
|
||||
const closeFn = useCallback(() => setOpen(false), []);
|
||||
|
||||
useEffect(() => {
|
||||
api = { open: openFn, close: closeFn };
|
||||
const onKey = (e: KeyboardEvent) => { if (e.key === 'Escape') closeFn(); };
|
||||
window.addEventListener('keydown', onKey);
|
||||
return () => { api = null; window.removeEventListener('keydown', onKey); };
|
||||
}, [openFn, closeFn]);
|
||||
|
||||
return (
|
||||
<aside
|
||||
className={`side-panel ${open ? 'side-panel-open' : ''}`}
|
||||
style={{ width: open ? width : 0 }}
|
||||
aria-hidden={!open}
|
||||
>
|
||||
<div className="side-panel-inner" style={{ width }}>
|
||||
<div className="side-panel-header">
|
||||
<span className="side-panel-title">{title}</span>
|
||||
<button type="button" className="drawer-close" onClick={closeFn} aria-label="关闭" title="关闭">
|
||||
<IconX />
|
||||
</button>
|
||||
</div>
|
||||
<div className="side-panel-content">{body}</div>
|
||||
</div>
|
||||
</aside>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,241 @@
|
||||
import { useMemo, useState, useRef, useCallback, useEffect } from 'react';
|
||||
import { findSimilarProductsBatch, computeSimilarity } from '../core/similarity.js';
|
||||
import { computeProductNodeCounts } from '../core/mining.js';
|
||||
import { openSidePanel } from './SidePanel';
|
||||
import { IconCompare } from './Icons';
|
||||
|
||||
function SubTree({ node, depth = 0 }: any) {
|
||||
return (
|
||||
<div style={{ fontFamily: 'var(--font-mono)', fontSize: 12, lineHeight: 1.8, paddingLeft: depth * 12 }}>
|
||||
<span style={{ color: 'var(--accent-primary)' }}>{node.part.code}</span> {node.part.name} <span className="text-muted">x{node.qty}</span>
|
||||
{node.children && node.children.map((c: any, i: number) => <SubTree key={i} node={c} depth={depth + 1} />)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// 收集 BOM 树中所有零件编码
|
||||
function getAllCodes(node: any, set: Set<any>) {
|
||||
set.add(node.part.code);
|
||||
if (node.children) node.children.forEach((c: any) => getAllCodes(c, set));
|
||||
}
|
||||
|
||||
export default function SimilarityView({ products, miningResult }: any) {
|
||||
const [selectedId, setSelectedId] = useState('');
|
||||
const [similar, setSimilar] = useState<any>(null);
|
||||
const [searching, setSearching] = useState(false);
|
||||
const [searchProgress, setSearchProgress] = useState<any>({ done: 0, total: 0 });
|
||||
|
||||
const abortRef = useRef<AbortController | null>(null);
|
||||
|
||||
const nodeCounts = useMemo(() => computeProductNodeCounts(products), [products]);
|
||||
|
||||
useEffect(() => {
|
||||
return () => abortRef.current?.abort();
|
||||
}, []);
|
||||
|
||||
const find = useCallback(async () => {
|
||||
if (!selectedId || miningResult.length === 0) return;
|
||||
|
||||
abortRef.current?.abort();
|
||||
|
||||
setSearching(true);
|
||||
setSimilar(null);
|
||||
setSearchProgress({ done: 0, total: 0 });
|
||||
|
||||
const controller = new AbortController();
|
||||
abortRef.current = controller;
|
||||
|
||||
await new Promise<void>(r => requestAnimationFrame(() => r()));
|
||||
if (controller.signal.aborted) return;
|
||||
|
||||
const accumulated: any[] = [];
|
||||
|
||||
await findSimilarProductsBatch(selectedId, miningResult, nodeCounts, {
|
||||
batchSize: 50,
|
||||
signal: controller.signal,
|
||||
onBatch: (batch: any, info: any) => {
|
||||
if (controller.signal.aborted) return;
|
||||
accumulated.push(...batch);
|
||||
const sorted = [...accumulated].sort((a: any, b: any) =>
|
||||
b.normalizedPct - a.normalizedPct ||
|
||||
b.weightedScore - a.weightedScore ||
|
||||
b.score - a.score
|
||||
);
|
||||
setSimilar(sorted);
|
||||
setSearchProgress(info);
|
||||
},
|
||||
onDone: (allResults: any) => {
|
||||
if (controller.signal.aborted) return;
|
||||
setSimilar(allResults);
|
||||
setSearching(false);
|
||||
},
|
||||
});
|
||||
|
||||
if (controller.signal.aborted) return;
|
||||
setSearching(false);
|
||||
}, [selectedId, miningResult, nodeCounts]);
|
||||
|
||||
function openDetail(target: any, item: any) {
|
||||
const targetProduct = products.find((p: any) => p.id === target);
|
||||
const other = products.find((p: any) => p.id === item.productId);
|
||||
const sim: any = computeSimilarity(target, item.productId, miningResult, nodeCounts);
|
||||
|
||||
// 计算各自独有零件
|
||||
const codesA = new Set<any>();
|
||||
const codesB = new Set<any>();
|
||||
if (targetProduct) getAllCodes(targetProduct.bom, codesA);
|
||||
if (other) getAllCodes(other.bom, codesB);
|
||||
const onlyA = [...codesA].filter((c: any) => !codesB.has(c));
|
||||
const onlyB = [...codesB].filter((c: any) => !codesA.has(c));
|
||||
|
||||
openSidePanel(
|
||||
target + ' vs ' + item.productId,
|
||||
<>
|
||||
<div style={{ marginBottom: 16, display: 'flex', gap: 12, flexWrap: 'wrap' }}>
|
||||
<div className="mining-stat">BOM 重合度 <strong>{sim.normalizedPct}%</strong></div>
|
||||
<div className="mining-stat">共享组件 <strong>{sim.sharedCount}</strong></div>
|
||||
<div className="mining-stat">共享节点 <strong>{sim.score}</strong></div>
|
||||
</div>
|
||||
<div style={{ marginBottom: 16, display: 'flex', gap: 12, flexWrap: 'wrap' }}>
|
||||
<div className="mining-stat" style={{ background: 'var(--surface-2)' }}>
|
||||
{target} 独有零件 <strong style={{ color: 'var(--orange)' }}>{onlyA.length}</strong>
|
||||
</div>
|
||||
<div className="mining-stat" style={{ background: 'var(--surface-2)' }}>
|
||||
{item.productId} 独有零件 <strong style={{ color: 'var(--orange)' }}>{onlyB.length}</strong>
|
||||
</div>
|
||||
<div className="mining-stat" style={{ background: 'var(--surface-2)' }}>
|
||||
{target} 总节点 <strong>{nodeCounts.get(target)}</strong>
|
||||
</div>
|
||||
<div className="mining-stat" style={{ background: 'var(--surface-2)' }}>
|
||||
{item.productId} 总节点 <strong>{nodeCounts.get(item.productId)}</strong>
|
||||
</div>
|
||||
</div>
|
||||
<p className="text-secondary" style={{ marginBottom: 16, fontSize: 13, lineHeight: 1.6 }}>
|
||||
BOM 重合度 = 共享公共组件节点数 / 两者中较大产品的总节点数。
|
||||
{sim.normalizedPct === 100 && ' 重合度 100% 表示较大产品的所有节点均被公共组件覆盖,但双方仍各有独有定制件,不代表两个 BOM 完全相同。'}
|
||||
</p>
|
||||
{sim.sharedComponents.map((comp: any, i: number) => (
|
||||
<div key={i} style={{ border: '1px solid var(--line-1)', borderRadius: 12, marginBottom: 12, overflow: 'hidden' }}>
|
||||
<div style={{ padding: '10px 14px', background: 'var(--surface-2)', display: 'flex', alignItems: 'center', gap: 8 }}>
|
||||
<span style={{ fontWeight: 600, fontSize: 13 }}>{comp.template.part.name}</span>
|
||||
<span className="mining-stat">节点 <strong>{comp.nodeCount}</strong></span>
|
||||
<span className="mining-stat">覆盖率 <strong>{comp.productCount}</strong></span>
|
||||
</div>
|
||||
<div style={{ padding: '12px 14px' }}>
|
||||
<SubTree node={comp.template} />
|
||||
<div style={{ marginTop: 8, fontSize: 11, color: 'var(--text-3)' }}>同时出现在 {target} 与 {other?.id} 中</div>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
{/* 独有零件列表 */}
|
||||
{(onlyA.length > 0 || onlyB.length > 0) && (
|
||||
<div style={{ marginTop: 16, border: '1px solid var(--line-1)', borderRadius: 12, padding: 14 }}>
|
||||
<div style={{ fontWeight: 600, fontSize: 13, marginBottom: 10 }}>双方差异零件</div>
|
||||
{onlyA.length > 0 && (
|
||||
<div style={{ marginBottom: 10 }}>
|
||||
<span style={{ fontSize: 12, color: 'var(--orange)', fontWeight: 600 }}>{target} 独有({onlyA.length}):</span>
|
||||
<div style={{ marginTop: 6, display: 'flex', flexWrap: 'wrap', gap: 6 }}>
|
||||
{onlyA.map((c: any, i: number) => (
|
||||
<span key={i} style={{ fontSize: 11, padding: '3px 8px', background: 'var(--surface-2)', border: '1px solid var(--line-1)', borderRadius: 6, fontFamily: 'var(--font-mono)' }}>{c}</span>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
{onlyB.length > 0 && (
|
||||
<div>
|
||||
<span style={{ fontSize: 12, color: 'var(--orange)', fontWeight: 600 }}>{item.productId} 独有({onlyB.length}):</span>
|
||||
<div style={{ marginTop: 6, display: 'flex', flexWrap: 'wrap', gap: 6 }}>
|
||||
{onlyB.map((c: any, i: number) => (
|
||||
<span key={i} style={{ fontSize: 11, padding: '3px 8px', background: 'var(--surface-2)', border: '1px solid var(--line-1)', borderRadius: 6, fontFamily: 'var(--font-mono)' }}>{c}</span>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
<div className="card">
|
||||
<div className="card-title"><span className="title-icon"><IconCompare /></span>选择目标产品</div>
|
||||
<div className="control-row">
|
||||
<select value={selectedId} style={{ width: 400 }} onChange={e => setSelectedId(e.target.value)} disabled={searching}>
|
||||
<option value="">-- 请选择产品 --</option>
|
||||
{products.map((p: any) => <option key={p.id} value={p.id}>{p.id} - {p.name}</option>)}
|
||||
</select>
|
||||
<button className="btn btn-primary" disabled={!selectedId || searching || miningResult.length === 0} onClick={find}>
|
||||
{searching ? '分析中...' : '查找相似产品'}
|
||||
</button>
|
||||
</div>
|
||||
{miningResult.length === 0 && <div className="text-secondary text-sm" style={{ marginTop: 8 }}>提示:请先在"公共组件挖掘"页面执行挖掘</div>}
|
||||
</div>
|
||||
|
||||
{searching && (
|
||||
<div className="card">
|
||||
<div className="sim-searching">
|
||||
<span className="loading-spinner" />
|
||||
<span>正在分析相似产品... {searchProgress.total > 0 ? `${searchProgress.done}/${searchProgress.total}` : ''}</span>
|
||||
{similar && similar.length > 0 && <span className="sim-searching-count">已找到 {similar.length} 个</span>}
|
||||
</div>
|
||||
{searchProgress.total > 0 && (
|
||||
<div className="load-progress-bar-track" style={{ marginTop: 10 }}>
|
||||
<div
|
||||
className="load-progress-bar-fill"
|
||||
style={{ width: `${(searchProgress.done / searchProgress.total) * 100}%` }}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{similar && similar.length > 0 && (
|
||||
<div className="card">
|
||||
<div className="card-title">
|
||||
相似产品(共 {similar.length} 个{searching ? ',持续更新中...' : ''})— 按 BOM 重合度排序
|
||||
</div>
|
||||
<table className="data-table">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>排名</th>
|
||||
<th>产品编码</th>
|
||||
<th>产品名称</th>
|
||||
<th>BOM 重合度</th>
|
||||
<th>共享组件</th>
|
||||
<th>共享节点</th>
|
||||
<th>操作</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{similar.map((s: any, i: number) => {
|
||||
const p = products.find((x: any) => x.id === s.productId);
|
||||
const pct = s.normalizedPct;
|
||||
return (
|
||||
<tr key={s.productId} className="sim-row-appear">
|
||||
<td><strong>#{i + 1}</strong></td>
|
||||
<td className="font-mono">{s.productId}</td>
|
||||
<td>{p?.name || s.productId}</td>
|
||||
<td>
|
||||
<div className="coverage-bar" style={{ height: 16, width: 120 }}>
|
||||
<div className="coverage-fill" style={{ width: `${pct}%` }}>{pct}%</div>
|
||||
</div>
|
||||
</td>
|
||||
<td>{s.sharedCount} 个</td>
|
||||
<td>{s.score}</td>
|
||||
<td><button className="btn btn-sm" onClick={() => openDetail(selectedId, s)}>详情</button></td>
|
||||
</tr>
|
||||
);
|
||||
})}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{similar && similar.length === 0 && !searching && (
|
||||
<div className="empty-state"><div className="empty-state-text">未找到相似产品</div></div>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
// Skeleton.tsx - 加载骨架屏
|
||||
export default function Skeleton({ rows = 5, height = 40 }: any) {
|
||||
return (
|
||||
<div className="skeleton-wrap">
|
||||
{Array.from({ length: rows }).map((_, i) => (
|
||||
<div key={i} className="skeleton" style={{ height, animationDelay: `${i * 0.08}s` }} />
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,103 @@
|
||||
import { useEffect, useState } from 'react';
|
||||
import { getStandardComponents, removeComponent, clearStore, subscribe } from '../core/store.js';
|
||||
import { openSidePanel } from './SidePanel';
|
||||
import ConfirmModal from './ConfirmModal';
|
||||
import BomTree from './BomTree';
|
||||
import { toast } from './Toast';
|
||||
import { IconLayers, IconEye, IconTrash } from './Icons';
|
||||
|
||||
export default function StandardLibrary() {
|
||||
const [components, setComponents] = useState<any[]>(getStandardComponents());
|
||||
const [confirm, setConfirm] = useState<any>({ open: false, type: null, fingerprint: null });
|
||||
|
||||
useEffect(() => {
|
||||
const unsubscribe = subscribe(() => setComponents(getStandardComponents()));
|
||||
return () => { unsubscribe(); };
|
||||
}, []);
|
||||
|
||||
const totalNodes = components.reduce((s: number, c: any) => s + c.nodeCount, 0);
|
||||
|
||||
function openStructure(comp: any) {
|
||||
openSidePanel(
|
||||
comp.template.part.name,
|
||||
<>
|
||||
<div style={{ marginBottom: 16, display: 'flex', gap: 8 }}>
|
||||
<span className="mining-stat">节点 <strong>{comp.nodeCount}</strong></span>
|
||||
<span className="mining-stat">来源产品 <strong>{comp.productCount}</strong></span>
|
||||
</div>
|
||||
<div style={{ border: '1px solid var(--line-1)', borderRadius: 12, padding: 14, marginBottom: 16 }}>
|
||||
<BomTree root={comp.template} height="60vh" />
|
||||
</div>
|
||||
<div style={{ border: '1px solid var(--line-1)', borderRadius: 12, padding: 14 }}>
|
||||
<div style={{ fontWeight: 600, fontSize: 13, marginBottom: 8 }}>来源产品({comp.sourceProducts.length} 个)</div>
|
||||
<div style={{ display: 'flex', flexWrap: 'wrap', gap: 6 }}>
|
||||
{comp.sourceProducts.map((p: any) => (
|
||||
<span key={p.id} style={{ fontSize: 11, padding: '3px 8px', background: 'var(--indigo-soft)', border: '1px solid var(--line-1)', borderRadius: 6, fontFamily: 'var(--font-mono)' }}>{p.id}</span>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
<div className="flex justify-between items-center mb-16">
|
||||
<div className="card-title" style={{ margin: 0 }}><span className="title-icon"><IconLayers /></span>标准组件库</div>
|
||||
{components.length > 0 && (
|
||||
<button className="btn btn-danger btn-sm" onClick={() => setConfirm({ open: true, type: 'clear' })}>清空组件库</button>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{components.length === 0 ? (
|
||||
<div className="empty-state">
|
||||
<div className="empty-state-icon">📭</div>
|
||||
<div className="empty-state-text">标准组件库为空</div>
|
||||
<div className="empty-state-hint">请前往"公共组件挖掘"页面采纳标准组件</div>
|
||||
</div>
|
||||
) : (
|
||||
<>
|
||||
<div className="stats-bar">
|
||||
<div className="stat-item"><span className="stat-value">{components.length}</span><span className="stat-label">标准组件数</span></div>
|
||||
<div className="stat-item"><span className="stat-value">{totalNodes}</span><span className="stat-label">总节点数</span></div>
|
||||
</div>
|
||||
<table className="data-table">
|
||||
<thead><tr><th>序号</th><th>组件名称</th><th>节点数</th><th>来源产品数</th><th>入库时间</th><th>操作</th></tr></thead>
|
||||
<tbody>
|
||||
{components.map((comp: any, i: number) => (
|
||||
<tr key={comp.fingerprint}>
|
||||
<td>{i + 1}</td>
|
||||
<td><strong>{comp.template.part.name}</strong> <span className="text-secondary text-sm">{comp.template.part.code}</span></td>
|
||||
<td>{comp.nodeCount}</td>
|
||||
<td>{comp.productCount}</td>
|
||||
<td className="text-secondary">{new Date(comp.adoptedAt).toLocaleString()}</td>
|
||||
<td style={{ whiteSpace: 'nowrap' }}>
|
||||
<div style={{ display: 'flex', gap: 6 }}>
|
||||
<button className="btn btn-sm" onClick={() => openStructure(comp)}><IconEye /> 查看结构</button>
|
||||
<button className="btn btn-danger btn-sm" onClick={() => setConfirm({ open: true, type: 'remove', fingerprint: comp.fingerprint })}><IconTrash /> 移除</button>
|
||||
</div>
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</>
|
||||
)}
|
||||
|
||||
|
||||
|
||||
<ConfirmModal
|
||||
open={confirm.open}
|
||||
title={confirm.type === 'clear' ? '清空标准组件库' : '移除标准组件'}
|
||||
message={confirm.type === 'clear' ? `确定要清空整个标准组件库吗?(共 ${components.length} 个组件)` : '确定要移除此标准组件吗?'}
|
||||
confirmText={confirm.type === 'clear' ? '清空' : '移除'}
|
||||
onConfirm={() => {
|
||||
if (confirm.type === 'clear') { clearStore(); toast('标准组件库已清空', 'info'); }
|
||||
else { removeComponent(confirm.fingerprint); toast('已移除标准组件', 'info'); }
|
||||
setConfirm({ ...confirm, open: false });
|
||||
}}
|
||||
onCancel={() => setConfirm({ ...confirm, open: false })}
|
||||
/>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
import { useEffect, useState, useCallback } from 'react';
|
||||
|
||||
// 全局 Toast 系统
|
||||
let pushToast: ((message: string, type?: string) => void) | null = null;
|
||||
|
||||
export function toast(message: string, type = 'success') {
|
||||
if (pushToast) pushToast(message, type);
|
||||
}
|
||||
|
||||
export default function ToastContainer() {
|
||||
const [items, setItems] = useState<any[]>([]);
|
||||
|
||||
const add = useCallback((message: string, type?: string) => {
|
||||
const id = Date.now() + Math.random();
|
||||
setItems(prev => [...prev, { id, message, type }]);
|
||||
setTimeout(() => {
|
||||
setItems(prev => prev.filter((t: any) => t.id !== id));
|
||||
}, 3000);
|
||||
}, []);
|
||||
|
||||
useEffect(() => { pushToast = add; return () => { pushToast = null; }; }, [add]);
|
||||
|
||||
return (
|
||||
<div className="toast-container">
|
||||
{items.map(t => (
|
||||
<div key={t.id} className={`toast toast-${t.type}`}>
|
||||
<span className="toast-dot"></span>
|
||||
{t.message}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
Reference in New Issue
Block a user