first commit

This commit is contained in:
Jerry
2026-10-15 10:40:26 +08:00
commit 7ec529cba1
157 changed files with 26572 additions and 0 deletions
+8
View File
@@ -0,0 +1,8 @@
# Preserve mechanical source assets byte-for-byte on all platforms.
*.urdf -text
*.step -text
*.stp -text
*.stl -text
*.STL -text
*.STEP -text
*.STP -text
+10
View File
@@ -0,0 +1,10 @@
node_modules/
dist/
.vite/
coverage/
test-results/
*.tsbuildinfo
*.log
.DS_Store
.env*
!.env.example
+3
View File
@@ -0,0 +1,3 @@
# 前后台坐标一致性测试依赖
此目录仅保留 Management/tests/urdf-coordinate-consistency.test.ts 引用的前台装配模块,来源于前台仓库提交 ed029742fa9fa1cd49fc1555b8f4de0f997f3088。它不包含前台应用入口,不参与后台生产构建。
+63
View File
@@ -0,0 +1,63 @@
# 按网站域名选择 API 与静态部署
2026-10-14 更新:Client 与 Management 共用 `../../shared/api-origin.ts`。同一份 dist 可部署到对应的开发或正式网站,由浏览器实际访问的 hostname 决定 API。
| 网站来源 | API |
| --- | --- |
| https://dev-cadworld.robotquan.com | https://dev-cadworld-api.robotquan.com |
| https://dev-cadworld-admin.robotquan.com | https://dev-cadworld-api.robotquan.com |
| https://cadworld.robotquan.com | https://cadworld-api.robotquan.com |
| https://cadworld-admin.robotquan.com | https://cadworld-api.robotquan.com |
| localhost、回环及局域网 IP | 本地开发代理 |
未知网站域名会明确报告未配置,不自动连到正式环境。`.env.local` 的 ROBOT_API_TARGET 仅控制本地代理。新增域名需在共享模块中明确配置并重新构建。
## 部署
运行 npm run build,将 dist 上传至对应的静态网站目录。网页网站只需配置路由回退:
```nginx
location / {
try_files $uri $uri/ /index.html;
}
```
线上业务请求直接访问 API 域名,无需在网页站点增加 /api/robot-* 或模型资源代理。服务端开发代理仅服务本地开发。旧说明中要求网页站点配置同源接口代理的内容已被本次直连方案取代。
## 请求与资源
JSON、multipart 图片上传、POST SSE、查询、重试与取消使用同一 API 地址规则。需求请求保留 credentials: include。后端返回的私有图片预览地址也转换为当前环境 API。
URDF、STL/OBJ/DAE 及贴图直接从 https://linkerbot.oss-cn-beijing.aliyuncs.com 下载。返回的 /admin-api/component-assets/ 或旧 /api/robot-model-assets/ 前缀只用于提取对象键,不再调用该下载接口。对象键中的 cadworld_dev/cadworld 等目录按接口返回值保留,不随页面环境替换。中文路径每段正确编码,查询参数和已返回的直连签名地址保留。模型请求不带业务 Cookie。JSON、SSE 和用户上传需求图片仍按网站域名访问业务 API。
## 后端跨域
网页与 API 域名不同。后端应允许对应网站的 Origin;OPTIONS 不应被鉴权或 CSRF 提前拦截。支持 GET、POST、PUT、PATCH、DELETE、HEAD、OPTIONS 及 Content-Type、X-Request-Id 请求头。响应需提供匹配的 Access-Control-Allow-Origin、Access-Control-Allow-Credentials: true,不能与通配 Origin * 组合。普通响应、SSE 和模型资源响应都应正确包含 CORS 头,不只是预检。
会话 Cookie 由 API 域名设置与接收,保留 HttpOnly / Secure 和合适的 SameSite 策略,前端不读写 Cookie。线上网站和 API 均使用 HTTPS。
## 验证结果
2026-10-14:前台 53 项测试通过,管理后台 82 项测试通过,两套构建成功。覆盖环境域名选择、本地代理、直连 JSON、multipart、SSE、私有图片和模型资源路径。
只读远端检查:正式 API 对正式后台的 GET /admin-api/components(X-Request-Id)预检以及正式前台 POST /api/robot-conversations(Content-Type)预检返回 200,包含准确 Origin、允许的请求头及 Allow-Credentials: true。开发 API 对开发前台/后台预检返回 403 Invalid CORS request,未携带 CORS 许可头,需后端补齐开发来源。此检查没有创建线上会话或执行上传,不等于完整线上业务验收。
## 文件坐标与接口对齐(2026-10-14)
连接计算统一使用 `T_child_root = T_parent_root × T_parent_port × inverse(T_child_port)`。接口位置和三个坐标轴同时重合,不再插入 X 轴 180° 翻转,不根据“头应该朝上”修改文件定义。局部关节、visual origin、网格和源文件字节保持不变,变换只作用于组件外层组。
后端可标识资源和配对节点,但额外装配矩阵不覆盖实际 URDF 接口计算。对齐只施加刚体变换,不缩放、镜像或剪切。没有唯一安装点的零件单独展示,不猜用根节点。跨零件关系缺失只影响连接,不隐藏正常加载的零件。
前后台联合回归测试使用含非零 XYZ/RPY、多级父节点和倒置接口的 URDF,检查前台组件内的累计矩阵与后台原始预览逐节点一致,装配后两接口完整世界矩阵重合,上传 File 内容没有变化。后台点位悬停和适配视图只调整相机与独立标记。颜色和光照是既有显示效果,不属于原始几何坐标。
## 本地来源与资源接口复查(2026-10-14,后续)
已修复 Vite 本地代理将浏览器 localhost Origin 转发到远端 API 后被 CORS 拒绝的问题。开发和 preview 在代理前校验请求 Origin 与当前 Host 一致,拒绝外站来源,校验通过后不向上游转发本地 Origin;该规则与独立 Node 本地代理一致。Management 使用同一中间件。线上按域名直连规则不变。
错误处理已修复:403/502 等非 JSON 网关响应保留 HTTP 状态,不再误报为后端字段格式不完整。新增回归测试通过,当前前台 59 项、后台 83 项测试通过;本地原需求已完成真实解析、匹配及两个模型加载。
开发 API 会话业务路径当前已允许开发前台。当前剩余线上问题仅限已测模型资源路径:/admin-api/component-assets/** 对开发后台 Origin 返回 200,对开发前台 Origin 返回 403 Invalid CORS request,同一文件匿名无 Origin 请求也是 200。后端需要在模型资源 CORS 规则中加入前台来源,不应仅开放 /api/**。此前文档中的整体开发来源失败记录是早期结果,以本段按路径区分的后续实测为准。
## 模型桶直连更新(2026-10-14)
前台和后台共用 `../../shared/object-storage.ts`。管理后台 STEP、URDF 及全部依赖资源直接拼接对象键下载;前台将接口返回的模型资源 URL 转成同一桶地址。业务接口和后端签名直传上传流程保持原有契约。此前模型下载接口的 403 排查记录只适用于旧下载方式。存储桶需对实际网站来源允许 GET/HEAD;前台开发来源的示例 URDF 已实测 200。前台 61 项、后台 88 项测试通过,均生产构建成功。
+141
View File
@@ -0,0 +1,141 @@
import type { AnalysisResult } from "./requirements";
export interface Conversation {
conversationId: string;
revision: number;
expiresAt: string;
}
export type AnalysisStatus =
| "processing"
| "ready"
| "needs_clarification"
| "failed"
| "cancelled"
| "superseded";
export interface AnalysisView {
analysisId: string;
conversationId: string;
revision: number;
status: AnalysisStatus;
canSubmit: boolean;
summary: string;
questions: string[];
warnings: string[];
result: AnalysisResult | null;
}
export interface AnalysisProgress {
analysisId: string;
revision: number;
stage: string;
message: string;
}
export interface Attachment {
attachmentId: string;
mimeType: string;
sizeBytes: number;
previewUrl: string;
}
export interface Resource {
relativePath: string;
url: string;
version: number;
expiresAt: string | null;
}
export interface Issue {
code?: string;
category?: string;
componentCode?: string;
message?: string;
reason?: string;
[key: string]: unknown;
}
export interface ComponentDto {
rotationAxis?: string | null;
componentCode: string;
componentName: string;
category: string;
description?: string;
material?: string;
massKg?: number | null;
degreesOfFreedom?: number;
torqueNm?: number;
functionDescription?: string;
shape?: string;
size?: string;
version: number;
urdfUrl?: string;
stepUrl?: string;
bomList?: unknown;
urdfInfo: {
rootLink?: string;
frames?: unknown[];
assembly?: { mountingFrame?: string; pairingConvention?: string };
[key: string]: unknown;
};
}
export interface SelectedComponent {
instanceId: string;
component: ComponentDto;
urdfMainPath: string;
resources: Resource[];
resourceIssues: Issue[];
}
export interface Connection {
parentInstanceId: string;
parentFrame: string;
parentLink: string;
childInstanceId: string;
childFrame: string;
childRootLink: string;
parentRootToInterface: number[];
childRootToInterface: number[];
childRootRelativeToParentRoot: number[];
}
export interface Assembly {
status: "ready" | "blocked";
rootInstanceId: string;
matrixLayout: "column-major";
connections: Connection[];
issues: Issue[];
}
export interface RequirementCheck {
intentId: string;
priority: "must" | "prefer" | "context";
status: "satisfied" | "unmet" | "unverified";
field?: string;
expected?: unknown;
actual?: unknown;
reason: string;
}
export interface Totals {
degreesOfFreedom: number;
massKg: number | null;
knownMassKg: number;
massComplete: boolean;
}
export interface Alternative extends Omit<SelectedComponent, "instanceId"> {
totals: Totals;
unmetRequirements: Issue[];
unmatchedKeywords: unknown[];
requirementChecks: RequirementCheck[];
assembly: Assembly;
degradationAcceptanceRequired: boolean;
}
export interface DemandMatch {
analysisId: string;
revision: number;
matchId: string;
status: "complete" | "partial" | "no_match";
rootCategory: string;
searchLimited: boolean;
degradationAcceptanceRequired: boolean;
degradationAccepted: boolean;
totals: Totals;
unmetRequirements: Issue[];
unmatchedKeywords: unknown[];
missingParts: Issue[];
requirementChecks: RequirementCheck[];
assembly: Assembly;
components: SelectedComponent[];
alternatives: { category: string; items: Alternative[] }[];
}
+101
View File
@@ -0,0 +1,101 @@
export type PartCategory =
| "torso_0"
| "head_0"
| "waist_0"
| "arm_l"
| "arm_r"
| "hand_l"
| "hand_r"
| "leg_l"
| "leg_r"
| "foot_l"
| "foot_r"
| "tail_0";
export interface RequirementFields {
componentName?: string;
degreesOfFreedom?: number;
material?: string;
functionDescription?: string;
shape?: string;
size?: string;
torqueNm?: number;
massKg?: number;
description?: string;
operators?: Partial<
Record<"degreesOfFreedom" | "massKg" | "torqueNm", "eq" | "lte" | "gte">
>;
}
export interface MatchRequest {
userInput: string;
requirements: string[];
requiredParts: PartCategory[];
robotRequirements: RequirementFields;
partRequirements: (RequirementFields & { category: PartCategory })[];
}
export interface AnalysisResult {
request: MatchRequest;
analysis: {
schemaVersion?: string;
intentItems?: {
id: string;
dimension: string;
subject: string;
requirement: string;
priority: "must" | "prefer" | "context";
source: "explicit" | "inferred";
evidenceIds: string[];
evidence: string;
}[];
observations?: {
id: string;
messageId: string;
imageId: string;
kind: "user_text" | "image_text" | "image_visual";
content: string;
clarity: "clear" | "uncertain";
region: number[];
}[];
images?: {
imageId: string;
type: string;
usage: string;
uncertainties: string[];
}[];
summary: string;
keywords: {
term: string;
source: "explicit" | "inferred";
evidence: string;
reason: string;
negated: boolean;
}[];
robotTypes: {
type: string;
source: "explicit" | "inferred";
evidence: string;
reason: string;
}[];
partCategories: {
category: PartCategory;
source: "explicit" | "inferred";
evidence: string;
reason: string;
}[];
excludedCategories: { category: PartCategory; evidence: string }[];
constraints: {
scope: "robot" | "part" | "unspecified";
categories: PartCategory[];
field: string;
value: string;
upperValue: string;
operator: string;
evidence: string;
}[];
unmodeled: { text: string; evidence: string; reason: string }[];
questions: string[];
warnings: string[];
catalogVersion?: string;
status: "ready" | "needs_clarification";
canSubmit: boolean;
};
}
+81
View File
@@ -0,0 +1,81 @@
export type Vector = [number, number, number];
export interface ModelLink {
mesh: string;
label?: string;
xyz: Vector;
rpy: Vector;
}
export interface ModelJoint {
source?: "urdf" | "assembly";
type?: string;
assemblyJointId?: string;
childOffset?: number[];
name: string;
parent: string;
child: string;
xyz: Vector;
rpy: Vector;
axis: Vector;
lower: number | null;
upper: number | null;
}
export interface ModelData {
root: string;
roots?: string[];
links: Record<string, ModelLink>;
joints: ModelJoint[];
}
export interface MeshData {
p: string;
i: string;
i32: boolean;
}
export interface ModelAsset extends ModelData {
meshes: Record<string, MeshData>;
}
// The workspace starts empty; example assets are never loaded implicitly.
export const model: ModelData = {
root: "",
links: {},
joints: [],
};
const labels: Record<string, string> = {
base_link: "基座",
torso_link: "躯干",
thigh_yaw: "髋部偏航",
thigh_roll: "髋部侧摆",
thigh_pitch: "髋部俯仰",
knee: "膝关节",
ankle_pitch: "踝部俯仰",
ankle_roll: "踝部侧摆",
arm_pitch: "肩部俯仰",
arm_roll: "肩部侧摆",
arm_yaw: "上臂旋转",
elbow_pitch: "肘部俯仰",
elbow_yaw: "前臂旋转",
};
export function linkLabel(name: string): string {
if (labels[name]) return labels[name];
const side = name.startsWith("left_")
? "左"
: name.startsWith("right_")
? "右"
: "";
const key = name.replace(/^(left|right)_/, "").replace(/_link$/, "");
return side + (labels[key] ?? key);
}
export const childrenOf = (name: string) =>
model.joints.filter((j) => j.parent === name);
export function downloadText(
name: string,
content: string,
type = "application/json",
) {
const url = URL.createObjectURL(new Blob([content], { type }));
const anchor = document.createElement("a");
anchor.href = url;
anchor.download = name;
anchor.click();
setTimeout(() => URL.revokeObjectURL(url), 1000);
}
+84
View File
@@ -0,0 +1,84 @@
import { Group, Vector3 } from "three";
import {
parseRotationAxis,
rotationAxisVector,
type RotationAxis,
} from "../../../shared/rotation-axis.ts";
import type {
ComponentFrames,
ResolvedConnection,
} from "./automatic-assembly.ts";
export interface AssemblyJoint {
id: string;
instanceId: string;
componentName: string;
rotationAxis: RotationAxis;
axis: [number, number, number];
}
export interface AssemblyMotion extends AssemblyJoint {
setAngle: (radians: number) => void;
}
/** Parent → interface → rotation → inverse child interface → original URDF.
* The zero pose is exactly the file-defined assembly, including all offsets.
*/
export function connectComponentGroups(
groups: Map<string, Group>,
parts: ComponentFrames[],
connections: ResolvedConnection[],
) {
const motions: AssemblyMotion[] = [],
warnings: string[] = [];
for (const connection of connections) {
const parent = groups.get(connection.parent)!,
child = groups.get(connection.child)!;
const parentPart = parts.find(
(part) => part.item.instanceId === connection.parent,
)!;
const childPart = parts.find(
(part) => part.item.instanceId === connection.child,
)!;
let rotationAxis: RotationAxis | null = null;
try {
rotationAxis = parseRotationAxis(childPart.item.component.rotationAxis);
} catch (error) {
warnings.push(
`${childPart.item.component.componentName}:${(error as Error).message},当前按固定连接展示。`,
);
}
child.matrixAutoUpdate = false;
if (!rotationAxis) {
parent.add(child);
child.matrix.copy(connection.relative);
continue;
}
const pivot = new Group(),
rotor = new Group();
const id = `assembly/${connection.child}`;
pivot.name = `${id}/interface`;
pivot.matrixAutoUpdate = false;
pivot.matrix.copy(parentPart.frames.get(connection.parentFrame)!);
rotor.name = id;
parent.add(pivot);
pivot.add(rotor);
rotor.add(child);
child.matrix.copy(childPart.frames.get(connection.childFrame)!).invert();
const axis = rotationAxisVector(rotationAxis),
vector = new Vector3(...axis);
motions.push({
id,
instanceId: connection.child,
componentName: childPart.item.component.componentName,
rotationAxis,
axis,
setAngle(radians) {
if (!Number.isFinite(radians))
throw new Error("关节角度必须是有效数值");
rotor.quaternion.setFromAxisAngle(vector, radians);
rotor.updateMatrix();
},
});
}
return { motions, warnings };
}
+69
View File
@@ -0,0 +1,69 @@
import { Matrix4 } from "three";
import type { Resource } from "../ai/demand-types";
import { resourceDownloadUrl } from "../../../shared/object-storage.ts";
export function modelResourceUrl(value: string, origin: string): string {
return resourceDownloadUrl(value, origin);
}
/** A placement must be rigid: never scale, shear or mirror a component. */
export function isRigidTransform(matrix: Matrix4): boolean {
const e = matrix.elements;
if (
!e.every(Number.isFinite) ||
[3, 7, 11].some((i) => Math.abs(e[i]) > 1e-8) ||
Math.abs(e[15] - 1) > 1e-8
)
return false;
const columns = [
[e[0], e[1], e[2]],
[e[4], e[5], e[6]],
[e[8], e[9], e[10]],
];
const dot = (a: number[], b: number[]) =>
a.reduce((sum, value, i) => sum + value * b[i], 0);
return (
columns.every((column) => Math.abs(dot(column, column) - 1) < 1e-5) &&
Math.abs(dot(columns[0], columns[1])) < 1e-5 &&
Math.abs(dot(columns[0], columns[2])) < 1e-5 &&
Math.abs(dot(columns[1], columns[2])) < 1e-5 &&
Math.abs(matrix.determinant() - 1) < 1e-5
);
}
// Accumulated root-to-port transforms. Match the full coordinate frames,
// including their file-defined directions; never insert a corrective rotation.
export function alignInterfaceFrames(parent: Matrix4, child: Matrix4): Matrix4 {
if (!isRigidTransform(parent) || !isRigidTransform(child))
throw Error("安装节点的坐标矩阵无效。");
return parent.clone().multiply(child.clone().invert());
}
export function resourcePath(value: string): string {
const clean = value
.replace(/\\/g, "/")
.replace(/^package:\/\//, "")
.replace(/^\.\//, "");
const path = new URL(clean, "https://urdf.invalid/");
return decodeURIComponent(path.pathname).replace(/^\//, "");
}
export function resolveResource(
resources: Resource[],
reference: string,
): Resource {
const byUrl = resources.find((resource) => resource.url === reference);
if (byUrl) return byUrl;
const path = resourcePath(reference);
const exact = resources.filter(
(resource) => resourcePath(resource.relativePath) === path,
);
if (exact.length === 1) return exact[0];
if (reference.startsWith("package://")) {
const candidates = resources.filter((resource) =>
path.endsWith("/" + resourcePath(resource.relativePath)),
);
if (candidates.length === 1) return candidates[0];
}
throw Error(`资源清单缺少或无法唯一定位:${path}`);
}
+170
View File
@@ -0,0 +1,170 @@
import {
interfaceIdentityFromLink,
partIdentityFromFileName,
} from "../../../shared/part-naming.ts";
import { Matrix4 } from "three";
import { alignInterfaceFrames } from "./assembly-plan.ts";
import type { Assembly, SelectedComponent } from "../ai/demand-types";
export interface ComponentFrames {
item: SelectedComponent;
rootLink: string;
frames: Map<string, Matrix4>;
ports: Map<string, string>;
}
export interface ResolvedConnection {
parent: string;
child: string;
parentFrame: string;
childFrame: string;
relative: Matrix4;
}
export function interfaceCategory(name: string): string | undefined {
return interfaceIdentityFromLink(name)?.key;
}
/** Prefer declared names; for existing files use the backend's explicit port type. */
export function componentPorts(linkNames: string[], metadata: unknown[] = []) {
const links = new Set(linkNames);
const ports = new Map<string, string>();
for (const name of linkNames) {
const category = interfaceCategory(name);
if (category) ports.set(name, category);
}
for (const value of metadata) {
if (!value || typeof value !== "object") continue;
const frame = value as { child?: unknown; interfaceType?: unknown };
if (
typeof frame.child !== "string" ||
typeof frame.interfaceType !== "string" ||
!links.has(frame.child) ||
ports.has(frame.child)
)
continue;
const category = interfaceCategory(
`LINK_${frame.interfaceType.toUpperCase()}`,
);
if (category) ports.set(frame.child, category);
}
return ports;
}
/** The main filename identifies the component; link names identify its sockets. */
export function componentCategory(item: SelectedComponent): string {
const filename = item.urdfMainPath?.split("/").at(-1) || "";
let decoded = filename;
try {
decoded = decodeURIComponent(filename);
} catch {
/* Keep the original filename. */
}
return (
partIdentityFromFileName(decoded)?.key ||
item.component.category.toLowerCase()
);
}
/** Display actual returned components. Business completeness never gates geometry. */
export function resolveAssembly(parts: ComponentFrames[], assembly: Assembly) {
const warnings: string[] = [],
connections: ResolvedConnection[] = [];
const world = new Map<string, Matrix4>();
if (!parts.length) return { world, connections, warnings };
const root =
parts.find((part) => part.item.instanceId === assembly.rootInstanceId) ||
parts.find((part) => componentCategory(part.item) === "torso_0") ||
parts[0];
world.set(root.item.instanceId, new Matrix4());
const usedPorts = new Set<string>();
let pending = parts.filter((part) => part !== root);
const reasons = new Map<string, string>();
while (pending.length) {
let progressed = false;
pending = pending.filter((child) => {
const id = child.item.instanceId;
const edges = assembly.connections.filter(
(edge) => edge.childInstanceId === id,
);
if (edges.length > 1) {
reasons.set(id, "后端返回了多个父连接");
return true;
}
const edge = edges[0];
if (edge && !world.has(edge.parentInstanceId)) {
reasons.set(id, "父零件尚未连接");
return true;
}
// The backend identifies resources and paired nodes. Always derive the
// placement from the actual URDF frames, never from an override matrix.
const candidates = parts.flatMap((parent) => {
const parentId = parent.item.instanceId;
if (
!world.has(parentId) ||
(edge && edge.parentInstanceId !== parentId)
)
return [];
const requestedFrame = edge?.parentFrame || edge?.parentLink;
if (requestedFrame && parent.frames.has(requestedFrame))
return !usedPorts.has(`${parentId}/${requestedFrame}`)
? [{ parent, frame: requestedFrame }]
: [];
return [...parent.ports]
.filter(
([frame, category]) =>
category === componentCategory(child.item) &&
!usedPorts.has(`${parentId}/${frame}`),
)
.map(([frame]) => ({ parent, frame }));
});
if (candidates.length !== 1) {
reasons.set(
id,
candidates.length
? "存在多个同类安装节点,无法唯一确定连接"
: "未找到对应的父安装节点",
);
return true;
}
const ownPorts = [...child.ports].filter(
([, category]) => category === componentCategory(child.item),
);
const childFrame = [
edge?.childFrame,
child.item.component.urdfInfo?.assembly?.mountingFrame,
ownPorts.length === 1 ? ownPorts[0][0] : undefined,
].find((name) => name && child.frames.has(name));
if (!childFrame || !child.frames.has(childFrame)) {
reasons.set(id, "无法唯一确定子安装节点");
return true;
}
const { parent, frame } = candidates[0];
let relative: Matrix4;
try {
relative = alignInterfaceFrames(
parent.frames.get(frame)!,
child.frames.get(childFrame)!,
);
} catch {
reasons.set(id, "安装节点坐标不是有效刚体变换");
return true;
}
world.set(
id,
world.get(parent.item.instanceId)!.clone().multiply(relative),
);
connections.push({
parent: parent.item.instanceId,
child: id,
parentFrame: frame,
childFrame,
relative,
});
usedPorts.add(`${parent.item.instanceId}/${frame}`);
progressed = true;
return false;
});
if (!progressed) break;
}
for (const part of pending)
warnings.push(
`${part.item.component.componentName}:${reasons.get(part.item.instanceId) || "无法确定连接"},已单独展示。`,
);
return { world, connections, warnings };
}
+408
View File
@@ -0,0 +1,408 @@
import { connectComponentGroups, type AssemblyJoint } from "./assembly-motion";
import * as THREE from "three";
import URDFLoader from "urdf-loader";
import { STLLoader } from "three/addons/loaders/STLLoader.js";
import { OBJLoader } from "three/addons/loaders/OBJLoader.js";
import { ColladaLoader } from "three/addons/loaders/ColladaLoader.js";
import { MTLLoader } from "three/addons/loaders/MTLLoader.js";
import {
resourcePath,
resolveResource,
modelResourceUrl,
} from "./assembly-plan";
import {
componentPorts,
resolveAssembly,
type ComponentFrames,
} from "./automatic-assembly";
import type { ModelData, Vector } from "../data/model";
import { disposeRobot } from "./robot";
import type {
DemandMatch,
SelectedComponent,
Resource,
} from "../ai/demand-types";
async function loadComponent(item: SelectedComponent, signal: AbortSignal) {
const resources = new Map<string, Resource>();
for (const resource of item.resources) {
const path = resourcePath(resource.relativePath);
if (resources.has(path)) throw Error("资源清单存在重复路径。");
resources.set(path, resource);
}
const resolve = (reference: string) =>
resolveResource(item.resources, reference);
const get = async (reference: string) => {
const resource = resolve(reference);
const url = modelResourceUrl(resource.url, window.location.origin);
const response = await fetch(url, {
credentials: "omit",
signal: AbortSignal.any([signal, AbortSignal.timeout(30000)]),
});
if (!response.ok)
throw Error(
`模型资源加载失败(${response.status}):${resource.relativePath}`,
);
return response;
};
const xml = await (await get(item.urdfMainPath)).text();
const document = new DOMParser().parseFromString(xml, "application/xml");
if (
document.querySelector("parsererror") ||
document.documentElement.tagName !== "robot"
)
throw Error("URDF 文件格式无效。");
const manager = new THREE.LoadingManager();
const loader = new URDFLoader(manager);
const jobs: Promise<void>[] = [];
const fail: string[] = [];
const loaded = new Promise<void>((resolve) => {
manager.onLoad = resolve;
});
manager.onError = () => {
fail.push("模型贴图或网格未能完整加载。");
};
manager.setURLModifier((reference) => {
return modelResourceUrl(resolve(reference).url, window.location.origin);
});
loader.workingPath = resourcePath(item.urdfMainPath).replace(/[^/]*$/, "");
loader.packages = (name) => `package://${name}/`;
loader.parseCollision = false;
loader.loadMeshCb = (path, _manager, done) => {
manager.itemStart(path);
const job = (async () => {
try {
signal.throwIfAborted();
const resource = resolve(path);
const extension = resource.relativePath
.split(".")
.at(-1)
?.toLowerCase();
const response = await get(path);
let object: THREE.Object3D;
if (extension === "stl") {
const geometry = new STLLoader().parse(await response.arrayBuffer());
object = new THREE.Mesh(
geometry,
new THREE.MeshStandardMaterial({
color: 0xb8bfc7,
metalness: 0.25,
roughness: 0.55,
}),
);
} else if (extension === "obj") {
const text = await response.text();
const obj = new OBJLoader(manager);
const base = resourcePath(path).replace(/[^/]*$/, "");
const libraries = [...text.matchAll(/^\s*mtllib\s+(.+)$/gm)];
if (libraries.length > 1)
throw Error("此 OBJ 包含多个材质库,暂不支持预览。");
if (libraries.length) {
const mtlPath = resourcePath(base + libraries[0][1].trim());
const materials = new MTLLoader(manager).parse(
await (await get(mtlPath)).text(),
mtlPath.replace(/[^/]*$/, ""),
);
materials.preload();
obj.setMaterials(materials);
}
object = obj.parse(text);
} else if (extension === "dae") {
const parsed = new ColladaLoader(manager).parse(
await response.text(),
resourcePath(path).replace(/[^/]*$/, ""),
);
if (!parsed) throw Error("DAE 解析失败。");
object = parsed.scene;
} else throw Error(`暂不支持 ${extension} 网格,支持 STL、OBJ、DAE。`);
const original = object instanceof THREE.Mesh ? object.material : null;
done(object);
if (
original &&
object instanceof THREE.Mesh &&
original !== object.material
)
for (const material of Array.isArray(original)
? original
: [original])
material.dispose();
} catch (error) {
fail.push(error instanceof Error ? error.message : "零件加载失败。");
done(new THREE.Group(), new Error(fail.at(-1)));
} finally {
manager.itemEnd(path);
}
})();
jobs.push(job);
};
let robot: ReturnType<URDFLoader["parse"]> | undefined;
try {
manager.itemStart("urdf-document");
robot = loader.parse(xml);
manager.itemEnd("urdf-document");
await Promise.all(jobs);
await Promise.race([
loaded,
new Promise<never>((_, reject) => {
const timeout = setTimeout(() => {
fail.push("贴图加载超时。");
reject(Error("贴图加载超时。"));
}, 45000);
loaded.finally(() => clearTimeout(timeout));
}),
]);
signal.throwIfAborted();
// URDF content is authoritative. Cached root metadata must not discard a
// successfully loaded model; failed optional meshes do not hide the rest.
let hasGeometry = false;
robot.traverse((object) => {
if ((object as THREE.Mesh).isMesh) hasGeometry = true;
});
if (fail.length && !hasGeometry) throw Error(fail.join(";"));
robot.userData.resourceWarnings = [...new Set(fail)];
robot.traverse((object) => {
if (object instanceof THREE.Mesh) {
const materials = Array.isArray(object.material)
? object.material
: [object.material];
object.material = materials.map((material) => {
if (material instanceof THREE.MeshStandardMaterial) return material;
const converted = new THREE.MeshStandardMaterial({
color: material.color || 0xb8bfc7,
map: material.map || null,
transparent: material.transparent,
opacity: material.opacity,
side: material.side,
roughness: 0.6,
metalness: 0.2,
});
material.dispose();
return converted;
});
if (object.material.length === 1) object.material = object.material[0];
let link: THREE.Object3D | null = object.parent;
while (link && !("isURDFLink" in link)) link = link.parent;
object.name = `${item.instanceId}/${link?.name || robot!.name}`;
}
});
return robot;
} catch (error) {
if (robot) disposeRobot(robot);
throw error;
}
}
export interface LoadedAssembly {
root: THREE.Group;
model: ModelData;
warnings: string[];
componentCount: number;
connectionCount: number;
assemblyJoints: AssemblyJoint[];
setJointAngle: (id: string, radians: number) => void;
getModel: () => ModelData;
}
export async function createDemandRobot(
match: DemandMatch,
signal: AbortSignal,
): Promise<LoadedAssembly> {
const root = new THREE.Group();
const loaded: {
item: SelectedComponent;
robot: Awaited<ReturnType<typeof loadComponent>>;
group: THREE.Group;
}[] = [];
const warnings: string[] = [];
try {
const ids = new Set<string>();
for (const item of match.components) {
if (ids.has(item.instanceId))
throw Error("后端返回了重复的零件实例编号。");
ids.add(item.instanceId);
try {
const robot = await loadComponent(item, signal);
const group = new THREE.Group();
group.name = item.instanceId;
group.add(robot);
root.add(group);
robot.updateMatrixWorld(true);
loaded.push({ item, robot, group });
for (const warning of robot.userData.resourceWarnings || [])
warnings.push(`${item.component.componentName}:${warning}`);
} catch (error) {
signal.throwIfAborted();
warnings.push(
`${item.component.componentName}:${error instanceof Error ? error.message : "文件加载失败"}`,
);
}
}
if (!loaded.length)
throw Error(warnings.join(";") || "接口未返回可加载的零件。");
const frames: ComponentFrames[] = loaded.map(({ item, robot }) => {
const inverse = robot.matrixWorld.clone().invert();
const entries = new Map<string, THREE.Matrix4>();
for (const [name, frame] of Object.entries({
...robot.joints,
...robot.links,
}))
entries.set(name, inverse.clone().multiply(frame.matrixWorld));
const ports = componentPorts(
Object.keys(robot.links),
item.component.urdfInfo?.frames,
);
return { item, rootLink: robot.name, frames: entries, ports };
});
const result = resolveAssembly(frames, match.assembly);
warnings.push(...result.warnings);
for (const { item, group } of loaded) {
const transform = result.world.get(item.instanceId);
group.visible = true;
if (transform) {
group.matrixAutoUpdate = false;
group.matrix.copy(transform);
}
}
root.updateMatrixWorld(true);
const connectedBounds = new THREE.Box3();
for (const { group } of loaded)
if (result.world.has(group.name))
connectedBounds.union(new THREE.Box3().setFromObject(group));
let cursor =
(connectedBounds.isEmpty() ? 0 : connectedBounds.max.x) +
Math.max(
connectedBounds.getSize(new THREE.Vector3()).length() * 0.15,
0.05,
);
for (const { item, group } of loaded) {
if (result.world.has(item.instanceId)) continue;
const bounds = new THREE.Box3().setFromObject(group);
if (bounds.isEmpty()) continue;
group.position.x = cursor - bounds.min.x;
cursor += bounds.getSize(new THREE.Vector3()).x + 0.05;
}
root.updateMatrixWorld(true);
const motion = connectComponentGroups(
new Map(loaded.map((part) => [part.item.instanceId, part.group])),
frames,
result.connections,
);
warnings.push(...motion.warnings);
root.updateMatrixWorld(true);
const model: ModelData = { root: "", roots: [], links: {}, joints: [] };
const nodeId = (instance: string, link: string) => `${instance}/${link}`;
for (const { item, robot } of loaded) {
const id = item.instanceId;
for (const [name, link] of Object.entries(robot.links)) {
const position = new THREE.Vector3(),
rotation = new THREE.Quaternion(),
scale = new THREE.Vector3();
link.matrixWorld.decompose(position, rotation, scale);
const rpy = new THREE.Euler().setFromQuaternion(rotation, "ZYX");
model.links[nodeId(id, name)] = {
mesh: name,
label: name === robot.name ? item.component.componentName : name,
xyz: position.toArray() as Vector,
rpy: [rpy.x, rpy.y, rpy.z],
};
}
for (const [name, joint] of Object.entries(robot.joints)) {
const parent = joint.parent?.name;
const child = joint.children.find(
(object) => "isURDFLink" in object,
)?.name;
if (!parent || !child) continue;
const euler = new THREE.Euler().setFromQuaternion(
joint.quaternion,
"ZYX",
);
model.joints.push({
name,
source: "urdf",
type: joint.jointType,
parent: nodeId(id, parent),
child: nodeId(id, child),
xyz: joint.position.toArray() as Vector,
rpy: [euler.x, euler.y, euler.z],
axis: joint.axis.toArray() as Vector,
lower: joint.limit.lower,
upper: joint.limit.upper,
});
}
const connection = result.connections.find((edge) => edge.child === id);
if (connection) {
const parentRobot = loaded.find(
(part) => part.item.instanceId === connection.parent,
)!.robot;
const moving = motion.motions.find((joint) => joint.instanceId === id);
const jointFrame = moving
? frames
.find((part) => part.item.instanceId === connection.parent)!
.frames.get(connection.parentFrame)!
: connection.relative;
const pos = new THREE.Vector3().setFromMatrixPosition(jointFrame);
const rot = new THREE.Euler().setFromRotationMatrix(jointFrame, "ZYX");
model.joints.push({
source: "assembly",
type: moving ? "continuous" : "fixed",
assemblyJointId: moving?.id,
childOffset: moving
? frames
.find((part) => part.item.instanceId === id)!
.frames.get(connection.childFrame)!
.clone()
.invert()
.toArray()
: undefined,
name: `${connection.parentFrame} → ${connection.childFrame}`,
parent: nodeId(connection.parent, parentRobot.name),
child: nodeId(id, robot.name),
xyz: pos.toArray() as Vector,
rpy: [rot.x, rot.y, rot.z],
axis: moving?.axis || [0, 0, 0],
lower: moving ? null : 0,
upper: moving ? null : 0,
});
} else model.roots!.push(nodeId(id, robot.name));
}
model.root = model.roots![0];
signal.throwIfAborted();
function getModel(): ModelData {
root.updateMatrixWorld(true);
const links = { ...model.links };
for (const { item, robot } of loaded)
for (const [name, link] of Object.entries(robot.links)) {
const position = new THREE.Vector3(),
rotation = new THREE.Quaternion(),
scale = new THREE.Vector3();
link.matrixWorld.decompose(position, rotation, scale);
const rpy = new THREE.Euler().setFromQuaternion(rotation, "ZYX");
const id = nodeId(item.instanceId, name);
links[id] = {
...links[id],
xyz: position.toArray() as Vector,
rpy: [rpy.x, rpy.y, rpy.z],
};
}
return { ...model, links };
}
return {
root,
model,
assemblyJoints: motion.motions.map(
({ setAngle: _setAngle, ...joint }) => joint,
),
setJointAngle(id, radians) {
const joint = motion.motions.find((joint) => joint.id === id);
if (!joint) throw new Error("未找到该装配关节");
joint.setAngle(radians);
root.updateMatrixWorld(true);
},
getModel,
warnings,
componentCount: loaded.length,
connectionCount: result.connections.length,
};
} catch (error) {
disposeRobot(root);
throw error;
}
}
+76
View File
@@ -0,0 +1,76 @@
import * as THREE from "three";
import { toCreasedNormals } from "three/addons/utils/BufferGeometryUtils.js";
import type { ModelAsset } from "../data/model";
function bytes(encoded: string) {
const raw = atob(encoded);
return Uint8Array.from(raw, (c) => c.charCodeAt(0));
}
export async function createRobot(data: ModelAsset, signal: AbortSignal) {
const links = new Map<string, THREE.Group>();
for (const [name, link] of Object.entries(data.links)) {
if (signal.aborted) break;
const group = new THREE.Group();
group.name = name;
const source = data.meshes[link.mesh];
const geometry = new THREE.BufferGeometry();
geometry.setAttribute(
"position",
new THREE.BufferAttribute(new Float32Array(bytes(source.p).buffer), 3),
);
const indices = bytes(source.i).buffer;
geometry.setIndex(
new THREE.BufferAttribute(
source.i32 ? new Uint32Array(indices) : new Uint16Array(indices),
1,
),
);
const creased = toCreasedNormals(geometry, Math.PI / 5);
geometry.dispose();
const material = new THREE.MeshStandardMaterial({
color: "#b8bfc7",
roughness: 0.58,
metalness: 0.28,
});
const mesh = new THREE.Mesh(creased, material);
mesh.name = name;
mesh.position.fromArray(link.xyz);
mesh.rotation.set(...link.rpy, "ZYX");
group.add(mesh);
links.set(name, group);
await new Promise<void>((resolve) =>
requestAnimationFrame(() => resolve()),
);
}
if (!signal.aborted) {
for (const joint of data.joints) {
const frame = new THREE.Group();
frame.name = joint.name;
frame.position.fromArray(joint.xyz);
frame.rotation.set(...joint.rpy, "ZYX");
frame.add(links.get(joint.child)!);
links.get(joint.parent)!.add(frame);
}
}
const root = links.get(data.root) ?? new THREE.Group();
if (signal.aborted) for (const link of links.values()) disposeRobot(link);
return root;
}
export function disposeRobot(root: THREE.Object3D) {
const textures = new Set<THREE.Texture>();
root.traverse((object) => {
if (object instanceof THREE.Mesh) {
object.geometry.dispose();
for (const material of Array.isArray(object.material)
? object.material
: [object.material]) {
for (const value of Object.values(material))
if (value instanceof THREE.Texture) textures.add(value);
material.dispose();
}
}
});
textures.forEach((texture) => texture.dispose());
}
+9
View File
@@ -0,0 +1,9 @@
node_modules/
dist/
.vite/
*.tsbuildinfo
.env.local
.DS_Store
coverage/
*.log
test-results/
+5
View File
@@ -0,0 +1,5 @@
node_modules
dist
public/vendor
tests/fixtures
package-lock.json
+1
View File
@@ -0,0 +1 @@
{ "singleQuote": true, "semi": false, "trailingComma": "all", "printWidth": 100 }
+93
View File
@@ -0,0 +1,93 @@
# CAD World Management
React + TypeScript 管理后台,保留组件库、用户管理和操作日志。使用黑色配色及 CAD World 标识。
组件库已经接入新版 `/admin-api`,不再使用本地组件数据库。新增组件只必填单个 STEP/STP 文件;URDF 文件夹、名称、分类及其余表单信息均选填。编辑时已保存的 STEP 满足必填要求,可只更新表单,或单独替换 STEP / URDF。未填数值保存为 null,显式填写 0 则保留 0。选择 URDF 时仍须提供可解析的完整文件夹。组件编码由后端签名接口分配,不能手动修改。
右侧“零件描述 / 基本信息”通过 Tab 切换,默认展示零件描述表单;基本信息只读展示 URDF 文件点位。零件描述展示名称、零件分类、自由度、材质、功能、形状、大小、扭矩、质量和描述。选择符合命名规则的 URDF 后分类从主文件名自动识别;未选择或无法识别时分类可手动填写,也可留空。选择 URDF 时名称默认使用主文件名(去掉扩展名),允许手动修改或清空;编码只交由后端生成,不展示编码输入框。质量单位为 kg,扭矩单位为 N·m,均可为 0。列表按服务端分页,关键词搜索名称或编码,分类精确筛选;默认按最近更新排序。
## 运行
零件描述底部新增 BOM 清单:下载 `.xlsx` 模板、导入 Excel、预览和清空。解析结果随保存请求的 `bomList` 数组提交,按照最新接口支持保存和详情回填;其他已有 JSON 结构原样保留,详见 [BOM 字段约定](docs/bom-contract.md)。
需要 Node.js 22.12 或以上。
```sh
npm install
npm run dev
```
访问 `http://127.0.0.1:8091`。开发服务监听 `0.0.0.0`,同一局域网可通过本机 IP 加端口 8091 访问。浏览器局域网 HTTP 地址也可生成请求编号、读取 STEP 和 URDF,不依赖仅安全上下文可用的 SHA-256 API。
`vite.config.ts` 将 `/admin-api` 代理至 `https://dev-cadworld-api.robotquan.com`,例如组件查询转发至 `https://dev-cadworld-api.robotquan.com/admin-api/components?page=1&size=10`,路径和查询参数保持不变。可通过 `ADMIN_API_TARGET` 环境变量覆盖,例如 `http://127.0.0.1:8992`。
上传使用接口文档规定的“后端签名、浏览器直传 OSS、后端校验入库”:直接使用签名响应中的 `uploadUrl` 和 `uploadFields`,不硬编码存储 Bucket,不经过 Vite 上传代理。开发、preview 和正式构建使用相同上传逻辑。OSS 必须允许页面实际来源的 POST 跨域请求;当前 OSS CORS 仍未配置完成,上传处于待验收状态,不能视为可上线。
正式部署使用 `npm run build` 生成的 `dist`,由静态 Web 服务托管。`../shared/api-origin.ts` 按页面域名选择 API:`dev-cadworld-admin.robotquan.com` 直连 `https://dev-cadworld-api.robotquan.com`,`cadworld-admin.robotquan.com` 直连 `https://cadworld-api.robotquan.com`;本机/局域网保留 Vite 开发代理。线上网页站点无需配置 `/admin-api` 代理,后端需允许对应网站的 CORS,OSS 另需允许实际上传来源。完整部署与验收要求见 `docs/deployment.md`。
目前文档没有认证或短信接口,登录继续保留约定的临时前端行为:填写手机号和验证码即可进入,获取验证码自动填入 `123456`。后台操作人由服务端配置决定,与前端填写手机号无关。
## 上传时读取 URDF 点位
上传页右侧依次为“零件描述”和“基本信息”,默认打开零件描述,选择文件不会强制切换标签。基本信息按文件顺序只读列出全部 joint,不提供坐标系选择或安装配置,原样读取名称、类型、父子 Link、origin XYZ(m)/RPY(rad),以及文件显式提供的轴向和关节限制。不会把普通 Link、visual/inertial origin 当作安装点,不推断安装用途,不添加配对关系,不改写文件。选择 URDF 时解析结果随保存请求的 `urdfInfo` 字段提交;未提供 URDF 时为 null。替换 URDF 时同步更新,未替换时保留详情 JSON。缺失属性展示为“文件未定义”,只读信息不补默认坐标。
悬停或键盘聚焦点位时,在 URDF 预览里高亮文件定义的位置;离开后移除标记,切换零件描述时清空高亮。标记独立存在于预览场景,不挂载到原始模型,不修改坐标、材质、层级或上传字节。自由度、功能、形状、大小和扭矩分别使用独立字段 degreesOfFreedom、functionDescription、shape、size、torqueNm;材质、质量和描述分别保存为 material、massKg 和 description。自由度为 0 至 2147483647 的整数,扭矩为 N·m 数值,质量和扭矩均校验最多 12 位整数及 6 位小数。编辑时回填固定字段,已保存的历史扩展数据保留,页面不提供自定义字段编辑入口。
悬停点位时相机平滑转向该点并居中,从模型中心朝点位的方向取景仅用于浏览,不表示安装朝向或配对关系。手动拖动/缩放立即接管相机。预览使用自由轨迹球旋转,可越过顶部、查看底部,不显示地面网格;右下角直接使用 [Three.js 官方 ViewHelper](https://threejs.org/docs/pages/ViewHelper.html),随相机实时变化,点击坐标轴可切换视角,不向文件添加坐标系。
STEP 的 OCCT 解析、三角化及法线计算在独立 Web Worker 中执行,结果通过可转移缓冲区返回;主线程分批创建预览网格。解析期间 URDF 选择、预览切换与表单操作保持可用。文件选择窗口有重复打开保护,取消或选中后恢复;离开页面或替换 STEP 时会终止旧解析任务。Worker 由 Vite 打包,WASM 随 `dist/vendor` 部署,无需额外服务。
STEP 和 URDF 统一使用中性灰色预览材质,颜色、金属度和粗糙度一致。显示副本与原模型共享几何,但使用独立材质,原始材质、文件颜色和上传字节保持不变;副本保留各材质槽、透明度、可见性和模型变换,卸载时仅释放副本材质。
统一预览使用中性补光、主方向光和 ACES 色调映射,避免过曝;主光阴影范围随模型尺寸适配,显示孔位和凹槽的遮挡层次。使用背面投影及随模型尺寸适配的法线偏移,减少 STEP 表面的自阴影条纹;不修改几何或安装坐标。
坐标信息独立于网格读取,三维预览失败时仍可查看已解析的内容。替换、移除 URDF 时同步刷新或清空;编辑已有组件时进入点位标签会按需读取已保存的 URDF。
后台使用窗口内布局,标题、操作栏和分页保持可见。上传页及文件检查页左右面板等高,预览随剩余空间缩放,长表单、点位和列表只在各自内部滚动。窄屏改为上下排列,在工作区内滚动,不撑高整页。
## URDF 文件检查
登录后连续点击左上角 Logo 三次进入 `/assembly-test`,不增加侧边栏菜单。页面默认加载随构建部署的躯干与 H-DOF0-R 原始 URDF/网格样例,不依赖本机 Downloads,也不上传文件或写入后端。
通过文件标签分别查看原始模型及文件里的 joint/origin 信息,也可更换完整 URDF 文件夹。前端不指定安装点配对、父子关系、旋转、间距或坐标轴对齐规则,不合并两份没有定义跨文件安装关系的 URDF。机械人员负责在文件中定义正确的安装关系;修改后重新导入即可按新文件读取。
完整显示文件定义的全部 visual 和子零件;统一灰色仅应用于显示副本,原始材质/颜色数据保留。不改网格坐标或模型根位姿,视图适应只调整相机。没有显式定义的点位属性显示“文件未定义”,不补造坐标值。读取 URDF 时遵循文件格式语义加载模型内部结构,不加入业务安装规则。退出时释放三维资源。
## 验证
```sh
npm test
npm run check
npm run build
npm run format:check
```
## 结构
- `src/pages/ComponentCatalogPage.tsx`:服务端分页、搜索、分类筛选、删除及列表/卡片视图。
- `src/pages/ComponentUploadPage.tsx`:双资源上传、模型预览、两组表单和版本冲突处理。
- `src/application/component-upload.ts`:单签名授权、4 路并发 OSS 上传、续签及上传重试。
- `src/application/component-gateway.ts`:组件 CRUD 与按需资源下载。
- `src/pages/UsersPage.tsx`、`src/pages/ActivityPage.tsx`:用户管理与通用操作日志。
- `src/pages/AssemblyTestPage.tsx`:隐藏 URDF 原文件检查页;不进行跨零件安装推断。
- `docs/admin-api.md`:本次采用的接口文档。
- `docs/architecture.md`、`docs/verification.md`:架构及本次验证结果。
- `docs/deployment.md`:正式环境网络、OSS CORS 与上线验收。
旧接口库、选面选孔、接口绑定、姿态计算、BREP 服务、封面、ZIP 导入、备份、IndexedDB 草稿及旧上传会话逻辑已从这个独立后台项目移除。其他目录中的原项目未修改。
URDF 零件与接口的命名、识别和保存约定见 [命名规则](docs/part-naming.md)。新建或替换 URDF 时按主文件名识别类型及左右,通过现有 `basicFields` 保存,原始安装坐标保持不变。
选择可识别的 URDF 后零件分类与文件识别结果统一(如 `torso_0`、`arm_l`),只读展示并作为 `category` 保存;其他情况分类可编辑或留空。列表分类建议使用同一套匹配键,通过后端已有 category 参数精确筛选。历史未规范命名的已保存文件保留原分类,替换 URDF 后按新命名自动识别。
## 坐标一致性回归(2026-10-14)
后台上传解析和模型预览保留文件内的 origin XYZ/RPY、内部层级及网格位置,不自动把头或其他零件转正。`urdfInfo` 保存相对 parent/link 的原始坐标;前台读取完整 URDF 后累计到组件根节点再对齐。新增联合测试验证前台装配与后台预览内部坐标一致,包括多级父节点、非零旋转、倒置安装点、完整坐标系重合及原文件内容不变。
## STEP 必填、其他选填(2026-10-14)
页面、表单校验和直传流程已支持仅 STEP。实测开发后端仍返回 422,要求 componentName、category、urdfObjectKeys 非空,因此服务器仍需同步放开这三项约束及无 URDF 的资源入库逻辑。前端不会填造名称、分类或 URDF 引用来绕过服务端校验。具体返回和同步要求见 `../releases/后台STEP必填-后端同步说明.txt`。87 项自动化测试及生产构建通过;未向真实后端上传或创建测试零件。
## 模型下载(2026-10-14)
STEP、URDF 和网格从 https://linkerbot.oss-cn-beijing.aliyuncs.com 直接下载,按接口返回对象键拼接,不再经过组件资源下载接口。本地及线上使用相同规则,保留对象键里的环境目录。业务 API 按页面域名选择环境,OSS 上传仍由后端签名授权。
+543
View File
@@ -0,0 +1,543 @@
# 后台 API 联调文档
后台保留组件库、用户管理、操作日志三个模块。以下路径以 `/admin-api` 为前缀,默认服务地址 `http://127.0.0.1:8992`。
## 1. 通用约定
JSON 请求设置 `Content-Type: application/json`。当前没有登录认证,操作人来自 `APP_ADMIN_OPERATOR_ID / APP_ADMIN_OPERATOR_NAME`,默认 `0 / TEST_OPERATOR`。上传令牌与该操作人绑定。
成功返回 HTTP 200,包括新增和删除:
```json
{ "code": "OK", "message": "success", "data": { "success": true }, "requestId": "请求编号" }
```
失败返回对应 HTTP 状态和错误码,`data` 可能省略:
```json
{
"code": "COMPONENT_REVISION_CONFLICT",
"message": "组件已修改或删除,请刷新后保存",
"requestId": "请求编号"
}
```
分页返回 `data={"items":[],"page":1,"size":20,"total":0}`。页码从 1 开始,默认每页 20,超过 100 按 100 处理。组件和日志按更新时间/操作时间、ID 倒序。数据库时间及日志筛选时间使用上海时区本地时间,例如 `2026-10-10T16:00:00`;上传会话与签名到期时间为 UTC ISO 时间,例如 `2026-10-10T08:30:00Z`。
前端保存响应中的 `requestId` 用于排查问题。避免在浏览器日志中输出上传令牌和签名字段。
## 2. 接口列表
| 方法 | 路径 | 作用 |
| ------ | --------------------------------------- | ---------------------------- |
| POST | /admin-api/storage/upload-signature | 分配编码及上传授权,或续签 |
| GET | /admin-api/components | 组件分页查询 |
| POST | /admin-api/components | 新增组件,校验上传文件后入库 |
| GET | /admin-api/components/{id} | 组件完整详情 |
| PUT | /admin-api/components/{id} | 全量更新表单,可替换资源 |
| DELETE | /admin-api/components/{id} | 逻辑删除组件 |
| GET | /admin-api/component-assets/{objectKey} | 下载资源文件 |
| GET | /admin-api/users | 用户分页查询 |
| POST | /admin-api/users | 创建用户 |
| GET | /admin-api/users/{id} | 用户详情 |
| PUT | /admin-api/users/{id} | 修改用户 |
| DELETE | /admin-api/users/{id} | 逻辑删除用户 |
| GET | /admin-api/operation-logs | 通用操作日志分页查询 |
| GET | /admin-api/operation-logs/{id} | 操作日志详情 |
接口库、端口、姿态、BREP、封面、后台文件流上传以及所有旧上传会话/确认路由均已删除,访问返回 404。上传没有独立的创建会话、上传确认接口。
## 3. 单签名接口
### 3.1 请求
`POST /admin-api/storage/upload-signature`,以下三种请求互斥:
| 场景 | JSON 请求 |
| -------------------- | --------------------------------- |
| 新增组件首次上传 | `{}` |
| 已有组件替换模型 | `{"componentId":123}` |
| 原会话签名到期后续签 | `{"uploadSessionToken":"原令牌"}` |
新增无需组件编码。后端生成 `CW-` 加无连字符的大写 UUID,例如 `CW-0123456789ABCDEF0123456789ABCDEF`,申请签名不创建组件记录。编辑使用原编码,生成新的上传批次;组件不存在返回 404。
续签不能同时提交 `componentId`。续签验证签名、有效期、操作人、环境及绑定组件,保持原编码、批次、令牌和目录。默认会话有效期 30 分钟、OSS 授权有效期 5 分钟;授权不超过会话到期时间,续签不延长会话。
### 3.2 响应
以下签名值仅为占位示例,实际表单字段必须使用后端返回值:
```json
{
"code": "OK",
"message": "success",
"requestId": "请求编号",
"data": {
"componentCode": "CW-0123456789ABCDEF0123456789ABCDEF",
"uploadSessionToken": "组件上传令牌",
"sessionExpiresAt": "2026-10-10T08:30:00Z",
"expiresAt": "2026-10-10T08:05:00Z",
"step": {
"uploadUrl": "https://linkerbot.oss-cn-beijing.aliyuncs.com/",
"keyPrefix": "cadworld_dev/components/CW-0123456789ABCDEF0123456789ABCDEF/step/abcdef0123456789abcdef0123456789/",
"uploadMethod": "POST",
"uploadFields": {
"x-oss-signature-version": "OSS4-HMAC-SHA256",
"x-oss-credential": "访问凭证范围",
"x-oss-date": "20261010T080000Z",
"success_action_status": "204",
"x-oss-forbid-overwrite": "true",
"policy": "Base64策略",
"x-oss-signature": "签名"
}
},
"urdf": {
"uploadUrl": "https://linkerbot.oss-cn-beijing.aliyuncs.com/",
"keyPrefix": "cadworld_dev/components/CW-0123456789ABCDEF0123456789ABCDEF/urdf/abcdef0123456789abcdef0123456789/",
"uploadMethod": "POST",
"uploadFields": {
"x-oss-signature-version": "OSS4-HMAC-SHA256",
"x-oss-credential": "访问凭证范围",
"x-oss-date": "20261010T080000Z",
"success_action_status": "204",
"x-oss-forbid-overwrite": "true",
"policy": "另一组Base64策略",
"x-oss-signature": "另一组签名"
}
}
}
}
```
一个 `uploadSessionToken` 同时绑定 STEP 和 URDF 两组目录,两组使用相同编码、批次。不得修改、互换授权字段或手工构造目录。
### 3.3 OSS 直传
每个文件分别向对应 `uploadUrl` 发一个 `multipart/form-data` POST:原样加入 `uploadFields`,再加入 `key=keyPrefix+相对路径`,最后加入 `file`。让浏览器自动设置 Content-Type 和 boundary。OSS 成功返回 HTTP 204。
对象键包含环境根目录,默认测试为 `cadworld_dev`,生产为 `cadworld`:
```text
{环境根目录}/components/{组件编码}/step/{批次}/{STEP文件名}
{环境根目录}/components/{组件编码}/urdf/{批次}/{URDF内部相对路径}
```
STEP 直接使用文件名。URDF 使用文件夹选择器提供的 `webkitRelativePath`,去掉最外层选中目录,保留内部结构。例如 `L20/robot.urdf`、`L20/meshes/base.stl` 分别上传为 `urdf.keyPrefix + robot.urdf`、`urdf.keyPrefix + meshes/base.stl`。不要打包 ZIP,也不要扁平化内部目录。
默认单文件上限 100 MiB。禁止同名覆盖字段已纳入签名;同批次相同对象键重复上传会被 OSS 拒绝。续签只刷新授权,已确认上传成功的文件无需再次上传。会话过期需要重新申请签名并上传至新批次;新增重新申请会分配新编码。
OSS CORS 需允许前端源站的表单 POST。OSS 上传失败由前端按 OSS 返回状态处理;OSS 成功后仍须保存组件。
## 4. 组件表单及资源规则
### 4.1 表单字段
POST 和 PUT 使用扁平 JSON,字段约定相同:
| 字段 | 类型 | 必填 / 默认值 / 限制 |
| ------------------- | --------------- | ------------------------------------------------------------------ |
| componentName | string | 必填,非空,最多 128 字符,允许同名 |
| category | string | 必填,非空,最多 64 字符,自由分类 |
| description | string | 默认 `""`,UTF-8 不超过 65535 字节 |
| material | string | 默认 `""`,最多 128 字符 |
| massKg | number | 默认 0,千克,非负 |
| degreesOfFreedom | integer | 默认 0,范围 0 至 2147483647,仅接受 JSON 整数,不接受小数或字符串 |
| functionDescription | string | 默认 `""`,最多 512 字符 |
| shape | string | 默认 `""`,最多 128 字符 |
| size | string | 默认 `""`,最多 128 字符,大小描述,可包含单位 |
| torqueNm | number | 默认 0,单位 N·m,非负 |
| bomList | JSON 对象或数组 | 默认 `[]`,内部结构自由 |
| urdfInfo | JSON 对象或数组 | POST / PUT 均必填,内部结构自由,允许 `{}` 或 `[]` |
| basicFields | 自定义字段数组 | 默认 `[]`,基本信息扩展字段 |
| parameterFields | 自定义字段数组 | 默认 `[]`,零件参数扩展字段 |
质量和扭矩最多 12 位整数、6 位小数,与 `DECIMAL(18,6)` 一致;不要在数值中提交单位文本。可选字段省略或传 null 会恢复默认值。名称、分类、材质、功能、形状和大小会裁剪首尾空白。
`bomList` 和 `urdfInfo` 直接提交 JSON 对象或数组,不接受字符串化的 JSON、数字或布尔值。`bomList` 省略或为 null 时保存为空数组;`urdfInfo` 省略或为 null 时返回 422。两者内部字段不做固定结构校验,`urdfInfo` 由前端提供,不由后端解析 URDF 文件生成。
自定义字段格式:
```json
{
"basicFields": [{ "name": "供应商型号", "value": "L20-RIGHT" }],
"parameterFields": [
{ "name": "额定电压", "value": "24V" },
{ "name": "额定扭矩", "value": "20 Nm" }
]
}
```
每组最多 100 项,名称非空且最多 64 字符,值为非 null 字符串、最多 2000 字符,可以为空字符串。同组名称裁剪后不可重复,两组之间可以重名;顺序与请求一致。
PUT 是全量表单更新,前端应提交完整表单,每次都必须提交 `urdfInfo`。省略可选字段会恢复默认值,提交空数组可清空 BOM 或自定义字段。
### 4.2 保存时的资源校验
新增必须同时提交 STEP 和 URDF 资源;修改可只替换一种,未提交的资源保持原引用。文件引用只能来自当前操作人、当前组件的有效令牌和对应目录。
后端检查全部对象键合法、无重复、无路径越界且实际存在,按 OSS HEAD 返回的实际大小校验,不接受前端提供的文件大小。STEP 是直接位于 STEP 批次目录的一个非空 `.step` 或 `.stp` 文件。URDF 清单 1 至 1000 项,必须恰好包含一个非空 `.urdf` 主文件,不支持以 `.rfs` 为主文件;扩展名大小写均可。
后端根据实际对象生成 `urdfPrefix`、`urdfMainObjectKey` 和 `urdfFiles`,清单保留请求顺序,元素为 `relativePath` 和 `sizeBytes`。无需提交这些数据库维护字段。
检查全部通过才写数据库。失败不切换原资源引用。旧批次、上传后未保存及删除组件后的文件暂不自动清理。校验覆盖清单的结构和对象存在性,不解析 URDF XML 内部的依赖引用。
## 5. 组件接口
### 5.1 新增
`POST /admin-api/components`。编码由令牌读取,不接受前端指定编码。签名、直传成功后提交:
```json
{
"componentName": "四孔安装板",
"category": "安装板",
"description": "用于固定机械组件",
"material": "铝合金",
"massKg": 0.35,
"degreesOfFreedom": 0,
"functionDescription": "固定机械组件",
"shape": "平板",
"size": "120 × 80 × 8 mm",
"torqueNm": 0,
"bomList": [{ "componentCode": "PART-001", "name": "安装螺钉", "quantity": 4 }],
"urdfInfo": { "robotName": "mounting_plate", "links": [{ "name": "base_link" }] },
"basicFields": [{ "name": "供应商型号", "value": "L20-RIGHT" }],
"parameterFields": [{ "name": "额定电压", "value": "24V" }],
"uploadSessionToken": "签名接口返回的令牌",
"stepObjectKey": "cadworld_dev/components/CW-0123456789ABCDEF0123456789ABCDEF/step/abcdef0123456789abcdef0123456789/model.step",
"urdfObjectKeys": [
"cadworld_dev/components/CW-0123456789ABCDEF0123456789ABCDEF/urdf/abcdef0123456789abcdef0123456789/robot.urdf",
"cadworld_dev/components/CW-0123456789ABCDEF0123456789ABCDEF/urdf/abcdef0123456789abcdef0123456789/meshes/base.stl"
]
}
```
成功返回完整组件详情,初始 `version=1`。重复使用已保存编码新增返回 409,包含已逻辑删除组件的编码。
### 5.2 详情及保存响应
`GET /admin-api/components/123`,POST / PUT 成功的 `data` 也使用此结构:
```json
{
"id": 123,
"componentCode": "CW-0123456789ABCDEF0123456789ABCDEF",
"componentName": "四孔安装板",
"category": "安装板",
"description": "用于固定机械组件",
"material": "铝合金",
"massKg": 0.35,
"degreesOfFreedom": 0,
"functionDescription": "固定机械组件",
"shape": "平板",
"size": "120 × 80 × 8 mm",
"torqueNm": 0,
"bomList": [{ "componentCode": "PART-001", "name": "安装螺钉", "quantity": 4 }],
"urdfInfo": { "robotName": "mounting_plate", "links": [{ "name": "base_link" }] },
"basicFields": [{ "name": "供应商型号", "value": "L20-RIGHT" }],
"parameterFields": [{ "name": "额定电压", "value": "24V" }],
"stepObjectKey": "cadworld_dev/components/CW-0123456789ABCDEF0123456789ABCDEF/step/abcdef0123456789abcdef0123456789/model.step",
"stepUrl": "http://127.0.0.1:8992/admin-api/component-assets/cadworld_dev/components/CW-0123456789ABCDEF0123456789ABCDEF/step/abcdef0123456789abcdef0123456789/model.step",
"urdfPrefix": "cadworld_dev/components/CW-0123456789ABCDEF0123456789ABCDEF/urdf/abcdef0123456789abcdef0123456789/",
"urdfBaseUrl": "http://127.0.0.1:8992/admin-api/component-assets/cadworld_dev/components/CW-0123456789ABCDEF0123456789ABCDEF/urdf/abcdef0123456789abcdef0123456789/",
"urdfMainObjectKey": "cadworld_dev/components/CW-0123456789ABCDEF0123456789ABCDEF/urdf/abcdef0123456789abcdef0123456789/robot.urdf",
"urdfUrl": "http://127.0.0.1:8992/admin-api/component-assets/cadworld_dev/components/CW-0123456789ABCDEF0123456789ABCDEF/urdf/abcdef0123456789abcdef0123456789/robot.urdf",
"urdfFiles": [
{ "relativePath": "robot.urdf", "sizeBytes": 4200 },
{ "relativePath": "meshes/base.stl", "sizeBytes": 15000 }
],
"version": 1,
"createdAt": "2026-10-10T16:01:00.123",
"updatedAt": "2026-10-10T16:01:00.123"
}
```
数据库只保存 Key。URL 在响应时生成,路径段经过编码。获取依赖文件时按 `/` 分段编码 `relativePath` 后拼接 `urdfBaseUrl`,不要对整个路径使用一次 `encodeURIComponent`。
### 5.3 修改
`PUT /admin-api/components/123`,必须提交最新 `version`,成功后递增。只改表单无需签名:
```json
{
"version": 1,
"componentName": "四孔安装板 V2",
"category": "安装板",
"description": "更新说明",
"material": "铝合金",
"massKg": 0.35,
"degreesOfFreedom": 0,
"functionDescription": "固定机械组件",
"shape": "平板",
"size": "120 × 80 × 8 mm",
"torqueNm": 0,
"bomList": [],
"urdfInfo": { "robotName": "mounting_plate", "links": [{ "name": "base_link" }] },
"basicFields": [],
"parameterFields": [{ "name": "额定电压", "value": "24V" }]
}
```
`componentCode` 可省略;若提交必须与原编码一致。`version` 范围 1 至 4294967295,达到上限不能继续修改。版本过期或原子更新冲突返回 409,前端重新加载详情后合并修改再保存。
替换 STEP:先用 `{"componentId":123}` 申请新批次,直传 STEP,再在完整表单和 version 之外提交:
```json
{
"uploadSessionToken": "编辑签名返回的令牌",
"stepObjectKey": "新授权的step.keyPrefix加文件名"
}
```
替换 URDF 则提交令牌和完整的 `urdfObjectKeys`,不提交 `stepObjectKey`;同时替换则两者一起提交。不替换时省略令牌及文件字段。仅提交令牌、空对象键或空 URDF 清单会被拒绝。
### 5.4 列表
`GET /admin-api/components?page=1&size=20&keyword=安装板&category=安装板`
| 参数 | 说明 |
| ----------- | ------------------ |
| page / size | 分页 |
| keyword | 名称或编码模糊查询 |
| category | 分类精确筛选 |
`items` 每项包含 `id`、`componentCode`、`componentName`、`category`、`description`、`degreesOfFreedom`、`functionDescription`、`shape`、`size`、`torqueNm`、`stepUrl`、`urdfUrl`、`version`、`createdAt`、`updatedAt`。列表不查询或返回 `bomList`、`urdfInfo`、自定义表单和 URDF 文件清单。编辑先获取详情;创建和修改成功返回的详情包含全部七个新增字段。
列表查询参数 `size` 是每页条数,响应 `items` 内的 `size` 是组件大小描述。
### 5.5 删除和下载
`DELETE /admin-api/components/123` 成功返回 `data={"success":true}`。将组件的 `deleted` 标记从 `0` 改为 `1`,保留数据库记录、删除前的日志目标快照和 OSS 文件。找不到组件或组件已删除时返回 404。
已删除组件不出现在列表和详情中,不能修改、申请编辑上传签名或续签绑定该组件的上传会话。组件编码仍保持唯一,不能复用原新增会话重新创建同编码组件。删除标记仅用于数据库内部,不增加到接口响应中。
使用详情中的 `stepUrl`、`urdfUrl` 或依赖文件 URL 直接 GET 下载。下载成功返回原文件流,不包 JSON;对象不存在返回 404。对象键区分大小写且必须属于当前环境根目录。
## 6. 浏览器完整上传示例
页面文件选择器:
```html
<input id="step" type="file" accept=".step,.stp" />
<input id="urdf" type="file" webkitdirectory multiple />
```
以下示例使用一次签名完成两类文件上传,授权即将到期时调用同一接口续签,上传全部成功后直接保存。表单取当前页面值;示例按顺序上传以便展示流程,实际页面可使用受控并发。
```javascript
async function adminApi(path, method, body) {
const response = await fetch(`/admin-api${path}`, {
method,
headers: { 'Content-Type': 'application/json' },
...(body === undefined ? {} : { body: JSON.stringify(body) }),
})
const result = await response.json()
if (!response.ok || result.code !== 'OK') {
throw new Error(`${result.message}; requestId=${result.requestId}`)
}
return result.data
}
function urdfRelativePath(file) {
const path = file.webkitRelativePath
if (!path || !path.includes('/')) throw new Error('请选择完整 URDF 文件夹')
return path.slice(path.indexOf('/') + 1) // 去掉选中文件夹的最外层目录
}
async function uploadAndSave(formValues, stepFile, urdfFiles, component = null) {
// 新增传 {};编辑传已有组件 ID。编辑可仅替换 STEP 或 URDF。
const files = Array.from(urdfFiles || [])
if (!component && (!stepFile || files.length === 0)) {
throw new Error('新增组件必须选择 STEP 文件和 URDF 文件夹')
}
const body = { ...formValues }
if (component) body.version = component.version
if (!stepFile && files.length === 0) {
return adminApi(`/components/${component.id}`, 'PUT', body)
}
let session = await adminApi(
'/storage/upload-signature',
'POST',
component ? { componentId: component.id } : {},
)
async function ensureSignature() {
if (Date.now() >= Date.parse(session.sessionExpiresAt)) {
throw new Error('上传会话已过期,请重新申请签名并重新上传')
}
if (Date.now() >= Date.parse(session.expiresAt) - 15000) {
session = await adminApi('/storage/upload-signature', 'POST', {
uploadSessionToken: session.uploadSessionToken,
})
}
}
async function upload(kind, file, relativePath) {
await ensureSignature()
const authorization = session[kind]
const key = authorization.keyPrefix + relativePath
const data = new FormData()
for (const [name, value] of Object.entries(authorization.uploadFields)) {
data.append(name, value)
}
data.append('key', key)
data.append('file', file) // 必须放最后;不要手工设置 Content-Type
const response = await fetch(authorization.uploadUrl, {
method: authorization.uploadMethod,
body: data,
})
if (response.status !== 204) {
throw new Error(`OSS 上传失败,HTTP ${response.status}`)
}
return key
}
if (stepFile) body.stepObjectKey = await upload('step', stepFile, stepFile.name)
if (files.length) {
body.urdfObjectKeys = []
for (const file of files) {
body.urdfObjectKeys.push(await upload('urdf', file, urdfRelativePath(file)))
}
}
await ensureSignature() // 保存前确认会话仍有效
body.uploadSessionToken = session.uploadSessionToken
// 不需要 complete 接口;保存接口执行文件检查并写入记录。
return adminApi(
component ? `/components/${component.id}` : '/components',
component ? 'PUT' : 'POST',
body,
)
}
// formValues 只含完整表单字段,不包含详情里的资源 URL、Key 或维护字段。
const saved = await uploadAndSave(
{
componentName: '四孔安装板',
category: '安装板',
description: '',
material: '铝合金',
massKg: 0,
degreesOfFreedom: 0,
functionDescription: '固定机械组件',
shape: '平板',
size: '120 × 80 × 8 mm',
torqueNm: 0,
bomList: [],
urdfInfo: {},
basicFields: [],
parameterFields: [],
},
document.querySelector('#step').files[0],
document.querySelector('#urdf').files,
)
// 编辑时第四个参数传 GET 详情返回的 component;未选择的资源保持原引用。
```
保存 409 时先刷新组件并处理版本冲突;保存失败不要把新 Key 当成已有资源展示。签名过期但会话有效可续签,会话过期则重新开始。对象同名覆盖被禁止,上传重试需跟踪已经确认成功的文件。
## 7. 用户管理
保持现有行为和表结构。列表支持 `page`、`size`、`keyword`(手机号或昵称)、`userType`(NORMAL / ADMIN)、`status`(ACTIVE / DISABLED)。详情返回 `id`、`phone`、`nickname`、`status`、`userType`、`createdAt`、`updatedAt`。
POST / PUT 请求:
```json
{ "phone": "13812345678", "nickname": "测试用户", "status": "ACTIVE", "userType": "NORMAL" }
```
手机号需符合大陆手机号格式并保持唯一,昵称必填且最多 64 字符。创建省略状态和类型时默认为 ACTIVE / NORMAL;修改省略则保留原值。逻辑删除后列表及详情不再返回该用户,手机号仍被占用。用户管理只记录运行日志。
## 8. 通用操作日志
当前仅组件 CREATE / UPDATE / DELETE 的成功、失败写入 `sys_operation_log`。文件校验失败及资源替换属于对应保存操作。签名、续签、列表、详情、下载和用户管理不写业务审计。
审计保持通用:当前组件事件使用 `module=COMPONENT`、`targetType=COMPONENT`,未来模块可使用其他编码。查询不写死组件模块。目标 ID 为字符串,可兼容其他业务的字符串主键。
### 8.1 查询条件
`GET /admin-api/operation-logs`
| 参数 | 说明 |
| ---------------------------------- | ---------------------------------------------- |
| page / size | 分页 |
| module / action | 模块及动作精确筛选,支持其他业务编码 |
| success | true / false |
| operatorId | 操作人 ID |
| targetType / targetId / targetCode | 目标类型、主键、业务编码精确筛选 |
| keyword | 目标名称或编码模糊筛选 |
| from / to | 操作时间闭区间,ISO 本地时间,from 不可晚于 to |
例如:`/admin-api/operation-logs?module=COMPONENT&action=DELETE&success=true&targetId=123`。
### 8.2 列表元素及详情
`GET /admin-api/operation-logs/{id}` 返回相同日志结构:
```json
{
"id": 900,
"module": "COMPONENT",
"action": "DELETE",
"targetType": "COMPONENT",
"targetId": "123",
"targetCode": "CW-0123456789ABCDEF0123456789ABCDEF",
"targetName": "四孔安装板",
"operatorId": 0,
"operatorName": "TEST_OPERATOR",
"requestPath": "/admin-api/components/{id:[0-9]+}",
"requestMethod": "DELETE",
"clientIp": "127.0.0.1",
"requestId": "请求编号",
"operatedAt": "2026-10-10T16:05:00.123",
"durationMs": 35,
"success": true,
"httpStatus": 200,
"errorCode": "",
"errorSummary": ""
}
```
删除保留操作前目标快照。失败事件记录已安全确认的目标标识,无法确定的字段为空字符串;新增失败可能尚无目标 ID。请求路径为路由模板,不保存查询参数。日志不保存请求体、表单自定义值、上传令牌或 OSS 签名。
审计写入独立事务,写日志失败不改变业务结果,运行日志记录安全定位信息和 requestId。
## 9. 常见错误
| HTTP | code | 处理 |
| ---- | ---------------------------------------- | -------------------------------------------------- |
| 422 | INVALID_REQUEST | 必填、类型、长度、精度、版本参数等错误,修正请求 |
| 422 | INVALID_UPLOAD_SIGNATURE_REQUEST | 续签令牌为空或与 componentId 同时提交 |
| 422 | INVALID_COMPONENT_UPLOAD_SESSION | 令牌无效、过期、操作人/环境/组件不匹配 |
| 422 | INVALID_STORAGE_OBJECT_KEY | 非当前环境相对对象键,或非法/越界路径 |
| 422 | INVALID_COMPONENT_UPLOAD_OBJECT | 文件类型、清单、目录、主文件数量或实际大小信息无效 |
| 422 | COMPONENT_UPLOAD_OBJECT_MISSING | OSS 未检测到文件,确认直传完成及 Key 正确 |
| 422 | DUPLICATE_CUSTOM_FIELD | 同一组自定义字段名称重复 |
| 422 | INVALID_COMPONENT_FORM | 说明超出 TEXT 字段容量 |
| 422 | COMPONENT_CODE_IMMUTABLE | 修改请求试图改变编码 |
| 413 | UPLOAD_TOO_LARGE | 实际文件超过大小限制 |
| 409 | COMPONENT_REVISION_CONFLICT | 重新加载最新组件并处理冲突 |
| 409 | COMPONENT_CODE_DUPLICATE | 同一编码已保存,不要重复新增 |
| 404 | COMPONENT_NOT_FOUND | 组件不存在或已删除 |
| 404 | USER_NOT_FOUND / OPERATION_LOG_NOT_FOUND | 对应记录不存在 |
| 409 | USER_PHONE_DUPLICATE | 手机号已占用,包含逻辑删除用户 |
| 500 | OSS_UPLOAD_SIGN_FAILED | 根据 requestId 排查签名配置或 OSS 调用 |
OSS 直传错误直接来自 OSS,不使用后台统一响应。后台保存成功才表示组件及资源引用已生效。
## 新增旋转轴 rotationAxis(2026-10-15)
组件新增、编辑请求以及详情、列表与匹配结果中的组件 DTO 增加可选顶层字段 `rotationAxis`。值为 `x`、`y`、`z`、`-x`、`-y`、`-z` 或 `null`;字母按小写保存。留空提交 `null`,表示固定连接;编辑时提交 `null` 也必须清除之前的轴。
```json
{ "rotationAxis": "z" }
```
后端需要保存字段,且在 `/admin-api/components` 的新增/编辑响应、详情响应和前台匹配返回的 `components[].component.rotationAxis` 中返回。此字段不放到 `urdfInfo`、`basicFields` 或 BOM 内,也不修改 URDF 原文、接口坐标或零件自由度。
前台在配件实际连接到父零件后,在连接点增加一个连续旋转的装配关节。轴方向按安装连接点局部坐标系解释,初始角度为 0:`T_child = T_parent × T_parentPort × R_axis(angle) × inverse(T_childPort)`。负轴遵循对应方向的右手规则。旋转带动配件和它的所有下级零件,URDF 内部的关节与 mesh 相对位姿保持原样。
没有该字段、值为空、根零件没有父连接时,不增加活动装配关节。未能配对的零件先单独展示;前台不会凭旋转轴猜测连接点。非法返回值提示原因并保留固定连接显示。
前台“属性 → 装配关节”中的 ±180° 是查看一圈的预览范围,不作为机械限位,也不回写 URDF 的 joint limit。需要机械限位时应另外约定限位字段。
后台保存后会核对响应中的 rotationAxis。如果后端忽略新字段,会明确提示“后端未返回一致的旋转轴”,保留当前输入,避免误报保存成功。
+41
View File
@@ -0,0 +1,41 @@
# 架构
浏览器通过 Vite 的 `/admin-api` 代理访问管理服务。组件、用户和操作日志都来自后端。前端只有登录的临时 sessionStorage,没有组件 IndexedDB、工作区状态仓库或持久化草稿。
## 组件与表单
列表直接请求分页,不先下载全量组件。编辑先加载详情和版本;STEP 资源用于初始预览,URDF 依赖文件在切换预览时才下载,最多 4 路并发。所有资产路径按段编码,经当前源站代理访问,不使用后端返回的内部主机地址。
表单字段使用新文档的扁平结构,PUT 提交完整表单,未替换的模型资源不随请求重复提交。组件编码不展示,名称默认取 URDF 主文件名(去扩展名),支持手动修改并保存,分类从该文件名自动识别为统一匹配键并只读展示。描述表单仅保留自由度、材质、功能、形状、大小、扭矩、质量及描述。自由度/功能/形状/大小/扭矩使用 parameterFields 的同名条目;材质/质量/描述使用现有顶层字段。质量非负并校验 DECIMAL(18,6) 的位数,扩展参数值最多 2000 字符。历史隐藏数据保留用于完整 PUT,页面不再提供任意扩展字段编辑。列表沿用后端 category 精确筛选。切换 Tab 保留输入,区域独立滚动;校验失败显示对应 Tab。
## 上传
1. 前端检查 STEP 单文件和 URDF 文件夹,去掉 URDF 最外层目录,保留内部路径与文件原始字节。
2. 保存时调用单签名接口:新增 `{}`,编辑 `{ componentId }`。
3. 原样复制每类的授权字段,添加 key,最后添加 file,最多 4 路并发直接 POST 到后端返回的 OSS 地址,不手工设置 multipart boundary,不携带浏览器 Cookie。没有本机上传转发地址、Bucket 硬编码或按开发环境切换的上传逻辑。目标 Bucket 必须允许实际页面 Origin 的 POST CORS,正式部署条件见 `deployment.md`。
4. 临近授权到期时对同一令牌续签;确认成功的文件在重试时跳过。会话到期或上传结果因网络问题不确定时使用新批次,避免同名覆盖。
5. 上传全部成功后提交对应 Key、令牌及表单,不调用旧创建会话、确认或 complete 接口。保存失败保留输入及已确认上传状态,后端成功响应后才回列表。
预览使用浏览器 OCCT WASM、Three.js 及 URDFLoader,只负责查看,不包含选面、孔组、安装面识别或绑定逻辑。预览失败会说明原因,允许符合上传结构规则的原文件继续交给后端校验。预览不改写 STEP、URDF 或依赖文件。
统一视图通过 `createPreviewModel` 生成显示副本,STEP 和 URDF 使用相同中性灰 MeshStandardMaterial。几何共享,材质独立持有并释放;保留原始节点变换、材质槽、透明度及可见性。原模型继续用于读取文件点位、计算取景和资源生命周期,不把显示颜色写回文件或接口。
## 并发编辑
PUT 使用详情中的 version。409 冲突后重新读取完整详情,对比原表单、本次编辑和最新表单:无冲突字段自动合并,同时修改的字段由用户选择;保留本次选中的替换资源,更新版本后由用户再次保存。保存进行中禁止通过编辑离开弹窗放弃更改;未保存时离开会提示。
## 用户与日志
用户仅使用 NORMAL/ADMIN、ACTIVE/DISABLED 及文档中的字段,不再保留编辑员、备注、最近登录时间或本地用户仓库。
日志保留通用 module、action 和字符串 targetId,支持目标名称/编码关键词及全部文档筛选条件;详情展示目标快照、错误码和请求编号。当前组件成功/失败操作由后端记录,前端不伪造日志,用户管理也不追加本地审计。
## 清理范围
移除旧接口库页面、接口/姿态/BREP 类型及网关、识别与拾取、封面、备份、ZIP 导入、IndexedDB 工作区/用户/组件存储、旧上传授权流程及其测试。复用的通知、格式化、模型预览和 URDF 依赖解析已独立精简。同步清理废弃 CSS 规则和不再使用的 npm 依赖。
## STEP 解析与上传选择隔离
`step-parser.worker.ts` 在 Web Worker 内执行 OCCT 解析、毫米到米的显示单位转换和网格法线计算,使用 Transferable 传回 Float32/Uint32 缓冲区。`step-loader.ts` 分批创建 Three.js 网格、计算包围盒并让出主线程;不修改上传 File。每次解析持有独立 Worker,完成、失败或 AbortSignal 取消均终止线程;编辑页面更换资源和卸载时取消旧任务,原有 generation 检查防止旧结果覆盖新选择。
STEP 与 URDF 卡片分别控制读取状态,打开文件选择器使用同步锁阻止连续点击重复打开,通过原生 cancel/change 事件解锁。STEP 解析不禁用 URDF 卡片或信息表单。正式构建将 Worker 输出到 `dist/assets`,WASM 使用应用 BASE_URL 下的 `vendor/occt-import-js` 文件,不依赖开发服务器专用代理。
+42
View File
@@ -0,0 +1,42 @@
# BOM 清单约定
前端在零件描述底部提供模板下载、Excel 导入和清单预览。Excel 在浏览器中解析,不上传原文件到 OSS,随保存组件的 POST / PUT JSON 请求提交解析结果。
**已按最新 `admin-api(3).md` 使用 `bomList` 字段,POST / PUT 提交完整值;保存响应和 GET 详情返回该字段。实际服务器写入及回填尚未联调。**
```json
{
"bomList": [
{
"partName": "H-DOF0-R-C",
"position": "头",
"dof": 0,
"material": "POM",
"function": "摄像头",
"shape": "圆形",
"size": "—",
"torque": "—"
}
]
}
```
| Excel 列 | JSON 字段 | 类型 |
| -------- | --------- | ---------------------------------------------- |
| 部件名称 | partName | string,非空 |
| 部位 | position | string |
| DOF | dof | 非负安全整数或 null;0 保留,空白或横线为 null |
| 材质 | material | string |
| 功能 | function | string |
| 形状 | shape | string |
| 大小 | size | string,保留单位和占位符 |
| 扭矩 | torque | string,保留单位和占位符 |
- `bomList` 接口允许 JSON 对象或数组,不接受字符串化 JSON;前端 Excel 导入生成以上八列对象数组。每次完整保存均携带该字段,显式 `[]` 表示清空;接口省略或 null 也会恢复为 `[]`。
- 详情返回其他 JSON 结构时原样保留,支持查看原始 JSON;重新导入或清空才会替换,不静默转为空数组。
- GET 详情支持 BOM 后应返回数组,未设置的组件返回 `[]`。列表接口不需要返回大清单。
- 支持 `.xlsx`,单文件不超过 10 MiB、最多 5000 条,每个文本单元格最多 2000 字符。只读第一张工作表,前 30 行定位八列表头,按列名匹配,按原始顺序导入。序号、标题和空行不提交。
- 模板含截图提供的一条示例,应替换或删除后上传。空文本字段使用空字符串,DOF 空白用 null。公式、日期等非文本/数字单元格给出行号错误,不读取缓存公式结果。
- 任一行校验失败则整份文件不覆盖已有 BOM。解析在 Worker 中执行,解析期间禁用保存,超时或卸载时终止 Worker。
- 保存响应中的 BOM 必须与请求一致。后端忽略字段或返回不一致时,页面明确提示、保留当前 BOM 和已保存记录 ID,后续重试更新该记录,避免重新新增。
- 编辑详情恢复已有 BOM,并纳入版本冲突合并。
+85
View File
@@ -0,0 +1,85 @@
# 正式部署与 OSS 直传
## 上传职责
本项目遵循 `admin-api.md` 的正式上传契约。开发环境、生产构建使用同一份代码:
1. 浏览器向 `/admin-api/storage/upload-signature` 申请授权。
2. 后端分配组件编码并返回短期上传签名、目标地址及允许的对象键前缀。
3. 浏览器将原始授权字段和文件直接 POST 到签名响应中的 OSS `uploadUrl`,不签名、不持有长期 AccessKey Secret,也不自行决定 Bucket。
4. OSS 返回 204 后,浏览器向组件新增/修改接口提交表单、令牌和文件引用。
5. 后端校验 OSS 中的实际文件、路径、大小和令牌后入库。只有组件保存成功,前端才显示完成。
签名、文件校验和业务入库归后端,文件传输由浏览器完成。这是阿里云的“服务端签名直传”方案;参考 [官方说明](https://help.aliyun.com/zh/oss/user-guide/obtain-signature-information-from-the-server-and-upload-data-to-oss)。如果产品改为文件先经过业务服务器,需要后端提供相应 multipart 上传接口,再统一修改 API 契约。当前没有擅自创建这种接口。
上传不依赖 Vite、本机转发地址或固定 Bucket。先前的本机上传代理已删除。
## 部署网络配置
2026-10-14 改为按网站域名直连 API,规则由 `../../shared/api-origin.ts` 统一管理:开发网站(dev-cadworld / dev-cadworld-admin)使用 dev-cadworld-api.robotquan.com,正式网站(cadworld / cadworld-admin)使用 cadworld-api.robotquan.com,所有线上域名均为 HTTPS。本机/局域网访问保留 Vite 开发代理。
执行 `npm run build`,上传 dist 到静态网站目录;网页网站不再需要 `/admin-api` 反向代理,只需 SPA 回退:
```nginx
location / {
try_files $uri $uri/ /index.html;
}
```
管理业务接口使用当前环境 API 并携带 credentials: include。URDF、STEP 和网格下载统一直连 https://linkerbot.oss-cn-beijing.aliyuncs.com,按对象键逐段编码,不带 Cookie;不再调用 /admin-api/component-assets/ 下载接口。OSS 上传仍使用后端签名返回的地址和字段。后端需开放对应网站来源的 CORS 和 X-Request-Id / Content-Type 预检,允许业务方法;返回匹配 Origin 和 Allow-Credentials: true。详细规则和当前远端预检结果见 `../../Client/docs/ai-deployment.md`。
2026-10-14 实测:正式 API 对正式网站预检已通过;开发 API 对开发网站预检返回 403 Invalid CORS request,需后端补齐开发来源。前端静态打包无法代替后端的跨域许可。
## OSS CORS:由存储管理员配置
正式前端域名目前未定。拥有 Bucket 配置权限的人需要先核对现有 CORS 规则,再新增或合并本项目规则;不能覆盖其他应用的规则。当前没有访问 OSS 控制台或修改 Bucket 配置的授权凭据,尚未执行云端配置。
| 配置项 | 本项目需要 |
| ----------------- | -------------------------------------------------------------- |
| AllowedOrigin | 页面实际来源,包括协议和端口;正式环境填写最终 HTTPS 前端域名 |
| AllowedMethod | POST |
| AllowedHeader | Content-Type(如果以后添加自定义请求头,应按实际请求同步配置) |
| MaxAgeSeconds | 600 可作为配置值 |
| 返回 Vary: Origin | 多来源时勾选,避免缓存混用来源 |
| ExposeHeader | 可选 `x-oss-request-id`,用于诊断;当前上传不依赖此项 |
| 凭据 | 上传不带浏览器 Cookie,无需凭据跨域 |
当前开发来源为 `http://127.0.0.1:8091`;若使用 `http://localhost:8091` 或局域网地址,也分别添加实际来源。正式域名确定后只调整 Bucket 的配置,不修改前端上传逻辑。来源不带路径或尾部 `/`,HTTP/HTTPS、不同端口是不同来源。表单里的 `x-oss-*` 是授权表单字段,不是需要额外允许的请求头。
建议明确列出需要的来源。CORS 不替代签名权限,不要开放 Bucket 公共写入、关闭 TLS 校验或在前端放长期密钥。
## 验收命令与上线条件
只读跨域检查,不上传文件、不读取云密钥、不修改 OSS:
```sh
npm run check:oss-cors -- \
--endpoint https://linkerbot.oss-cn-beijing.aliyuncs.com/ \
--origin http://127.0.0.1:8091
```
部署时把 endpoint 换成正式签名返回的实际地址,origin 换成最终前端来源。可以重复 `--origin` 检查多个来源。失败退出码为 1,不能当作验收通过。脚本只检查 POST/CORS 通路,不能代替实际文件上传和后端保存验证。
部署验收必须在正式静态站点上执行:组件列表、用户与日志筛选;仅 STEP 且表单全部留空上传并保存、STEP + 完整 URDF 上传并保存;刷新详情与两种预览;单独替换 STEP、单独替换 URDF;版本冲突及失败重试;资源下载内容一致。大文件、批量文件及慢网络也需按实际业务规模验证。正式来源 CORS 和实际端到端验收通过之前,不能宣称上线完成。
## 服务端筛选
前端原样展示 API 的 items 和 total,不在本地筛选或排序业务记录。
| 页面 | 接口支持的筛选 |
| -------- | ---------------------------------------------------------------------------------------- |
| 组件库 | keyword、category |
| 用户管理 | keyword、userType、status |
| 操作日志 | module、action、success、operatorId、keyword、targetType、targetId、targetCode、from、to |
每个列表另使用接口的 page / size。未知日志模块和动作按返回值显示,不生成前端业务日志。组件没有分类目录接口,因此提供分类精确匹配输入框,不生成预设筛选选项。登录保留用户要求的现有行为,不在此次工作中新增认证 API。
## STEP 必填规则同步(2026-10-14)
管理页面只要求 STEP;URDF、名称、分类、描述、BOM 和其他表单字段均选填。只上传 STEP 时签名响应无需提供 URDF 授权,保存请求不含 urdfObjectKeys,urdfInfo 为 null;未填质量、扭矩和自由度为 null。已有 STEP 的组件编辑不要求重新上传。
真实开发 API 校验仍返回 422:componentName / category must not be blank,urdfObjectKeys must not be empty。必须由后端同步取消这三项必填校验及服务层对 URDF 资源的强制要求,保留 STEP、上传令牌和已选资源有效性校验。旧 admin-api.md 记录的是此前契约,不能据此判断新规则已在服务器生效。同步要求和实测返回见 ../../releases/后台STEP必填-后端同步说明.txt。仅 STEP 的真实端到端入库仍待后端更新后验收。
## 模型文件直接下载(2026-10-14)
本地、开发站点和正式站点均使用同一桶域名,保留 API 返回对象键的环境目录;不自动把 cadworld_dev 改成其他目录。共享实现见 ../../shared/object-storage.ts。下载无业务 Cookie 和自定义请求头,桶需对实际页面来源允许 GET/HEAD。仅资源下载方式改变,业务 API 和服务端签名直传上传流程不变。
+54
View File
@@ -0,0 +1,54 @@
# 零件文件、分类与 Link 接口命名规范(2026-10-14)
前台与后台使用同一份识别代码:`shared/part-naming.ts`。
## 文件名
格式:`部位名称_R/L/0_模型特征描述.扩展名`。
例如:`头_0_兔头零自由度.urdf`、`臂_L_轻量三自由度.step`、`足_R_长连杆.stp`。
下划线分隔,部位和左右取前两段,其余内容是非空的模型特征描述。中文部位或对应英文均可识别;字母识别不区分大小写,但推荐按本表大写书写。原文件名、URDF 和网格不会被程序改写。`0` 表示不分左右;`L/R` 是零件的机械左右,不是屏幕左右。当前启用下表的 12 种分类。
| 部位 | Link 接口名 | 保存/匹配分类 |
| ---- | -------------- | ------------- |
| 躯干 | `LINK_TORSO_0` | `torso_0` |
| 头 | `LINK_HEAD_0` | `head_0` |
| 腰 | `LINK_WAIST_0` | `waist_0` |
| 左臂 | `LINK_ARM_L` | `arm_l` |
| 右臂 | `LINK_ARM_R` | `arm_r` |
| 左手 | `LINK_HAND_L` | `hand_l` |
| 右手 | `LINK_HAND_R` | `hand_r` |
| 左足 | `LINK_LEG_L` | `leg_l` |
| 右足 | `LINK_LEG_R` | `leg_r` |
| 左脚 | `LINK_FOOT_L` | `foot_l` |
| 右脚 | `LINK_FOOT_R` | `foot_r` |
| 尾 | `LINK_TAIL_0` | `tail_0` |
足对应 LEG,脚对应 FOOT,互不混用。旧的 PEDAL 分类不再作为足的新命名。
## 后台上传
STEP 必填,URDF、表单信息与 BOM 仍为选填。URDF 主文件或 STEP 文件符合规范时,自动生成只读分类,并保存 `basicFields` 中的 `partType` 与 `partSide`;比如 `leg` 与 `l`。仅上传 STEP 也会识别分类。
优先读取 URDF 主文件名,未识别时读取 STEP 文件名。两者都识别但部位或左右不同,显示具体错误并阻止提交;特征描述可以不同。文件名未识别时,保留手填分类能力,不新增必填项。文件夹名、STL 名、robot name 不参与零件分类。
```json
{
"category": "leg_l",
"basicFields": [
{ "name": "partType", "value": "leg" },
{ "name": "partSide", "value": "l" }
]
}
```
`urdfInfo.frames` 保留原始 joint、parent/child、xyz/rpy、axis、limit;child link 按本表识别后生成 `interfaceType`。URDF 根 link 在 `rootLink` 中保留,前台也能从实际文件识别根 link 接口。
## 前台装配
主 URDF 文件名确定零件分类,文件名未识别时使用接口返回的分类。同类、同侧接口匹配,如父 `LINK_LEG_L` 对子 `LINK_LEG_L`;不会把 LEG 接到 FOOT,也不会把 L 接到 R。后端明确给定节点配对时使用明确节点。
从实际 URDF 累积关节变换,令父子安装接口坐标系重合:`子零件变换 = 父接口变换 × 子接口变换的逆`。内部 joint / visual / mesh 的坐标、方向和单位保持原样,不添加自动翻转。旧缓存的 `urdfInfo.frames.interfaceType` 不覆盖文件中 Link 名的识别结果。多个同类节点无法唯一配对时提示并单独展示,不随机选取。
旧的 `LINK_head`、`Link-head`、省略 0、中文 Link 或 PEDAL 接口不再按新规范自动识别;模型资源仍可加载。机械需要在源文件中修改 Link 并同步 joint 的引用后重新上传;只改文件名不会改变文件内部接口。旧记录不会被批量修改。服务器的检索目录和 AI 分类也应将旧 `pedal_l/r` 同步为 `leg_l/r`。
Binary file not shown.

After

Width:  |  Height:  |  Size: 85 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 63 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 61 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 64 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 27 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 76 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 65 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 14 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 63 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 64 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 59 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 64 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 65 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 66 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 61 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 63 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 64 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 68 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 60 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 61 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 64 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 66 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 60 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 54 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 61 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 60 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 61 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 61 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 65 KiB

+12
View File
@@ -0,0 +1,12 @@
# 第三方资源
STEP 浏览器解析使用 npm 包 `occt-import-js` 0.0.23。公开 WASM 为该版本原始分发文件,未做二进制修改,加载脚本使用同版本 npm 依赖。
上游仓库:<https://github.com/kovacsv/occt-import-js>。
原分发许可证已一同保留:
- `public/vendor/occt-import-js/license.occt-import-js.txt`
- `public/vendor/occt-import-js/license.occt.txt`
其他 JavaScript 依赖的版本、上游与许可证信息保留在 `package-lock.json` 及 npm 包分发内容中。
+40
View File
@@ -0,0 +1,40 @@
# URDF 基本信息约定
依据最新 [后台 API 文档](admin-api.md),组件 POST / PUT 每次都提交 `urdfInfo`,使用 JSON 对象或数组,不能字符串化。后端保存前端提供的内容,保存响应和 GET 详情返回;列表不返回。接口允许空对象或空数组,但本页面新增或替换资源时必须成功读取文件,不使用空对象掩盖解析失败。
本页面从上传主文件读取以下结构,与“基本信息”标签使用同一份解析数据:
```json
{
"urdfInfo": {
"robotName": "躯干_0_宽躯躯干",
"rootLink": "BASE",
"frames": [
{
"name": "J2",
"kind": "joint",
"type": "fixed",
"parent": "BASE",
"child": "LINK_head",
"interfaceType": "head_0",
"originExplicit": true,
"xyz": [0, 0.0434269852498788, 0],
"rpy": [-1.5707963267949, -1.5707963267949, 0],
"axis": [0, 0, 0],
"limits": {}
}
]
}
}
```
- `robotName` 是 robot/name;`rootLink` 根据文件内部 joint 关系确定。
- `frames` 按文件顺序保留全部 joint。`parent` / `child` 是文件内节点引用,不表示与其他组件的装配关系。
- `xyz` 为 joint/origin/xyz,单位米;`rpy` 为 joint/origin/rpy,单位弧度;保留源文件数值精度,不改变位置、轴向或添加安装偏移。
- `originExplicit` 表示文件是否显式声明 joint/origin。`xyz`、`rpy`、`axis` 文件未定义则省略,不自行补零。
- `limits` 按文件保留 lower、upper、effort、velocity;未定义为 `{}`。
- `interfaceType` 是 child 名按约定规则识别出的零件匹配键,例如 LINK_head → head_0、LINK_arm_r → arm_r;无法识别为 null。它是名称分类,不是推断安装关系。
- 新选/替换 URDF 时重新解析并替换整个 `urdfInfo`。撤销替换时恢复已有详情值。仅改表单或 STEP 时完整保留详情返回的 JSON(包括后端额外字段或其他结构),不以预览解析覆盖。
- 保存响应同时核对 `bomList` 和 `urdfInfo`。若数据缺失或改变,保留当前输入和已保存 ID,重试使用 PUT,避免重复新增。
原始 URDF 文件及依赖资源继续按现有 OSS 直传流程保存,JSON 不替代源文件。
+221
View File
@@ -0,0 +1,221 @@
# 新版 API 验证记录
验证日期:2026-10-12,采用 `docs/admin-api.md`。当前联调目标为 `https://dev-cadworld-api.robotquan.com`;此前联调记录使用原开发地址。
## 代码与契约
- 当前仅保留组件库、用户管理、操作日志,以及要求保留的临时登录。
- 删除 32 个废弃源码文件、旧数据库/上传/机械接口测试、历史联调说明和废弃资源样例,清理 198 条不可达 CSS 规则及 JSZip、fake-indexeddb、Zod 依赖。
- 源码导入检查没有不可达业务文件。源码不再包含 IndexedDB、接口库、姿态/BREP、选面选孔、ZIP/备份和旧上传会话 API。
- 单元测试覆盖完整扁平表单、自由分类、非负数及精度、两组自定义字段、STEP/URDF 路径规则、OSS 授权字段/文件顺序、单资源替换、续签/到期/重试、版本合并、通用日志过滤、用户字段映射、登录和 URDF 依赖解析。
- 最终检查:8 个测试文件、39 项测试通过;TypeScript 检查、生产构建和全项目格式检查通过。
## 实际后端验证
- 组件列表、签名、用户列表、操作日志列表和详情使用新版路由。
- 签名正常返回组件编码、令牌、两类 POST 授权;没有创建会话或 complete 请求。
- 用项目中的公开测试样例从服务端分别直传一个 STEP、一个 URDF 和 STL 依赖文件,OSS 均返回 204。
- 保存完整表单及两组自定义字段成功,组件 version 从 1 开始。
- 表单更新成功,未提交资源替换字段时原 Key 保持不变。
- 浏览器加载后端组件详情,STEP 显示 10 个模型面,URDF 按需下载后显示 2 个 Link、1 个关节;质量 0 和自定义字段均正确恢复。
- 浏览器模拟同时编辑:远端更新名称和说明,本地修改说明;保存收到 409 后显示冲突选择。本地说明与远端新名称合并,重新保存成功,version 增至 4。
- 下载三个资源并计算 SHA-256,均与上传样例字节一致。
- 已删除本次创建的联调组件记录。DELETE 成功,操作日志保留删除前的名称、编码、目标 ID 和请求编号;成功修改、冲突失败及删除均可查询。OSS 中的联调文件依照当前后端策略保留,前端不提供云文件清理接口。
## 接口复查补充(2026-10-12)
- 通过本机 `/admin-api` 代理重新查询组件、用户、日志列表,以及用户和日志详情,均返回 HTTP 200、`code=OK`。
- 上传签名与同一令牌续签均返回 HTTP 200、`code=OK`,续签令牌保持一致。
- OSS 对 `Origin: http://127.0.0.1:8091`、请求方法 POST 的跨域预检返回 HTTP 403,仍无 `Access-Control-Allow-Origin`。
- 专门创建临时普通用户,读取详情,修改昵称、角色和停用状态,按手机号/角色/状态筛选,再恢复启用,均成功;重复手机号返回预期的 409 `USER_PHONE_DUPLICATE`。
- 已逻辑删除本次测试用户,删除返回 HTTP 200;删除后详情返回预期的 404 `USER_NOT_FOUND`,按测试手机号查询列表为 0 条。没有修改原有用户;按后端规则,逻辑删除的测试手机号仍会占用。
- 上述用户测试是通过代理执行真实 API 请求;没有据此宣称用户页面的每一个交互均已重新进行浏览器测试。组件资源替换、大文件和长时间续传仍需在 OSS CORS 修复后完成浏览器端到端复测。
## 当前上传状态:正式直传,OSS CORS 待配置
- 上传已恢复为 `admin-api.md` 规定的后端签名、浏览器直传 OSS、后端校验保存;删除本机上传代理、硬编码 Bucket 的适配与对应部署说明。
- 开发、preview 和正式构建都直接使用签名响应的 `uploadUrl`,上传不带浏览器 Cookie,不依赖 Vite 转发文件。增加测试,验证更换后端返回的生产 Bucket 地址时无需修改业务代码。
- 之前通过同源转发得到的浏览器上传成功记录,只证明文件与保存链路可用,不能作为当前正式直传方式通过的证据。其测试组件记录已清理,OSS 样例文件按后端策略保留;当前没有宣称直传端到端完成。
- 当前 OSS 预检对本机来源返回 403,缺少允许来源的响应头;缺少 OSS 配置权限,未修改云端 CORS。正式前端域名用户已明确为未定。
- `deployment.md` 记录目标 Bucket CORS、生产 API 网关、HTTPS 与静态路由回退的配置要求。`npm run check:oss-cors` 可以只读检查指定来源,不自动修改云配置,也不替代真实浏览器上传验收。
- 组件 keyword/category 已实测匹配与不匹配;日志 module、action、success、operatorId、keyword、targetId、targetType、targetCode、from、to 各实测匹配与不匹配,共 20 项通过。所有列表展示后端 items/total,查询层限制为文档字段,不做本地业务筛选或排序。
- 先前的组件单资源替换联调中,STEP 替换保留 URDF,URDF 替换保留 STEP,版本递增符合契约;正式 CORS 配置完成后仍需在实际部署来源复测。
- 当前 9 个测试文件、43 项测试覆盖上传、表单、版本冲突、查询契约和预览依赖;正式域名 CORS、大文件与长时间弱网上传未完成验收。
## 隐藏 URDF 装配测试页(2026-10-12)
- 连续点击 Logo 三次进入受当前登录保护的 `/assembly-test`,侧边栏不增加入口;刷新测试页可重新加载样例。
- 随项目发布躯干和 H-DOF0-R 的 URDF 与网格,共 9 份原始文件。逐一校验与用户提供的源文件、生产 dist 副本字节相同;运行时不依赖 Downloads 路径。
- 默认分离展示完整模型;J1 与 base_link 仅为手动试装的预选项,不推断坐标系用途。点击试装对齐时,位置为 `[-100.38, 10, 0] mm`,采用原点重合、Z 相向、X 同向的可切换假设。坐标变换支持非零源安装口偏移、完整旋转、局部轴间距及转角。
- 浏览器实际验证三次点击入口、J3 安装口切换、分离查看、安装对齐、改为 Link1 坐标系并调整旋转关节。B 根位姿随选择和关节角度更新,显示三维原始网格及坐标标记。
- 原始 Link1 网格为空,页面仅说明此事实,不生成替代网格,也不将试装结果标为机械接口已确认。完整显示原始 visual 与全部子零件;已删除测试时的统一染色和子零件隐藏处理,坐标辅助默认关闭。
- 添加 4 项装配矩阵测试;当前共 10 个测试文件、47 项通过,TypeScript、生产构建与格式检查通过。
## 上传时读取 URDF 点位(2026-10-12)
- 右侧新增“安装点位”标签,选择 URDF 后自动进入。仅展示原始 joint/origin;XYZ 为米,RPY 为弧度,不生成安装角色或配对,不换算或改写原始数值。
- 浏览器验证躯干 J1~J4 的读取与切换、更换为 H-DOF0-R 后刷新为 Link1(revolute),读取轴向及上下限、力矩、速度;移除文件后清空点位。
- 数据读取先于网格预览;编辑已有组件时按需下载现有 URDF,新增流程没有新增 API 字段或请求。测试过程未点击保存或修改后端数据。
- 新增 5 项原始点位解析测试,覆盖两份实际样例、排除 visual/inertial 坐标、缺省值与精度、非法结构/数值。共 11 个测试文件、52 项通过;TypeScript、生产构建、格式检查通过。
- 测试页将普通子 Link 从点位选择列表移除,根 Link 明确标为参考坐标系,关节保留文件类型 fixed/revolute,避免将 fixed 误称为已确认安装位。
## 安装关系完全由机械文件定义(2026-10-12)
- 删除测试页的默认 J1/base_link 配对、Z 轴朝向选择、旋转/间距补偿、关节角度修改、坐标标记与安装结果计算;删除仅用于上述假设的 assembly.ts 及其 4 项测试。
- 保留三次点击 Logo 的入口,改为 URDF 文件检查:用标签分别预览原始文件,不改变模型根位姿,不将两份缺少跨文件安装关系的 URDF 自动拼装。
- 点位只读解析器不再为缺失的 xyz/rpy/axis 属性填入默认数值,界面标明“文件未定义”。原文件始终按原始字节上传;父子关系来自文件,不提供编辑或重绑定。
- 浏览器验证两个原文件标签切换及点位展示,确认已无试装对齐、坐标补偿、关节调节或安装结果控件。历史手动试装记录仅描述此前版本,已被本节变更取代。
- 当前 10 个测试文件、49 项通过;TypeScript、生产构建及格式检查通过。新增回归检查确保缺失的 origin 属性与 axis 不会被补成坐标值。
## 统一只读展示(2026-10-12)
- 上传页与隐藏文件检查页共用同一个只读组件;移除坐标系下拉框与选中状态,按文件顺序列出全部 joint/origin。
- 点位列表只用于查看文件内容,父子关系、坐标、轴向、限位全部来自原文件;没有重新绑定、手动调整或安装选择操作。
- 安装关系仍须由机械文件明确,程序不通过名字或第一个点位猜测配对。
- 浏览器核对躯干 J1~J4 全部列出且数值与文件一致,点位面板没有选择框;URDF 原始信息及模型读取相关 9 项测试、TypeScript、生产构建和格式检查通过。
## 两个标签与原始点位悬停高亮(2026-10-12)
- 上传页右侧统一为“安装点位”和“匹配信息”,点位在前。原基本信息/参数表单合并到匹配信息,同一表单继续保留原 API 字段和校验。
- 悬停/聚焦点位时显示预览专用蓝色点标记,位置读取对应 URDF joint 的真实世界变换;标记单独放在预览场景,不修改原始模型位姿、材质或层级。移开、切换标签或资源后移除。
- 不在 STEP 与 URDF 之间猜测点位映射;悬停时切回 URDF 预览。已有组件优先读取 URDF,STEP 预览按需加载。
- 新增测试核对嵌套旋转关节下的原始点位位置与模型不变,并拒绝其他文件的旧点位引用。
- 浏览器验证两个标签、J1/J2 点位联动高亮、切换表单后标记消失、填写值跨标签保留;测试填写值已还原,未点击保存。共 11 个测试文件、51 项通过,TypeScript、生产构建及格式检查通过。
- 父/子 Link 标签改为“文件内父节点/子节点”,注明这些字段仅表示单份 URDF 内部结构,不代表跨零件安装关系;BASE 原值直接来自文件的 parent/link。
## 自由旋转与点位自动取景(2026-10-12)
- 悬停/聚焦文件点位时,相机在 500ms 内平滑转到点位所在方向并将点位居中。手动操作相机立即中止自动取景;不修改模型姿态、材质、内部关系、文件数值或上传内容。取景方向不作为安装数据。
- 统一预览改为自由轨迹球控制,可越过旋转极点及查看底部;左键旋转、右键平移、滚轮缩放,地面网格已移除。
- 右下角 XYZ 为实时视图方向指示,按相机姿态投影,增大字体并避开标签重叠,不添加模型坐标系。
- 使用用户提供的躯干文件验证 J1/J2 自动定位、手动翻转、重置视角和无网格显示,未提交保存或调用上传接口。
- 新增相机取景不改模型、中心点退化处理及底部视角 XYZ 投影测试;12 个测试文件共 54 项通过,TypeScript、生产构建及格式检查通过。
## 窗口自适应与标签调整(2026-10-12)
- 上传页标签依次为“零件描述 / 基本信息”,默认零件描述,保留原表单和文件点位内容。导入 URDF 不再强制切换标签;键盘 Home/End 与左右键顺序同步调整。
- 外壳约束为窗口高度,上传页与文件检查页左右面板上下边界对齐,模型预览填满剩余空间,长表单与点位独立滚动。列表页工具栏、分页固定在面板内,表格/卡片独立滚动,长筛选区限制高度。
- 浏览器测量上传页在 1920×1080、1280×720、1024×768 下左右底边一致,文档宽高等于窗口;390×844 下采用上下布局,工作区内部滚动,文档无溢出。
- 文件检查页在 1280×720 下左右均为 464px 高,点位内容 1335px 在 407px 容器内滚动;日志页 390×844 下筛选区内部滚动,分页仍在窗口内。日志接口此次返回 HTTP 500,仅验证错误状态布局,未修改接口请求或后端数据。
- 导入躯干后仍默认展示零件描述,基本信息显示原始 J1~J4;Home 键切回首个描述标签。聚焦底部标签字段时表单内部滚动约 400px,文档及 page 容器滚动均保持 0。
- 生产构建及格式检查通过;未增加布局单元测试,使用实际浏览器尺寸、边界和滚动高度验证。
## 官方视角控件(2026-10-12)
- 统一模型预览直接使用 Three.js 自带 ViewHelper;删除自绘 SVG、坐标投影函数、旧外框和相应样式。本节取代此前自绘 XYZ 指示实现。
- 控件由 Three.js 在独立视口渲染,点击轴可围绕当前查看中心切换视角。与 TrackballControls 同步相机朝向,保留 360° 旋转、平移、缩放、重置及原始点位自动取景。
- 新增实际 ViewHelper 与 TrackballControls 的衔接回归测试:非零查看中心、Z 朝上的初始视角切换到 X 轴后,相机仍准确朝向查看中心,中心坐标不变。
- 浏览器使用原始躯干文件核对控件显示、点击 X 轴后模型居中、基本信息点位高亮与自动取景;未调用保存上传。13 个测试文件共 54 项通过,生产构建及格式检查通过。
## 预览过曝与孔位细节(2026-10-12)
- 移除过强且带色偏的照明,使用中性半球补光(0.35)、主方向光(1.4)和弱补光(0.25),启用 ACES 色调映射,曝光 0.85。
- 主光启用 2048px PCFSoft 阴影;光源位置、阴影相机范围和法线偏移随模型包围盒尺寸适配。模型投射/接收自身阴影,预览卸载时恢复原始阴影标记;没有修改材质、几何、文件变换或上传数据。
- 浏览器使用同一份原始躯干 URDF,放大及旋转核对多个侧面的孔位、接口和凹槽;白色表面不再整片过曝,凹槽可见遮挡阴影。未保存或上传资源。
- 生产构建、54 项现有测试及格式检查通过;照明变化通过实际渲染验证。
## 新开发域名接口复查(2026-10-12)
目标:`https://dev-cadworld-api.robotquan.com`,通过运行中的同源 `/admin-api` 代理测试。直连组件列表与代理均为 HTTP 200 / OK。
| 接口 | 实测结果 |
| --------------------------------------------- | -------------------------------------------------------------------------------------------------------- |
| POST `/admin-api/storage/upload-signature` | 首次申请、原会话续签、已有组件资源替换均 200;续签保留令牌、编码及两类资源前缀 |
| GET `/admin-api/components` | 分页与 keyword/category 查询 200,测试组件精确检出,清理后 total=0 |
| POST `/admin-api/components` | 小样例实际直传后保存 200,初始 version=1,完整表单返回一致 |
| GET `/admin-api/components/{id}` | 测试组件详情 200,表单、资源清单与保存内容一致 |
| PUT `/admin-api/components/{id}` | 全量表单更新、单独替换 STEP、单独替换 URDF 均 200;版本递增,未替换的资源保持原引用 |
| DELETE `/admin-api/components/{id}` | 仅删除本次新建测试组件,200;删除后详情 404 / COMPONENT_NOT_FOUND |
| GET `/admin-api/component-assets/{objectKey}` | STEP、URDF、STL 均 200,下载 SHA-256 与项目样例一致 |
| GET `/admin-api/users` | 分页、keyword、userType、status 请求均 200,能检出已知记录 |
| GET `/admin-api/users/{id}` | 现有记录详情 200,文档字段齐全;不存在记录 404 / USER_NOT_FOUND |
| POST `/admin-api/users` | 非法手机号返回 422 / INVALID_REQUEST;正常新增未实测,避免占用手机号 |
| PUT `/admin-api/users/{id}` | 非法输入返回 422 / INVALID_REQUEST;未修改现有用户,正常修改未实测 |
| DELETE `/admin-api/users/{id}` | 不存在记录返回 404 / USER_NOT_FOUND;未删除现有用户,正常逻辑删除未实测 |
| GET `/admin-api/operation-logs` | 分页及文档十项筛选均 200;测试组件留下 CREATE、三次 UPDATE、DELETE 五条成功日志,目标 ID/编码/名称可回查 |
| GET `/admin-api/operation-logs/{id}` | 已有记录详情 200,字段匹配;不存在记录 404 / OPERATION_LOG_NOT_FOUND |
参数校验:空组件请求、非法用户手机号、互斥签名参数、倒置日志时间区间均按约定返回 422;不存在的组件/用户删除按约定 404。这些是正常校验响应,不是接口故障。现有前端 54 项测试和 TypeScript 检查通过。
**尚未打通的是浏览器 OSS 跨域上传。** 使用签名返回的真实地址测试,`http://127.0.0.1:8091` 和 `http://localhost:8091` 的 POST 预检均为 403,未返回允许来源/方法/请求头。命令行实际 POST 六个小样例资源均返回 204,但也没有 `Access-Control-Allow-Origin`;命令行不受浏览器 CORS 约束,所以这些成功不能视为页面上传验收成功。需由 Bucket 管理员配置允许来源、POST 和 Content-Type,详见部署文档;无需修改组件 API 的前端参数或添加临时上传代理。
本次未改动现有用户与业务组件。测试组件 ID=3 已删除;按后端既定保留策略,联调审计日志及六个小样例 OSS 对象(总计 266056 字节)仍保留。未记录签名字段、上传令牌或用户手机号。
定位请求编号:首次签名 `8afe25984e7a4621983ae4fc257d8479`;组件新增 `e7e97eb59b2f4d408c2aa0cab41d1cf1`;STEP 替换 `ec3b7d5090d14717b1c4be47a50c7f25`;URDF 替换 `00d3c2778d4942b5b7af4a1995a70bb8`;测试组件删除 `da4bc76147644ff291bdfeedc4b743db`。
## STEP 与 URDF 统一预览颜色(2026-10-12)
- 两种格式统一通过显示副本使用中性灰 MeshStandardMaterial(颜色 `#e0e0e0`、金属度 0、粗糙度 0.75),共享当前预览灯光和曝光。本节取代此前预览直接使用原始文件材质的显示策略。
- 原模型、原材质及文件字节不改动,副本只共享几何;保留模型变换、材质槽、透明度和可见性,副本卸载不释放源模型的几何或材质。
- 背面投影及随模型大小适配的法线偏移减少 STEP 的自阴影条纹,继续显示接口凹槽。
- 使用同一个躯干的 STEP 和新 URDF,在独立浏览器页中切换比对灰色和细节,未保存或上传,不覆盖用户编辑页。构建、56 项测试及格式检查通过;新增测试覆盖两种原始材质的统一显示、源数据不变、材质槽/透明度保留及独立资源释放。
## 截图
- `screenshots/urdf-readonly-points.jpg`:上传页统一只读列出全部文件点位,没有坐标系选择操作。
- `screenshots/urdf-file-inspection.jpg`:只读原始 URDF 文件检查,不添加安装规则。
- `screenshots/component-new-api.jpg`:后端详情、STEP 预览及新表单扩展字段(联调记录清理前)。
- `screenshots/activity-new-api.jpg`:新通用日志与目标快照。
- `screenshots/three-view-helper.png`:官方 ViewHelper 与原始 URDF 预览。
- `screenshots/model-lighting-detail.png`:调整照明及自身阴影后的孔位细节。
- `screenshots/step-neutral-preview.png`、`screenshots/urdf-neutral-preview.png`:同一躯干的两种格式使用统一灰色预览材质。
## STEP 解析期间的独立文件选择(2026-10-12)
- 生产构建 `vite preview` 本机 8092:使用实际 `躯干.STEP`,STEP 仍显示“正在解析 STEP 预览…”时,点击 URDF 文件夹选择器约 270 ms 打开;两份实际模型都加载成功。
- 重新选择 STEP 后,在其解析期间切换已加载 URDF 成功,URDF 更换按钮保持可用;截图 `screenshots/independent-model-import.png`。没有保存或上传业务数据。
- 回归覆盖 Worker 返回几何、保留源文件字节、取消解析、解析失败清理、已取消任务不启动,以及 STEP 忙时 URDF 仍可选、连续点击仅一个窗口、cancel/change 后正常恢复。
- 8091 开发模式实际 STEP 解析成功,显示 6612 个模型面,URDF 选择按钮保持可用,浏览器无 error 日志。
- 最终 `npm run build`、`npm run format:check` 和 61 项测试均通过。
## 按名称识别零件与接口类型(2026-10-12)
- 单元测试覆盖 24 个中英文名称、两种分隔符、12 个匹配键、左右组合限制、未知名称、接口前缀规则、坐标不变、basicFields 序列化与旧类型替换;66 项测试通过。
- 浏览器导入机械新躯干模型的临时副本,仅主文件改为 `躯干-0-机械型号.urdf`:识别 `torso_0`;J1/J2/J3/J4 子节点分别识别 `arm_r` / `head_0` / `arm_l` / `waist_0`。点位数值保留原精度,J2 可正常高亮。
- 截图 `screenshots/part-name-identity.png` 与 `screenshots/interface-name-identity.png`。没有修改原机械文件,也没有保存后端测试记录。
- `npm run build`、`npm run format:check` 通过。类型按已有 basicFields 契约提交;后端按 partType/partSide 查询候选零件尚需增加 API 支持。
## 零件分类自动识别与标签图标(2026-10-12)
- 右侧两个标签使用 lucide-react 的 FilePenLine(零件描述)和 Network(基本信息),主品牌 Logo 保持既有图片。
- 分类只读,使用 URDF 主文件名识别出的规范键;取消上方重复类型面板和手动分类建议。提交时 category 与 partType/partSide 由同一识别结果生成,防止旧“结构件”等手填分类混入。
- 浏览器选择实际 `躯干_0_宽躯躯干`:分类为 torso_0 且 readOnly;替换为 `头_0_卤蛋零自由度头` 后即时更新为 head_0,模型正常加载。截图 `screenshots/automatic-part-category.png`;未上传或保存后端记录。
- 列表提供 12 种规范分类建议,仍通过已有 category 精确筛选参数请求后端,没有添加前端记录筛选或未支持的查询字段。
- 构建、格式检查和 67 项测试通过。
## 自定义字段排版(2026-10-12)
- 两组自定义字段统一为横向标题栏:标题、独立计数标记、右侧添加按钮。计数字号与标题分离,按钮为 30 px 紧凑高度;窄面板不足时自动换行。
- 新增字段采用独立卡片,名称与删除按钮对齐,内容区单独一行,统一 12 px 间距。两组的添加、输入、删除已在浏览器验证。
- 实测右侧内容宽 263 px,无横向溢出,两组添加按钮的左右边界一致;页面根节点无整体滚动溢出。
- 截图 `screenshots/custom-fields-layout.png`、`screenshots/custom-fields-layout-detail.png`;构建与格式检查通过。本次仅调整展示结构和样式,未保存业务数据。
## 零件描述精简(2026-10-12)
- 描述页仅保留自动分类、自由度、材质、功能、形状、大小、扭矩、质量(kg)和自由描述输入框。移除名称/编码/厂商/标签及自定义字段编辑器,删除无引用的编辑组件与样式。
- 名称由当前 URDF 主文件名生成(去扩展名),替换文件后更新;保存时再次从文件名取值。组件编码分配与上传请求沿用原流程。
- 自由度/功能/形状/大小/扭矩保存到已有 parameterFields 的同名条目,支持详情回填、修改和清空;material/massKg/description 使用现有字段。完整 PUT 保留历史隐藏数据,避免编辑新表单时丢失旧记录。
- 70 项测试、TypeScript 和生产构建通过。新增测试覆盖参数保存/回填/清空、历史数据保留和文件名称派生。浏览器导入躯干文件自动识别 torso_0,验证九个显示字段、内部滚动和整页无溢出;未向真实后端新增测试组件。
- 页面截图:screenshots/part-description.png。
## BOM Excel 导入(2026-10-12)
- 零件描述底部增加 BOM 清单、下载模板和上传 Excel。模板包含参考图中的八个业务字段与首条示例,序号不进入 JSON。
- ExcelJS 4.4.0 在独立 Worker 解析第一张工作表。按表头映射,保留 DOF 0 与单位文本,跳过空行;公式/日期、缺少名称、重复/缺少表头、超出行数及单元格限制时整份导入失败,保留已有清单。
- BOM 支持预览、分页、重新上传、清空和编辑回填。JSON 保存请求新增可选 bom 对象数组,未导入时不增加此字段;清空显式提交 []。后端支持情况尚未联调,待办见 bom-contract.md。
- 保存响应缺少或改变 BOM 时不提示整体成功,保留输入与已保存记录 ID,避免重复创建。
- 77 项自动测试通过,覆盖真实模板解析、表头映射、空白与零、行校验、JSON 数组保存与清空、详情回填、后端忽略字段检测。生产构建通过,依赖审计无已知漏洞。
- 浏览器验证开发服务的模板下载、真实文件导入和完整清单。另使用生产构建预览验证打包后的 Worker 成功解析同一文件,结果与模板一致;未向真实后端写入测试组件。
- 预览截图:screenshots/bom-preview.png。
## 2026-10-12 最新后台 API(admin-api(3).md)
- docs/admin-api.md 已同步用户提供的最新文档;用户、日志、OSS 签名及资源路径协议无变化。
- POST/PUT 按新扁平字段提交 degreesOfFreedom(整数)、functionDescription、shape、size、torqueNm(N·m 数值),移除 manufacturer、tags、lengthMm/widthMm/heightMm 及旧的自动参数映射。材质/质量/描述及已有扩展字段保留。
- BOM 正式字段使用 bomList,始终随全量表单提交;Excel 八列结构不变,后端其他自由 JSON 结构也能查看并原样保留。
- 基本信息按同一份 URDF 解析数据生成必填 urdfInfo,保留名称、文件内父子节点、XYZ/RPY、axis、limits 和名称识别类型,不补坐标、不推断装配。替换文件时更新,撤销替换时恢复详情,仅改表单/STEP 不覆盖原 JSON。
- 保存响应校对两份 JSON;不一致时保留输入及已保存 ID,避免重复创建。
- 80 项测试通过,覆盖字段默认值/范围/单位、JSON 对象/数组回填、缺失 urdfInfo、POST/仅表单 PUT、缺省坐标与精度、BOM 导入及响应差异。
- 生产构建通过。浏览器使用用户的躯干_0_宽躯躯干文件夹验证四个点位、名称/分类自动识别及 Excel Worker 导入;控制台无错误。
- 只读请求测试环境组件列表返回 OK、items 为空;没有可用于详情验证的已有记录,本次未向远程服务器写入测试组件。真实 OSS 上传、保存及再打开的完整回填仍待实际联调。
+14
View File
@@ -0,0 +1,14 @@
<!doctype html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta name="theme-color" content="#050505" />
<meta name="description" content="CAD World 组件与机械接口管理工作台" />
<title>CAD World · Management</title>
</head>
<body>
<div id="root"></div>
<script type="module" src="/src/main.tsx"></script>
</body>
</html>
+5507
View File
File diff suppressed because it is too large Load Diff
+46
View File
@@ -0,0 +1,46 @@
{
"name": "cadworld-management",
"version": "0.1.0",
"private": true,
"type": "module",
"scripts": {
"dev": "vite --host 0.0.0.0 --port 8091 --strictPort",
"build": "tsc -b && vite build",
"preview": "vite preview --host 0.0.0.0 --port 8091 --strictPort",
"test": "vitest run",
"check": "tsc -b",
"check:oss-cors": "node scripts/check-oss-cors.mjs",
"format": "prettier --write .",
"format:check": "prettier --check ."
},
"dependencies": {
"exceljs": "4.4.0",
"lucide-react": "^0.468.0",
"occt-import-js": "0.0.23",
"react": "^19.1.0",
"react-dom": "^19.1.0",
"react-router-dom": "^7.6.0",
"three": "0.183.2",
"urdf-loader": "0.12.6"
},
"devDependencies": {
"@types/node": "^22.15.0",
"@types/react": "^19.1.0",
"@types/react-dom": "^19.1.0",
"@types/three": "^0.183.0",
"@vitejs/plugin-react": "^5.0.0",
"jsdom": "^29.0.2",
"prettier": "^3.9.9",
"typescript": "~5.9.0",
"vite": "^7.0.0",
"vitest": "^4.1.4"
},
"engines": {
"node": ">=22.12.0"
},
"overrides": {
"exceljs": {
"uuid": "11.1.1"
}
}
}
@@ -0,0 +1,105 @@
<?xml version="1.0" encoding="utf-8"?>
<!-- This URDF was automatically created by SolidWorks to URDF Exporter! Originally created by Stephen Brawner (brawner@gmail.com)
Commit Version: 1.6.0-4-g7f85cfe Build Version: 1.6.7995.38578
For more information, please see http://wiki.ros.org/sw_urdf_exporter -->
<robot
name="H-DOF0-R(URDF)">
<link
name="base_link">
<inertial>
<origin
xyz="-7.94843479098614E-05 -0.000101849084169811 -0.0402166203520094"
rpy="0 0 0" />
<mass
value="0.068072613582502" />
<inertia
ixx="6.55512095760579E-05"
ixy="1.31722714450651E-09"
ixz="1.48311662317917E-07"
iyy="7.00534066769677E-05"
iyz="-9.07716445822466E-08"
izz="4.74277521570556E-05" />
</inertial>
<visual>
<origin
xyz="0 0 0"
rpy="0 0 0" />
<geometry>
<mesh
filename="package://H-DOF0-R(URDF)/meshes/base_link.STL" />
</geometry>
<material
name="">
<color
rgba="1 1 1 1" />
</material>
</visual>
<collision>
<origin
xyz="0 0 0"
rpy="0 0 0" />
<geometry>
<mesh
filename="package://H-DOF0-R(URDF)/meshes/base_link.STL" />
</geometry>
</collision>
</link>
<link
name="Link1">
<inertial>
<origin
xyz="-7.29048633876416E-05 -0.000165379048968763 -0.0408053224100978"
rpy="0 0 0" />
<mass
value="0.0760207590919301" />
<inertia
ixx="8.03551847643866E-05"
ixy="1.32033044205573E-09"
ixz="1.23872216929103E-07"
iyy="8.48684182281494E-05"
iyz="-1.2550095499697E-07"
izz="5.15694936320691E-05" />
</inertial>
<visual>
<origin
xyz="0 0 0"
rpy="0 0 0" />
<geometry>
<mesh
filename="package://H-DOF0-R(URDF)/meshes/Link1.STL" />
</geometry>
<material
name="">
<color
rgba="1 1 1 1" />
</material>
</visual>
<collision>
<origin
xyz="0 0 0"
rpy="0 0 0" />
<geometry>
<mesh
filename="package://H-DOF0-R(URDF)/meshes/Link1.STL" />
</geometry>
</collision>
</link>
<joint
name="Link1"
type="revolute">
<origin
xyz="0 7.2197E-05 0.005"
rpy="0 0 0" />
<parent
link="base_link" />
<child
link="Link1" />
<axis
xyz="0 0 -1" />
<limit
lower="-1.8"
upper="1.8"
effort="100"
velocity="50" />
</joint>
</robot>
@@ -0,0 +1,19 @@
[
{
"id": "torso",
"name": "躯干",
"files": [
"urdf/机器人_3.urdf",
"meshes/BASE.STL",
"meshes/LINK1.1.STL",
"meshes/LINK1.2.STL",
"meshes/LINK1.3.STL",
"meshes/LINK1.4.STL"
]
},
{
"id": "h-dof0-r",
"name": "H-DOF0-R",
"files": ["urdf/H-DOF0-R(URDF).urdf", "meshes/base_link.STL", "meshes/Link1.STL"]
}
]
@@ -0,0 +1,259 @@
<?xml version="1.0" encoding="utf-8"?>
<!-- This URDF was automatically created by SolidWorks to URDF Exporter! Originally created by Stephen Brawner (brawner@gmail.com)
Commit Version: 1.7.2+g1847c98ccf62 Build Version: 1.7.2.0
For more information, please see http://wiki.ros.org/sw_urdf_exporter -->
<robot
name="机器人_3">
<link
name="BASE">
<inertial>
<origin
xyz="5.84988574477819E-08 -0.0221072974333878 0.00708210719782402"
rpy="0 0 0" />
<mass
value="0.8530807511686" />
<inertia
ixx="0.0034239595145081"
ixy="4.49992622650466E-09"
ixz="2.48024798913326E-08"
iyy="0.00478603080068325"
iyz="5.31970347582682E-05"
izz="0.00400733426526815" />
</inertial>
<visual>
<origin
xyz="0 0 0"
rpy="0 0 0" />
<geometry>
<mesh
filename="package://机器人_3/meshes/BASE.STL" />
</geometry>
<material
name="">
<color
rgba="1 1 1 1" />
</material>
</visual>
<collision>
<origin
xyz="0 0 0"
rpy="0 0 0" />
<geometry>
<mesh
filename="package://机器人_3/meshes/BASE.STL" />
</geometry>
</collision>
</link>
<link
name="LINK1.1">
<inertial>
<origin
xyz="5.60427894696185E-05 -0.00753621925936619 -0.0220865141643683"
rpy="0 0 0" />
<mass
value="0.0127701140619706" />
<inertia
ixx="5.04695556235442E-06"
ixy="-1.08518067053191E-08"
ixz="4.39666619947628E-09"
iyy="3.46594649077607E-06"
iyz="-3.37467772173804E-07"
izz="2.6768103146614E-06" />
</inertial>
<visual>
<origin
xyz="0 0 0"
rpy="0 0 0" />
<geometry>
<mesh
filename="package://机器人_3/meshes/LINK1.1.STL" />
</geometry>
<material
name="">
<color
rgba="1 1 1 1" />
</material>
</visual>
<collision>
<origin
xyz="0 0 0"
rpy="0 0 0" />
<geometry>
<mesh
filename="package://机器人_3/meshes/LINK1.1.STL" />
</geometry>
</collision>
</link>
<joint
name="J1"
type="fixed">
<origin
xyz="-0.10038 0.01 0"
rpy="0 -1.5708 0" />
<parent
link="BASE" />
<child
link="LINK1.1" />
<axis
xyz="0 0 0" />
</joint>
<link
name="LINK1.2">
<inertial>
<origin
xyz="-0.00753621925936619 -5.60427894695924E-05 -0.0220865141643683"
rpy="0 0 0" />
<mass
value="0.0127701140619706" />
<inertia
ixx="3.46594649077607E-06"
ixy="1.08518067053246E-08"
ixz="-3.37467772173804E-07"
iyy="5.04695556235442E-06"
iyz="-4.39666619947511E-09"
izz="2.6768103146614E-06" />
</inertial>
<visual>
<origin
xyz="0 0 0"
rpy="0 0 0" />
<geometry>
<mesh
filename="package://机器人_3/meshes/LINK1.2.STL" />
</geometry>
<material
name="">
<color
rgba="1 1 1 1" />
</material>
</visual>
<collision>
<origin
xyz="0 0 0"
rpy="0 0 0" />
<geometry>
<mesh
filename="package://机器人_3/meshes/LINK1.2.STL" />
</geometry>
</collision>
</link>
<joint
name="J2"
type="fixed">
<origin
xyz="0 0.043427 0"
rpy="-1.5708 -1.5708 0" />
<parent
link="BASE" />
<child
link="LINK1.2" />
<axis
xyz="0 0 0" />
</joint>
<link
name="LINK1.3">
<inertial>
<origin
xyz="-5.60427894696187E-05 0.00753621925936619 -0.0220865141643683"
rpy="0 0 0" />
<mass
value="0.0127701140619706" />
<inertia
ixx="5.04695556235442E-06"
ixy="-1.08518067053196E-08"
ixz="-4.39666619947629E-09"
iyy="3.46594649077607E-06"
iyz="3.37467772173804E-07"
izz="2.6768103146614E-06" />
</inertial>
<visual>
<origin
xyz="0 0 0"
rpy="0 0 0" />
<geometry>
<mesh
filename="package://机器人_3/meshes/LINK1.3.STL" />
</geometry>
<material
name="">
<color
rgba="1 1 1 1" />
</material>
</visual>
<collision>
<origin
xyz="0 0 0"
rpy="0 0 0" />
<geometry>
<mesh
filename="package://机器人_3/meshes/LINK1.3.STL" />
</geometry>
</collision>
</link>
<joint
name="J3"
type="fixed">
<origin
xyz="0.10038 0.01 0"
rpy="3.1416 -1.5708 0" />
<parent
link="BASE" />
<child
link="LINK1.3" />
<axis
xyz="0 0 0" />
</joint>
<link
name="LINK1.4">
<inertial>
<origin
xyz="0.00753621925936619 5.60427894696192E-05 -0.0220865141643683"
rpy="0 0 0" />
<mass
value="0.0127701140619706" />
<inertia
ixx="3.46594649077607E-06"
ixy="1.08518067053192E-08"
ixz="3.37467772173804E-07"
iyy="5.04695556235442E-06"
iyz="4.39666619947911E-09"
izz="2.6768103146614E-06" />
</inertial>
<visual>
<origin
xyz="0 0 0"
rpy="0 0 0" />
<geometry>
<mesh
filename="package://机器人_3/meshes/LINK1.4.STL" />
</geometry>
<material
name="">
<color
rgba="1 1 1 1" />
</material>
</visual>
<collision>
<origin
xyz="0 0 0"
rpy="0 0 0" />
<geometry>
<mesh
filename="package://机器人_3/meshes/LINK1.4.STL" />
</geometry>
</collision>
</link>
<joint
name="J4"
type="fixed">
<origin
xyz="0 -0.098473 0"
rpy="1.5708 -1.5708 0" />
<parent
link="BASE" />
<child
link="LINK1.4" />
<axis
xyz="0 0 0" />
</joint>
</robot>
Binary file not shown.

After

Width:  |  Height:  |  Size: 13 KiB

Binary file not shown.
@@ -0,0 +1,504 @@
GNU LESSER GENERAL PUBLIC LICENSE
Version 2.1, February 1999
Copyright (C) 1991, 1999 Free Software Foundation, Inc.
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
[This is the first released version of the Lesser GPL. It also counts
as the successor of the GNU Library Public License, version 2, hence
the version number 2.1.]
Preamble
The licenses for most software are designed to take away your
freedom to share and change it. By contrast, the GNU General Public
Licenses are intended to guarantee your freedom to share and change
free software--to make sure the software is free for all its users.
This license, the Lesser General Public License, applies to some
specially designated software packages--typically libraries--of the
Free Software Foundation and other authors who decide to use it. You
can use it too, but we suggest you first think carefully about whether
this license or the ordinary General Public License is the better
strategy to use in any particular case, based on the explanations below.
When we speak of free software, we are referring to freedom of use,
not price. Our General Public Licenses are designed to make sure that
you have the freedom to distribute copies of free software (and charge
for this service if you wish); that you receive source code or can get
it if you want it; that you can change the software and use pieces of
it in new free programs; and that you are informed that you can do
these things.
To protect your rights, we need to make restrictions that forbid
distributors to deny you these rights or to ask you to surrender these
rights. These restrictions translate to certain responsibilities for
you if you distribute copies of the library or if you modify it.
For example, if you distribute copies of the library, whether gratis
or for a fee, you must give the recipients all the rights that we gave
you. You must make sure that they, too, receive or can get the source
code. If you link other code with the library, you must provide
complete object files to the recipients, so that they can relink them
with the library after making changes to the library and recompiling
it. And you must show them these terms so they know their rights.
We protect your rights with a two-step method: (1) we copyright the
library, and (2) we offer you this license, which gives you legal
permission to copy, distribute and/or modify the library.
To protect each distributor, we want to make it very clear that
there is no warranty for the free library. Also, if the library is
modified by someone else and passed on, the recipients should know
that what they have is not the original version, so that the original
author's reputation will not be affected by problems that might be
introduced by others.
Finally, software patents pose a constant threat to the existence of
any free program. We wish to make sure that a company cannot
effectively restrict the users of a free program by obtaining a
restrictive license from a patent holder. Therefore, we insist that
any patent license obtained for a version of the library must be
consistent with the full freedom of use specified in this license.
Most GNU software, including some libraries, is covered by the
ordinary GNU General Public License. This license, the GNU Lesser
General Public License, applies to certain designated libraries, and
is quite different from the ordinary General Public License. We use
this license for certain libraries in order to permit linking those
libraries into non-free programs.
When a program is linked with a library, whether statically or using
a shared library, the combination of the two is legally speaking a
combined work, a derivative of the original library. The ordinary
General Public License therefore permits such linking only if the
entire combination fits its criteria of freedom. The Lesser General
Public License permits more lax criteria for linking other code with
the library.
We call this license the "Lesser" General Public License because it
does Less to protect the user's freedom than the ordinary General
Public License. It also provides other free software developers Less
of an advantage over competing non-free programs. These disadvantages
are the reason we use the ordinary General Public License for many
libraries. However, the Lesser license provides advantages in certain
special circumstances.
For example, on rare occasions, there may be a special need to
encourage the widest possible use of a certain library, so that it becomes
a de-facto standard. To achieve this, non-free programs must be
allowed to use the library. A more frequent case is that a free
library does the same job as widely used non-free libraries. In this
case, there is little to gain by limiting the free library to free
software only, so we use the Lesser General Public License.
In other cases, permission to use a particular library in non-free
programs enables a greater number of people to use a large body of
free software. For example, permission to use the GNU C Library in
non-free programs enables many more people to use the whole GNU
operating system, as well as its variant, the GNU/Linux operating
system.
Although the Lesser General Public License is Less protective of the
users' freedom, it does ensure that the user of a program that is
linked with the Library has the freedom and the wherewithal to run
that program using a modified version of the Library.
The precise terms and conditions for copying, distribution and
modification follow. Pay close attention to the difference between a
"work based on the library" and a "work that uses the library". The
former contains code derived from the library, whereas the latter must
be combined with the library in order to run.
GNU LESSER GENERAL PUBLIC LICENSE
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
0. This License Agreement applies to any software library or other
program which contains a notice placed by the copyright holder or
other authorized party saying it may be distributed under the terms of
this Lesser General Public License (also called "this License").
Each licensee is addressed as "you".
A "library" means a collection of software functions and/or data
prepared so as to be conveniently linked with application programs
(which use some of those functions and data) to form executables.
The "Library", below, refers to any such software library or work
which has been distributed under these terms. A "work based on the
Library" means either the Library or any derivative work under
copyright law: that is to say, a work containing the Library or a
portion of it, either verbatim or with modifications and/or translated
straightforwardly into another language. (Hereinafter, translation is
included without limitation in the term "modification".)
"Source code" for a work means the preferred form of the work for
making modifications to it. For a library, complete source code means
all the source code for all modules it contains, plus any associated
interface definition files, plus the scripts used to control compilation
and installation of the library.
Activities other than copying, distribution and modification are not
covered by this License; they are outside its scope. The act of
running a program using the Library is not restricted, and output from
such a program is covered only if its contents constitute a work based
on the Library (independent of the use of the Library in a tool for
writing it). Whether that is true depends on what the Library does
and what the program that uses the Library does.
1. You may copy and distribute verbatim copies of the Library's
complete source code as you receive it, in any medium, provided that
you conspicuously and appropriately publish on each copy an
appropriate copyright notice and disclaimer of warranty; keep intact
all the notices that refer to this License and to the absence of any
warranty; and distribute a copy of this License along with the
Library.
You may charge a fee for the physical act of transferring a copy,
and you may at your option offer warranty protection in exchange for a
fee.
2. You may modify your copy or copies of the Library or any portion
of it, thus forming a work based on the Library, and copy and
distribute such modifications or work under the terms of Section 1
above, provided that you also meet all of these conditions:
a) The modified work must itself be a software library.
b) You must cause the files modified to carry prominent notices
stating that you changed the files and the date of any change.
c) You must cause the whole of the work to be licensed at no
charge to all third parties under the terms of this License.
d) If a facility in the modified Library refers to a function or a
table of data to be supplied by an application program that uses
the facility, other than as an argument passed when the facility
is invoked, then you must make a good faith effort to ensure that,
in the event an application does not supply such function or
table, the facility still operates, and performs whatever part of
its purpose remains meaningful.
(For example, a function in a library to compute square roots has
a purpose that is entirely well-defined independent of the
application. Therefore, Subsection 2d requires that any
application-supplied function or table used by this function must
be optional: if the application does not supply it, the square
root function must still compute square roots.)
These requirements apply to the modified work as a whole. If
identifiable sections of that work are not derived from the Library,
and can be reasonably considered independent and separate works in
themselves, then this License, and its terms, do not apply to those
sections when you distribute them as separate works. But when you
distribute the same sections as part of a whole which is a work based
on the Library, the distribution of the whole must be on the terms of
this License, whose permissions for other licensees extend to the
entire whole, and thus to each and every part regardless of who wrote
it.
Thus, it is not the intent of this section to claim rights or contest
your rights to work written entirely by you; rather, the intent is to
exercise the right to control the distribution of derivative or
collective works based on the Library.
In addition, mere aggregation of another work not based on the Library
with the Library (or with a work based on the Library) on a volume of
a storage or distribution medium does not bring the other work under
the scope of this License.
3. You may opt to apply the terms of the ordinary GNU General Public
License instead of this License to a given copy of the Library. To do
this, you must alter all the notices that refer to this License, so
that they refer to the ordinary GNU General Public License, version 2,
instead of to this License. (If a newer version than version 2 of the
ordinary GNU General Public License has appeared, then you can specify
that version instead if you wish.) Do not make any other change in
these notices.
Once this change is made in a given copy, it is irreversible for
that copy, so the ordinary GNU General Public License applies to all
subsequent copies and derivative works made from that copy.
This option is useful when you wish to copy part of the code of
the Library into a program that is not a library.
4. You may copy and distribute the Library (or a portion or
derivative of it, under Section 2) in object code or executable form
under the terms of Sections 1 and 2 above provided that you accompany
it with the complete corresponding machine-readable source code, which
must be distributed under the terms of Sections 1 and 2 above on a
medium customarily used for software interchange.
If distribution of object code is made by offering access to copy
from a designated place, then offering equivalent access to copy the
source code from the same place satisfies the requirement to
distribute the source code, even though third parties are not
compelled to copy the source along with the object code.
5. A program that contains no derivative of any portion of the
Library, but is designed to work with the Library by being compiled or
linked with it, is called a "work that uses the Library". Such a
work, in isolation, is not a derivative work of the Library, and
therefore falls outside the scope of this License.
However, linking a "work that uses the Library" with the Library
creates an executable that is a derivative of the Library (because it
contains portions of the Library), rather than a "work that uses the
library". The executable is therefore covered by this License.
Section 6 states terms for distribution of such executables.
When a "work that uses the Library" uses material from a header file
that is part of the Library, the object code for the work may be a
derivative work of the Library even though the source code is not.
Whether this is true is especially significant if the work can be
linked without the Library, or if the work is itself a library. The
threshold for this to be true is not precisely defined by law.
If such an object file uses only numerical parameters, data
structure layouts and accessors, and small macros and small inline
functions (ten lines or less in length), then the use of the object
file is unrestricted, regardless of whether it is legally a derivative
work. (Executables containing this object code plus portions of the
Library will still fall under Section 6.)
Otherwise, if the work is a derivative of the Library, you may
distribute the object code for the work under the terms of Section 6.
Any executables containing that work also fall under Section 6,
whether or not they are linked directly with the Library itself.
6. As an exception to the Sections above, you may also combine or
link a "work that uses the Library" with the Library to produce a
work containing portions of the Library, and distribute that work
under terms of your choice, provided that the terms permit
modification of the work for the customer's own use and reverse
engineering for debugging such modifications.
You must give prominent notice with each copy of the work that the
Library is used in it and that the Library and its use are covered by
this License. You must supply a copy of this License. If the work
during execution displays copyright notices, you must include the
copyright notice for the Library among them, as well as a reference
directing the user to the copy of this License. Also, you must do one
of these things:
a) Accompany the work with the complete corresponding
machine-readable source code for the Library including whatever
changes were used in the work (which must be distributed under
Sections 1 and 2 above); and, if the work is an executable linked
with the Library, with the complete machine-readable "work that
uses the Library", as object code and/or source code, so that the
user can modify the Library and then relink to produce a modified
executable containing the modified Library. (It is understood
that the user who changes the contents of definitions files in the
Library will not necessarily be able to recompile the application
to use the modified definitions.)
b) Use a suitable shared library mechanism for linking with the
Library. A suitable mechanism is one that (1) uses at run time a
copy of the library already present on the user's computer system,
rather than copying library functions into the executable, and (2)
will operate properly with a modified version of the library, if
the user installs one, as long as the modified version is
interface-compatible with the version that the work was made with.
c) Accompany the work with a written offer, valid for at
least three years, to give the same user the materials
specified in Subsection 6a, above, for a charge no more
than the cost of performing this distribution.
d) If distribution of the work is made by offering access to copy
from a designated place, offer equivalent access to copy the above
specified materials from the same place.
e) Verify that the user has already received a copy of these
materials or that you have already sent this user a copy.
For an executable, the required form of the "work that uses the
Library" must include any data and utility programs needed for
reproducing the executable from it. However, as a special exception,
the materials to be distributed need not include anything that is
normally distributed (in either source or binary form) with the major
components (compiler, kernel, and so on) of the operating system on
which the executable runs, unless that component itself accompanies
the executable.
It may happen that this requirement contradicts the license
restrictions of other proprietary libraries that do not normally
accompany the operating system. Such a contradiction means you cannot
use both them and the Library together in an executable that you
distribute.
7. You may place library facilities that are a work based on the
Library side-by-side in a single library together with other library
facilities not covered by this License, and distribute such a combined
library, provided that the separate distribution of the work based on
the Library and of the other library facilities is otherwise
permitted, and provided that you do these two things:
a) Accompany the combined library with a copy of the same work
based on the Library, uncombined with any other library
facilities. This must be distributed under the terms of the
Sections above.
b) Give prominent notice with the combined library of the fact
that part of it is a work based on the Library, and explaining
where to find the accompanying uncombined form of the same work.
8. You may not copy, modify, sublicense, link with, or distribute
the Library except as expressly provided under this License. Any
attempt otherwise to copy, modify, sublicense, link with, or
distribute the Library is void, and will automatically terminate your
rights under this License. However, parties who have received copies,
or rights, from you under this License will not have their licenses
terminated so long as such parties remain in full compliance.
9. You are not required to accept this License, since you have not
signed it. However, nothing else grants you permission to modify or
distribute the Library or its derivative works. These actions are
prohibited by law if you do not accept this License. Therefore, by
modifying or distributing the Library (or any work based on the
Library), you indicate your acceptance of this License to do so, and
all its terms and conditions for copying, distributing or modifying
the Library or works based on it.
10. Each time you redistribute the Library (or any work based on the
Library), the recipient automatically receives a license from the
original licensor to copy, distribute, link with or modify the Library
subject to these terms and conditions. You may not impose any further
restrictions on the recipients' exercise of the rights granted herein.
You are not responsible for enforcing compliance by third parties with
this License.
11. If, as a consequence of a court judgment or allegation of patent
infringement or for any other reason (not limited to patent issues),
conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot
distribute so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you
may not distribute the Library at all. For example, if a patent
license would not permit royalty-free redistribution of the Library by
all those who receive copies directly or indirectly through you, then
the only way you could satisfy both it and this License would be to
refrain entirely from distribution of the Library.
If any portion of this section is held invalid or unenforceable under any
particular circumstance, the balance of the section is intended to apply,
and the section as a whole is intended to apply in other circumstances.
It is not the purpose of this section to induce you to infringe any
patents or other property right claims or to contest validity of any
such claims; this section has the sole purpose of protecting the
integrity of the free software distribution system which is
implemented by public license practices. Many people have made
generous contributions to the wide range of software distributed
through that system in reliance on consistent application of that
system; it is up to the author/donor to decide if he or she is willing
to distribute software through any other system and a licensee cannot
impose that choice.
This section is intended to make thoroughly clear what is believed to
be a consequence of the rest of this License.
12. If the distribution and/or use of the Library is restricted in
certain countries either by patents or by copyrighted interfaces, the
original copyright holder who places the Library under this License may add
an explicit geographical distribution limitation excluding those countries,
so that distribution is permitted only in or among countries not thus
excluded. In such case, this License incorporates the limitation as if
written in the body of this License.
13. The Free Software Foundation may publish revised and/or new
versions of the Lesser General Public License from time to time.
Such new versions will be similar in spirit to the present version,
but may differ in detail to address new problems or concerns.
Each version is given a distinguishing version number. If the Library
specifies a version number of this License which applies to it and
"any later version", you have the option of following the terms and
conditions either of that version or of any later version published by
the Free Software Foundation. If the Library does not specify a
license version number, you may choose any version ever published by
the Free Software Foundation.
14. If you wish to incorporate parts of the Library into other free
programs whose distribution conditions are incompatible with these,
write to the author to ask for permission. For software which is
copyrighted by the Free Software Foundation, write to the Free
Software Foundation; we sometimes make exceptions for this. Our
decision will be guided by the two goals of preserving the free status
of all derivatives of our free software and of promoting the sharing
and reuse of software generally.
NO WARRANTY
15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO
WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW.
EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR
OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY
KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE
LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME
THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN
WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY
AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU
FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR
CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE
LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING
RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A
FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF
SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH
DAMAGES.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Libraries
If you develop a new library, and you want it to be of the greatest
possible use to the public, we recommend making it free software that
everyone can redistribute and change. You can do so by permitting
redistribution under these terms (or, alternatively, under the terms of the
ordinary General Public License).
To apply these terms, attach the following notices to the library. It is
safest to attach them to the start of each source file to most effectively
convey the exclusion of warranty; and each file should have at least the
"copyright" line and a pointer to where the full notice is found.
<one line to give the library's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301
USA
Also add information on how to contact you by electronic and paper mail.
You should also get your employer (if you work as a programmer) or your
school, if any, to sign a "copyright disclaimer" for the library, if
necessary. Here is a sample; alter the names:
Yoyodyne, Inc., hereby disclaims all copyright interest in the
library `Frob' (a library for tweaking knobs) written by James Random
Hacker.
<signature of Ty Coon>, 1 April 1990
Ty Coon, President of Vice
That's all there is to it!
+502
View File
@@ -0,0 +1,502 @@
GNU LESSER GENERAL PUBLIC LICENSE
Version 2.1, February 1999
Copyright (C) 1991, 1999 Free Software Foundation, Inc.
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
[This is the first released version of the Lesser GPL. It also counts
as the successor of the GNU Library Public License, version 2, hence
the version number 2.1.]
Preamble
The licenses for most software are designed to take away your
freedom to share and change it. By contrast, the GNU General Public
Licenses are intended to guarantee your freedom to share and change
free software--to make sure the software is free for all its users.
This license, the Lesser General Public License, applies to some
specially designated software packages--typically libraries--of the
Free Software Foundation and other authors who decide to use it. You
can use it too, but we suggest you first think carefully about whether
this license or the ordinary General Public License is the better
strategy to use in any particular case, based on the explanations below.
When we speak of free software, we are referring to freedom of use,
not price. Our General Public Licenses are designed to make sure that
you have the freedom to distribute copies of free software (and charge
for this service if you wish); that you receive source code or can get
it if you want it; that you can change the software and use pieces of
it in new free programs; and that you are informed that you can do
these things.
To protect your rights, we need to make restrictions that forbid
distributors to deny you these rights or to ask you to surrender these
rights. These restrictions translate to certain responsibilities for
you if you distribute copies of the library or if you modify it.
For example, if you distribute copies of the library, whether gratis
or for a fee, you must give the recipients all the rights that we gave
you. You must make sure that they, too, receive or can get the source
code. If you link other code with the library, you must provide
complete object files to the recipients, so that they can relink them
with the library after making changes to the library and recompiling
it. And you must show them these terms so they know their rights.
We protect your rights with a two-step method: (1) we copyright the
library, and (2) we offer you this license, which gives you legal
permission to copy, distribute and/or modify the library.
To protect each distributor, we want to make it very clear that
there is no warranty for the free library. Also, if the library is
modified by someone else and passed on, the recipients should know
that what they have is not the original version, so that the original
author's reputation will not be affected by problems that might be
introduced by others.
Finally, software patents pose a constant threat to the existence of
any free program. We wish to make sure that a company cannot
effectively restrict the users of a free program by obtaining a
restrictive license from a patent holder. Therefore, we insist that
any patent license obtained for a version of the library must be
consistent with the full freedom of use specified in this license.
Most GNU software, including some libraries, is covered by the
ordinary GNU General Public License. This license, the GNU Lesser
General Public License, applies to certain designated libraries, and
is quite different from the ordinary General Public License. We use
this license for certain libraries in order to permit linking those
libraries into non-free programs.
When a program is linked with a library, whether statically or using
a shared library, the combination of the two is legally speaking a
combined work, a derivative of the original library. The ordinary
General Public License therefore permits such linking only if the
entire combination fits its criteria of freedom. The Lesser General
Public License permits more lax criteria for linking other code with
the library.
We call this license the "Lesser" General Public License because it
does Less to protect the user's freedom than the ordinary General
Public License. It also provides other free software developers Less
of an advantage over competing non-free programs. These disadvantages
are the reason we use the ordinary General Public License for many
libraries. However, the Lesser license provides advantages in certain
special circumstances.
For example, on rare occasions, there may be a special need to
encourage the widest possible use of a certain library, so that it becomes
a de-facto standard. To achieve this, non-free programs must be
allowed to use the library. A more frequent case is that a free
library does the same job as widely used non-free libraries. In this
case, there is little to gain by limiting the free library to free
software only, so we use the Lesser General Public License.
In other cases, permission to use a particular library in non-free
programs enables a greater number of people to use a large body of
free software. For example, permission to use the GNU C Library in
non-free programs enables many more people to use the whole GNU
operating system, as well as its variant, the GNU/Linux operating
system.
Although the Lesser General Public License is Less protective of the
users' freedom, it does ensure that the user of a program that is
linked with the Library has the freedom and the wherewithal to run
that program using a modified version of the Library.
The precise terms and conditions for copying, distribution and
modification follow. Pay close attention to the difference between a
"work based on the library" and a "work that uses the library". The
former contains code derived from the library, whereas the latter must
be combined with the library in order to run.
GNU LESSER GENERAL PUBLIC LICENSE
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
0. This License Agreement applies to any software library or other
program which contains a notice placed by the copyright holder or
other authorized party saying it may be distributed under the terms of
this Lesser General Public License (also called "this License").
Each licensee is addressed as "you".
A "library" means a collection of software functions and/or data
prepared so as to be conveniently linked with application programs
(which use some of those functions and data) to form executables.
The "Library", below, refers to any such software library or work
which has been distributed under these terms. A "work based on the
Library" means either the Library or any derivative work under
copyright law: that is to say, a work containing the Library or a
portion of it, either verbatim or with modifications and/or translated
straightforwardly into another language. (Hereinafter, translation is
included without limitation in the term "modification".)
"Source code" for a work means the preferred form of the work for
making modifications to it. For a library, complete source code means
all the source code for all modules it contains, plus any associated
interface definition files, plus the scripts used to control compilation
and installation of the library.
Activities other than copying, distribution and modification are not
covered by this License; they are outside its scope. The act of
running a program using the Library is not restricted, and output from
such a program is covered only if its contents constitute a work based
on the Library (independent of the use of the Library in a tool for
writing it). Whether that is true depends on what the Library does
and what the program that uses the Library does.
1. You may copy and distribute verbatim copies of the Library's
complete source code as you receive it, in any medium, provided that
you conspicuously and appropriately publish on each copy an
appropriate copyright notice and disclaimer of warranty; keep intact
all the notices that refer to this License and to the absence of any
warranty; and distribute a copy of this License along with the
Library.
You may charge a fee for the physical act of transferring a copy,
and you may at your option offer warranty protection in exchange for a
fee.
2. You may modify your copy or copies of the Library or any portion
of it, thus forming a work based on the Library, and copy and
distribute such modifications or work under the terms of Section 1
above, provided that you also meet all of these conditions:
a) The modified work must itself be a software library.
b) You must cause the files modified to carry prominent notices
stating that you changed the files and the date of any change.
c) You must cause the whole of the work to be licensed at no
charge to all third parties under the terms of this License.
d) If a facility in the modified Library refers to a function or a
table of data to be supplied by an application program that uses
the facility, other than as an argument passed when the facility
is invoked, then you must make a good faith effort to ensure that,
in the event an application does not supply such function or
table, the facility still operates, and performs whatever part of
its purpose remains meaningful.
(For example, a function in a library to compute square roots has
a purpose that is entirely well-defined independent of the
application. Therefore, Subsection 2d requires that any
application-supplied function or table used by this function must
be optional: if the application does not supply it, the square
root function must still compute square roots.)
These requirements apply to the modified work as a whole. If
identifiable sections of that work are not derived from the Library,
and can be reasonably considered independent and separate works in
themselves, then this License, and its terms, do not apply to those
sections when you distribute them as separate works. But when you
distribute the same sections as part of a whole which is a work based
on the Library, the distribution of the whole must be on the terms of
this License, whose permissions for other licensees extend to the
entire whole, and thus to each and every part regardless of who wrote
it.
Thus, it is not the intent of this section to claim rights or contest
your rights to work written entirely by you; rather, the intent is to
exercise the right to control the distribution of derivative or
collective works based on the Library.
In addition, mere aggregation of another work not based on the Library
with the Library (or with a work based on the Library) on a volume of
a storage or distribution medium does not bring the other work under
the scope of this License.
3. You may opt to apply the terms of the ordinary GNU General Public
License instead of this License to a given copy of the Library. To do
this, you must alter all the notices that refer to this License, so
that they refer to the ordinary GNU General Public License, version 2,
instead of to this License. (If a newer version than version 2 of the
ordinary GNU General Public License has appeared, then you can specify
that version instead if you wish.) Do not make any other change in
these notices.
Once this change is made in a given copy, it is irreversible for
that copy, so the ordinary GNU General Public License applies to all
subsequent copies and derivative works made from that copy.
This option is useful when you wish to copy part of the code of
the Library into a program that is not a library.
4. You may copy and distribute the Library (or a portion or
derivative of it, under Section 2) in object code or executable form
under the terms of Sections 1 and 2 above provided that you accompany
it with the complete corresponding machine-readable source code, which
must be distributed under the terms of Sections 1 and 2 above on a
medium customarily used for software interchange.
If distribution of object code is made by offering access to copy
from a designated place, then offering equivalent access to copy the
source code from the same place satisfies the requirement to
distribute the source code, even though third parties are not
compelled to copy the source along with the object code.
5. A program that contains no derivative of any portion of the
Library, but is designed to work with the Library by being compiled or
linked with it, is called a "work that uses the Library". Such a
work, in isolation, is not a derivative work of the Library, and
therefore falls outside the scope of this License.
However, linking a "work that uses the Library" with the Library
creates an executable that is a derivative of the Library (because it
contains portions of the Library), rather than a "work that uses the
library". The executable is therefore covered by this License.
Section 6 states terms for distribution of such executables.
When a "work that uses the Library" uses material from a header file
that is part of the Library, the object code for the work may be a
derivative work of the Library even though the source code is not.
Whether this is true is especially significant if the work can be
linked without the Library, or if the work is itself a library. The
threshold for this to be true is not precisely defined by law.
If such an object file uses only numerical parameters, data
structure layouts and accessors, and small macros and small inline
functions (ten lines or less in length), then the use of the object
file is unrestricted, regardless of whether it is legally a derivative
work. (Executables containing this object code plus portions of the
Library will still fall under Section 6.)
Otherwise, if the work is a derivative of the Library, you may
distribute the object code for the work under the terms of Section 6.
Any executables containing that work also fall under Section 6,
whether or not they are linked directly with the Library itself.
6. As an exception to the Sections above, you may also combine or
link a "work that uses the Library" with the Library to produce a
work containing portions of the Library, and distribute that work
under terms of your choice, provided that the terms permit
modification of the work for the customer's own use and reverse
engineering for debugging such modifications.
You must give prominent notice with each copy of the work that the
Library is used in it and that the Library and its use are covered by
this License. You must supply a copy of this License. If the work
during execution displays copyright notices, you must include the
copyright notice for the Library among them, as well as a reference
directing the user to the copy of this License. Also, you must do one
of these things:
a) Accompany the work with the complete corresponding
machine-readable source code for the Library including whatever
changes were used in the work (which must be distributed under
Sections 1 and 2 above); and, if the work is an executable linked
with the Library, with the complete machine-readable "work that
uses the Library", as object code and/or source code, so that the
user can modify the Library and then relink to produce a modified
executable containing the modified Library. (It is understood
that the user who changes the contents of definitions files in the
Library will not necessarily be able to recompile the application
to use the modified definitions.)
b) Use a suitable shared library mechanism for linking with the
Library. A suitable mechanism is one that (1) uses at run time a
copy of the library already present on the user's computer system,
rather than copying library functions into the executable, and (2)
will operate properly with a modified version of the library, if
the user installs one, as long as the modified version is
interface-compatible with the version that the work was made with.
c) Accompany the work with a written offer, valid for at
least three years, to give the same user the materials
specified in Subsection 6a, above, for a charge no more
than the cost of performing this distribution.
d) If distribution of the work is made by offering access to copy
from a designated place, offer equivalent access to copy the above
specified materials from the same place.
e) Verify that the user has already received a copy of these
materials or that you have already sent this user a copy.
For an executable, the required form of the "work that uses the
Library" must include any data and utility programs needed for
reproducing the executable from it. However, as a special exception,
the materials to be distributed need not include anything that is
normally distributed (in either source or binary form) with the major
components (compiler, kernel, and so on) of the operating system on
which the executable runs, unless that component itself accompanies
the executable.
It may happen that this requirement contradicts the license
restrictions of other proprietary libraries that do not normally
accompany the operating system. Such a contradiction means you cannot
use both them and the Library together in an executable that you
distribute.
7. You may place library facilities that are a work based on the
Library side-by-side in a single library together with other library
facilities not covered by this License, and distribute such a combined
library, provided that the separate distribution of the work based on
the Library and of the other library facilities is otherwise
permitted, and provided that you do these two things:
a) Accompany the combined library with a copy of the same work
based on the Library, uncombined with any other library
facilities. This must be distributed under the terms of the
Sections above.
b) Give prominent notice with the combined library of the fact
that part of it is a work based on the Library, and explaining
where to find the accompanying uncombined form of the same work.
8. You may not copy, modify, sublicense, link with, or distribute
the Library except as expressly provided under this License. Any
attempt otherwise to copy, modify, sublicense, link with, or
distribute the Library is void, and will automatically terminate your
rights under this License. However, parties who have received copies,
or rights, from you under this License will not have their licenses
terminated so long as such parties remain in full compliance.
9. You are not required to accept this License, since you have not
signed it. However, nothing else grants you permission to modify or
distribute the Library or its derivative works. These actions are
prohibited by law if you do not accept this License. Therefore, by
modifying or distributing the Library (or any work based on the
Library), you indicate your acceptance of this License to do so, and
all its terms and conditions for copying, distributing or modifying
the Library or works based on it.
10. Each time you redistribute the Library (or any work based on the
Library), the recipient automatically receives a license from the
original licensor to copy, distribute, link with or modify the Library
subject to these terms and conditions. You may not impose any further
restrictions on the recipients' exercise of the rights granted herein.
You are not responsible for enforcing compliance by third parties with
this License.
11. If, as a consequence of a court judgment or allegation of patent
infringement or for any other reason (not limited to patent issues),
conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot
distribute so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you
may not distribute the Library at all. For example, if a patent
license would not permit royalty-free redistribution of the Library by
all those who receive copies directly or indirectly through you, then
the only way you could satisfy both it and this License would be to
refrain entirely from distribution of the Library.
If any portion of this section is held invalid or unenforceable under any
particular circumstance, the balance of the section is intended to apply,
and the section as a whole is intended to apply in other circumstances.
It is not the purpose of this section to induce you to infringe any
patents or other property right claims or to contest validity of any
such claims; this section has the sole purpose of protecting the
integrity of the free software distribution system which is
implemented by public license practices. Many people have made
generous contributions to the wide range of software distributed
through that system in reliance on consistent application of that
system; it is up to the author/donor to decide if he or she is willing
to distribute software through any other system and a licensee cannot
impose that choice.
This section is intended to make thoroughly clear what is believed to
be a consequence of the rest of this License.
12. If the distribution and/or use of the Library is restricted in
certain countries either by patents or by copyrighted interfaces, the
original copyright holder who places the Library under this License may add
an explicit geographical distribution limitation excluding those countries,
so that distribution is permitted only in or among countries not thus
excluded. In such case, this License incorporates the limitation as if
written in the body of this License.
13. The Free Software Foundation may publish revised and/or new
versions of the Lesser General Public License from time to time.
Such new versions will be similar in spirit to the present version,
but may differ in detail to address new problems or concerns.
Each version is given a distinguishing version number. If the Library
specifies a version number of this License which applies to it and
"any later version", you have the option of following the terms and
conditions either of that version or of any later version published by
the Free Software Foundation. If the Library does not specify a
license version number, you may choose any version ever published by
the Free Software Foundation.
14. If you wish to incorporate parts of the Library into other free
programs whose distribution conditions are incompatible with these,
write to the author to ask for permission. For software which is
copyrighted by the Free Software Foundation, write to the Free
Software Foundation; we sometimes make exceptions for this. Our
decision will be guided by the two goals of preserving the free status
of all derivatives of our free software and of promoting the sharing
and reuse of software generally.
NO WARRANTY
15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO
WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW.
EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR
OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY
KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE
LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME
THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN
WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY
AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU
FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR
CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE
LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING
RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A
FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF
SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH
DAMAGES.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Libraries
If you develop a new library, and you want it to be of the greatest
possible use to the public, we recommend making it free software that
everyone can redistribute and change. You can do so by permitting
redistribution under these terms (or, alternatively, under the terms of the
ordinary General Public License).
To apply these terms, attach the following notices to the library. It is
safest to attach them to the start of each source file to most effectively
convey the exclusion of warranty; and each file should have at least the
"copyright" line and a pointer to where the full notice is found.
<one line to give the library's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
Also add information on how to contact you by electronic and paper mail.
You should also get your employer (if you work as a programmer) or your
school, if any, to sign a "copyright disclaimer" for the library, if
necessary. Here is a sample; alter the names:
Yoyodyne, Inc., hereby disclaims all copyright interest in the
library `Frob' (a library for tweaking knobs) written by James Random Hacker.
<signature of Ty Coon>, 1 April 1990
Ty Coon, President of Vice
That's all there is to it!
Binary file not shown.
+84
View File
@@ -0,0 +1,84 @@
// Read-only deployment check: no upload, credentials, or bucket modification.
const args = process.argv.slice(2)
let endpoint
const origins = []
for (let index = 0; index < args.length; index += 2) {
const flag = args[index],
value = args[index + 1]
if (!value || !['--endpoint', '--origin'].includes(flag)) {
console.error(
'用法:npm run check:oss-cors -- --endpoint https://bucket.oss-region.aliyuncs.com/ --origin https://管理后台域名 [--origin http://127.0.0.1:8091]',
)
process.exit(2)
}
if (flag === '--endpoint') endpoint = new URL(value)
else {
const url = new URL(value)
if (
!['http:', 'https:'].includes(url.protocol) ||
url.username ||
url.password ||
url.href !== `${url.origin}/`
) {
throw new Error('来源必须是完整的 http/https origin,不能带路径、查询参数或凭据')
}
origins.push(url.origin)
}
}
if (
!endpoint ||
endpoint.protocol !== 'https:' ||
endpoint.username ||
endpoint.password ||
endpoint.search ||
endpoint.hash ||
endpoint.pathname !== '/' ||
!origins.length
) {
console.error('必须提供 HTTPS OSS 根地址及至少一个 --origin')
process.exit(2)
}
let failed = false
for (const origin of new Set(origins)) {
try {
const response = await fetch(endpoint, {
method: 'OPTIONS',
redirect: 'manual',
signal: AbortSignal.timeout(15000),
headers: {
Origin: origin,
'Access-Control-Request-Method': 'POST',
'Access-Control-Request-Headers': 'content-type',
},
})
const allowOrigin = response.headers.get('access-control-allow-origin')
const methods = (response.headers.get('access-control-allow-methods') || '')
.toUpperCase()
.split(',')
.map((value) => value.trim())
const headers = (response.headers.get('access-control-allow-headers') || '')
.toLowerCase()
.split(',')
.map((value) => value.trim())
const passed =
response.ok &&
(allowOrigin === origin || allowOrigin === '*') &&
methods.includes('POST') &&
(headers.includes('content-type') || headers.includes('*'))
console.log(
JSON.stringify({
origin,
endpoint: endpoint.origin,
status: response.status,
allowOrigin,
passed,
}),
)
failed ||= !passed
await response.body?.cancel()
} catch (error) {
console.error(JSON.stringify({ origin, passed: false, error: error.message }))
failed = true
}
}
process.exitCode = failed ? 1 : 0
+37
View File
@@ -0,0 +1,37 @@
import { useState, type ReactNode } from 'react'
import { Navigate, useLocation } from 'react-router-dom'
import { authGateway } from '@/application/auth'
import { readAuthSession, writeAuthSession } from '@/application/auth-session'
import { AuthContext, useAuth } from './auth-context'
export function AuthProvider({ children }: { children: ReactNode }) {
const [user, setUser] = useState(readAuthSession)
return (
<AuthContext.Provider
value={{
user,
async signIn(phone, code) {
const next = await authGateway.signIn(phone, code)
writeAuthSession(next)
setUser(next)
},
async leave() {
await authGateway.signOut()
writeAuthSession(null)
setUser(null)
},
}}
>
{children}
</AuthContext.Provider>
)
}
export function RequireSession({ children }: { children: ReactNode }) {
const { user } = useAuth()
const location = useLocation()
return user ? (
children
) : (
<Navigate to="/login" replace state={{ from: location.pathname + location.search }} />
)
}
+33
View File
@@ -0,0 +1,33 @@
import { createContext, useContext, useEffect, useState, type ReactNode } from 'react'
import { AlertCircle, CheckCircle2, X } from 'lucide-react'
type Notify = (message: string, variant?: 'success' | 'error') => void
const NotificationContext = createContext<Notify | null>(null)
export function Notifications({ children }: { children: ReactNode }) {
const [toast, setToast] = useState<{ message: string; variant: 'success' | 'error' } | null>(null)
useEffect(() => {
if (!toast) return
const timer = setTimeout(() => setToast(null), 5000)
return () => clearTimeout(timer)
}, [toast])
return (
<NotificationContext.Provider
value={(message, variant = 'success') => setToast({ message, variant })}
>
{children}
{toast && (
<div className={`toast toast-${toast.variant}`} role="status">
{toast.variant === 'error' ? <AlertCircle size={19} /> : <CheckCircle2 size={19} />}
<span>{toast.message}</span>
<button aria-label="关闭提示" onClick={() => setToast(null)}>
<X size={16} />
</button>
</div>
)}
</NotificationContext.Provider>
)
}
export function useNotify(): Notify {
const value = useContext(NotificationContext)
if (!value) throw new Error('Notifications is required')
return value
}
+180
View File
@@ -0,0 +1,180 @@
import { useEffect, useRef, useState, type MouseEvent } from 'react'
import { NavLink, Outlet, useLocation, useNavigate } from 'react-router-dom'
import { Boxes, ScrollText, ChevronRight, Menu, X, UserRound, LogOut, Users } from 'lucide-react'
import { useNotify } from './Notifications'
import { useAuth } from './auth-context'
const items = [{ to: '/components', name: '组件库', icon: Boxes }]
export function Shell() {
const location = useLocation(),
navigate = useNavigate()
const notify = useNotify()
const { user, leave } = useAuth()
const logoClicks = useRef({
count: 0,
last: 0,
timer: undefined as ReturnType<typeof setTimeout> | undefined,
})
useEffect(() => () => clearTimeout(logoClicks.current.timer), [])
function clickBrand(event: MouseEvent<HTMLAnchorElement>) {
if (event.metaKey || event.ctrlKey || event.shiftKey || event.altKey || event.button !== 0)
return
event.preventDefault()
const clicks = logoClicks.current,
now = Date.now()
clearTimeout(clicks.timer)
clicks.count = now - clicks.last < 650 ? clicks.count + 1 : 1
clicks.last = now
if (clicks.count === 3) {
clicks.count = 0
navigate('/assembly-test')
} else {
clicks.timer = setTimeout(() => {
clicks.count = 0
navigate('/components')
}, 650)
}
}
const [menuOpen, setMenuOpen] = useState(false)
const [mobile, setMobile] = useState(() => window.matchMedia('(max-width: 900px)').matches)
useEffect(() => {
const query = window.matchMedia('(max-width: 900px)')
const change = () => {
setMobile(query.matches)
if (!query.matches) setMenuOpen(false)
}
query.addEventListener('change', change)
return () => query.removeEventListener('change', change)
}, [])
useEffect(() => {
setMenuOpen(false)
}, [location.pathname])
useEffect(() => {
const handler = (event: KeyboardEvent) => {
if (event.key === 'Escape') setMenuOpen(false)
if ((event.metaKey || event.ctrlKey) && event.key.toLowerCase() === 'k') {
const field = document.querySelector<HTMLInputElement>('[data-search]')
if (field) {
event.preventDefault()
field.focus()
}
}
}
window.addEventListener('keydown', handler)
return () => window.removeEventListener('keydown', handler)
}, [])
const section =
location.pathname === '/assembly-test'
? 'URDF 文件检查'
: location.pathname.startsWith('/activity')
? '操作日志'
: location.pathname.startsWith('/users')
? '用户管理'
: '组件库'
async function exit() {
try {
await leave()
navigate('/login', { replace: true })
} catch {
notify('暂时无法退出,请稍后重试。', 'error')
}
}
return (
<div className="app-shell">
{menuOpen && (
<button
className="sidebar-scrim"
aria-label="关闭导航遮罩"
onClick={() => setMenuOpen(false)}
/>
)}
<aside
inert={mobile && !menuOpen ? true : undefined}
className={`sidebar ${menuOpen ? 'sidebar-open' : ''}`}
>
<NavLink
to="/components"
className="brand"
aria-label="CAD World Management 首页"
onClick={clickBrand}
>
<img src="/logo.png" alt="CAD World" />
<span>管理控制台</span>
</NavLink>
<button
className="sidebar-close icon-button"
aria-label="关闭导航"
onClick={() => setMenuOpen(false)}
>
<X size={20} />
</button>
<div className="nav-caption">资源管理</div>
<nav aria-label="主导航">
{items.map((item) => (
<NavLink
to={item.to}
key={item.to}
className={({ isActive }) => `nav-item ${isActive ? 'active' : ''}`}
>
<item.icon size={19} strokeWidth={1.8} />
<span>{item.name}</span>
</NavLink>
))}
</nav>
<div className="nav-caption tools-caption">系统管理</div>
<nav aria-label="系统导航">
<NavLink to="/users" className={({ isActive }) => `nav-item ${isActive ? 'active' : ''}`}>
<Users size={19} strokeWidth={1.8} />
<span>用户管理</span>
</NavLink>
<NavLink
to="/activity"
className={({ isActive }) => `nav-item ${isActive ? 'active' : ''}`}
>
<ScrollText size={19} strokeWidth={1.8} />
<span>操作日志</span>
</NavLink>
</nav>
</aside>
<div className="main-shell">
<header className="topbar">
<div className="topbar-left">
<button
className="menu-toggle icon-button"
aria-label="打开导航"
onClick={() => setMenuOpen(true)}
>
<Menu size={20} />
</button>
<span className="topbar-label">管理控制台</span>
<ChevronRight size={14} />
<strong>{section}</strong>
</div>
<div className="topbar-right">
{user ? (
<>
<span className="account-name">
<UserRound size={16} />
{user.name || `${user.phone.slice(0, 3)}****${user.phone.slice(-4)}`}
</span>
<button className="icon-button" aria-label="退出登录" onClick={() => void exit()}>
<LogOut size={17} />
</button>
</>
) : (
<button className="account-button" onClick={() => void exit()}>
<UserRound size={16} />
<span>登录</span>
</button>
)}
</div>
</header>
<main
className={`page ${location.pathname.includes('/new') || /\/components\/[^/]+$/.test(location.pathname) ? 'editor-page' : ''}`}
>
<Outlet />
</main>
</div>
</div>
)
}
+16
View File
@@ -0,0 +1,16 @@
import { createContext, useContext, type Context } from 'react'
import type { AuthUser } from '@/application/auth'
export interface AuthContextValue {
user: AuthUser | null
signIn: (phone: string, code: string) => Promise<void>
leave: () => Promise<void>
}
export const AuthContext: Context<AuthContextValue | null> =
import.meta.hot?.data.authContext ?? createContext<AuthContextValue | null>(null)
if (import.meta.hot) import.meta.hot.data.authContext = AuthContext
export function useAuth(): AuthContextValue {
const context = useContext<AuthContextValue | null>(AuthContext)
if (!context) throw new Error('AuthProvider is required')
return context
}
+80
View File
@@ -0,0 +1,80 @@
import { createBrowserRouter, Navigate, Link, useRouteError } from 'react-router-dom'
import { Shell } from './Shell'
import { ComponentCatalogPage } from '@/pages/ComponentCatalogPage'
import { LoginPage } from '@/pages/LoginPage'
import { ActivityPage } from '@/pages/ActivityPage'
import { UsersPage } from '@/pages/UsersPage'
import { RequireSession } from './AuthProvider'
import { Button } from '@/components/ui'
import { lazy, Suspense } from 'react'
import { Loading } from '@/components/ui'
const ComponentUploadRoute = lazy(() =>
import('@/pages/ComponentUploadPage').then((module) => ({ default: module.ComponentUploadPage })),
)
const AssemblyTestRoute = lazy(() =>
import('@/pages/AssemblyTestPage').then((module) => ({ default: module.AssemblyTestPage })),
)
function ErrorPage() {
const error = useRouteError()
return (
<div className="error-page">
<img src="/logo.png" alt="CAD World" />
<h1>页面暂时无法加载</h1>
<p>{error instanceof Error ? error.message : '请重新打开工作区。'}</p>
<Button onClick={() => window.location.assign('/components')}>重新打开组件库</Button>
</div>
)
}
export const router = createBrowserRouter([
{ path: '/login', element: <LoginPage />, errorElement: <ErrorPage /> },
{
path: '/',
element: (
<RequireSession>
<Shell />
</RequireSession>
),
errorElement: <ErrorPage />,
children: [
{ index: true, element: <Navigate to="/components" replace /> },
{ path: 'components', element: <ComponentCatalogPage /> },
{
path: 'components/new',
element: (
<Suspense fallback={<Loading />}>
<ComponentUploadRoute key="new-component" />
</Suspense>
),
},
{
path: 'components/:id',
element: (
<Suspense fallback={<Loading />}>
<ComponentUploadRoute />
</Suspense>
),
},
{ path: 'activity', element: <ActivityPage /> },
{ path: 'users', element: <UsersPage /> },
{
path: 'assembly-test',
element: (
<Suspense fallback={<Loading text="正在加载 URDF 文件…" />}>
<AssemblyTestRoute />
</Suspense>
),
},
{
path: '*',
element: (
<div className="error-page">
<h1>这个页面不存在</h1>
<Link className="button button-primary" to="/components">
返回组件库
</Link>
</div>
),
},
],
},
])
@@ -0,0 +1,68 @@
import { api, queryString, type Page } from '@/infrastructure/admin-api'
export const logActions = {
CREATE: '新增',
UPDATE: '修改',
DELETE: '删除',
} as const
export interface OperationLog {
id: number
module: string
action: string
targetId?: string
targetType?: string
targetCode?: string
targetName?: string
errorCode?: string
operatorId: number
operatorName: string
requestPath: string
requestMethod: string
clientIp: string
requestId: string
operatedAt: string
durationMs: number
success: boolean
httpStatus: number
errorSummary?: string
}
export const activityGateway = {
list(
query: {
page: number
size: number
module?: string
action?: string
success?: boolean
operatorId?: number
keyword?: string
targetId?: string
targetType?: string
targetCode?: string
from?: string
to?: string
},
signal?: AbortSignal,
) {
const {
page,
size,
module,
action,
success,
operatorId,
keyword,
targetId,
targetType,
targetCode,
from,
to,
} = query
return api<Page<OperationLog>>(
`/admin-api/operation-logs${queryString({ page, size, module, action, success, operatorId, keyword, targetId, targetType, targetCode, from, to })}`,
{ signal },
)
},
detail(id: number) {
return api<OperationLog>(`/admin-api/operation-logs/${id}`)
},
}
@@ -0,0 +1,35 @@
import type { AuthUser } from './auth'
const SESSION_KEY = 'cadworld-management-session'
export function readAuthSession(): AuthUser | null {
try {
const raw = sessionStorage.getItem(SESSION_KEY)
if (!raw) return null
const session = JSON.parse(raw)
const user = session?.user
if (
session.version !== 1 ||
session.mode !== 'temporary' ||
!user ||
typeof user.id !== 'string' ||
!user.id.startsWith('temporary-') ||
typeof user.phone !== 'string' ||
!user.phone.trim() ||
typeof user.name !== 'string'
)
return null
return { id: user.id, phone: user.phone, name: user.name }
} catch {
return null
}
}
export function writeAuthSession(user: AuthUser | null) {
try {
sessionStorage.removeItem('cadworld-management-preview')
if (user)
sessionStorage.setItem(SESSION_KEY, JSON.stringify({ version: 1, mode: 'temporary', user }))
else sessionStorage.removeItem(SESSION_KEY)
} catch {
/* In-memory login still works when browser storage is disabled. */
}
}
+19
View File
@@ -0,0 +1,19 @@
import { temporaryAuthGateway } from './temporary-auth'
export interface AuthUser {
id: string
phone: string
name: string
}
export interface AuthGateway {
requestCode(phone: string): Promise<string>
signIn(phone: string, code: string): Promise<AuthUser>
signOut(): Promise<void>
}
export const authGateway: AuthGateway = temporaryAuthGateway
export function safeReturnPath(path: unknown): string {
return typeof path === 'string' &&
/^\/(components|activity|users|assembly-test)(\/[^?#]*)?(\?[^#]*)?$/.test(path)
? path
: '/components'
}
@@ -0,0 +1,19 @@
import type { PartInformation } from '@/domain/component-catalog'
export function mergeComponentForm(
base: PartInformation,
local: PartInformation,
remote: PartInformation,
) {
const merged = { ...remote },
conflicts: (keyof PartInformation)[] = []
for (const key of Object.keys(base) as (keyof PartInformation)[]) {
if (JSON.stringify(local[key]) === JSON.stringify(base[key])) continue
if (
JSON.stringify(remote[key]) !== JSON.stringify(base[key]) &&
JSON.stringify(remote[key]) !== JSON.stringify(local[key])
)
conflicts.push(key)
Object.assign(merged, { [key]: local[key] })
}
return { merged, conflicts }
}
@@ -0,0 +1,67 @@
import { api, queryString, downloadFile, assetUrl, type Page } from '@/infrastructure/admin-api'
import {
hasUrdfResources,
type ComponentDetail,
type ComponentForm,
type ComponentSummary,
} from '@/domain/component-catalog'
export interface ComponentResources {
uploadSessionToken?: string
stepObjectKey?: string
urdfObjectKeys?: string[]
}
export const componentGateway = {
list(
query: { page: number; size: number; keyword?: string; category?: string },
signal?: AbortSignal,
) {
const { page, size, keyword, category } = query
return api<Page<ComponentSummary>>(
`/admin-api/components${queryString({ page, size, keyword, category })}`,
{ signal },
)
},
detail(id: string, signal?: AbortSignal) {
if (!/^[1-9]\d*$/.test(id)) throw new Error('组件编号不合法,请返回组件库选择组件')
return api<ComponentDetail>(`/admin-api/components/${id}`, { signal })
},
save(
form: ComponentForm,
resources: ComponentResources,
existing?: { id: number; version: number },
) {
return api<ComponentDetail>(
existing ? `/admin-api/components/${existing.id}` : '/admin-api/components',
{
method: existing ? 'PUT' : 'POST',
body: { ...form, ...(existing ? { version: existing.version } : {}), ...resources },
},
)
},
async remove(id: number) {
await api(`/admin-api/components/${id}`, { method: 'DELETE' })
},
step(item: ComponentDetail, signal?: AbortSignal) {
return downloadFile(assetUrl(item.stepObjectKey), item.stepObjectKey.split('/').at(-1)!, signal)
},
async urdf(item: ComponentDetail, signal?: AbortSignal) {
if (!hasUrdfResources(item)) return []
const files = item.urdfFiles!
const result: File[] = new Array(files.length)
let index = 0
await Promise.all(
Array.from({ length: Math.min(4, result.length) }, async () => {
while (index < result.length) {
const current = index++,
file = files[current]
result[current] = await downloadFile(
assetUrl(item.urdfPrefix + file.relativePath),
`urdf/${file.relativePath}`,
signal,
)
}
}),
)
return result
},
}
@@ -0,0 +1,180 @@
import { api, ApiError, validateUploadSize } from '@/infrastructure/admin-api'
import { urdfRelativePath, validateStepFile, validateUrdfFolder } from '@/domain/component-catalog'
import type { ComponentResources } from './component-gateway'
export interface UploadAuthorization {
uploadUrl: string
keyPrefix: string
uploadMethod: 'POST'
uploadFields: Record<string, string>
}
export interface UploadSignature {
componentCode: string
uploadSessionToken: string
sessionExpiresAt: string
expiresAt: string
step?: UploadAuthorization
urdf?: UploadAuthorization
}
export interface UploadProgress {
completed: number
total: number
componentCode: string
}
interface UploadJob {
kind: 'step' | 'urdf'
file: File
path: string
}
/** Keeps confirmed files across save retries without overwriting OSS objects. */
export class ComponentUploadSession {
private signature: UploadSignature | null = null
private jobs: UploadJob[] = []
private completed = new Set<string>()
private renewal: Promise<void> | null = null
private componentId?: number
reset() {
this.signature = null
this.completed.clear()
}
private async ensureSignature(signal?: AbortSignal, restart = false) {
if (this.renewal) return this.renewal
if (this.signature && Date.now() < Date.parse(this.signature.expiresAt) - 15000) return
this.renewal = (async () => {
if (this.signature && Date.now() >= Date.parse(this.signature.sessionExpiresAt)) {
if (!restart) throw new Error('上传会话已过期,请再次保存以重新上传')
this.reset()
}
const previous = this.signature
const next = await api<UploadSignature>('/admin-api/storage/upload-signature', {
method: 'POST',
signal,
body: previous
? { uploadSessionToken: previous.uploadSessionToken }
: this.componentId
? { componentId: this.componentId }
: {},
})
if (
!Number.isFinite(Date.parse(next.expiresAt)) ||
!Number.isFinite(Date.parse(next.sessionExpiresAt))
)
throw new Error('上传签名缺少有效的到期时间')
const kinds = [...new Set(this.jobs.map((job) => job.kind))]
for (const kind of kinds)
if (!next[kind]) throw new Error(`上传签名缺少 ${kind.toUpperCase()} 授权`)
if (
previous &&
(previous.uploadSessionToken !== next.uploadSessionToken ||
kinds.some((kind) => previous[kind]?.keyPrefix !== next[kind]?.keyPrefix))
)
throw new Error('续签返回的上传批次不一致,请重新上传')
this.signature = next
})().finally(() => {
this.renewal = null
})
return this.renewal
}
async upload(
step: File | null,
urdf: File[],
componentId?: number,
onProgress?: (progress: UploadProgress) => void,
signal?: AbortSignal,
): Promise<ComponentResources> {
if (!step && !urdf.length) return {}
if (step) validateStepFile([step])
if (urdf.length) validateUrdfFolder(urdf)
const jobs: UploadJob[] = [
...(step ? [{ kind: 'step' as const, file: step, path: step.name }] : []),
...urdf.map((file) => ({ kind: 'urdf' as const, file, path: urdfRelativePath(file) })),
]
if (
componentId !== this.componentId ||
jobs.length !== this.jobs.length ||
jobs.some((job, index) => job.file !== this.jobs[index].file)
)
this.reset()
this.componentId = componentId
this.jobs = jobs
await this.ensureSignature(signal, true)
const session = this.signature!
const progress = () =>
onProgress?.({
completed: this.completed.size,
total: jobs.length,
componentCode: session.componentCode,
})
progress()
let index = 0,
failure: unknown,
uncertain = false
const workers = Array.from({ length: Math.min(4, jobs.length) }, async () => {
while (index < jobs.length && !failure) {
const job = jobs[index++],
identity = `${job.kind}/${job.path}`
if (this.completed.has(identity)) continue
try {
// A session expiring mid-batch must not silently mix files from two batches.
if (Date.now() >= Date.parse(session.sessionExpiresAt))
throw new Error('上传会话已过期,请再次保存以重新上传')
await this.ensureSignature(signal)
validateUploadSize(job.file)
const authorization = this.signature![job.kind]
if (!authorization) throw new Error(`上传签名缺少 ${job.kind.toUpperCase()} 授权`)
if (authorization.uploadMethod !== 'POST') throw new Error('不支持的 OSS 上传方式')
const data = new FormData()
Object.entries(authorization.uploadFields).forEach(([name, value]) =>
data.append(name, value),
)
data.append('key', authorization.keyPrefix + job.path)
data.append('file', job.file)
let response: Response
try {
response = await fetch(authorization.uploadUrl, {
method: 'POST',
body: data,
credentials: 'omit',
signal: AbortSignal.any([AbortSignal.timeout(150000), ...(signal ? [signal] : [])]),
})
} catch {
uncertain = true
throw new Error('OSS 上传连接失败,请检查网络和存储跨域配置,再次保存会重新上传')
}
if (response.status !== 204) {
if (response.status === 409) uncertain = true
const xml = new DOMParser().parseFromString(await response.text(), 'text/xml')
throw new ApiError(
`文件“${job.path}”上传失败:${xml.querySelector('Message')?.textContent || `HTTP ${response.status}`}`,
response.status,
xml.querySelector('Code')?.textContent || 'OSS_UPLOAD_FAILED',
xml.querySelector('RequestId')?.textContent || undefined,
)
}
this.completed.add(identity)
progress()
} catch (value) {
failure = value
}
}
})
await Promise.all(workers)
if (failure) {
if (uncertain) this.reset()
throw failure
}
if (Date.now() >= Date.parse(session.sessionExpiresAt)) {
this.reset()
throw new Error('上传会话已过期,请再次保存以重新上传')
}
await this.ensureSignature(signal)
return {
uploadSessionToken: this.signature!.uploadSessionToken,
...(step ? { stepObjectKey: session.step!.keyPrefix + step.name } : {}),
...(urdf.length
? { urdfObjectKeys: urdf.map((file) => session.urdf!.keyPrefix + urdfRelativePath(file)) }
: {}),
}
}
}
@@ -0,0 +1,39 @@
interface FileEntry {
isFile: boolean
isDirectory: boolean
name: string
file: (ok: (file: File) => void, fail: (error: DOMException) => void) => void
createReader: () => {
readEntries: (ok: (entries: FileEntry[]) => void, fail: (error: DOMException) => void) => void
}
}
export async function droppedFiles(transfer: DataTransfer): Promise<File[]> {
const entries = [...transfer.items]
.map((item) =>
(
item as DataTransferItem & { webkitGetAsEntry?: () => FileEntry | null }
).webkitGetAsEntry?.(),
)
.filter(Boolean) as unknown as FileEntry[]
if (!entries.length || !entries.some((entry) => entry.isDirectory)) return [...transfer.files]
const files: File[] = []
async function read(entry: FileEntry, path: string, depth: number): Promise<void> {
if (depth > 30 || files.length > 1500) throw new Error('文件夹层级或文件数量过多。')
if (entry.isFile) {
const file = await new Promise<File>((resolve, reject) => entry.file(resolve, reject))
Object.defineProperty(file, 'webkitRelativePath', { value: path + entry.name })
files.push(file)
} else {
const reader = entry.createReader()
while (true) {
const children = await new Promise<FileEntry[]>((resolve, reject) =>
reader.readEntries(resolve, reject),
)
if (!children.length) break
for (const child of children) await read(child, path + entry.name + '/', depth + 1)
}
}
}
for (const entry of entries) await read(entry, '', 0)
return files
}
@@ -0,0 +1,16 @@
import type { AuthGateway } from './auth'
/** Frontend-only temporary login. It sends no SMS and grants no backend access. */
export const temporaryAuthGateway: AuthGateway = {
async requestCode(phone) {
if (!phone.trim()) throw new Error('请输入手机号。')
return '123456'
},
async signIn(phone, code) {
const value = phone.trim()
if (!value) throw new Error('请输入手机号。')
if (!code.trim()) throw new Error('请输入验证码。')
return { id: `temporary-${value}`, phone: value, name: '管理员' }
},
async signOut() {},
}
+41
View File
@@ -0,0 +1,41 @@
import { normalizeResourceReference, resourceDependenciesFromBytes } from '@/domain/urdf-resources'
const normalized = (path: string): string => {
let value = normalizeResourceReference(path)
for (const prefix of ['package://', 'file://'])
if (value.startsWith(prefix)) value = value.slice(prefix.length)
while (value.startsWith('/')) value = value.slice(1)
while (value.startsWith('../')) value = value.slice(3)
return value
}
export function matchResource(reference: string, files: File[]): File {
const path = normalized(reference)
const exact = files.filter((file) => normalized(file.webkitRelativePath || file.name) === path)
if (exact.length === 1) return exact[0]
const suffix = files.filter((file) => {
const name = normalized(file.webkitRelativePath || file.name)
return name.endsWith('/' + path) || path.endsWith('/' + name)
})
if (suffix.length === 1) return suffix[0]
const basename = path.split('/').pop()
const matches = files.filter((file) => file.name === basename)
if (matches.length !== 1) throw new Error('资源缺失或路径有歧义:' + reference)
return matches[0]
}
export async function validateUrdfResources(xml: string, files: File[]): Promise<void> {
const document = new DOMParser().parseFromString(xml, 'text/xml')
const pending = Array.from(
document.querySelectorAll('mesh[filename],texture[filename]'),
(node) => node.getAttribute('filename')!,
)
const seen = new Set<string>()
while (pending.length) {
const reference = pending.shift()!
if (seen.has(reference) || /^data:image\/(png|jpeg|webp|gif);base64,/.test(reference)) continue
seen.add(reference)
const file = matchResource(reference, files)
for (const dependency of resourceDependenciesFromBytes(reference, await file.arrayBuffer()))
if (!seen.has(dependency)) pending.push(dependency)
}
}
@@ -0,0 +1,64 @@
import { api, queryString, type Page } from '@/infrastructure/admin-api'
import { validateUser, type ManagedUser, type UserInput, type UserStatus } from '@/domain/users'
interface UserDto {
id: number
phone: string
nickname: string
userType: 'NORMAL' | 'ADMIN'
status: 'ACTIVE' | 'DISABLED'
createdAt: string
updatedAt: string
}
function fromDto(item: UserDto): ManagedUser {
return {
id: String(item.id),
name: item.nickname,
phone: item.phone,
role: item.userType === 'ADMIN' ? 'admin' : 'viewer',
status: item.status === 'ACTIVE' ? 'enabled' : 'disabled',
createdAt: item.createdAt,
updatedAt: item.updatedAt,
}
}
function toDto(input: UserInput) {
const valid = validateUser(input)
return {
nickname: valid.name,
phone: valid.phone,
userType: valid.role === 'admin' ? 'ADMIN' : 'NORMAL',
status: valid.status === 'enabled' ? 'ACTIVE' : 'DISABLED',
}
}
export const userGateway = {
async listUsers(
query: { page?: number; size?: number; keyword?: string; role?: string; status?: string } = {},
signal?: AbortSignal,
) {
const result = await api<Page<UserDto>>(
`/admin-api/users${queryString({ page: query.page ?? 1, size: query.size ?? 10, keyword: query.keyword, userType: query.role === 'all' ? undefined : query.role === 'admin' ? 'ADMIN' : query.role === 'viewer' ? 'NORMAL' : undefined, status: query.status === 'enabled' ? 'ACTIVE' : query.status === 'disabled' ? 'DISABLED' : undefined })}`,
{ signal },
)
return { ...result, items: result.items.map(fromDto) }
},
async detail(id: string) {
return fromDto(await api<UserDto>(`/admin-api/users/${encodeURIComponent(id)}`))
},
async createUser(input: UserInput) {
return fromDto(await api<UserDto>('/admin-api/users', { method: 'POST', body: toDto(input) }))
},
async updateUser(id: string, input: UserInput) {
return fromDto(
await api<UserDto>(`/admin-api/users/${encodeURIComponent(id)}`, {
method: 'PUT',
body: toDto(input),
}),
)
},
async setUserStatus(id: string, status: UserStatus) {
const item = await userGateway.detail(id)
return userGateway.updateUser(id, { ...item, status })
},
async remove(id: string) {
await api(`/admin-api/users/${encodeURIComponent(id)}`, { method: 'DELETE' })
},
}
+197
View File
@@ -0,0 +1,197 @@
import { useEffect, useRef, useState } from 'react'
import { Download, Upload, List, X, LoaderCircle } from 'lucide-react'
import { BOM_COLUMNS, isBomItems, type BomItem } from '@/domain/bom'
import type { JsonContainer } from '@/domain/json'
import { parseBomExcel } from '@/infrastructure/bom-parser'
import { errorMessage } from '@/domain/format'
import { Button, Modal, Notice } from './ui'
export function BomEditor({
value,
onChange,
onBusyChange,
}: {
value: JsonContainer
onChange: (items: BomItem[]) => void
onBusyChange: (busy: boolean) => void
}) {
const input = useRef<HTMLInputElement>(null)
const controller = useRef<AbortController | null>(null)
const [busy, setBusy] = useState(false)
const [error, setError] = useState('')
const [fileName, setFileName] = useState('')
const [opened, setOpened] = useState(false)
const [page, setPage] = useState(1)
const standard = isBomItems(value)
const items: BomItem[] = standard ? (value as BomItem[]) : []
useEffect(() => () => controller.current?.abort(), [])
async function read(file: File) {
controller.current?.abort()
const request = new AbortController()
controller.current = request
setError('')
setBusy(true)
onBusyChange(true)
try {
const parsed = await parseBomExcel(file, request.signal)
if (request.signal.aborted) return
onChange(parsed)
setFileName(file.name)
setPage(1)
} catch (error) {
if (!request.signal.aborted) setError(errorMessage(error))
} finally {
if (controller.current === request) {
controller.current = null
setBusy(false)
onBusyChange(false)
}
}
}
return (
<section className="bom-editor" aria-label="BOM 清单">
<div className="bom-editor-heading">
<h2>BOM 清单</h2>
<div className="bom-editor-actions">
<a
className="button button-secondary"
href={`${import.meta.env.BASE_URL}templates/bom-template.xlsx`}
download="BOM清单模板.xlsx"
>
<Download size={13} />
下载模板
</a>
<Button disabled={busy} onClick={() => input.current?.click()}>
{busy ? <LoaderCircle size={13} className="spin" /> : <Upload size={13} />}
{busy ? '解析中…' : '上传 Excel'}
</Button>
<input
ref={input}
type="file"
accept=".xlsx,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
hidden
aria-label="上传 BOM Excel"
onChange={(event) => {
const file = event.target.files?.[0]
event.target.value = ''
if (file) void read(file)
}}
/>
</div>
</div>
<p className="bom-editor-hint">
支持 .xlsx,读取第一张工作表。模板首条为示例,请替换后上传。
</p>
{error && <Notice variant="error">{error}</Notice>}
{!standard && (
<div className="bom-editor-items">
<p className="bom-editor-hint">
已有清单使用其他 JSON 结构,保存时会完整保留。重新上传将替换该清单。
</p>
<Button onClick={() => setOpened(true)}>查看已有清单</Button>
<Button disabled={busy} onClick={() => onChange([])}>
清空 BOM 清单
</Button>
</div>
)}
{items.length ? (
<>
<div className="bom-editor-summary">
<div>
<strong>共 {items.length} 项</strong>
{fileName && <small title={fileName}>{fileName}</small>}
</div>
<Button
aria-label="清空 BOM 清单"
disabled={busy}
onClick={() => {
onChange([])
setFileName('')
setError('')
}}
>
<X size={14} />
</Button>
</div>
<div className="bom-editor-items">
{items.slice(0, 3).map((item, index) => (
<div className="bom-editor-item" key={index}>
<strong>{item.partName}</strong>
<span>
{item.position || '未填写部位'} · DOF {item.dof ?? '未填写'} ·{' '}
{item.material || '未填写材质'}
</span>
</div>
))}
</div>
<Button
className="bom-view-button"
onClick={() => {
setPage(1)
setOpened(true)
}}
>
<List size={14} />
查看完整清单
</Button>
<p className="bom-editor-hint">保存组件时一并提交解析后的清单。</p>
</>
) : standard ? (
<div className="bom-editor-empty">上传 Excel 后,在这里查看解析结果。</div>
) : null}
{opened && (
<Modal
className="bom-preview-dialog"
title={standard ? `BOM 清单 · ${items.length} 条` : 'BOM 清单'}
description={
standard ? '按 Excel 原有顺序展示,空行不导入。' : '原样展示接口返回的 JSON 清单。'
}
onClose={() => setOpened(false)}
footer={
<>
{standard && (
<>
<Button disabled={page === 1} onClick={() => setPage(page - 1)}>
上一页
</Button>
<span>
{page} / {Math.max(1, Math.ceil(items.length / 25))}
</span>
<Button disabled={page * 25 >= items.length} onClick={() => setPage(page + 1)}>
下一页
</Button>
</>
)}
<Button onClick={() => setOpened(false)}>关闭</Button>
</>
}
>
{!standard ? (
<pre className="bom-json-preview">{JSON.stringify(value, null, 2)}</pre>
) : (
<div className="bom-table-scroll">
<table className="bom-table">
<thead>
<tr>
{BOM_COLUMNS.map(({ key, label }) => (
<th key={key}>{label}</th>
))}
</tr>
</thead>
<tbody>
{items.slice((page - 1) * 25, page * 25).map((item, index) => (
<tr key={index}>
{BOM_COLUMNS.map(({ key }) => (
<td key={key}>{item[key] ?? ''}</td>
))}
</tr>
))}
</tbody>
</table>
</div>
)}
</Modal>
)}
</section>
)
}
@@ -0,0 +1,92 @@
import { useState } from 'react'
import { mergeComponentForm } from '@/application/component-conflict'
import {
partInformation,
type PartInformation,
type ComponentDetail,
} from '@/domain/component-catalog'
import { Button, Modal } from './ui'
const labels: Record<keyof PartInformation, string> = {
name: '组件名称',
rotationAxis: '旋转轴',
bomList: 'BOM 清单',
urdfInfo: 'URDF 文件基本信息',
category: '零件分类',
description: '描述',
degreesOfFreedom: '自由度',
function: '功能',
shape: '形状',
size: '大小',
torque: '扭矩',
material: '材质',
weightKg: '质量',
basicFields: '基本信息自定义字段',
parameterFields: '零件参数自定义字段',
}
const display = (value: PartInformation[keyof PartInformation]) =>
typeof value === 'object' && value !== null ? JSON.stringify(value) : value || '空'
export function ComponentConflictDialog({
base,
local,
remote,
onClose,
onMerge,
}: {
base: PartInformation
local: PartInformation
remote: ComponentDetail
onClose: () => void
onMerge: (value: PartInformation) => void
}) {
const latest = partInformation(remote),
{ merged, conflicts } = mergeComponentForm(base, local, latest)
const [choices, setChoices] = useState<
Partial<Record<keyof PartInformation, 'local' | 'remote'>>
>({})
return (
<Modal
title="组件已被其他人修改"
description="已读取最新版本。未冲突的字段会自动合并,上传资源和本次输入会保留。"
onClose={onClose}
footer={
<>
<Button onClick={onClose}>继续编辑</Button>
<Button
variant="primary"
onClick={() => {
for (const key of conflicts)
if (choices[key] === 'remote') Object.assign(merged, { [key]: latest[key] })
onMerge(merged)
}}
>
合并并返回检查
</Button>
</>
}
>
{!conflicts.length ? (
<p>表单字段没有冲突,可以保留本次修改并采用最新版本。</p>
) : (
conflicts.map((key) => (
<fieldset className="component-conflict-field" key={key}>
<legend>{labels[key]}</legend>
{(['local', 'remote'] as const).map((source) => (
<label key={source}>
<input
type="radio"
name={`conflict-${key}`}
checked={(choices[key] || 'local') === source}
onChange={() => setChoices((value) => ({ ...value, [key]: source }))}
/>
<span>
<strong>{source === 'local' ? '本次修改' : '最新数据'}</strong>
<small>{display(source === 'local' ? local[key] : latest[key])}</small>
</span>
</label>
))}
</fieldset>
))
)}
</Modal>
)
}
@@ -0,0 +1,140 @@
import { useEffect, useRef, useState } from 'react'
import { FileBox, FolderOpen, Upload, Check, LoaderCircle, X } from 'lucide-react'
import { Button } from './ui'
import { droppedFiles } from '@/application/dropped-files'
import { errorMessage } from '@/domain/format'
export function ComponentSourceUpload({
kind,
name,
detail,
busy,
onFiles,
onRemove,
required = true,
}: {
kind: 'step' | 'urdf'
name?: string
detail?: string
busy: boolean
onFiles: (files: File[]) => void
onRemove?: () => void
required?: boolean
}) {
const input = useRef<HTMLInputElement>(null)
const pickerOpen = useRef(false)
const [picking, setPicking] = useState(false)
const [drag, setDrag] = useState(false),
[error, setError] = useState('')
const isStep = kind === 'step',
Icon = isStep ? FileBox : FolderOpen
useEffect(() => {
const node = input.current
const cancel = () => {
pickerOpen.current = false
setPicking(false)
}
node?.addEventListener('cancel', cancel)
return () => node?.removeEventListener('cancel', cancel)
}, [])
return (
<section
className={`component-source-card ${name ? 'has-source' : ''} ${drag ? 'dragging' : ''}`}
onDragOver={(event) => {
event.preventDefault()
if (!busy && !pickerOpen.current) setDrag(true)
}}
onDragLeave={() => setDrag(false)}
onDrop={(event) => {
event.preventDefault()
setDrag(false)
if (busy || pickerOpen.current) return
setError('')
void droppedFiles(event.dataTransfer)
.then(onFiles)
.catch((value) => setError(errorMessage(value)))
}}
>
<input
ref={(node) => {
input.current = node
if (!isStep) node?.setAttribute('webkitdirectory', '')
}}
type="file"
hidden
multiple={!isStep}
accept={isStep ? '.step,.stp' : undefined}
onChange={(event) => {
pickerOpen.current = false
setPicking(false)
setError('')
onFiles(Array.from(event.target.files ?? []))
event.target.value = ''
}}
/>
<div className="component-source-title">
<span className="component-source-icon">
<Icon size={21} />
</span>
<div>
<h2>{isStep ? 'STEP 模型' : 'URDF 资源'}</h2>
<p>{isStep ? '单个 .step / .stp 文件' : '包含主文件及依赖的完整文件夹'}</p>
</div>
<span className="source-required">{required ? '必填' : '选填'}</span>
</div>
<div className="component-source-content">
{busy ? (
<>
<LoaderCircle className="spin" size={17} />
<span>{isStep ? '正在解析 STEP 预览…' : '正在读取 URDF 资源…'}</span>
</>
) : name ? (
<>
<Check size={17} />
<div>
<strong title={name}>{name}</strong>
<small>{detail}</small>
</div>
{onRemove && (
<button
type="button"
className="icon-button"
aria-label={isStep ? '移除 STEP 文件' : '移除 URDF 文件夹'}
onClick={onRemove}
>
<X size={15} />
</button>
)}
</>
) : (
<p>{isStep ? '拖入一个 STEP 文件' : '拖入一个 URDF 文件夹'}</p>
)}
</div>
<Button
disabled={busy || picking}
onClick={() => {
if (busy || pickerOpen.current || !input.current) return
pickerOpen.current = true
setPicking(true)
try {
input.current.click()
} catch (value) {
pickerOpen.current = false
setPicking(false)
setError(errorMessage(value))
}
}}
>
<Upload size={14} />
{isStep
? name
? '更换 STEP 文件'
: '选择 STEP 文件'
: name
? '更换 URDF 文件夹'
: '选择 URDF 文件夹'}
</Button>
{error && <p className="field-error">{error}</p>}
</section>
)
}
+47
View File
@@ -0,0 +1,47 @@
import { useEffect, useRef, useState } from 'react'
import { useBlocker } from 'react-router-dom'
import { Button, Modal } from './ui'
export function useEditorGuard(busy = false) {
const [dirty, setDirty] = useState(false),
leaving = useRef(false)
const blocker = useBlocker(() => (dirty || busy) && !leaving.current)
useEffect(() => {
const handler = (event: BeforeUnloadEvent) => {
if ((dirty || busy) && !leaving.current) {
event.preventDefault()
event.returnValue = ''
}
}
window.addEventListener('beforeunload', handler)
return () => window.removeEventListener('beforeunload', handler)
}, [dirty, busy])
const dialog =
blocker.state === 'blocked' ? (
<Modal
title={busy ? '正在保存组件' : '更改尚未保存'}
description={
busy
? '资源上传和保存正在进行,请完成后再离开。'
: '当前更改尚未保存,离开后将丢失这次编辑。'
}
onClose={() => blocker.reset()}
footer={
<>
<Button onClick={() => blocker.reset()}>继续编辑</Button>
<Button variant="danger" disabled={busy} onClick={() => blocker.proceed()}>
放弃更改并离开
</Button>
</>
}
/>
) : null
return {
markDirty: () => setDirty(true),
allowLeave: () => {
leaving.current = true
setDirty(false)
},
dialog,
}
}
+343
View File
@@ -0,0 +1,343 @@
import { useEffect, useRef, useState } from 'react'
import * as THREE from 'three'
import { TrackballControls } from 'three/examples/jsm/controls/TrackballControls.js'
import { ViewHelper } from 'three/addons/helpers/ViewHelper.js'
import { Maximize, RotateCcw, Move3D, LoaderCircle, Box, Upload } from 'lucide-react'
import { disposeObject } from '@/infrastructure/urdf-loader'
import { createPointHighlight } from '@/infrastructure/point-highlight'
import { pointView } from '@/infrastructure/viewer-camera'
import { createPreviewModel } from '@/infrastructure/preview-model'
import { Notice } from './ui'
interface Props {
model?: THREE.Object3D | null
busy?: boolean
error?: string
fileName?: string
onImport?: () => void
highlightPoint?: THREE.Object3D | null
}
interface Runtime {
renderer: THREE.WebGLRenderer
scene: THREE.Scene
camera: THREE.PerspectiveCamera
controls: TrackballControls
fit: () => void
invalidate: () => void
focus: (point: THREE.Vector3) => () => void
}
export function ModelPreview(props: Props) {
const host = useRef<HTMLDivElement>(null),
helperHost = useRef<HTMLDivElement>(null),
runtime = useRef<Runtime | null>(null),
current = useRef(props)
const [rendererError, setRendererError] = useState('')
current.current = props
useEffect(() => {
const element = host.current
if (!element) return
let renderer: THREE.WebGLRenderer
try {
renderer = new THREE.WebGLRenderer({ antialias: true, alpha: false })
} catch {
setRendererError('此浏览器无法初始化三维预览,请启用硬件加速后重试。')
return
}
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 1.75))
renderer.setClearColor(0x020202)
renderer.outputColorSpace = THREE.SRGBColorSpace
renderer.toneMapping = THREE.ACESFilmicToneMapping
renderer.toneMappingExposure = 0.85
renderer.shadowMap.enabled = true
renderer.shadowMap.type = THREE.PCFSoftShadowMap
renderer.autoClear = false
renderer.domElement.setAttribute('aria-label', '三维模型预览')
renderer.domElement.setAttribute('role', 'img')
element.appendChild(renderer.domElement)
const scene = new THREE.Scene(),
camera = new THREE.PerspectiveCamera(40, 1, 0.0001, 1000)
camera.up.set(0, 0, 1)
camera.position.set(0.2, -0.3, 0.2)
const controls = new TrackballControls(camera, renderer.domElement)
controls.staticMoving = true
controls.rotateSpeed = 2.2
controls.zoomSpeed = 1.2
controls.panSpeed = 0.4
controls.keys = ['', '', '']
const viewHelper = new ViewHelper(camera, element)
viewHelper.setLabels('X', 'Y', 'Z')
viewHelper.location.right = 12
viewHelper.location.bottom = 12
viewHelper.center = controls.target
const updateControlBounds = () => controls.handleResize()
renderer.domElement.addEventListener('pointerdown', updateControlBounds, true)
// Neutral fill and a dominant key light reveal surface detail without overexposure.
scene.add(new THREE.HemisphereLight(0xffffff, 0x666666, 0.35))
const keyLight = new THREE.DirectionalLight(0xffffff, 1.4)
keyLight.castShadow = true
keyLight.shadow.mapSize.set(2048, 2048)
keyLight.shadow.bias = -0.0001
const fillLight = new THREE.DirectionalLight(0xffffff, 0.25)
scene.add(keyLight, keyLight.target, fillLight, fillLight.target)
let frame = 0,
lastFrameTime = performance.now(),
disposed = false,
interacting = false,
animate: ((time: number) => boolean) | null = null
const invalidate = () => {
if (disposed || frame) return
frame = requestAnimationFrame((time) => {
frame = 0
const delta = Math.min((time - lastFrameTime) / 1000, 0.05)
lastFrameTime = time
if (viewHelper.animating) {
viewHelper.update(delta)
// Keep the free-rotation controls aligned with the helper's camera orientation.
camera.up.set(0, 1, 0).applyQuaternion(camera.quaternion)
controls.update()
} else if (animate) {
if (!animate(time)) animate = null
} else controls.update()
renderer.clear()
renderer.render(scene, camera)
if (current.current.model) viewHelper.render(renderer)
if (interacting || animate || viewHelper.animating) invalidate()
})
}
const start = () => {
animate = null
viewHelper.animating = false
interacting = true
invalidate()
}
const end = () => {
interacting = false
invalidate()
}
const clickHelper = (event: MouseEvent) => {
if (!current.current.model || event.button !== 0) return
if (!viewHelper.handleClick(event)) return
animate = null
lastFrameTime = performance.now()
invalidate()
}
const helperElement = helperHost.current
helperElement?.addEventListener('click', clickHelper)
const focus = (point: THREE.Vector3) => {
const model = current.current.model
const view = model && pointView(model, point, camera)
if (!view) return () => {}
viewHelper.animating = false
const fromTarget = controls.target.clone()
const fromOffset = camera.position.clone().sub(fromTarget)
const fromDistance = fromOffset.length()
const direction = fromOffset.clone().normalize()
const rotation = new THREE.Quaternion().setFromUnitVectors(direction, view.direction)
const fromUp = camera.up.clone()
const started = performance.now()
const transition = (time: number) => {
const progress = Math.min((time - started) / 500, 1)
const eased = progress * progress * (3 - 2 * progress)
const turn = new THREE.Quaternion().slerp(rotation, eased)
controls.target.lerpVectors(fromTarget, view.target, eased)
camera.position
.copy(direction)
.applyQuaternion(turn)
.multiplyScalar(THREE.MathUtils.lerp(fromDistance, view.distance, eased))
.add(controls.target)
camera.up.copy(fromUp).applyQuaternion(turn)
camera.lookAt(controls.target)
return progress < 1
}
animate = transition
invalidate()
return () => {
if (animate === transition) animate = null
}
}
function fit() {
animate = null
viewHelper.animating = false
const model = current.current.model
if (!model) return
model.updateMatrixWorld(true)
const box = new THREE.Box3().setFromObject(model)
if (box.isEmpty()) return
const center = box.getCenter(new THREE.Vector3()),
size = box.getSize(new THREE.Vector3()).length()
const lightingSize = Math.max(size, 0.001)
keyLight.position
.copy(center)
.addScaledVector(new THREE.Vector3(3, -4, 5).normalize(), lightingSize * 2)
keyLight.target.position.copy(center)
fillLight.position
.copy(center)
.addScaledVector(new THREE.Vector3(-3, 2, -1).normalize(), lightingSize * 2)
fillLight.target.position.copy(center)
const shadowCamera = keyLight.shadow.camera
shadowCamera.left = shadowCamera.bottom = -lightingSize * 0.6
shadowCamera.right = shadowCamera.top = lightingSize * 0.6
shadowCamera.near = lightingSize * 0.5
shadowCamera.far = lightingSize * 3.5
shadowCamera.updateProjectionMatrix()
keyLight.shadow.normalBias = lightingSize * 0.001
const distance = Math.max(size * 1.8, 0.01)
camera.up.set(0, 0, 1)
camera.position
.copy(center)
.add(new THREE.Vector3(0.85, -1.2, 0.85).normalize().multiplyScalar(distance))
camera.near = Math.max(size / 1000, 0.000001)
camera.far = Math.max(size * 1000, 10)
camera.updateProjectionMatrix()
controls.target.copy(center)
controls.minDistance = size * 0.03
controls.maxDistance = size * 30
controls.update()
invalidate()
}
const resize = () => {
const width = element.clientWidth,
height = element.clientHeight
if (!width || !height) return
renderer.setSize(width, height, false)
camera.aspect = width / height
camera.updateProjectionMatrix()
controls.handleResize()
invalidate()
}
const observer = new ResizeObserver(resize)
observer.observe(element)
controls.addEventListener('change', invalidate)
controls.addEventListener('start', start)
controls.addEventListener('end', end)
renderer.domElement.addEventListener('pointercancel', end)
window.addEventListener('blur', end)
runtime.current = { renderer, scene, camera, controls, fit, invalidate, focus }
resize()
return () => {
disposed = true
cancelAnimationFrame(frame)
observer.disconnect()
controls.removeEventListener('change', invalidate)
controls.removeEventListener('start', start)
controls.removeEventListener('end', end)
renderer.domElement.removeEventListener('pointercancel', end)
window.removeEventListener('blur', end)
controls.dispose()
helperElement?.removeEventListener('click', clickHelper)
viewHelper.dispose()
keyLight.shadow.dispose()
renderer.domElement.removeEventListener('pointerdown', updateControlBounds, true)
scene.clear()
renderer.dispose()
renderer.forceContextLoss()
renderer.domElement.remove()
runtime.current = null
}
}, [])
useEffect(() => {
const value = runtime.current
if (!value || !props.model) return
const preview = createPreviewModel(props.model)
value.scene.add(preview.root)
value.fit()
return () => {
value.scene.remove(preview.root)
preview.dispose()
value.invalidate()
}
}, [props.model])
useEffect(() => {
const value = runtime.current
if (!value || !props.model || !props.highlightPoint) return
const marker = createPointHighlight(props.model, props.highlightPoint)
if (!marker) return
value.scene.add(marker)
const cancelFocus = value.focus(marker.position)
value.invalidate()
return () => {
cancelFocus()
value.scene.remove(marker)
disposeObject(marker)
value.invalidate()
}
}, [props.model, props.highlightPoint])
return (
<div className="model-preview">
<div className="viewer-toolbar">
<div className="viewer-mode">
<span>
<Move3D size={15} />
浏览
</span>
</div>
<div>
<button
type="button"
className="icon-button"
title="适应视图"
aria-label="适应视图"
disabled={!props.model}
onClick={() => runtime.current?.fit()}
>
<Maximize size={16} />
</button>
<button
type="button"
className="icon-button"
title="重置相机"
aria-label="重置相机"
disabled={!props.model}
onClick={() => runtime.current?.fit()}
>
<RotateCcw size={16} />
</button>
</div>
</div>
<div className="viewer-canvas" ref={host} />
<div
ref={helperHost}
className="viewer-view-helper"
hidden={!props.model}
role="group"
aria-label="Three.js 视角控件"
title="点击坐标轴切换视角"
/>
{!props.model && !props.busy && !rendererError && (
<div className="viewer-empty">
<div className="viewer-empty-icon">
<Box size={55} strokeWidth={1} />
</div>
<strong>模型从这里开始</strong>
<p>选择 STEP 文件或 URDF 文件夹,在这里查看三维模型。</p>
{props.onImport && (
<button type="button" className="button button-secondary" onClick={props.onImport}>
<Upload size={16} />
选择模型文件
</button>
)}
</div>
)}
{props.busy && (
<div className="viewer-loading" role="status">
<LoaderCircle size={28} className="spin" />
<span>正在解析模型…</span>
</div>
)}
{(props.error || rendererError) && (
<div className="viewer-error">
<Notice variant="error">{props.error || rendererError}</Notice>
</div>
)}
<div className="viewer-caption">
<span>
{props.model
? props.highlightPoint
? `点位:${props.highlightPoint.name}`
: props.fileName || '原始模型预览'
: '3D PREVIEW'}
</span>
</div>
</div>
)
}
@@ -0,0 +1,104 @@
import { Crosshair } from 'lucide-react'
import type { FrameVector, UrdfFrames } from '@/domain/urdf-frames'
import { interfaceIdentityFromLink } from '@/domain/part-naming'
import { Loading, Notice } from './ui'
const vectorText = (value?: FrameVector) => (value ? value.join(' / ') : '文件未定义')
export function UrdfInstallationPoints({
data,
busy,
error,
highlightedName,
onPointHover,
}: {
data: UrdfFrames | null
busy: boolean
error: string
highlightedName?: string | null
onPointHover?: (name: string | null) => void
}) {
if (!data) {
if (busy) return <Loading text="正在读取 URDF 文件…" />
if (error) return <Notice variant="error">{error}</Notice>
return (
<div className="urdf-frames-empty">
<Crosshair size={28} />
<strong>文件原始点位</strong>
<p>选择 URDF 文件夹后,按文件内容只读展示。</p>
</div>
)
}
if (!data.frames.length) return <Notice>该文件没有 joint 点位信息,系统不补充安装点。</Notice>
return (
<div className="urdf-frames">
<p className="urdf-frames-note">
{onPointHover
? '悬停点位可高亮文件原始位置,并自动转动视角查看。'
: '按文件顺序列出全部 joint / origin,仅供查看,不是安装配置。'}
{' 接口类型按文件中的名称识别,位置与方向保持文件原值;预览只调整相机,不自动翻转模型。'}
</p>
{data.frames.map((frame) => {
const identity = interfaceIdentityFromLink(frame.child)
return (
<article
className={`urdf-frame-card ${highlightedName === frame.name ? 'is-highlighted' : ''}`}
key={frame.name}
aria-label={`文件点位 ${frame.name}`}
tabIndex={onPointHover ? 0 : undefined}
onMouseEnter={() => onPointHover?.(frame.name)}
onMouseLeave={() => onPointHover?.(null)}
onFocus={() => onPointHover?.(frame.name)}
onBlur={() => onPointHover?.(null)}
>
<header>
<h3>{frame.name}</h3>
{frame.type && <span>{frame.type}</span>}
</header>
<dl className="urdf-frame-identity">
<div>
<dt title="URDF 原始 parent/link">文件内父节点</dt>
<dd>{frame.parent || '文件未定义'}</dd>
</div>
<div>
<dt title="URDF 原始 child/link">文件内子节点</dt>
<dd>{frame.child}</dd>
</div>
<div>
<dt>接口匹配类型</dt>
<dd>{identity ? identity.key : '未按命名规则定义'}</dd>
</div>
</dl>
<FrameValue label="XYZ" unit="m" value={vectorText(frame.xyz)} />
<FrameValue label="RPY" unit="rad" value={vectorText(frame.rpy)} />
{frame.axis && <FrameValue label="axis XYZ" value={vectorText(frame.axis)} />}
{(frame.limits.lower != null || frame.limits.upper != null) && (
<FrameValue
label="lower / upper"
unit={frame.type === 'prismatic' ? 'm' : 'rad'}
value={`${frame.limits.lower ?? '文件未定义'} / ${frame.limits.upper ?? '文件未定义'}`}
/>
)}
{frame.limits.effort != null && (
<FrameValue label="effort" value={String(frame.limits.effort)} />
)}
{frame.limits.velocity != null && (
<FrameValue label="velocity" value={String(frame.limits.velocity)} />
)}
</article>
)
})}
</div>
)
}
function FrameValue({ label, unit, value }: { label: string; unit?: string; value: string }) {
return (
<div className="urdf-frame-value">
<span>
{label}
{unit && <small>{unit}</small>}
</span>
<code>{value}</code>
</div>
)
}
+200
View File
@@ -0,0 +1,200 @@
import { useEffect, useId, useRef, type ReactNode } from 'react'
import { createPortal } from 'react-dom'
import { X, AlertCircle, LoaderCircle, Box, SearchX, ChevronRight } from 'lucide-react'
import { Link } from 'react-router-dom'
export function Button({
children,
variant = 'secondary',
className = '',
...props
}: React.ButtonHTMLAttributes<HTMLButtonElement> & {
variant?: 'primary' | 'secondary' | 'danger' | 'ghost'
}) {
return (
<button type="button" className={`button button-${variant} ${className}`} {...props}>
{children}
</button>
)
}
export function Notice({
children,
variant = 'info',
}: {
children: ReactNode
variant?: 'info' | 'error'
}) {
return (
<div className={`notice notice-${variant}`} role={variant === 'error' ? 'alert' : 'note'}>
<AlertCircle size={17} />
<div>{children}</div>
</div>
)
}
export function Field({
label,
required,
hint,
children,
}: {
label: string
required?: boolean
hint?: string
children: ReactNode
}) {
return (
<label className="field">
<span>
{label}
{required && <b> *</b>}
</span>
{children}
{hint && <small>{hint}</small>}
</label>
)
}
export function Loading({ text = '正在加载…' }: { text?: string }) {
return (
<div className="loading">
<LoaderCircle size={24} className="spin" />
<span>{text}</span>
</div>
)
}
export function EmptyState({
title,
description,
action,
filtered = false,
}: {
title: string
description: string
action?: ReactNode
filtered?: boolean
}) {
return (
<div className="empty-state">
<div className="empty-art">
<div className="empty-art-grid" />
{filtered ? <SearchX strokeWidth={1.25} size={46} /> : <Box strokeWidth={1.25} size={46} />}
<span className="empty-art-dot" />
</div>
<h3>{title}</h3>
<p>{description}</p>
{action}
</div>
)
}
export function PageHeading({
eyebrow,
title,
description,
children,
}: {
eyebrow?: string
title: string
description: string
children?: ReactNode
}) {
return (
<div className="page-heading">
<div>
{eyebrow && <div className="eyebrow">{eyebrow}</div>}
<h1>{title}</h1>
<p>{description}</p>
</div>
<div className="page-actions">{children}</div>
</div>
)
}
export function Breadcrumb({ section, title }: { section: 'components'; title: string }) {
return (
<div className="breadcrumb">
<Link to={`/${section}`}>组件库</Link>
<ChevronRight size={14} />
<span>{title}</span>
</div>
)
}
export function Modal({
title,
description,
children,
onClose,
footer,
className = '',
}: {
title: string
description?: string
children?: ReactNode
onClose: () => void
footer?: ReactNode
className?: string
}) {
const id = useId(),
ref = useRef<HTMLDivElement>(null),
close = useRef(onClose)
close.current = onClose
useEffect(() => {
const previous = document.activeElement as HTMLElement | null
const overflow = document.body.style.overflow
document.body.style.overflow = 'hidden'
const focusable = () =>
Array.from(
ref.current?.querySelectorAll<HTMLElement>(
'button:not(:disabled),input,select,textarea,a[href],[tabindex="0"]',
) ?? [],
)
focusable()[0]?.focus()
const onKey = (event: KeyboardEvent) => {
if (event.key === 'Escape') close.current()
if (event.key === 'Tab') {
const items = focusable(),
first = items[0],
last = items.at(-1)
if (event.shiftKey && document.activeElement === first) {
event.preventDefault()
last?.focus()
} else if (!event.shiftKey && document.activeElement === last) {
event.preventDefault()
first?.focus()
}
}
}
document.addEventListener('keydown', onKey)
return () => {
document.body.style.overflow = overflow
document.removeEventListener('keydown', onKey)
previous?.focus()
}
}, [])
return createPortal(
<div
className="modal-backdrop"
onMouseDown={(event) => {
if (event.target === event.currentTarget) onClose()
}}
>
<div
className={`modal ${className}`}
role="dialog"
aria-modal="true"
aria-labelledby={id}
ref={ref}
>
<header>
<div>
<h2 id={id}>{title}</h2>
{description && <p>{description}</p>}
</div>
<button className="icon-button" aria-label="关闭弹窗" onClick={onClose}>
<X size={20} />
</button>
</header>
{children && <div className="modal-body">{children}</div>}
{footer && <footer>{footer}</footer>}
</div>
</div>,
document.body,
)
}
+93
View File
@@ -0,0 +1,93 @@
export const BOM_COLUMNS = [
{ key: 'partName', label: '部件名称' },
{ key: 'position', label: '部位' },
{ key: 'dof', label: 'DOF' },
{ key: 'material', label: '材质' },
{ key: 'function', label: '功能' },
{ key: 'shape', label: '形状' },
{ key: 'size', label: '大小' },
{ key: 'torque', label: '扭矩' },
] as const
export interface BomItem {
partName: string
position: string
dof: number | null
material: string
function: string
shape: string
size: string
torque: string
}
export const MAX_BOM_ROWS = 5000
export const MAX_BOM_BYTES = 10 * 1024 * 1024
const header = (value: unknown) =>
String(value ?? '')
.trim()
.toLowerCase()
export function parseBomRows(rows: unknown[][]): BomItem[] {
const headerIndex = rows
.slice(0, 30)
.findIndex((row) =>
BOM_COLUMNS.every(({ label }) => row.some((cell) => header(cell) === label.toLowerCase())),
)
if (headerIndex < 0)
throw new Error(
`未找到完整表头,请使用模板:${BOM_COLUMNS.map(({ label }) => label).join('、')}`,
)
const headings = rows[headerIndex].map(header)
const indices = BOM_COLUMNS.map(({ label }) => {
const matches = headings.flatMap((name, index) => (name === label.toLowerCase() ? [index] : []))
if (matches.length !== 1) throw new Error(`表头“${label}”重复,请只保留一列`)
return matches[0]
})
const result: BomItem[] = []
rows.slice(headerIndex + 1).forEach((row, index) => {
const line = headerIndex + index + 2
const values = indices.map((column, position) => {
const value = row[column]
if (value == null) return ''
if (typeof value !== 'string' && typeof value !== 'number')
throw new Error(
`第 ${line} 行“${BOM_COLUMNS[position].label}”请填写文本或数字,不支持公式、日期或其他单元格类型`,
)
const text = String(value).trim()
if (text.length > 2000)
throw new Error(`第 ${line} 行“${BOM_COLUMNS[position].label}”超过 2000 字符`)
return text
})
if (values.every((value) => value === '')) return
if (!values[0]) throw new Error(`第 ${line} 行缺少部件名称`)
const dofText = values[2]
const dof = !dofText || /^[-—–]+$/.test(dofText) ? null : Number(dofText)
if (dof !== null && (!/^\d+$/.test(dofText) || !Number.isSafeInteger(dof)))
throw new Error(`第 ${line} 行 DOF 须为非负整数,可留空`)
result.push({
partName: values[0],
position: values[1],
dof,
material: values[3],
function: values[4],
shape: values[5],
size: values[6],
torque: values[7],
})
if (result.length > MAX_BOM_ROWS) throw new Error(`BOM 最多导入 ${MAX_BOM_ROWS} 条`)
})
if (!result.length) throw new Error('Excel 中没有 BOM 数据,请在表头下方填写部件信息')
return result
}
export function isBomItems(value: unknown): value is BomItem[] {
return (
Array.isArray(value) &&
value.every(
(item) =>
item !== null &&
typeof item === 'object' &&
BOM_COLUMNS.every(({ key }) =>
key === 'dof'
? item[key] === null || (Number.isSafeInteger(item[key]) && item[key] >= 0)
: typeof item[key] === 'string',
),
)
)
}
+206
View File
@@ -0,0 +1,206 @@
import { parseRotationAxis, type RotationAxis } from '../../../shared/rotation-axis'
import { filePath } from './format'
import { cloneJson, type JsonContainer } from './json'
export interface CustomField {
name: string
value: string
}
export interface ComponentForm {
rotationAxis?: RotationAxis | null
componentName: string
category: string
description: string
material: string
massKg: number | null
degreesOfFreedom: number | null
functionDescription: string
shape: string
size: string
torqueNm: number | null
bomList: JsonContainer
urdfInfo: JsonContainer | null
basicFields: CustomField[]
parameterFields: CustomField[]
}
export interface ComponentSummary {
id: number
componentCode: string
componentName: string
category: string
description: string
degreesOfFreedom: number | null
functionDescription: string
shape: string
size: string
torqueNm: number | null
stepUrl: string
urdfUrl?: string | null
version: number
createdAt: string
updatedAt: string
}
export interface ComponentDetail extends ComponentSummary, ComponentForm {
stepObjectKey: string
urdfPrefix?: string | null
urdfMainObjectKey?: string | null
urdfBaseUrl?: string | null
urdfFiles?: { relativePath: string; sizeBytes: number }[] | null
}
export function hasUrdfResources(item?: ComponentDetail): boolean {
return Boolean(item?.urdfMainObjectKey && item.urdfPrefix && item.urdfFiles?.length)
}
export function urdfComponentName(fileName: string): string {
return fileName
.split('/')
.at(-1)!
.replace(/\.urdf$/i, '')
}
export interface PartInformation {
rotationAxis: string
name: string
category: string
description: string
material: string
weightKg: string
degreesOfFreedom: string
function: string
shape: string
size: string
torque: string
basicFields: CustomField[]
parameterFields: CustomField[]
bomList: JsonContainer
urdfInfo: JsonContainer | null
}
export const emptyPartInformation = (): PartInformation => ({
name: '',
rotationAxis: '',
category: '',
description: '',
material: '',
weightKg: '',
degreesOfFreedom: '',
function: '',
shape: '',
size: '',
torque: '',
basicFields: [],
parameterFields: [],
bomList: [],
urdfInfo: null,
})
export function partInformation(item: ComponentDetail): PartInformation {
return {
rotationAxis: item.rotationAxis ?? '',
name: item.componentName || '',
category: item.category || '',
description: item.description || '',
material: item.material || '',
weightKg: item.massKg == null ? '' : String(item.massKg),
degreesOfFreedom: item.degreesOfFreedom == null ? '' : String(item.degreesOfFreedom),
function: item.functionDescription || '',
shape: item.shape || '',
size: item.size || '',
torque: item.torqueNm == null ? '' : String(item.torqueNm),
basicFields: (item.basicFields || []).map((field) => ({ ...field })),
parameterFields: (item.parameterFields || []).map((field) => ({ ...field })),
bomList: cloneJson(item.bomList ?? [], 'BOM 清单'),
urdfInfo: item.urdfInfo == null ? null : cloneJson(item.urdfInfo, 'URDF 基本信息'),
}
}
export function validateStepFile(files: File[]): File {
if (files.length !== 1 || !/\.(step|stp)$/i.test(files[0].name))
throw new Error('请选择一个 STEP / STP 文件')
if (!files[0].size) throw new Error('STEP 文件不能为空')
if (files[0].size > 100 * 1024 * 1024) throw new Error('STEP 文件不能超过 100 MiB')
if (/[\\/\x00-\x1f]/.test(files[0].name) || files[0].name === '..')
throw new Error('STEP 文件名不合法')
return files[0]
}
export function urdfRelativePath(file: File): string {
const path = file.webkitRelativePath
if (!path?.includes('/')) throw new Error('请选择完整 URDF 文件夹')
const relative = path.slice(path.indexOf('/') + 1)
if (
/[\\\x00-\x1f:]/.test(relative) ||
relative.split('/').some((part) => !part || part === '.' || part === '..')
)
throw new Error('URDF 资源包含不合法的路径')
return relative
}
export function validateUrdfFolder(files: File[]): File {
if (!files.length || files.length > 1000) throw new Error('URDF 文件夹需包含 1 至 1000 个文件')
const roots = new Set(files.map((file) => filePath(file).split('/')[0]))
if (roots.size !== 1) throw new Error('请只选择一个完整 URDF 文件夹')
const paths = files.map(urdfRelativePath)
if (new Set(paths).size !== paths.length) throw new Error('URDF 资源路径重复')
for (const file of files)
if (file.size > 100 * 1024 * 1024) throw new Error(`文件“${file.name}”超过 100 MiB`)
const main = files.filter((file) => /\.urdf$/i.test(file.name))
if (main.length !== 1 || !main[0].size)
throw new Error('文件夹中必须包含且只能包含一个非空 .urdf 主文件')
return main[0]
}
function numeric(value: string, label: string): number | null {
const trimmed = value.trim()
if (!trimmed) return null
if (!/^\d{1,12}(?:\.\d{1,6})?$/.test(trimmed))
throw new Error(`${label}须为非负数,最多 12 位整数和 6 位小数`)
const number = Number(trimmed)
const normalized = trimmed
.replace(/^0+(?=\d)/, '')
.replace(/(\.\d*?)0+$/, '$1')
.replace(/\.$/, '')
if (String(number) !== normalized)
throw new Error(`${label}超出浏览器可精确表示的范围,请减少有效数字`)
return number
}
export function customFields(fields: CustomField[], group: string): CustomField[] {
if (fields.length > 100) throw new Error(`${group}最多添加 100 个自定义字段`)
const names = new Set<string>()
return fields.map((field) => {
const name = field.name.trim()
if (!name || name.length > 64) throw new Error(`${group}字段名称须为 1–64 个字符`)
if (names.has(name)) throw new Error(`${group}字段名称不能重复:${name}`)
if (typeof field.value !== 'string' || field.value.length > 2000)
throw new Error(`${name}的值最多 2000 个字符`)
names.add(name)
return { name, value: field.value }
})
}
export function componentForm(info: PartInformation): ComponentForm {
const componentName = info.name.trim(),
category = info.category.trim()
if (componentName.length > 128) throw new Error('组件名称最多 128 个字符')
if (category.length > 64) throw new Error('零件分类最多 64 个字符')
for (const [key, label, limit] of [
['material', '材质', 128],
['function', '功能', 512],
['shape', '形状', 128],
['size', '大小', 128],
] as const)
if (info[key].trim().length > limit) throw new Error(`${label}最多 ${limit} 个字符`)
const dof = info.degreesOfFreedom.trim()
if (dof && (!/^\d+$/.test(dof) || Number(dof) > 2147483647))
throw new Error('自由度须为 0 至 2147483647 的整数')
if (new TextEncoder().encode(info.description).length > 65535)
throw new Error('描述超过 65535 字节')
return {
componentName,
rotationAxis: parseRotationAxis(info.rotationAxis),
category,
description: info.description,
material: info.material.trim(),
massKg: numeric(info.weightKg, '质量'),
degreesOfFreedom: dof ? Number(dof) : null,
functionDescription: info.function.trim(),
shape: info.shape.trim(),
size: info.size.trim(),
torqueNm: numeric(info.torque, '扭矩'),
bomList: cloneJson(info.bomList, 'BOM 清单'),
urdfInfo: info.urdfInfo == null ? null : cloneJson(info.urdfInfo, 'URDF 基本信息'),
basicFields: customFields(info.basicFields, '基本信息'),
parameterFields: customFields(info.parameterFields, '零件参数'),
}
}
+29
View File
@@ -0,0 +1,29 @@
export const errorMessage = (error: unknown): string =>
error instanceof Error ? error.message : '操作失败,请重试'
export const filePath = (file: File): string => file.webkitRelativePath || file.name
export function requestId(): string {
return Array.from(crypto.getRandomValues(new Uint8Array(16)), (value) =>
value.toString(16).padStart(2, '0'),
).join('')
}
export function formatBytes(bytes: number): string {
return bytes < 1024
? `${bytes} B`
: bytes < 1024 ** 2
? `${(bytes / 1024).toFixed(1)} KB`
: `${(bytes / 1024 ** 2).toFixed(1)} MB`
}
export function formatDate(value: string): string {
const date = new Date(
value.endsWith('Z') || /[+-]\d\d:\d\d$/.test(value) ? value : `${value}+08:00`,
)
if (!value || !Number.isFinite(date.getTime())) return '—'
return new Intl.DateTimeFormat('zh-CN', {
month: '2-digit',
day: '2-digit',
hour: '2-digit',
minute: '2-digit',
hour12: false,
timeZone: 'Asia/Shanghai',
}).format(date)
}
+1
View File
@@ -0,0 +1 @@
export const validPhone = (phone: string) => /^1[3-9]\d{9}$/.test(phone)
+23
View File
@@ -0,0 +1,23 @@
export type JsonValue = string | number | boolean | null | JsonContainer
export type JsonContainer = { [key: string]: JsonValue } | JsonValue[]
/** API JSON fields must be containers, never pre-stringified JSON or scalars. */
export function cloneJson(value: unknown, label: string): JsonContainer {
if (value === null || typeof value !== 'object') throw new Error(`${label}须为 JSON 对象或数组`)
return JSON.parse(JSON.stringify(value)) as JsonContainer
}
export function sameJson(expected: JsonContainer, actual: unknown): boolean {
if (actual === null || typeof actual !== 'object') return false
const canonical = (value: unknown): unknown => {
if (Array.isArray(value)) return value.map(canonical)
if (value !== null && typeof value === 'object')
return Object.fromEntries(
Object.entries(value)
.sort(([a], [b]) => a.localeCompare(b))
.map(([key, item]) => [key, canonical(item)]),
)
return value
}
return JSON.stringify(canonical(expected)) === JSON.stringify(canonical(actual))
}
+33
View File
@@ -0,0 +1,33 @@
import type { CustomField, PartInformation } from './component-catalog'
import type { PartIdentity } from '../../../shared/part-naming'
export {
PART_TYPES,
PART_CATEGORY_OPTIONS,
sideLabel,
partIdentityFromFileName,
partIdentityFromSources,
interfaceIdentityFromLink,
} from '../../../shared/part-naming'
export type { PartType, PartSide, PartIdentity } from '../../../shared/part-naming'
export const PART_IDENTITY_FIELDS = ['partType', 'partSide'] as const
export function isPartIdentityField(field: CustomField): boolean {
return PART_IDENTITY_FIELDS.some((name) => name.toLowerCase() === field.name.trim().toLowerCase())
}
export function withPartIdentity(fields: CustomField[], part: PartIdentity | null): CustomField[] {
const custom = fields.filter((field) => !isPartIdentityField(field))
return part
? [...custom, { name: 'partType', value: part.type }, { name: 'partSide', value: part.side }]
: custom
}
/** The submitted category and identity metadata must come from the same file. */
export function applyPartIdentity(
info: PartInformation,
part: PartIdentity | null,
): PartInformation {
return part
? { ...info, category: part.key, basicFields: withPartIdentity(info.basicFields, part) }
: info
}

Some files were not shown because too many files have changed in this diff Show More