打通vibemake
CI / typecheck + test + build (push) Has been cancelled

This commit is contained in:
2026-11-05 16:21:37 +08:00
parent 7e01147566
commit 1fde96c05e
109 changed files with 9343 additions and 339 deletions
+15 -5
View File
@@ -73,6 +73,7 @@ export interface ModelFrame {
export interface ProjectFile {
name: string;
text: string;
bytes?: Uint8Array;
}
const rotZ = (r: number): THREE.Matrix4 => new THREE.Matrix4().makeRotationZ(r);
@@ -245,6 +246,9 @@ export function mountComponents(
const vrmlLoader = new VRMLLoader();
const gltfLoader = new GLTFLoader();
const cache = modelCache;
// Private files never share name-based entries between projects or reloads.
// The CAD tessellator's persistent cache remains keyed by the actual bytes.
const privateCache = new Map<string, Promise<THREE.Object3D | null>>();
const added: THREE.Object3D[] = [];
const pendingLoads: Promise<unknown>[] = [];
const disposables: { dispose(): void }[] = [];
@@ -287,17 +291,22 @@ export function mountComponents(
case 'wrl':
return Promise.resolve().then(() => {
try {
return vrmlIntoMm(vrmlLoader.parse(file.text, name) as THREE.Object3D);
return vrmlIntoMm(
vrmlLoader.parse(
file.bytes ? new TextDecoder().decode(file.bytes) : file.text,
name,
) as THREE.Object3D,
);
} catch {
return null;
}
});
case 'step':
case 'stp':
return loadCadModel(enc.encode(file.text), 'step');
return loadCadModel(file.bytes ?? enc.encode(file.text), 'step');
case 'iges':
case 'igs':
return loadCadModel(enc.encode(file.text), 'iges');
return loadCadModel(file.bytes ?? enc.encode(file.text), 'iges');
default:
return Promise.resolve(null);
}
@@ -361,10 +370,11 @@ export function mountComponents(
load = () => loadBytes(full, bytes);
}
let p = cache.get(key);
const selectedCache = where.mount === HostedLibraryMount() ? cache : privateCache;
let p = selectedCache.get(key);
if (!p) {
p = load();
cache.set(key, p);
selectedCache.set(key, p);
inFlight.add(fullName);
void p.finally(() => {
inFlight.delete(fullName);
+1 -1
View File
@@ -87,7 +87,7 @@ export interface Viewer3D {
board: import('@ziroeda/pcbnew/board.js').BOARD,
stackup: import('./board_adapter_colors.js').StackupColors | undefined,
render: Viewer3dRenderOptions,
projectFiles?: { name: string; text: string }[],
projectFiles?: { name: string; text: string; bytes?: Uint8Array }[],
) => void;
/** `GetCurrentCamera().GetViewMatrix()` — what a saved viewport (`VIEWPORT3D`) holds. */
getViewMatrix: () => number[];
+16 -2
View File
@@ -60,6 +60,7 @@ function createLocalizedElement(
type: ElementType,
props: Record<string, unknown> | null,
key?: Key,
isStaticChildren = false,
): ReactJSX.Element {
const localized = { ...(props ?? {}) };
if (typeof localized.children === 'string' || Array.isArray(localized.children)) {
@@ -69,6 +70,12 @@ function createLocalizedElement(
if (name in localized) localized[name] = localize(localized[name]);
}
if (key !== undefined) localized.key = key;
// JSX's static siblings are positional arguments to createElement, not a
// dynamic list. Preserve that distinction so React does not demand keys for
// ordinary markup, while nested mapped lists still receive key validation.
if (isStaticChildren && Array.isArray(localized.children)) {
return createElement(type, localized as ComponentProps<typeof type>, ...localized.children);
}
return createElement(type, localized as ComponentProps<typeof type>);
}
@@ -80,15 +87,22 @@ export function jsx(
return createLocalizedElement(type, props, key);
}
export const jsxs = jsx;
export function jsxs(
type: ElementType,
props: Record<string, unknown> | null,
key?: Key,
): ReactJSX.Element {
return createLocalizedElement(type, props, key, true);
}
export { Fragment };
export function jsxDEV(
type: ElementType,
props: Record<string, unknown> | null,
key?: Key,
isStaticChildren = false,
): ReactJSX.Element {
return createLocalizedElement(type, props, key);
return createLocalizedElement(type, props, key, isStaticChildren);
}
export namespace JSX {
+30
View File
@@ -0,0 +1,30 @@
// SPDX-License-Identifier: GPL-3.0-or-later
/** Optional host port. Native editors do not know about accounts or HTTP. */
export interface ProjectSnapshotParticipant {
flush: () => void | Promise<void>;
isBusy?: () => boolean;
isDirty?: () => boolean;
}
export interface ProjectSnapshotHost {
readonly scope: string;
register(key: string, participant: ProjectSnapshotParticipant): () => void;
modified(): void;
save(): Promise<void>;
command?(action: 'open' | 'new' | 'save-as' | 'download'): void;
writeFile(path: string, bytes: Uint8Array): void;
relativePath?(path: string): string;
storeLibrary(
kind: 'symbols' | 'footprints',
nickname: string,
text: string,
itemName?: string,
): void;
}
let host: ProjectSnapshotHost | null = null;
export const projectSnapshotHost = (): ProjectSnapshotHost | null => host;
export function installProjectSnapshotHost(next: ProjectSnapshotHost): () => void {
host = next;
return () => {
if (host === next) host = null;
};
}
+25
View File
@@ -0,0 +1,25 @@
// SPDX-License-Identifier: GPL-3.0-or-later
import { useEffect, useRef } from 'react';
import { projectSnapshotHost, type ProjectSnapshotParticipant } from './project_snapshot.js';
/** Callbacks follow the live frame; identity is captured only at mount. */
export function useProjectSnapshot(
key: string,
participant: ProjectSnapshotParticipant,
revision: unknown,
): void {
const host = useRef(projectSnapshotHost()).current;
const live = useRef(participant);
live.current = participant;
useEffect(
() =>
host?.register(key, {
flush: () => live.current.flush(),
isDirty: () => live.current.isDirty?.() ?? false,
isBusy: () => live.current.isBusy?.() ?? false,
}),
[host, key],
);
useEffect(() => {
if (revision !== undefined && (live.current.isDirty?.() ?? true)) host?.modified();
}, [host, revision]);
}
+3 -1
View File
@@ -22,6 +22,7 @@
*/
import { useEffect } from 'react';
import { projectSnapshotHost } from './project_snapshot.js';
export interface UnsavedGuardTarget {
addEventListener(type: string, listener: (e: BeforeUnloadEvent) => void): void;
@@ -51,7 +52,8 @@ export function installUnsavedGuard(target?: UnsavedGuardTarget | null): () => v
*/
export function useUnsavedGuard(unsaved: boolean, target?: UnsavedGuardTarget): void {
useEffect(() => {
if (!unsaved) return;
// A platform workspace owns the single leave/close guard for every editor.
if (!unsaved || projectSnapshotHost()) return;
return installUnsavedGuard(target);
}, [unsaved, target]);
}
+10 -8
View File
@@ -1,11 +1,13 @@
# Cloud accounts, sync, collaboration, telemetry and support chat are disabled
# in the default VibeMake build. Enable them only with VITE_ENABLE_CLOUD=true or
# VITE_ENABLE_TELEMETRY=true and an explicitly configured service.
# Production defaults to the real API; never set mock in a production build.
VITE_PCB_API_MODE=real
# Leave empty to use the same environment selection as VibeMake.
# Use /api explicitly only when the deployment provides an API reverse proxy.
VITE_PCB_API_BASE=
VITE_BASE=/pcb/
# Legacy cloud accounts, sync and collaboration stay disabled in platform mode.
# AI and telemetry require explicitly configured services.
VITE_ENABLE_AI=false
# Optional: base URL of the hosted 3D-model library. Production builds default
# to the R2-hosted full KiCad 10 set (see .env.production); set it here (via
# .env.local) to also use the full library in dev. Unset in dev = the small
# bundled demo set under /models3d (this repo's public/models3d).
# Optional hosted 3D library override; defaults are in src/libraryHosts.ts.
VITE_MODELS3D_URL=
+1
View File
@@ -0,0 +1 @@
VITE_PCB_API_MODE=mock
+7 -7
View File
@@ -3,15 +3,15 @@
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta name="theme-color" content="#0b0c0e" />
<meta name="theme-color" content="#07080a" />
<meta name="description" content="VibeMake PCB 是一款基于浏览器的电子设计工作台,支持原理图绘制、PCB 布局和 KiCad 兼容文件。" />
<meta property="og:type" content="website" />
<meta property="og:title" content="VibeMake PCB — 电子设计工作台" />
<meta property="og:description" content="在浏览器中绘制原理图和 PCB,项目保存在本地,并兼容 KiCad 文件。" />
<meta property="og:title" content="VibeMake PCB - 电子设计工作台" />
<meta property="og:description" content="使用 VibeMake 账号管理原理图与 PCB 项目,支持手动保存、本机草稿与 KiCad 原生工程。" />
<meta property="og:site_name" content="VibeMake PCB" />
<meta name="twitter:card" content="summary" />
<meta name="twitter:title" content="VibeMake PCB — 电子设计工作台" />
<meta name="twitter:description" content="在浏览器中绘制原理图和 PCB,项目保存在本地,并兼容 KiCad 文件。" />
<meta name="twitter:title" content="VibeMake PCB - 电子设计工作台" />
<meta name="twitter:description" content="使用 VibeMake 账号管理原理图与 PCB 项目,支持手动保存、本机草稿与 KiCad 原生工程。" />
<!-- Always revalidate the entry document so a new deploy is picked up without
a manual hard-refresh. The hashed JS/CSS bundles it references are
immutable, and vercel.json says so in a Cache-Control header, so only this
@@ -24,9 +24,9 @@
so the tab shows no icon. Vite prefixes the base (VITE_BASE) at build
time, so a deploy under a repo subpath still finds it. -->
<link rel="icon" type="image/svg+xml" href="/vibemake-mark.svg" />
<title>VibeMake PCB — 电子设计工作台</title>
<title>VibeMake PCB - 电子设计工作台</title>
<style>
html, body, #root { height: 100%; margin: 0; }
html, body, #root { height: 100%; margin: 0; overflow: hidden; }
body { font-family: 'Sora', 'PingFang SC', 'Microsoft YaHei', system-ui, sans-serif; }
</style>
</head>
+2
View File
@@ -6,6 +6,8 @@
"type": "module",
"scripts": {
"dev": "vite",
"dev:mock": "vite --mode mock",
"sync:site-navigation": "node scripts/sync-site-navigation.mjs",
"build": "tsc --noEmit && vite build",
"build:calc": "vite build --config vite.calc.config.ts && node scripts/inline-calc.mjs",
"preview": "vite preview --port 4173",
Binary file not shown.

After

Width:  |  Height:  |  Size: 27 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 20 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 37 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 58 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 110 KiB

+119
View File
@@ -0,0 +1,119 @@
// Import only public navigation design assets. The standalone PCB build never
// imports the website's auth, publishing, workspace or other business scripts.
import { readFile, writeFile, mkdir, copyFile } from 'node:fs/promises';
import { resolve, dirname, join } from 'node:path';
import { fileURLToPath } from 'node:url';
const designer = resolve(dirname(fileURLToPath(import.meta.url)), '..');
const source = resolve(process.argv[2] || join(designer, '../../vibemake'));
const target = join(designer, 'src/assets/site-brand');
const [css, layout, users, fonts, cad] = await Promise.all([
readFile(join(source, 'css/style.css'), 'utf8'),
readFile(join(source, 'js/layout.js'), 'utf8'),
readFile(join(source, 'js/source.js'), 'utf8'),
readFile(join(source, 'css/fonts.css'), 'utf8'),
readFile(join(source, 'css/cad.css'), 'utf8'),
]);
function between(text, start, end) {
const from = text.indexOf(start);
const to = text.indexOf(end, from + start.length);
if (from < 0 || to < 0) throw new Error(`Website navigation source changed: ${start}`);
return text.slice(from, to).trim();
}
const tokens = between(css, ':root {', '\n}\n').replace(':root {', '');
const typography = between(css, 'body {', '\n}')
.split('\n')
.filter((line) => /font-family:|font-size:|line-height:|-webkit-font-smoothing:/.test(line))
.join('\n');
const mobile = between(
css,
'@media (max-width: 820px) {\n .container, .nav-inner',
'\n\n .hero',
).replace('.container, .nav-inner', '.nav-inner');
const navigation = `/* Generated from vibemake/css/style.css. Run pnpm sync:site-navigation. */
/* Scoped source rules keep the professional editor's own theme isolated. */
.vm-site-shell, .vm-cad-list {
${tokens}
${typography}
a { color: inherit; text-decoration: none; }
button { font: inherit; color: inherit; cursor: pointer; }
input { font: inherit; color: inherit; }
img { display: block; max-width: 100%; }
${between(css, 'h1, h2, h3, h4, h5, h6 {', '\n')}
.ic { flex: 0 0 auto; }
${between(css, '.btn {', '.chip {')}
${between(css, '.btn:disabled {', '\n')}
${between(css, '.avatar {', '/* ---------- 顶部导航')}
${between(css, '/* ---------- 顶部导航 ---------- */', '/* ⌘K 面板 */')}
${between(css, '.nav-user {', '.load-more {')}
${mobile}
}
&:lang(en) {
${mobile.replace('@media (max-width: 820px)', '@media (min-width: 821px) and (max-width: 1100px)').replace(' [data-desktop-only] { display: none !important; }\n', '')}
}
}
}
`;
const nav = [
...between(layout, 'const NAV = [', '\n];').matchAll(
/\{ id: '([^']+)', label: '([^']+)', href: '([^']+)'([^}]*)\}/g,
),
].map((match) => ({
id: match[1],
label: match[2],
href: match[3],
desktopOnly: match[4].includes('desktopOnly: true'),
}));
if (nav.length !== 6) throw new Error('Check the website navigation before synchronizing.');
const icons = Object.fromEntries(
['search', 'upload', 'menu', 'cube', 'arrow', 'globe', 'plus', 'edit', 'trash', 'save'].map(
(key) => {
const match = layout.match(new RegExp(` ${key}: '([^']+)'`));
if (!match) throw new Error(`Missing website icon: ${key}`);
const shapes = [...match[1].matchAll(/<(path|circle) ([^>]+)\/>/g)].map((shape) => ({
tag: shape[1],
attributes: Object.fromEntries(
[...shape[2].matchAll(/(d|cx|cy|r)="([^"]*)"/g)].map((attribute) => [
attribute[1],
attribute[2],
]),
),
}));
if (!shapes.length) throw new Error(`Review the updated website icon: ${key}`);
return [key, shapes];
},
),
);
const palette = [...between(users, 'const PALETTE = [', '];').matchAll(/'(#[^']+)'/g)].map(
(m) => m[1],
);
await mkdir(join(target, 'css'), { recursive: true });
await mkdir(join(target, 'vendor/fonts'), { recursive: true });
await mkdir(join(designer, 'public/brand'), { recursive: true });
await Promise.all([
writeFile(join(target, 'css/navigation.css'), navigation),
writeFile(join(target, 'css/fonts.css'), fonts),
writeFile(
join(target, 'css/cad.css'),
`/* Generated from vibemake/css/cad.css. Keep CAD layout and metrics unchanged. */\n.vm-cad-design {\n${cad.replaceAll('.cad-page', '&')}\n}\n`,
),
writeFile(
join(target, 'navigation.ts'),
`// Generated public design data from VibeMake; no business code.\nexport const SITE_NAV = ${JSON.stringify(nav, null, 2)} as const;\nexport const SITE_ICONS = ${JSON.stringify(icons, null, 2)} as const;\nexport const AVATAR_PALETTE = ${JSON.stringify(palette)} as const;\n`,
),
...Array.from({ length: 12 }, (_, i) =>
copyFile(
join(source, `vendor/fonts/f${i + 1}.woff2`),
join(target, `vendor/fonts/f${i + 1}.woff2`),
),
),
...[256, 384, 512, 768].map((width) =>
copyFile(
join(source, `assets/brand/make-web-${width}.png`),
join(designer, `public/brand/make-web-${width}.png`),
),
),
]);
console.log(
'Synchronized VibeMake navigation CSS, local fonts, logo, links, icons and avatar palette.',
);
+197 -65
View File
@@ -51,7 +51,8 @@ import { useRoute } from './nav/useRoute.js';
import { fileForFrame, type ProjectView, type Route } from './nav/route.js';
import { installSettingsSync } from './cloud/settingsSync.js';
import type { DemoMeta } from './home/demos.js';
import { useAuth } from './auth/AuthProvider.js';
import { useOptionalAuth } from './auth/AuthProvider.js';
import type { PlatformBridge } from './platform/bridge.js';
import { isGithubId } from './home/github_id.js';
import {
reportCloudFailed,
@@ -447,11 +448,11 @@ const projectDirPrefix = (files: PickedFile[]): string => {
* without reloading or losing state. Each is kept mounted once used and toggled
* with CSS so heavy documents are parsed only once.
*/
export function App(): JSX.Element {
export function App({ platform }: { platform?: PlatformBridge } = {}): JSX.Element {
// A language change must re-render every mounted editor without remounting
// it, so active documents and tool state remain intact.
useUiLanguage();
const { session } = useAuth();
const session = useOptionalAuth()?.session;
const userId = session?.user.id ?? null;
// Read from inside debounced callbacks that must not be rebuilt on sign-in.
const userIdRef = useRef<string | null>(userId);
@@ -504,7 +505,7 @@ export function App(): JSX.Element {
// Signed out this installs nothing at all, which is what keeps an anonymous
// session byte-for-byte what it was: localStorage written by the mutator,
// read by the next page load, with nothing in between.
useEffect(() => installSettingsSync(userId), [userId]);
useEffect(() => (platform ? undefined : installSettingsSync(userId)), [userId, platform]);
const [view, setView] = useState<
| 'home'
@@ -527,15 +528,18 @@ export function App(): JSX.Element {
* of the open project and was never told which project they are. The project
* manager is the only side that knows, and says so through `onOpenProject`.
*/
const { route, navigate } = useRoute();
const legacyNav = useRoute(!platform);
const { route, navigate } = platform ?? legacyNav;
/**
* `EDA_3D_VIEWER_FRAME` open over the board editor. The frame is the
* editor's child and the editor owns showing it; App only holds the fact so
* the address can carry it (`/p/<uid>/pcb/3d`) and apply it back.
*/
const [pcb3dOpen, setPcb3dOpen] = useState(false);
const [openUid, setOpenUid] = useState<string | null>(null);
const [projectFiles, setProjectFiles] = useState<PickedFile[] | null>(null);
const [openUid, setOpenUid] = useState<string | null>(platform?.runtime.code ?? null);
const [projectFiles, setProjectFiles] = useState<PickedFile[] | null>(
() => platform?.runtime.getTextFiles() ?? null,
);
/**
* The text of every file an editor has handed up this session, keyed by the
* project-relative name — the freshest copy of the project there is.
@@ -708,7 +712,7 @@ export function App(): JSX.Element {
} | null>(null);
// Fetch the editors in the background while the launcher is on screen, so
// opening one is not the first time its code is asked for.
useEffect(() => prefetchEditors(), []);
useEffect(() => (platform ? undefined : prefetchEditors()), [platform]);
const [schMounted, setSchMounted] = useState(false);
const [pcbMounted, setPcbMounted] = useState(false);
const [symMounted, setSymMounted] = useState(false);
@@ -817,7 +821,10 @@ export function App(): JSX.Element {
else if (v === 'symviewer') setSymvMounted(true);
}, []);
// The two big frames, built while the manager is up. See `warmFrames`.
useEffect(() => (view === 'home' ? warmFrames(mountFor) : undefined), [view, mountFor]);
useEffect(
() => (!platform && view === 'home' ? warmFrames(mountFor) : undefined),
[view, mountFor, platform],
);
/** Raise the frame a demo address names over the demo now open. */
const applyDemoFrame = useCallback(
(v: 'schematic' | 'pcb' | 'symbols' | 'footprints' | undefined, child: '3d' | undefined) => {
@@ -860,7 +867,12 @@ export function App(): JSX.Element {
*/
const routeForState = useCallback((): Route => {
if (view === 'calculator') return { kind: 'tool', tool: 'calculator' };
if (view === 'drawingsheet') return { kind: 'tool', tool: 'drawing-sheet' };
if (view === 'drawingsheet')
return {
kind: 'tool',
tool: 'drawing-sheet',
...(platform && dsRequest ? { file: dsRequest.name } : {}),
};
if (view === 'image') return { kind: 'tool', tool: 'image-converter' };
if (view === 'gerber') return { kind: 'tool', tool: 'gerber' };
const pv: ProjectView =
@@ -897,7 +909,7 @@ export function App(): JSX.Element {
// the 3D viewer over the board editor: `/pcb/3d`
...(pv === 'pcb' && pcb3dOpen ? { child: '3d' as const } : {}),
};
}, [view, openUid, startFile, symFile, fpFile, demoRoute, pcb3dOpen]);
}, [view, openUid, startFile, symFile, fpFile, demoRoute, pcb3dOpen, platform, dsRequest]);
// Restore the last view on reload. The ADDRESS is asked first, and only when
// it names nothing does this fall back to the old behaviour -- the saved view
@@ -907,7 +919,7 @@ export function App(): JSX.Element {
// you had been in. It stays for one release so a session already in progress
// still restores.
const [restoring, setRestoring] = useState(
() => !!loadSession() || route.kind === 'project' || route.kind === 'demo',
() => !platform && (!!loadSession() || route.kind === 'project' || route.kind === 'demo'),
);
const restored = useRef(false);
@@ -960,6 +972,7 @@ export function App(): JSX.Element {
* addresses at all.
*/
const appliedRoute = useRef<string | null>(null);
const platformApplying = useRef<string | null>(null);
useEffect(() => {
const key = JSON.stringify(route);
if (appliedRoute.current === key) return;
@@ -967,6 +980,42 @@ export function App(): JSX.Element {
restored.current = true;
appliedRoute.current = key;
if (platform) {
platformApplying.current = key;
if (route.kind === 'project') {
const v = route.view === 'manager' ? 'home' : route.view;
if (route.file) {
if (route.view === 'symbols') setSymFile(route.file);
else if (route.view === 'footprints') setFpFile(route.file);
else setStartFile(route.file);
}
mountFor(v);
setView(v);
if (route.file && (route.view === 'symbols' || route.view === 'footprints'))
expressLibEdit(route.view, route.file);
setPcb3dOpen(route.view === 'pcb' && route.child === '3d');
} else if (route.kind === 'tool') {
if (route.tool === 'drawing-sheet' && route.file) {
const file = platform.runtime.getTextFiles().find((f) => f.name === route.file);
if (file)
setDsRequest((prior) => ({
name: file.name,
text: file.text,
nonce: (prior?.nonce ?? 0) + 1,
}));
}
const v =
route.tool === 'drawing-sheet'
? 'drawingsheet'
: route.tool === 'image-converter'
? 'image'
: route.tool;
mountFor(v);
setView(v);
}
return;
}
void (async () => {
try {
if (!storageAvailable()) return;
@@ -1085,6 +1134,7 @@ export function App(): JSX.Element {
demoSource?.id,
applyDemoFrame,
expressLibEdit,
platform,
]);
/**
@@ -1103,6 +1153,16 @@ export function App(): JSX.Element {
useEffect(() => {
if (restoring) return;
const next = routeForState();
if (platformApplying.current) {
if (JSON.stringify(next) !== platformApplying.current) return;
platformApplying.current = null;
}
if (
platform &&
appliedRoute.current === JSON.stringify(route) &&
JSON.stringify(next) === JSON.stringify(route)
)
return;
// Replace when only which file is open changed -- switching sheets should
// not fill Back with one entry per sheet -- and push for a change of place,
// so Back returns to the project manager rather than leaving the app.
@@ -1115,11 +1175,11 @@ export function App(): JSX.Element {
before.view === next.view;
appliedRoute.current = JSON.stringify(next);
navigate(next, { replace: onlyFile });
}, [routeForState, restoring, navigate]);
}, [routeForState, restoring, navigate, platform, route]);
// Remember the current view (+ open sheet) so a reload can restore it.
useEffect(() => {
if (restoring) return;
if (platform || restoring) return;
// The browser is a child window, not a place to reopen into: a reload
// comes back to the frame that raised it.
const opener =
@@ -1130,7 +1190,7 @@ export function App(): JSX.Element {
: view;
const restorable = opener === 'fpviewer' || opener === 'symviewer' ? 'home' : opener;
saveSession({ view: restorable, startFile });
}, [view, startFile, restoring]);
}, [view, startFile, restoring, platform]);
// Autosave: the schematic editor hands us its updated sheets (by basename).
// Debounce-write just those files back to IndexedDB (preserving the rest), so
@@ -1180,6 +1240,7 @@ export function App(): JSX.Element {
/** Whether the queued local write contains anything this user authored. */
const needsCloudPush = useRef(false);
const writePending = useCallback(() => {
if (platform) return;
const cur = projectFilesRef.current;
if (!cur || pendingWrite.current.size === 0 || !storageAvailable()) return;
const files = [...pendingWrite.current].map(([name, bytes]) => ({ name, bytes }));
@@ -1209,9 +1270,15 @@ export function App(): JSX.Element {
console.warn('Autosave failed:', e);
}
})();
}, [scheduleCloudPush]);
}, [scheduleCloudPush, platform]);
const onProjectChange = useCallback(
(changed: PickedFile[], opts?: { push?: boolean }) => {
if (platform) {
platform.runtime.writeTextFiles(changed);
for (const f of changed) liveEdits.current.set(f.name, f.text);
setProjectFiles(platform.runtime.getTextFiles());
return;
}
const cur = projectFilesRef.current;
if (!cur || !storageAvailable()) return;
const fullByBase = new Map(cur.map((f) => [pcbBasename(f.name), f.name]));
@@ -1247,7 +1314,7 @@ export function App(): JSX.Element {
clearTimeout(saveTimer.current);
saveTimer.current = setTimeout(writePending, LOCAL_WRITE_IDLE_MS);
},
[writePending],
[writePending, platform],
);
/**
* Every mounted editor's "serialise what you are holding, now" callback,
@@ -1270,6 +1337,19 @@ export function App(): JSX.Element {
);
const registerSchFlush = useMemo(() => registerFlushFor('schematic'), [registerFlushFor]);
const registerPcbFlush = useMemo(() => registerFlushFor('pcb'), [registerFlushFor]);
useEffect(() => {
if (!platform) return;
return platform.runtime.register('app-frames', {
flush: async () => {
await new Promise<void>((resolve) => requestAnimationFrame(() => resolve()));
for (const flush of editorFlush.current.values()) flush();
},
});
}, [platform]);
useEffect(() => {
if (!platform) return;
return platform.runtime.subscribe(() => setProjectFiles(platform.runtime.getTextFiles()));
}, [platform]);
/** Ask every mounted editor to serialise now. One that throws must not stop
* the others: this runs on the page's last callback and on the crash path. */
const flushEditors = useCallback(() => {
@@ -1331,23 +1411,31 @@ export function App(): JSX.Element {
* app wrote something". If autosave should record anything it is
* `kind: 'autosave'`, and that is a separate decision.
*/
const saveProjectFiles = useCallback(async (files: PickedFile[]): Promise<void> => {
const cur = projectFilesRef.current;
if (!cur || files.length === 0 || !storageAvailable()) return;
try {
const rec = (await listProjects()).find((p) => p.name === projectNameOf(cur));
if (!rec) return;
await updateProjectFiles(
rec.id,
files.map((f) => ({ name: f.name, bytes: enc.encode(f.text) })),
);
// Only now is the project on disk the thing worth remembering.
const loaded = await loadProject(rec.id);
if (loaded) await recordSnapshot(rec.id, loaded.files, 'save', rec.name);
} catch {
/* storage disabled */
}
}, []);
const saveProjectFiles = useCallback(
async (files: PickedFile[]): Promise<void> => {
if (platform) {
platform.runtime.writeTextFiles(files);
await platform.runtime.save();
return;
}
const cur = projectFilesRef.current;
if (!cur || files.length === 0 || !storageAvailable()) return;
try {
const rec = (await listProjects()).find((p) => p.name === projectNameOf(cur));
if (!rec) return;
await updateProjectFiles(
rec.id,
files.map((f) => ({ name: f.name, bytes: enc.encode(f.text) })),
);
// Only now is the project on disk the thing worth remembering.
const loaded = await loadProject(rec.id);
if (loaded) await recordSnapshot(rec.id, loaded.files, 'save', rec.name);
} catch {
/* storage disabled */
}
},
[platform],
);
/**
* The restore half of `SCH_EDITOR_CONTROL::Revert`
@@ -1372,6 +1460,7 @@ export function App(): JSX.Element {
* reload from `initialProject` whenever it changes.
*/
const revertProject = useCallback(async (): Promise<boolean> => {
if (platform) return false;
const cur = projectFilesRef.current;
if (!cur || !storageAvailable()) return false;
try {
@@ -1387,14 +1476,15 @@ export function App(): JSX.Element {
} catch {
return false;
}
}, [openProjectFiles]);
}, [openProjectFiles, platform]);
/** The open project's record in the store, found by name as persistFilesNow finds it. */
const openProjectRecordId = useCallback(async (): Promise<string | null> => {
if (platform) return platform.runtime.localRecordId;
const cur = projectFilesRef.current;
if (!cur || !storageAvailable()) return null;
return (await listProjects()).find((p) => p.name === projectNameOf(cur))?.id ?? null;
}, []);
}, [platform]);
/** A demo's empty folders: kept for the session, as its other edits are. */
const demoEmptyFolders = useRef<string[]>([]);
@@ -1406,10 +1496,11 @@ export function App(): JSX.Element {
/** The open project's empty folders, by the names its files have. */
const loadProjectEmptyFolders = useCallback(async (): Promise<readonly string[]> => {
if (platform) return platform.runtime.nativeProject().directories;
if (demoProject) return demoEmptyFolders.current;
const id = await openProjectRecordId();
return id ? listEmptyFolders(id) : [];
}, [demoProject, openProjectRecordId]);
}, [demoProject, openProjectRecordId, platform]);
/**
* New, empty folders in the open project: a footprint library's `.pretty`, which
@@ -1417,6 +1508,10 @@ export function App(): JSX.Element {
*/
const makeProjectFolders = useCallback(
(folders: string[]) => {
if (platform) {
for (const folder of folders) platform.runtime.addDirectory(folder);
return;
}
if (demoProject) {
demoEmptyFolders.current = [...new Set([...demoEmptyFolders.current, ...folders])];
return;
@@ -1430,25 +1525,34 @@ export function App(): JSX.Element {
/* storage disabled */
});
},
[demoProject, openProjectRecordId],
[demoProject, openProjectRecordId, platform],
);
const persistFilesNow = useCallback((files: PickedFile[]) => {
const cur = projectFilesRef.current;
if (!cur || files.length === 0 || !storageAvailable()) return;
void (async () => {
try {
const rec = (await listProjects()).find((p) => p.name === projectNameOf(cur));
if (rec)
await updateProjectFiles(
rec.id,
files.map((f) => ({ name: f.name, bytes: enc.encode(f.text) })),
);
} catch {
/* storage disabled */
const persistFilesNow = useCallback(
(files: PickedFile[]) => {
if (platform) {
platform.runtime.writeFiles(
files.map((f) => ({ name: f.name, bytes: f.bytes ?? enc.encode(f.text) })),
);
return;
}
})();
}, []);
const cur = projectFilesRef.current;
if (!cur || files.length === 0 || !storageAvailable()) return;
void (async () => {
try {
const rec = (await listProjects()).find((p) => p.name === projectNameOf(cur));
if (rec)
await updateProjectFiles(
rec.id,
files.map((f) => ({ name: f.name, bytes: enc.encode(f.text) })),
);
} catch {
/* storage disabled */
}
})();
},
[platform],
);
/**
* A library editor's write into the open project - a symbol or footprint library file, or
@@ -1499,6 +1603,12 @@ export function App(): JSX.Element {
*/
const onSaveToProject = useCallback(
(path: string, text: string) => {
if (platform) {
if (path.startsWith('/'))
void projectStoreFileSystem().write(path, enc.encode(text)).catch(console.error);
else writeProjectFiles([{ name: path, text }]);
return;
}
const cur = projectFilesRef.current;
const first = path.replace(/^\/+/, '').split('/')[0] ?? '';
const mine = cur ? projectNameOf(cur) : null;
@@ -1519,7 +1629,7 @@ export function App(): JSX.Element {
.write(path, enc.encode(text))
.catch((e) => console.warn('Save failed:', e));
},
[persistFilesNow],
[persistFilesNow, platform, writeProjectFiles],
);
// A generated output file (plot / drill / report / export) from an editor goes to the user's
@@ -1537,19 +1647,29 @@ export function App(): JSX.Element {
// The active project's .kicad_pro (full name), validated against the open
// files; defaults to the first .kicad_pro. `activeBase` scopes every editor.
const activeProName = useMemo(() => {
if (platform) return platform.runtime.nativeProject().roots.project;
if (!projectFiles) return null;
const pros = projectFiles.filter((f) => /\.kicad_pro$/i.test(f.name)).map((f) => f.name);
return (activePro && pros.includes(activePro) ? activePro : pros[0]) ?? null;
}, [projectFiles, activePro]);
const activeBase = activeProName ? projBaseOf(activeProName) : '';
}, [projectFiles, activePro, platform]);
const activeBase = activeProName
? platform
? activeProName.replace(/\.kicad_pro$/i, '')
: projBaseOf(activeProName)
: '';
const pcbFile = useMemo<PickedFile | null>(() => {
if (platform) {
const selected = route.kind === 'project' && route.view === 'pcb' ? route.file : null;
const root = selected ?? platform.runtime.nativeProject().roots.board;
return projectFiles?.find((file) => file.name === root) ?? null;
}
if (standalonePcb) return standalonePcb;
if (!projectFiles) return null;
const boards = projectFiles.filter((f) => /\.kicad_pcb$/i.test(f.name));
// The active project's board, else any board (single-project projects).
return boards.find((f) => activeBase && inProject(f.name, activeBase)) ?? boards[0] ?? null;
}, [projectFiles, standalonePcb, activeBase]);
}, [projectFiles, standalonePcb, activeBase, platform, route]);
/** What the pcbnew frame is built on: the project's board, else the empty one. */
const boardFile: PickedFile = pcbFile ?? WARM_BOARD;
const hasSchematic = useMemo(
@@ -1696,13 +1816,14 @@ export function App(): JSX.Element {
window.location.reload();
}, []);
useEffect(() => {
if (platform) return;
const container = 'serviceWorker' in navigator ? navigator.serviceWorker : null;
watchForStaleBuild(window, container);
if (container) watchForUpdate(container, reloadPage);
}, [reloadPage]);
}, [reloadPage, platform]);
useEffect(() => {
if (updateReady && view === 'home') applyUpdate();
}, [updateReady, view]);
if (!platform && updateReady && view === 'home') applyUpdate();
}, [updateReady, view, platform]);
const [updateClosed, setUpdateClosed] = useState(false);
const updateNotice =
updateReady && !updateClosed ? (
@@ -1720,12 +1841,16 @@ export function App(): JSX.Element {
/** File > Close Project, for the whole app: the editors drop the project too,
* not only the manager's tree. */
const closeProject = useCallback(() => {
if (platform) {
platform.runtime.command?.('open');
return;
}
openProjectFiles(null);
setOpenUid(null);
setStartFile(null);
setDemoRoute(null);
setView('home');
}, [openProjectFiles]);
}, [openProjectFiles, platform]);
const closeProjectRef = useRef(closeProject);
closeProjectRef.current = closeProject;
@@ -1934,7 +2059,8 @@ export function App(): JSX.Element {
* once; the manager's button raises the one that exists.
*/
let manager: JSX.Element | null = null;
if (view === 'home') {
if (platform && view === 'home') manager = <>{platform.manager}</>;
if (!platform && view === 'home') {
// Keep the open project visible in the manager tree on return from an editor,
// including any .kicad_wks saved into it this session (not yet in projectFiles).
// Overlay flushed edits (liveEdits) so a reopen from the tree sees them, and
@@ -2082,9 +2208,14 @@ export function App(): JSX.Element {
}
return (
<ProjectSyncProvider projectName={projectName} projectUid={openUid} view={syncView}>
<ProjectSyncProvider
disabled={!!platform}
projectName={projectName}
projectUid={openUid}
view={syncView}
>
{manager}
{view !== 'home' && <SaveIndicator />}
{!platform && view !== 'home' && <SaveIndicator />}
{aiEnabled() && <AiDock />}
{schMounted && (
<div style={frameStyle(view === 'schematic')}>
@@ -2151,7 +2282,7 @@ export function App(): JSX.Element {
{pcbMounted && (
<div style={frameStyle(view === 'pcb')}>
<Frozen shown={view === 'pcb'}>
<Suspense fallback={frameLoading('PCB Editor')}>
<Suspense fallback={null}>
<PcbEditorMount
fileName={pcbBasename(boardFile.name)}
text={boardFile.text}
@@ -2171,6 +2302,7 @@ export function App(): JSX.Element {
prev ? prev.map((f) => (f.name === name ? { ...f, text } : f)) : prev,
);
persistFilesNow([{ name, text }]);
if (platform) void platform.runtime.save().catch(() => undefined);
}}
projectName={projectName}
projectFiles={projectFiles ?? undefined}
@@ -0,0 +1,49 @@
/* Generated from vibemake/css/cad.css. Keep CAD layout and metrics unchanged. */
.vm-cad-design {
&{--cad-bg:#07080a;--cad-bg2:#0b0c0f;--cad-surface:#0f1114;--cad-surface2:#15181c;--cad-text:#f3f4f6;--cad-soft:#c9cdd3;--cad-muted:#8f96a0;--cad-accent:#c8ff3e;--cad-ink:#0d1203;--cad-border:#262b32;background:var(--cad-bg);color:var(--cad-text);min-height:100dvh}
& [hidden]{display:none!important}& :focus-visible{outline:2px solid var(--cad-accent);outline-offset:3px}
.cad-nav{height:72px;display:flex;align-items:center;gap:24px;padding:0 40px;border-bottom:1px solid var(--cad-border);background:var(--cad-bg2)}
.cad-brand{display:flex;align-items:center;flex-shrink:0}.cad-brand img{width:112px;height:42px;object-fit:contain}.cad-nav-links{display:flex;align-items:center;gap:24px}.cad-nav a{color:var(--cad-soft);text-decoration:none}.cad-nav a[aria-current]{color:var(--cad-accent)}.cad-spacer{flex:1}.cad-language{color:var(--cad-soft);background:var(--cad-surface);border:1px solid var(--cad-border);border-radius:7px;padding:8px}
.cad-main{max-width:1240px;padding:48px 40px 72px;margin:auto}.cad-heading{display:flex;align-items:center;justify-content:space-between;gap:24px;margin-bottom:32px}.cad-heading h1{font-size:30px;line-height:1.3;margin:0}.cad-eyebrow{color:var(--cad-accent);font-size:12px;letter-spacing:.16em;margin:0 0 12px}.cad-search{display:flex;align-items:center;gap:10px;background:var(--cad-surface);border:1px solid var(--cad-border);border-radius:10px;padding:10px 14px;max-width:440px;margin-bottom:28px;color:var(--cad-muted)}.cad-search input{border:0;background:transparent;color:var(--cad-text);width:100%;outline-offset:5px}
.cad-grid{display:grid;grid-template-columns:repeat(auto-fill,minmax(260px,1fr));gap:20px}.cad-card{background:var(--cad-surface);border:1px solid var(--cad-border);border-radius:14px;overflow:hidden}.cad-card:hover{border-color:#4a535e}.cad-card-art{height:152px;display:grid;place-items:center;background:var(--cad-bg2);color:var(--cad-muted);border-bottom:1px solid var(--cad-border)}.cad-card-art svg{width:52px;height:52px;stroke-width:1}.cad-card-body{padding:20px}.cad-card h2{font-size:17px;overflow-wrap:anywhere;margin:0 0 8px}.cad-card small{color:var(--cad-muted);font-size:12px}.cad-card-actions{display:flex;gap:8px;margin-top:20px}.cad-card-actions .btn:first-child{margin-right:auto}.cad-state{min-height:360px;display:flex;flex-direction:column;justify-content:center;align-items:center;gap:18px;text-align:center}.cad-state h1,.cad-state h2,.cad-state p{margin:0}.cad-state p{color:var(--cad-muted);max-width:600px;line-height:1.7}.cad-state>.ic{width:52px;height:52px;color:var(--cad-accent)}.cad-pagination{display:flex;justify-content:center;align-items:center;gap:20px;margin-top:32px;color:var(--cad-muted)}
.cad-editor{height:100dvh;overflow:hidden}.cad-editor .cad-nav{height:52px;padding:0 16px;gap:14px}.cad-editor .cad-brand img{width:96px;height:36px}.cad-product-name{font-size:13px;color:var(--cad-soft);white-space:nowrap}.cad-project-name{border:0;background:transparent;color:var(--cad-text);font-weight:600;max-width:25vw;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;cursor:pointer}.cad-save-state{font-size:12px;white-space:nowrap;color:var(--cad-muted)}.cad-save-state[data-state=conflict],.cad-save-state[data-state=failed]{color:#ffb870}.cad-editor .cad-main{position:absolute;inset:52px 0 0;max-width:none;padding:0;display:grid;place-items:center}.cad-viewport{position:absolute;inset:52px 0 0;overflow:hidden}.cad-viewport canvas{display:block;width:100%;height:100%;outline:none;touch-action:none}.cad-blocker{position:fixed;inset:52px 0 0;z-index:80;background:var(--cad-bg);display:grid;place-items:center}.cad-notice{position:fixed;bottom:24px;left:50%;transform:translateX(-50%);max-width:min(780px,90vw);z-index:120;padding:14px 20px;border:1px solid #826b33;border-radius:10px;background:var(--cad-surface2);color:var(--cad-text);font-size:13px;line-height:1.6}.cad-dialog-actions{display:flex;gap:12px;flex-wrap:wrap;justify-content:flex-end;margin-top:24px}.cad-account{position:relative}.cad-user-menu{position:absolute;right:0;top:calc(100% + 8px);min-width:240px;background:var(--cad-surface);border:1px solid var(--cad-border);border-radius:10px;padding:12px;z-index:110;box-shadow:0 12px 32px #0008}.cad-user-menu p{overflow-wrap:anywhere;color:var(--cad-muted);font-size:12px;padding:4px}.cad-user-menu button{width:100%;text-align:left;margin-top:6px}& .modal{z-index:150}& .btn{min-height:36px}& .btn-primary{background:var(--cad-accent);color:var(--cad-ink)}
@media(max-width:1100px){.cad-nav-links{gap:12px}.cad-editor .cad-product-name{display:none}.cad-editor .cad-nav{gap:8px}.cad-save-state{max-width:190px;overflow:hidden;text-overflow:ellipsis}}
@media(max-width:820px){.cad-nav{padding:0 16px;gap:12px}.cad-nav-links{display:none}.cad-main{padding:28px 20px}.cad-heading{align-items:flex-start}.cad-editor .cad-project-name,.cad-editor .cad-save-state{display:none}.cad-state{padding:24px}.cad-editor .cad-nav{flex-wrap:nowrap}}
@media(prefers-reduced-motion:reduce){& *{scroll-behavior:auto!important;transition:none!important;animation-duration:.01ms!important}}
& .sr-only{position:absolute;width:1px;height:1px;padding:0;margin:-1px;overflow:hidden;clip:rect(0,0,0,0);white-space:nowrap;border:0}
& .cad-card{border-radius:8px}
.cad-eyebrow{letter-spacing:0}
.cad-editor .nav{position:fixed;inset:0 0 auto;height:var(--nav)}
.cad-editor .nav-inner{height:100%}
.cad-editor .nav-links:not(.cad-engine-menus){display:none}
.cad-editor .cad-engine-menus{align-items:center}
.cad-editor .cad-engine-menus button{position:relative;padding:4px 0;border:0;background:none;color:var(--muted);font:inherit;font-size:14px;cursor:pointer;transition:color .2s}
.cad-editor .cad-engine-menus button:hover{color:var(--text)}
.cad-editor .cad-engine-menus button:focus-visible{outline:2px solid var(--accent);outline-offset:5px;border-radius:2px}
.cad-editor .cad-save-state{max-width:220px;overflow:hidden;text-overflow:ellipsis;color:var(--muted);font-size:12px;white-space:nowrap}
.cad-editor .cad-save-state[data-state=conflict],.cad-editor .cad-save-state[data-state=failed],.cad-editor .cad-save-state[data-state=expired]{color:#ffb870}
.cad-editor .cad-main{inset:var(--nav) 0 0}
.cad-editor .cad-viewport{inset:var(--nav) 0 0}
.cad-editor .cad-blocker{inset:var(--nav) 0 0}
@media(max-width:1100px){.cad-editor .cad-save-state{max-width:130px}}
& .nav .btn{min-height:34px}
.cad-editor{--nav:42px}
.cad-editor .nav-inner{width:100%;max-width:none;margin:0;padding:0 12px;gap:12px}
.cad-editor .nav-logo{min-height:0}
.cad-editor .nav-logo img{width:92px;height:34px}
.cad-appbar-left{display:flex;align-items:center;gap:2px;flex:0 0 auto}
.cad-appbar-divider{height:24px;border-left:1px solid var(--border);margin:0 6px 0 2px}
.cad-appbar-left .cad-engine-menus{margin-right:0}
.cad-editor .cad-engine-menus button{padding:4px 9px;border-radius:3px}
.cad-editor .cad-engine-menus button:hover{background:rgba(255,255,255,.06)}
.cad-appbar-icon{width:32px!important;height:32px!important;flex:0 0 32px;border-radius:3px!important}
.cad-appbar-icon:hover{background:rgba(255,255,255,.08)}
.cad-appbar-icon:disabled{opacity:.35;cursor:default}
.cad-appbar-icon:disabled:hover{background:transparent}
.cad-editor .cad-editor-utility{display:flex;align-items:center;gap:2px;margin-right:0}
.cad-editor .cad-editor-utility button{padding:0}
.cad-editor .nav-actions{gap:8px;margin-left:auto}
.cad-editor .nav-actions .cad-editor-utility{margin-right:8px}
.cad-editor .cad-engine-menus button:focus-visible,.cad-editor .cad-appbar-icon:focus-visible{outline:2px solid var(--accent);outline-offset:2px}
}
@@ -0,0 +1,109 @@
/* 本地字体(scripts/vendor.mjs 生成),只含拉丁字符,中文用系统字体 */
/* latin-ext */
@font-face {
font-family: 'JetBrains Mono';
font-style: normal;
font-weight: 400;
font-display: swap;
src: url(../vendor/fonts/f1.woff2) format('woff2');
unicode-range: U+0100-02BA, U+02BD-02C5, U+02C7-02CC, U+02CE-02D7, U+02DD-02FF, U+0304, U+0308, U+0329, U+1D00-1DBF, U+1E00-1E9F, U+1EF2-1EFF, U+2020, U+20A0-20AB, U+20AD-20C4, U+2113, U+2C60-2C7F, U+A720-A7FF;
}
/* latin */
@font-face {
font-family: 'JetBrains Mono';
font-style: normal;
font-weight: 400;
font-display: swap;
src: url(../vendor/fonts/f2.woff2) format('woff2');
unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+0304, U+0308, U+0329, U+2000-206F, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD;
}
/* latin-ext */
@font-face {
font-family: 'JetBrains Mono';
font-style: normal;
font-weight: 500;
font-display: swap;
src: url(../vendor/fonts/f3.woff2) format('woff2');
unicode-range: U+0100-02BA, U+02BD-02C5, U+02C7-02CC, U+02CE-02D7, U+02DD-02FF, U+0304, U+0308, U+0329, U+1D00-1DBF, U+1E00-1E9F, U+1EF2-1EFF, U+2020, U+20A0-20AB, U+20AD-20C4, U+2113, U+2C60-2C7F, U+A720-A7FF;
}
/* latin */
@font-face {
font-family: 'JetBrains Mono';
font-style: normal;
font-weight: 500;
font-display: swap;
src: url(../vendor/fonts/f4.woff2) format('woff2');
unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+0304, U+0308, U+0329, U+2000-206F, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD;
}
/* latin-ext */
@font-face {
font-family: 'Sora';
font-style: normal;
font-weight: 400;
font-display: swap;
src: url(../vendor/fonts/f5.woff2) format('woff2');
unicode-range: U+0100-02BA, U+02BD-02C5, U+02C7-02CC, U+02CE-02D7, U+02DD-02FF, U+0304, U+0308, U+0329, U+1D00-1DBF, U+1E00-1E9F, U+1EF2-1EFF, U+2020, U+20A0-20AB, U+20AD-20C4, U+2113, U+2C60-2C7F, U+A720-A7FF;
}
/* latin */
@font-face {
font-family: 'Sora';
font-style: normal;
font-weight: 400;
font-display: swap;
src: url(../vendor/fonts/f6.woff2) format('woff2');
unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+0304, U+0308, U+0329, U+2000-206F, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD;
}
/* latin-ext */
@font-face {
font-family: 'Sora';
font-style: normal;
font-weight: 500;
font-display: swap;
src: url(../vendor/fonts/f7.woff2) format('woff2');
unicode-range: U+0100-02BA, U+02BD-02C5, U+02C7-02CC, U+02CE-02D7, U+02DD-02FF, U+0304, U+0308, U+0329, U+1D00-1DBF, U+1E00-1E9F, U+1EF2-1EFF, U+2020, U+20A0-20AB, U+20AD-20C4, U+2113, U+2C60-2C7F, U+A720-A7FF;
}
/* latin */
@font-face {
font-family: 'Sora';
font-style: normal;
font-weight: 500;
font-display: swap;
src: url(../vendor/fonts/f8.woff2) format('woff2');
unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+0304, U+0308, U+0329, U+2000-206F, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD;
}
/* latin-ext */
@font-face {
font-family: 'Sora';
font-style: normal;
font-weight: 600;
font-display: swap;
src: url(../vendor/fonts/f9.woff2) format('woff2');
unicode-range: U+0100-02BA, U+02BD-02C5, U+02C7-02CC, U+02CE-02D7, U+02DD-02FF, U+0304, U+0308, U+0329, U+1D00-1DBF, U+1E00-1E9F, U+1EF2-1EFF, U+2020, U+20A0-20AB, U+20AD-20C4, U+2113, U+2C60-2C7F, U+A720-A7FF;
}
/* latin */
@font-face {
font-family: 'Sora';
font-style: normal;
font-weight: 600;
font-display: swap;
src: url(../vendor/fonts/f10.woff2) format('woff2');
unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+0304, U+0308, U+0329, U+2000-206F, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD;
}
/* latin-ext */
@font-face {
font-family: 'Sora';
font-style: normal;
font-weight: 700;
font-display: swap;
src: url(../vendor/fonts/f11.woff2) format('woff2');
unicode-range: U+0100-02BA, U+02BD-02C5, U+02C7-02CC, U+02CE-02D7, U+02DD-02FF, U+0304, U+0308, U+0329, U+1D00-1DBF, U+1E00-1E9F, U+1EF2-1EFF, U+2020, U+20A0-20AB, U+20AD-20C4, U+2113, U+2C60-2C7F, U+A720-A7FF;
}
/* latin */
@font-face {
font-family: 'Sora';
font-style: normal;
font-weight: 700;
font-display: swap;
src: url(../vendor/fonts/f12.woff2) format('woff2');
unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+0304, U+0308, U+0329, U+2000-206F, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD;
}
@@ -0,0 +1,145 @@
/* Generated from vibemake/css/style.css. Run pnpm sync:site-navigation. */
/* Scoped source rules keep the professional editor's own theme isolated. */
.vm-site-shell, .vm-cad-list {
--bg: #07080a;
--bg-2: #0b0c0f;
--surface: #0f1114;
--surface-2: #15181c;
--panel: rgba(15, 17, 20, 0.78);
--line: rgba(255, 255, 255, 0.07);
--line-strong: rgba(255, 255, 255, 0.13);
--text: #f3f4f6;
--soft: #c9cdd3;
--muted: #8f96a0;
--dim: #5c636c;
--accent: #c8ff3e;
--accent-ink: #0d1203;
--accent-soft: rgba(200, 255, 62, 0.1);
--accent-line: rgba(200, 255, 62, 0.32);
--danger: #ff6b5b;
--ok: #46e38a;
--nav: 64px;
--font: 'Sora', 'PingFang SC', 'Hiragino Sans GB', 'Microsoft YaHei', system-ui, sans-serif;
--mono: 'JetBrains Mono', ui-monospace, SFMono-Regular, Menlo, monospace;
color-scheme: dark;
font-family: var(--font);
font-size: 15px;
line-height: 1.65;
-webkit-font-smoothing: antialiased;
a { color: inherit; text-decoration: none; }
button { font: inherit; color: inherit; cursor: pointer; }
input { font: inherit; color: inherit; }
img { display: block; max-width: 100%; }
h1, h2, h3, h4, h5, h6 { margin: 0; font-weight: 600; letter-spacing: -0.015em; }
.ic { flex: 0 0 auto; }
.btn {
display: inline-flex; align-items: center; justify-content: center; gap: 8px;
height: 40px; padding: 0 18px;
border-radius: 999px;
border: 1px solid var(--line-strong);
background: rgba(255, 255, 255, 0.03);
font-size: 14px; font-weight: 500; white-space: nowrap;
transition: background .2s, border-color .2s, transform .15s, color .2s;
}
.btn:hover { background: rgba(255, 255, 255, 0.08); border-color: rgba(255, 255, 255, 0.24); }
.btn:active { transform: scale(0.98); }
.btn-primary { background: var(--accent); border-color: var(--accent); color: var(--accent-ink); font-weight: 600; }
.btn-primary:hover { background: #d8ff70; border-color: #d8ff70; }
.btn-light { background: var(--text); border-color: var(--text); color: #0b0c0e; font-weight: 600; }
.btn-light:hover { background: #fff; border-color: #fff; }
.btn-ghost { background: transparent; border-color: transparent; color: var(--soft); }
.btn-ghost:hover { background: rgba(255, 255, 255, 0.06); border-color: transparent; }
.btn-danger { background: var(--danger); border-color: var(--danger); color: #1a0705; font-weight: 600; }
.btn-sm { height: 34px; padding: 0 14px; font-size: 13px; }
.btn-lg { height: 50px; padding: 0 26px; font-size: 15px; }
.btn.on { color: var(--accent); border-color: var(--accent-line); background: var(--accent-soft); }
.icon-btn { display: grid; place-items: center; width: 40px; height: 40px; border: 0; border-radius: 999px; background: transparent; color: var(--soft); }
.icon-btn:hover { background: rgba(255, 255, 255, 0.07); color: var(--text); }
.round-btn { display: grid; place-items: center; width: 44px; height: 44px; border-radius: 50%; border: 1px solid var(--line-strong); background: rgba(10, 11, 13, 0.5); color: var(--soft); backdrop-filter: blur(10px); }
.round-btn:hover { color: var(--text); border-color: rgba(255, 255, 255, 0.3); }
.btn:disabled { opacity: .55; pointer-events: none; }
.avatar {
display: inline-grid; place-items: center; flex: 0 0 auto;
border-radius: 50%;
background: color-mix(in srgb, var(--c) 20%, #0e0f12);
color: var(--c);
box-shadow: inset 0 0 0 1px color-mix(in srgb, var(--c) 38%, transparent);
font-weight: 600; line-height: 1;
}
/* ---------- 顶部导航 ---------- */
.nav {
position: sticky; top: 0; z-index: 50;
height: var(--nav);
border-bottom: 1px solid transparent;
transition: background .25s, border-color .25s;
}
.nav.scrolled, .nav.overlay, .nav.open {
background: rgba(7, 8, 10, 0.72);
backdrop-filter: blur(18px) saturate(1.5);
-webkit-backdrop-filter: blur(18px) saturate(1.5);
border-bottom-color: var(--line);
}
.nav.overlay { position: fixed; left: 0; right: 0; }
.nav-inner { display: flex; align-items: center; gap: 44px; height: 100%; max-width: 1240px; margin: 0 auto; padding: 0 40px; }
.nav-logo { display: flex; align-items: center; flex-shrink: 0; min-height: 44px; }
.nav-logo img { display: block; width: 112px; height: 42px; object-fit: contain; }
.nav-links { display: flex; gap: 30px; margin-right: auto; }
.nav-links a { position: relative; color: var(--muted); font-size: 14px; transition: color .2s; }
.nav-links a:hover { color: var(--text); }
.nav-links a.active { color: var(--text); }
.nav-links a.active::after { content: ''; position: absolute; left: 50%; bottom: -10px; width: 4px; height: 4px; margin-left: -2px; border-radius: 50%; background: var(--accent); }
.nav-actions { display: flex; align-items: center; gap: 10px; margin-left: auto; }
.nav-search {
display: inline-flex; align-items: center; gap: 8px;
height: 34px; padding: 0 8px 0 12px;
border-radius: 999px; border: 1px solid var(--line-strong);
background: rgba(255, 255, 255, 0.025);
color: var(--muted); font-size: 13px;
}
.nav-search:hover { color: var(--text); border-color: rgba(255, 255, 255, 0.24); }
.nav-search span { min-width: 72px; text-align: left; }
kbd { font-family: var(--mono); font-size: 10.5px; padding: 1px 6px; border: 1px solid var(--line-strong); border-radius: 6px; color: var(--muted); }
.nav-menu { display: none; }
.sheet { display: none; }
.no-desktop-tools [data-desktop-only] { display: none !important; }
.nav-user { display: inline-flex; align-items: center; gap: 8px; height: 36px; padding: 0 12px 0 4px; border-radius: 999px; border: 1px solid var(--line); background: rgba(255, 255, 255, 0.03); color: var(--text); font-size: 13px; cursor: pointer; }
.nav-user:hover { border-color: var(--line-strong); }
.nav-user > span:not(.avatar) { max-width: 120px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.user-pop { position: fixed; z-index: 96; min-width: 220px; padding: 8px; border-radius: 16px; border: 1px solid var(--line-strong); background: #101215; box-shadow: 0 24px 60px rgba(0, 0, 0, 0.5); }
.user-pop .who { display: grid; padding: 8px 12px 10px; border-bottom: 1px solid var(--line); margin-bottom: 6px; }
.user-pop .who small { color: var(--dim); font-size: 12px; }
.user-pop button { display: flex; align-items: center; gap: 10px; width: 100%; height: 38px; padding: 0 12px; border: 0; border-radius: 10px; background: transparent; color: var(--soft); font-size: 13.5px; text-align: left; cursor: pointer; }
.user-pop button:hover { background: rgba(255, 255, 255, 0.05); color: var(--text); }
@media (max-width: 820px) {
.nav-inner { padding: 0 20px; }
[data-desktop-only] { display: none !important; }
.nav-inner { gap: 16px; }
.nav-logo img { width: 96px; height: 36px; }
.nav-links, .hide-sm { display: none; }
.nav-search span, .nav-search kbd { display: none; }
.nav-search { width: 40px; height: 40px; padding: 0; justify-content: center; }
.nav-menu { display: grid; }
.nav.open .sheet { display: grid; gap: 4px; padding: 12px 20px 20px; background: rgba(7, 8, 10, 0.96); border-bottom: 1px solid var(--line); }
.sheet a { padding: 12px 4px; font-size: 16px; color: var(--soft); border-bottom: 1px solid var(--line); }
.sheet a.active { color: var(--accent); }
.sheet-actions { display: flex; gap: 10px; margin-top: 14px; }
.sheet-actions .btn { flex: 1; }
}
&:lang(en) {
@media (min-width: 821px) and (max-width: 1100px) {
.nav-inner { padding: 0 20px; }
.nav-inner { gap: 16px; }
.nav-logo img { width: 96px; height: 36px; }
.nav-links, .hide-sm { display: none; }
.nav-search span, .nav-search kbd { display: none; }
.nav-search { width: 40px; height: 40px; padding: 0; justify-content: center; }
.nav-menu { display: grid; }
.nav.open .sheet { display: grid; gap: 4px; padding: 12px 20px 20px; background: rgba(7, 8, 10, 0.96); border-bottom: 1px solid var(--line); }
.sheet a { padding: 12px 4px; font-size: 16px; color: var(--soft); border-bottom: 1px solid var(--line); }
.sheet a.active { color: var(--accent); }
.sheet-actions { display: flex; gap: 10px; margin-top: 14px; }
.sheet-actions .btn { flex: 1; }
}
}
}
@@ -0,0 +1,156 @@
// Generated public design data from VibeMake; no business code.
export const SITE_NAV = [
{
"id": "home",
"label": "首页",
"href": "/",
"desktopOnly": false
},
{
"id": "explore",
"label": "社区",
"href": "/explore/",
"desktopOnly": false
},
{
"id": "studio",
"label": "工作台",
"href": "/studio/",
"desktopOnly": false
},
{
"id": "cad",
"label": "CAD",
"href": "/cad/",
"desktopOnly": true
},
{
"id": "pcb",
"label": "PCB",
"href": "/pcb/",
"desktopOnly": true
},
{
"id": "workspace",
"label": "我的",
"href": "/workspace/",
"desktopOnly": false
}
] as const;
export const SITE_ICONS = {
"search": [
{
"tag": "circle",
"attributes": {
"cx": "11",
"cy": "11",
"r": "7"
}
},
{
"tag": "path",
"attributes": {
"d": "m20 20-3.5-3.5"
}
}
],
"upload": [
{
"tag": "path",
"attributes": {
"d": "M12 16V4M6 10l6-6 6 6M4 20h16"
}
}
],
"menu": [
{
"tag": "path",
"attributes": {
"d": "M4 7h16M4 12h16M4 17h16"
}
}
],
"cube": [
{
"tag": "path",
"attributes": {
"d": "M12 2 3 7v10l9 5 9-5V7z"
}
},
{
"tag": "path",
"attributes": {
"d": "m3 7 9 5 9-5M12 12v10"
}
}
],
"arrow": [
{
"tag": "path",
"attributes": {
"d": "M5 12h14M13 6l6 6-6 6"
}
}
],
"globe": [
{
"tag": "circle",
"attributes": {
"cx": "12",
"cy": "12",
"r": "9"
}
},
{
"tag": "path",
"attributes": {
"d": "M3 12h18M12 3a14 14 0 0 1 0 18M12 3a14 14 0 0 0 0 18"
}
}
],
"plus": [
{
"tag": "path",
"attributes": {
"d": "M12 5v14M5 12h14"
}
}
],
"edit": [
{
"tag": "path",
"attributes": {
"d": "M4 20h4L19 9l-4-4L4 16z"
}
},
{
"tag": "path",
"attributes": {
"d": "m13.5 6.5 4 4"
}
}
],
"trash": [
{
"tag": "path",
"attributes": {
"d": "M4 7h16M10 11v6M14 11v6M6 7l1 13h10l1-13M9 7V4h6v3"
}
}
],
"save": [
{
"tag": "path",
"attributes": {
"d": "M5 3h12l4 4v14H3V3z"
}
},
{
"tag": "path",
"attributes": {
"d": "M7 3v6h10V3M7 21v-8h10v8"
}
}
]
} as const;
export const AVATAR_PALETTE = ["#c8ff3e","#5ea8ff","#ff7a9a","#ffb347","#7cf0c8","#b79cff","#ffd166","#6ee7ff"] as const;
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
+5
View File
@@ -646,3 +646,8 @@ export function useAuth(): AuthContextValue {
if (!ctx) throw new Error('useAuth must be used within <AuthProvider>');
return ctx;
}
/** Platform workspaces deliberately do not mount the legacy auth provider. */
export function useOptionalAuth(): AuthContextValue | null {
return useContext(AuthContext);
}
+3 -1
View File
@@ -88,8 +88,10 @@ export function missingFeatures(probes: Probe[] = PROBES): Missing[] {
* do about it — an unexplained failure is the thing being fixed, so a generic
* "unsupported browser" would only be a prettier white screen.
*/
export function unsupportedMessage(missing: readonly Missing[]): string {
export function unsupportedMessage(missing: readonly Missing[], platform = false): string {
const list = missing.map((m) => m.feature).join(', ');
if (platform)
return `This browser is missing ${list}. Please use a current desktop version of Chrome, Edge, Firefox or Safari. Cloud projects remain in your account; unsaved drafts remain in their original browser.`;
return (
`This browser is missing ${list}, which VibeMake PCB needs to run.\n\n` +
'Please use a current version of Chrome, Edge, Firefox or Safari. ' +
+1 -1
View File
@@ -106,7 +106,7 @@ export interface Viewer3DFrameProps {
*/
board: BOARD_3D_HANDLE | null;
/** The open project's own files, so ${KIPRJMOD} model paths resolve. */
projectFiles?: { name: string; text: string }[];
projectFiles?: { name: string; text: string; bytes?: Uint8Array }[];
/**
* `PCB_BASE_FRAME::Update3DView`'s `aTitle` (pcb_base_frame.cpp:161): a
* parent may override the child frame's title, and exactly two do — the
@@ -27,7 +27,7 @@ import { preloadSchematicLibraries } from './preload.js';
import { remapEvent } from './hotkey_bindings.js';
import { applyHotkeyOverrides } from './hotkey_list.js';
import { useProjectSync } from '../../sync/ProjectSyncProvider.js';
import { useAuth } from '../../auth/AuthProvider.js';
import { useOptionalAuth } from '../../auth/AuthProvider.js';
import { PresencePanel } from '../../ui/PresencePanel.js';
import { DialogAssignFootprints } from '@ziroeda/cvpcb/cvpcb_mainframe_ui.js';
import { useCvpcbApp } from './cvpcb_app.js';
@@ -61,6 +61,10 @@ import {
useSchematicTheme,
} from '../../prefs/useSettings.js';
function useEditorAuth(): ReturnType<EESCHEMA_APP['useAuth']> {
return { session: useOptionalAuth()?.session ?? null };
}
/** One object per mount; every member is stable across renders. */
export function useEeschemaApp(): EESCHEMA_APP {
return useMemo<EESCHEMA_APP>(
@@ -113,7 +117,7 @@ export function useEeschemaApp(): EESCHEMA_APP {
applyHotkeyOverrides,
useProjectSync,
useAuth,
useAuth: useEditorAuth,
PresencePanel: (props) => <PresencePanel {...props} />,
AssignFootprints: (props) => <AssignFootprintsWithApp {...props} />,
+9
View File
@@ -151,7 +151,16 @@ export async function projectAt(path: string): Promise<ProjectMeta | null> {
return (await byDisplayName()).get(name) ?? null;
}
let platformFileSystem: FileSystem | null = null;
export function installPlatformFileSystem(fs: FileSystem): () => void {
platformFileSystem = fs;
return () => {
if (platformFileSystem === fs) platformFileSystem = null;
};
}
export function projectStoreFileSystem(): FileSystem {
if (platformFileSystem) return platformFileSystem;
const resolve = async (path: string): Promise<Resolved> => {
if (!isValidPath(path)) throw new FsError(FsErrorCode.INVALID, path);
const parts = segments(path);
+9 -172
View File
@@ -1,175 +1,12 @@
// SPDX-License-Identifier: GPL-3.0-or-later
// Copyright (C) 2026 ZiroEDA and contributors.
// Portions derived from KiCad, copyright The KiCad Developers. See NOTICE.md.
// Modified by VibeMake to keep cloud and telemetry disabled by default.
import {
InstallErrorPresenter,
InstallInfoPresenter,
InstallMessageDialogPresenter,
InstallQuestionPresenter,
} from '@ziroeda/common/confirm_ui.js';
import { StrictMode } from 'react';
import { createRoot } from 'react-dom/client';
import { App } from './App.js';
import { AuthProvider } from './auth/AuthProvider.js';
import { AuthGate } from './auth/AuthGate.js';
import { DesktopGate } from './mobile/DesktopGate.js';
import { ErrorBoundary } from './ui/ErrorBoundary.js';
import { StorageBanner } from './ui/StorageBanner.js';
import { TooltipLayer } from '@ziroeda/common/widgets/tooltip.js';
import { HotkeyListHost } from './ui/hotkey_list_host.js';
import { SENTRY, SetSentryBackend, SetSentryBuildInfo } from '@ziroeda/common/app_monitor.js';
import { GetBuildVersion, GetMajorMinorVersion } from '@ziroeda/common/build_version.js';
import { SENTRY_RELEASE, sentryBackend } from './telemetry/sentry_backend.js';
import { installGlobalErrorHandlers } from './telemetry/global_handlers.js';
import { startUsageStats } from './telemetry/usage.js';
import { installOverlayScrollbars } from '@ziroeda/common/widgets/overlay_scrollbars.js';
import { installDialogSizeHints } from '@ziroeda/common/dialog_shim.js';
import { SetFileDialog, SetSaveFileDialog } from '@ziroeda/wx/filedlg.js';
import { InitPgm } from './pgm_app.js';
import { wxInitAllImageHandlers } from '@ziroeda/wx/wx_image.js';
import { OpenFileDialog } from './fs/OpenFileDialog.js';
import { SaveAsDialog } from './fs/SaveAsDialog.js';
import { installOutlineFontProvider } from '@ziroeda/common/font/outline_fonts.js';
import { missingFeatures, unsupportedMessage } from './browser_support.js';
import { checkStorageHealth, setTemplateSink } from './home/projectStore.js';
import { updateUserTemplateFiles } from './home/user_templates.js';
import { authEnabled } from './auth/supabaseClient.js';
import { setCloudBackend } from './cloud/cloudStore.js';
import { supabaseBackend } from './cloud/supabaseBackend.js';
import { settings } from './prefs/settings.js';
import { setUiLanguage } from '@ziroeda/common/i18n.js';
// `APP_MONITOR::SENTRY::Instance()->Init()`, as PGM_BASE::InitPgm starts it:
// before rendering, so a crash during the first paint is still reported. It
// does nothing when VITE_SENTRY_DSN is unset or the user has opted out.
const telemetryEnabled = import.meta.env.VITE_ENABLE_TELEMETRY === 'true';
if (telemetryEnabled) {
SetSentryBackend(sentryBackend);
SetSentryBuildInfo({
commitHash: SENTRY_RELEASE,
majorMinor: GetMajorMinorVersion(),
version: GetBuildVersion(),
});
SENTRY.Instance().Init();
}
// The error boundary only sees render and commit. Nearly everything here is a
// pointer handler, a key handler or an await — none of which reach a boundary,
// all of which were going to a console nobody reads.
if (telemetryEnabled) installGlobalErrorHandlers();
// Anonymous usage counts (screens, active minutes, referrer). Nothing is sent
// without VITE_POSTHOG_KEY, with privacy.usage_stats off, or under DNT/GPC.
if (telemetryEnabled) startUsageStats();
// KiCad's scrollbars are GTK3 overlay scrollbars: no layout cost, invisible
// until the pointer is inside that scrolled window, a 3 px indicator that
// thickens near the edge. shell.css turns the browser's permanent 15 px ones
// off; this draws GTK's. Installed at boot rather than per editor because every
// frame in KiCad gets them from the theme, not from its own code.
installOverlayScrollbars();
// `Fit()` once, then `SetSizeHints()` — the two lines every KiCad dialog ends
// with. `.ze-modal` ports the first as `width: max-content`, which keeps
// tracking the content forever, so a dialog moved under the user whenever its
// own text changed. Installed here rather than per dialog because in wx it
// comes from the dialog base class, not from the dialog.
installDialogSizeHints();
// PGM_BASE::InitPgm: the program object exists before any frame does.
InitPgm();
setUiLanguage(settings.common.system.language);
settings.subscribe(() => setUiLanguage(settings.common.system.language));
// DisplayErrorMessage (common/confirm.cpp): the modal error box common/ code raises.
InstallErrorPresenter();
InstallQuestionPresenter();
InstallInfoPresenter();
InstallMessageDialogPresenter();
// wxFileDialog, for the dialogs in common/ that open one (common/wx/filedlg.tsx).
// The chooser's `kind` is its own set of shared folders; common passes a string.
SetFileDialog((p) => (
<OpenFileDialog {...p} kind={p.kind as Parameters<typeof OpenFileDialog>[0]['kind']} />
));
// ...and its wxFD_SAVE form, the Save As chooser every editor's Save As opens.
SetSaveFileDialog((p) => (
<SaveAsDialog {...p} kind={p.kind as Parameters<typeof SaveAsDialog>[0]['kind']} />
));
// `textWidth` measures an outline face with the glyphs the renderer fills
// (#154); until a face has loaded both sides fall back to the stroke font.
installOutlineFontProvider();
// The real storage test, at boot. storageAvailable() only proves the API
// exists; this proves a write/read/delete round-trip lands. Without it the
// first a user hears of a full or read-only origin is a save failing mid-edit,
// which is the case storageHealth.ts was written to catch — the function was
// documented as the boot check and nothing ever called it.
//
// Fire-and-forget on purpose: a rejection is already reported through the
// health layer, and a storage probe must never be able to stop the app booting.
void checkStorageHealth().catch(() => undefined);
// Edit Template opens a template as a project; this is what sends each save
// back into the template it came from, so editing a template edits the template
// rather than forking it. Installed here rather than imported by the project
// store, which would point that dependency backwards - see setTemplateSink.
setTemplateSink((templateId, files, projectName) =>
updateUserTemplateFiles(templateId, files, projectName).then(() => undefined),
);
// The cloud store works against an interface so its failure paths are reachable
// from tests; this is where the real transport goes in. Without Supabase
// configured nothing is installed and every cloud call refuses loudly, which is
// correct: `sync.ts` gates on `authEnabled` and never makes one.
if (authEnabled) setCloudBackend(supabaseBackend());
import { PlatformErrorBoundary } from './platform/PlatformErrorBoundary.js';
import { PlatformApp } from './platform/PlatformApp.js';
import './platform/platform.css';
const root = document.getElementById('root');
if (!root) throw new Error('Missing #root element');
// Before anything renders. An unsupported browser otherwise gets a white
// screen: a TypeError out of a file the user has never heard of, and nothing
// on the page to say whether the app is broken or their browser is. The crash
// screen cannot help, because the failure is usually before React mounts.
const missing = missingFeatures();
if (missing.length > 0) {
root.textContent = unsupportedMessage(missing);
root.setAttribute(
'style',
'padding:2rem;max-width:40rem;margin:0 auto;white-space:pre-wrap;line-height:1.5',
);
} else {
// Outermost first:
// ErrorBoundary, catches throws from every layer below, gate and auth alike.
// DesktopGate, a phone that can't run the editors is turned away before we
// ask it to sign in (and before auth touches the network).
// StorageBanner, sibling of the auth tree, so a storage failure is shouted
// about whether or not the user is signed in, but inside the
// gate, so a turned-away phone isn't warned about an app it
// is not running.
// The image handlers InitPgm registered come first: an image decodes as its file is read, so
// they are ready before any frame can open one. A handler that cannot load is reported and the
// app comes up without it, as wx does with an image type it has no handler for.
void wxInitAllImageHandlers()
.catch((aError: unknown) => console.error('wxInitAllImageHandlers:', aError))
.then(() => {
createRoot(root).render(
<StrictMode>
<ErrorBoundary>
<DesktopGate>
<AuthProvider>
<AuthGate>
<App />
</AuthGate>
</AuthProvider>
<StorageBanner />
{/* One tooltip layer for the whole document. It draws every tooltip
in the app, including the ~460 plain `title` attributes across the
editors and dialogs, by borrowing the attribute for the duration
of the hover (see ui/Tooltip.tsx). Mounted here rather than inside
App because App returns early for the restore screen and for the
project manager, so a layer in its final return never reaches
either of them. */}
<TooltipLayer />
{/* ACTIONS::listHotKeys is AS_GLOBAL: one dialog and one Ctrl+F1, above
every frame, rather than a copy in each editor. */}
<HotkeyListHost />
</DesktopGate>
</ErrorBoundary>
</StrictMode>,
);
});
}
if (!root) throw new Error('Missing #root');
createRoot(root).render(
<PlatformErrorBoundary>
<PlatformApp />
</PlatformErrorBoundary>,
);
+1 -1
View File
@@ -79,7 +79,7 @@ export type Route =
view?: Exclude<ProjectView, 'manager'>;
child?: ChildFrame;
}
| { kind: 'tool'; tool: ToolName }
| { kind: 'tool'; tool: ToolName; file?: string }
/**
* The sign-in wall, whose step is part of the address like every other place
* in the app.
+5 -3
View File
@@ -52,10 +52,11 @@ export interface Nav {
*/
const NAV_EVENT = 'ziro:navigate';
export function useRoute(): Nav {
export function useRoute(enabled = true): Nav {
const [route, setRoute] = useState<Route>(here);
useEffect(() => {
if (!enabled) return;
// Back and Forward. Without this the address changes and the app does not,
// which is worse than not having addresses at all.
const onPop = (): void => setRoute(here());
@@ -65,7 +66,7 @@ export function useRoute(): Nav {
window.removeEventListener('popstate', onPop);
window.removeEventListener(NAV_EVENT, onPop);
};
}, []);
}, [enabled]);
// Canonicalise once, on the first render that has a window.
//
@@ -74,11 +75,12 @@ export function useRoute(): Nav {
// address into the form the app writes. `replaceState`, so the pre-canonical
// address is not a Back target that would bounce straight back here.
useEffect(() => {
if (!enabled) return;
const canonical = hrefFor(route);
if (canonical !== window.location.pathname + window.location.search) {
window.history.replaceState(window.history.state, '', canonical);
}
}, [route]);
}, [route, enabled]);
const navigate = useCallback<Nav['navigate']>((to, opts) => {
// Against the ADDRESS, not against the last render's route: a navigation
+144
View File
@@ -0,0 +1,144 @@
// SPDX-License-Identifier: GPL-3.0-or-later
import { useEffect, useState } from 'react';
import { Modal, NameForm, errorText, useTr } from './ui.js';
import { importFiles, safePath } from './archive.js';
import { WorkspaceError, type NativeProject, type PcbProjectApi } from './types.js';
interface Source {
id: string;
title: string;
files: string[];
base: string;
}
/** Catalogs contain public engineering data only, never the legacy user store. */
export default function CatalogImport({
api,
close,
create,
}: {
api: PcbProjectApi;
close: () => void;
create: (name: string, project: NativeProject, requestId: string) => Promise<void>;
}): JSX.Element {
const tr = useTr();
const [kind, setKind] = useState<'templates' | 'demos'>('templates');
const [rows, setRows] = useState<Source[]>([]),
[selected, setSelected] = useState('');
const [error, setError] = useState(''),
[loading, setLoading] = useState(true);
const [base, setBase] = useState(''),
[id] = useState(() => crypto.randomUUID());
useEffect(() => {
const controller = new AbortController();
setLoading(true);
setError('');
setRows([]);
setSelected('');
void (async () => {
const host =
kind === 'templates'
? `${import.meta.env.BASE_URL}templates`
: (await import('../libraryHosts.js')).DEMOS_HOST;
const response = await fetch(`${host}/index.json`, { signal: controller.signal });
if (!response.ok) throw new Error('无法加载模板或示例,请重试。');
const json = await response.json();
const items = json[kind] as Source[];
if (!Array.isArray(items)) throw new Error('目录格式不正确。');
const visible = items.filter(
(s) => !['jetson-agx-thor-baseboard', 'vme-wren'].includes(s.id),
);
if (!controller.signal.aborted) {
setRows(visible);
setBase(host);
setSelected(visible[0]?.id ?? '');
}
})()
.catch((e) => {
if (!controller.signal.aborted) setError(errorText(e));
})
.finally(() => {
if (!controller.signal.aborted) setLoading(false);
});
return () => controller.abort();
}, [kind]);
return (
<Modal title={tr('从模板或示例创建', 'Create from template or example')} close={close}>
<div className="vm-form">
<label>
{tr('来源', 'Source')}
<select value={kind} onChange={(e) => setKind(e.target.value as typeof kind)}>
<option value="templates">{tr('工程模板', 'Project templates')}</option>
<option value="demos">{tr('示例工程', 'Example projects')}</option>
</select>
</label>
{loading ? (
<p role="status">{tr('正在读取目录…', 'Loading catalog…')}</p>
) : (
<label>
{tr('工程', 'Project')}
<select value={selected} onChange={(e) => setSelected(e.target.value)}>
{rows.map((s) => (
<option key={s.id} value={s.id}>
{s.title}
</option>
))}
</select>
</label>
)}
{error && (
<p role="alert" className="vm-error">
{error}
</p>
)}
</div>
<NameForm
key={`${kind}:${selected}`}
initial={rows.find((s) => s.id === selected)?.title ?? ''}
cancel={close}
label={tr('创建并打开', 'Create and open')}
submit={async (name) => {
const source = rows.find((s) => s.id === selected);
if (!source || loading) throw new Error('请选择工程。');
const limits = await api.capabilities();
if (source.files.length > limits.maxFileCount)
throw new WorkspaceError('PCB_TOO_MANY_FILES');
const files = [];
let total = 0;
const encodePath = (path: string): string =>
safePath(path).split('/').map(encodeURIComponent).join('/');
for (const path of source.files) {
const response = await fetch(`${base}/${encodePath(source.id)}/${encodePath(path)}`, {
signal: AbortSignal.timeout(30000),
});
if (!response.ok) throw new Error(`资源读取失败: ${path}`);
const chunks: Uint8Array[] = [];
let size = 0;
const reader = response.body?.getReader();
if (!reader) throw new Error('资源响应缺少内容。');
try {
for (;;) {
const { value, done } = await reader.read();
if (done) break;
size += value.length;
total += value.length;
if (size > limits.maxFileBytes || total > limits.maxUnpackedBytes)
throw new WorkspaceError('PCB_UNPACKED_TOO_LARGE');
chunks.push(value);
}
} finally {
await reader.cancel();
}
const bytes = new Uint8Array(size);
let offset = 0;
for (const part of chunks) {
bytes.set(part, offset);
offset += part.length;
}
files.push({ name: path, bytes });
}
const project = importFiles(files, limits);
await create(name, project, id);
}}
/>
</Modal>
);
}
+17
View File
@@ -0,0 +1,17 @@
// SPDX-License-Identifier: GPL-3.0-or-later
export function CircuitIcon(): JSX.Element {
return (
<svg
width="32"
height="32"
viewBox="0 0 32 32"
fill="none"
stroke="currentColor"
strokeWidth="1.5"
aria-hidden="true"
>
<rect x="9" y="9" width="14" height="14" rx="3" />
<path d="M12 3v6m8-6v6M12 23v6m8-6v6M3 12h6m-6 8h6m14-8h6m-6 8h6M13 13h6v6h-6z" />
</svg>
);
}
+70
View File
@@ -0,0 +1,70 @@
// SPDX-License-Identifier: GPL-3.0-or-later
import { useEffect, useState } from 'react';
import { App } from '../App.js';
import type { PlatformBridge } from './bridge.js';
import { installProjectSnapshotHost } from '@ziroeda/common/project_snapshot.js';
import { installPlatformFileSystem } from '../fs/project_store_fs.js';
import { workspaceFileSystem } from './filesystem.js';
import { initializeEditorEnvironment } from './editor-environment.js';
import { errorText } from './ui.js';
import { settings } from '../prefs/settings.js';
import { setUiLanguage } from '@ziroeda/common/i18n.js';
import type { Locale } from './ui.js';
import { TooltipLayer } from '@ziroeda/common/widgets/tooltip.js';
import { HotkeyListHost } from '../ui/hotkey_list_host.js';
import { installAccountResources } from './account-resources.js';
import { missingFeatures, unsupportedMessage } from '../browser_support.js';
export default function EditorHost({
bridge,
locale,
}: {
bridge: PlatformBridge;
locale: Locale;
}): JSX.Element {
const runtime = bridge.runtime;
const [ready, setReady] = useState(false),
[error, setError] = useState<unknown>(null);
useEffect(() => {
let cancelled = false;
const uninstallHost = installProjectSnapshotHost(runtime);
const uninstallFs = installPlatformFileSystem(workspaceFileSystem(runtime));
const uninstallResources = installAccountResources(runtime);
settings.setPlatformOwner(runtime.ownerUserCode);
void initializeEditorEnvironment(runtime.ownerUserCode).then(
() => {
if (cancelled) return;
const missing = missingFeatures().filter(
(m) => !['local storage of projects', 'cross-tab locking'].includes(m.feature),
);
if (missing.length) setError(new Error(unsupportedMessage(missing, true)));
else setReady(true);
},
(e: unknown) => {
if (!cancelled) setError(e);
},
);
return () => {
cancelled = true;
uninstallFs();
uninstallHost();
uninstallResources();
};
}, [runtime]);
useEffect(() => {
setUiLanguage(locale === 'zh' ? 'zh_CN' : 'en');
settings.common.system.language = locale === 'zh' ? '简体中文' : 'English';
}, [locale]);
return error ? (
<div role="alert">{errorText(error)}</div>
) : ready ? (
<>
<App platform={bridge} />
<TooltipLayer />
<HotkeyListHost />
</>
) : (
<div className="vm-loading" role="status">
正在初始化编辑环境…
</div>
);
}
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,52 @@
// SPDX-License-Identifier: GPL-3.0-or-later
import { Component, type ReactNode } from 'react';
import type { WorkspaceRuntime } from './runtime.js';
import { downloadBytes, errorText, messageText } from './ui.js';
/** Lightweight outer boundary: no editor imports on the project list. */
export class PlatformErrorBoundary extends Component<
{ children: ReactNode; runtime?: WorkspaceRuntime },
{ error: Error | null; recoveryError?: string }
> {
override state: { error: Error | null; recoveryError?: string } = { error: null };
static getDerivedStateFromError(error: Error): { error: Error } {
return { error };
}
override render(): ReactNode {
if (!this.state.error) return this.props.children;
return (
<div className="vm-platform">
<main className="vm-empty" role="alert">
<h1>{messageText('页面发生错误')}</h1>
<p>
{messageText(
'请先保留当前页面。再次打开时可恢复已落盘草稿,最后尚未序列化的操作可能无法恢复。',
)}
</p>
<pre>{this.state.error.message}</pre>
{this.props.runtime && (
<button
onClick={() => {
const runtime = this.props.runtime!;
void import('./archive-client.js')
.then(async ({ packProject }) => {
const archive = await packProject(
runtime.nativeProject(),
'recovery',
runtime.limits,
runtime.abort.signal,
);
downloadBytes(archive.bytes, 'pcb-recovery.zip');
})
.catch((error: unknown) => this.setState({ recoveryError: errorText(error) }));
}}
>
{messageText('下载当前已序列化副本')}
</button>
)}
{this.state.recoveryError && <p role="alert">{this.state.recoveryError}</p>}
<button onClick={() => location.reload()}>{messageText('重新加载')}</button>
</main>
</div>
);
}
}
+312
View File
@@ -0,0 +1,312 @@
// SPDX-License-Identifier: GPL-3.0-or-later
import {
useEffect,
useRef,
useState,
type CSSProperties,
type MouseEvent,
type ReactNode,
} from 'react';
import { AVATAR_PALETTE, SITE_NAV } from '../assets/site-brand/navigation.js';
import { SiteIcon } from './SiteIcon.js';
import type { PlatformUser } from './types.js';
import { useTr, type Locale } from './ui.js';
import '../assets/site-brand/css/fonts.css';
import '../assets/site-brand/css/navigation.css';
import '../assets/site-brand/css/cad.css';
import './site-header.css';
const ENGLISH_NAV: Record<string, string> = {
home: 'Home',
explore: 'Community',
studio: 'Studio',
workspace: 'My projects',
};
/** Website design, PCB account/session callbacks. Never boots the old site shell. */
export function PlatformHeader({
user,
locale,
setLocale,
siteLink,
openProjects,
login,
logout,
editor = false,
children,
status,
}: {
user: PlatformUser | null;
locale: Locale;
setLocale: (locale: Locale) => void;
siteLink: (event: MouseEvent<HTMLAnchorElement>) => void;
openProjects: () => void;
login: () => void;
logout: () => void;
editor?: boolean;
children?: ReactNode;
status?: ReactNode;
}): JSX.Element {
const tr = useTr();
const [menu, setMenu] = useState(false);
const [sheet, setSheet] = useState(false);
const [scrolled, setScrolled] = useState(false);
const shell = useRef<HTMLDivElement>(null);
const account = useRef<HTMLDivElement>(null);
const accountButton = useRef<HTMLButtonElement>(null);
const sheetButton = useRef<HTMLButtonElement>(null);
const search = useRef<HTMLAnchorElement>(null);
useEffect(() => {
const scrollArea = shell.current?.parentElement;
const onScroll = (): void => setScrolled((scrollArea?.scrollTop ?? 0) > 20);
onScroll();
scrollArea?.addEventListener('scroll', onScroll, { passive: true });
return () => scrollArea?.removeEventListener('scroll', onScroll);
}, []);
useEffect(() => {
const onPointer = (event: PointerEvent): void => {
if (!account.current?.contains(event.target as Node)) setMenu(false);
};
const onKey = (event: KeyboardEvent): void => {
if (event.key === 'Escape') {
if (menu) accountButton.current?.focus();
if (sheet) sheetButton.current?.focus();
setMenu(false);
setSheet(false);
}
if (!editor && (event.metaKey || event.ctrlKey) && event.key.toLowerCase() === 'k') {
event.preventDefault();
// Community search belongs to the main site and uses its leave guard.
search.current?.click();
}
};
document.addEventListener('pointerdown', onPointer);
document.addEventListener('keydown', onKey);
return () => {
document.removeEventListener('pointerdown', onPointer);
document.removeEventListener('keydown', onKey);
};
}, [menu, sheet, editor]);
// biome-ignore lint/correctness/useExhaustiveDependencies: account identity is the trigger; an old account's menus must close on account switch.
useEffect(() => {
setMenu(false);
setSheet(false);
}, [user?.userCode]);
const link = (event: MouseEvent<HTMLAnchorElement>): void => {
setMenu(false);
setSheet(false);
siteLink(event);
};
const projects = (): void => {
setMenu(false);
setSheet(false);
openProjects();
};
const language = (): void => {
setLocale(locale === 'zh' ? 'en' : 'zh');
setMenu(false);
setSheet(false);
};
const name = user?.nickname || user?.email || user?.userCode || '?';
let hash = 0;
for (const ch of user?.userCode || user?.nickname || '?')
hash = (hash * 31 + ch.charCodeAt(0)) >>> 0;
const navigation = SITE_NAV.map((item) => (
<a
key={item.id}
href={item.id === 'pcb' ? import.meta.env.BASE_URL : item.href}
data-desktop-only={item.desktopOnly || undefined}
className={item.id === 'pcb' ? 'active' : undefined}
aria-current={item.id === 'pcb' ? 'page' : undefined}
onClick={
item.id === 'pcb'
? (event) => {
event.preventDefault();
projects();
}
: link
}
>
{locale === 'en' ? ENGLISH_NAV[item.id] || item.label : item.label}
</a>
));
const signIn = (
<button className="btn btn-sm btn-primary" onClick={login}>
{tr('登录', 'Sign in')}
</button>
);
return (
<div
ref={shell}
className={`vm-site-shell${editor ? ' cad-editor vm-workbar' : ''}`}
lang={locale === 'zh' ? 'zh-CN' : 'en'}
>
<header className={`nav${scrolled ? ' scrolled' : ''}${sheet ? ' open' : ''}`}>
<div className="nav-inner">
<a
className="nav-logo"
href={editor ? import.meta.env.BASE_URL : '/'}
aria-label={
editor ? tr('返回项目列表', 'Back to projects') : tr('make 首页', 'make home')
}
onClick={
editor
? (event) => {
event.preventDefault();
projects();
}
: link
}
>
<img
src={`${import.meta.env.BASE_URL}brand/make-web-384.png`}
srcSet={[256, 384, 512, 768]
.map((width) => `${import.meta.env.BASE_URL}brand/make-web-${width}.png ${width}w`)
.join(', ')}
sizes={editor ? '92px' : '(max-width: 820px) 96px, 112px'}
alt="make"
width={editor ? 92 : 112}
height={editor ? 34 : 42}
/>
</a>
{editor ? (
children
) : (
<nav className="nav-links" aria-label={tr('网站导航', 'Website navigation')}>
{navigation}
</nav>
)}
<div className="nav-actions">
{editor ? (
status
) : (
<>
<a
ref={search}
className="nav-search"
href="/explore/?focus=1"
onClick={link}
aria-label={tr('搜索社区项目', 'Search community projects')}
>
<SiteIcon name="search" size={15} />
<span>{tr('搜索', 'Search')}</span>
<kbd>⌘K</kbd>
</a>
<a
className="btn btn-sm btn-ghost hide-sm site-publish"
href="/#publish"
onClick={link}
title={tr('前往主站发布项目', 'Publish a project on the main website')}
>
<SiteIcon name="upload" size={14} />
{tr('发布项目', 'Publish')}
</a>
</>
)}
<div className={`site-account${editor ? '' : ' hide-sm'}`} ref={account}>
{user ? (
<>
<button
ref={accountButton}
className="nav-user"
title={user.email}
aria-expanded={menu}
aria-controls="pcb-account-menu"
onClick={() => setMenu(!menu)}
>
<span
className="avatar"
style={
{ '--c': AVATAR_PALETTE[hash % AVATAR_PALETTE.length] } as CSSProperties
}
aria-hidden="true"
>
{name.slice(0, 1).toUpperCase()}
</span>
<span>{name}</span>
</button>
{menu && (
<div
className="user-pop"
id="pcb-account-menu"
aria-label={tr('账号菜单', 'Account menu')}
>
<div className="who">
<b>{name}</b>
<small>{user.email}</small>
</div>
<button onClick={projects}>
<SiteIcon name="cube" size={15} />
{tr('我的 PCB 项目', 'My PCB projects')}
</button>
{!editor && (
<button onClick={language}>
<SiteIcon name="globe" size={15} />
{locale === 'zh' ? 'English' : '简体中文'}
</button>
)}
<button
onClick={() => {
setMenu(false);
logout();
}}
>
<SiteIcon name="arrow" size={15} />
{tr('退出登录', 'Sign out')}
</button>
</div>
)}
</>
) : (
signIn
)}
</div>
{!editor && !user && (
<button
className="btn btn-sm btn-ghost hide-sm"
onClick={language}
aria-label={tr('切换为英文', 'Switch to Chinese')}
>
{locale === 'zh' ? 'EN' : '中文'}
</button>
)}
{!editor && (
<button
ref={sheetButton}
className="icon-btn nav-menu"
aria-label={tr('菜单', 'Menu')}
aria-expanded={sheet}
aria-controls="pcb-site-menu"
onClick={() => setSheet(!sheet)}
>
<SiteIcon name="menu" size={20} />
</button>
)}
</div>
</div>
{!editor && (
<nav className="sheet" id="pcb-site-menu" aria-label={tr('网站菜单', 'Website menu')}>
{navigation}
<div className="sheet-actions">
<button className="btn" onClick={language}>
{locale === 'zh' ? 'English' : '简体中文'}
</button>
{user ? (
<button
className="btn"
onClick={() => {
setSheet(false);
logout();
}}
>
{tr('退出登录', 'Sign out')}
</button>
) : (
signIn
)}
</div>
</nav>
)}
</header>
</div>
);
}
+421
View File
@@ -0,0 +1,421 @@
// SPDX-License-Identifier: GPL-3.0-or-later
import { lazy, Suspense, useEffect, useState } from 'react';
import type { NativeProject, PcbProject, PcbProjectApi } from './types.js';
import { Modal, NameForm, errorText, useTr } from './ui.js';
import { CircuitIcon } from './CircuitIcon.js';
import { SiteIcon } from './SiteIcon.js';
import '../assets/site-brand/css/cad.css';
const CatalogImport = lazy(() => import('./CatalogImport.js'));
export function ProjectList({
api,
open,
create,
importProject,
}: {
api: PcbProjectApi;
open: (p: PcbProject) => void;
create: (name: string, requestId: string) => Promise<void>;
importProject: (name: string, project: NativeProject, requestId: string) => Promise<void>;
}): JSX.Element {
const tr = useTr();
const [catalog, setCatalog] = useState(false);
const [page, setPage] = useState(1),
[search, setSearch] = useState(''),
[keyword, setKeyword] = useState(''),
[refresh, setRefresh] = useState(0);
const [result, setResult] = useState<{ items: PcbProject[]; total: number } | null>(null),
[error, setError] = useState<unknown>(null),
[loading, setLoading] = useState(true);
const [dialog, setDialog] = useState<{
kind: 'create' | 'rename' | 'delete' | 'import';
project?: PcbProject;
requestId: string;
} | null>(null);
const [imported, setImported] = useState<NativeProject | null>(null),
[importError, setImportError] = useState(''),
[importBusy, setImportBusy] = useState(false),
[deleteBusy, setDeleteBusy] = useState(false);
useEffect(() => {
const timer = setTimeout(() => {
setKeyword(search.trim());
setPage(1);
}, 250);
return () => clearTimeout(timer);
}, [search]);
// biome-ignore lint/correctness/useExhaustiveDependencies: refresh explicitly retries the same list request after a mutation or failure.
useEffect(() => {
let alive = true;
setLoading(true);
setError(null);
void api
.list(page, keyword)
.then(
(data) => {
if (alive) {
if (!data.items.length && page > 1 && data.total > 0)
setPage(Math.max(1, Math.ceil(data.total / 20)));
else setResult(data);
}
},
(e: unknown) => {
if (alive) setError(e);
},
)
.finally(() => {
if (alive) setLoading(false);
});
return () => {
alive = false;
};
}, [api, page, keyword, refresh]);
const close = (): void => {
setDialog(null);
setImported(null);
setImportError('');
};
const selectFiles = async (files: FileList | null): Promise<void> => {
if (!files?.length) return;
setImportBusy(true);
setImportError('');
setImported(null);
try {
const limits = await api.capabilities();
const selected = [...files];
if (
selected.length > limits.maxFileCount ||
selected.reduce((n, f) => n + f.size, 0) > limits.maxUnpackedBytes
)
throw new Error(tr('导入工程超过容量限制。', 'The project exceeds the import limits.'));
const project =
selected.length === 1 && /\.zip$/i.test(selected[0]!.name)
? await (await import('./archive-client.js')).unpackProject(
new Uint8Array(await selected[0]!.arrayBuffer()),
limits,
false,
)
: (await import('./archive.js')).importFiles(
await Promise.all(
selected.map(async (file) => ({
name: file.webkitRelativePath || file.name,
bytes: new Uint8Array(await file.arrayBuffer()),
})),
),
limits,
);
setImported(project);
} catch (e) {
setImportError(errorText(e));
} finally {
setImportBusy(false);
}
};
return (
<main className="vm-projects cad-main vm-cad-list">
<div className="cad-heading">
<div>
<p className="cad-eyebrow">VIBEMAKE PCB</p>
<h1>{tr('我的 PCB 项目', 'My PCB projects')}</h1>
</div>
<div className="vm-project-actions">
<button
className="btn btn-sm"
onClick={() => setDialog({ kind: 'import', requestId: crypto.randomUUID() })}
>
{tr('导入工程', 'Import project')}
</button>
<button className="btn btn-sm" onClick={() => setCatalog(true)}>
{tr('模板与示例', 'Templates and examples')}
</button>
<button
className="btn btn-primary"
onClick={() => setDialog({ kind: 'create', requestId: crypto.randomUUID() })}
>
<SiteIcon name="plus" />
{tr('新建项目', 'New project')}
</button>
</div>
</div>
<label className="cad-search">
<SiteIcon name="search" />
<input
type="search"
maxLength={100}
placeholder={tr('搜索项目名称', 'Search projects')}
aria-label={tr('搜索项目', 'Search projects')}
value={search}
onChange={(e) => setSearch(e.target.value)}
/>
</label>
{loading ? (
<div
className="cad-grid"
aria-label={tr('正在加载项目', 'Loading projects')}
aria-busy="true"
>
{[1, 2, 3, 4, 5, 6].map((id) => (
<div key={id} className="cad-card vm-skeleton" />
))}
</div>
) : error ? (
<div className="cad-state" role="alert">
<h2>{tr('项目加载失败', 'Could not load projects')}</h2>
<p>{errorText(error)}</p>
<button className="btn btn-primary" onClick={() => setRefresh((n) => n + 1)}>
{tr('重试', 'Retry')}
</button>
</div>
) : !result?.items.length ? (
<div className="cad-state">
<span className="vm-empty-mark" aria-hidden="true">
<CircuitIcon />
</span>
<h2>
{keyword
? tr('没有找到相关项目', 'No matching projects')
: tr('从你的第一块电路板开始', 'Start with your first board')}
</h2>
<p>
{keyword
? tr('试试其他名称。', 'Try another name.')
: tr(
'新建空白工程,或导入已有的 KiCad 设计。',
'Create a blank project or import a KiCad design.',
)}
</p>
<button
className="btn btn-primary"
onClick={() =>
keyword
? setSearch('')
: setDialog({ kind: 'create', requestId: crypto.randomUUID() })
}
>
{keyword ? tr('清除搜索', 'Clear search') : tr('新建项目', 'New project')}
</button>
</div>
) : (
<>
<div className="cad-grid">
{result.items.map((project) => (
<article className="cad-card" key={project.pcbProjectCode}>
<a
className="cad-card-art"
href={`${import.meta.env.BASE_URL}p/${encodeURIComponent(project.pcbProjectCode)}/pcb`}
aria-label={`${tr('打开项目', 'Open project')} ${project.name}`}
onClick={(event) => {
event.preventDefault();
open(project);
}}
>
<CircuitIcon />
</a>
<div className="cad-card-body">
<h2>{project.name}</h2>
<small>
{project.savedAt
? `${tr('最近保存', 'Last saved')} ${new Date(project.savedAt).toLocaleString()}`
: tr('尚未保存到云端', 'Not saved to cloud')}
</small>
<div className="cad-card-actions">
<button className="btn btn-sm" onClick={() => open(project)}>
{tr('打开', 'Open')}
</button>
<button
className="btn btn-sm"
onClick={() =>
setDialog({ kind: 'rename', project, requestId: crypto.randomUUID() })
}
aria-label={`${tr('重命名', 'Rename')} ${project.name}`}
title={tr('重命名', 'Rename')}
>
<SiteIcon name="edit" />
</button>
<button
className="btn btn-sm"
onClick={() =>
setDialog({ kind: 'delete', project, requestId: crypto.randomUUID() })
}
aria-label={`${tr('删除', 'Delete')} ${project.name}`}
title={tr('删除', 'Delete')}
>
<SiteIcon name="trash" />
</button>
</div>
</div>
</article>
))}
</div>
<nav className="cad-pagination" aria-label={tr('分页', 'Pagination')}>
<button className="btn btn-sm" disabled={page === 1} onClick={() => setPage(page - 1)}>
{tr('上一页', 'Previous')}
</button>
<span>
{page} / {Math.max(1, Math.ceil(result.total / 20))}
</span>
<button
className="btn btn-sm"
disabled={page * 20 >= result.total}
onClick={() => setPage(page + 1)}
>
{tr('下一页', 'Next')}
</button>
</nav>
</>
)}
{catalog && (
<Suspense fallback={<p role="status">{tr('正在加载…', 'Loading…')}</p>}>
<CatalogImport api={api} close={() => setCatalog(false)} create={importProject} />
</Suspense>
)}
{dialog && (
<Modal
title={
dialog.kind === 'rename'
? tr('重命名项目', 'Rename project')
: dialog.kind === 'delete'
? tr('删除项目', 'Delete project')
: dialog.kind === 'import'
? tr('导入工程', 'Import project')
: tr('新建 PCB 项目', 'New PCB project')
}
close={close}
busy={importBusy || deleteBusy}
>
{dialog.kind === 'delete' ? (
<div className="vm-form">
<p>
{tr('确定删除', 'Delete')}「{dialog.project!.name}」?
{tr('此操作无法撤销。', 'This cannot be undone.')}
</p>
{importError && (
<p role="alert" className="vm-error">
{importError}
</p>
)}
<footer>
<button onClick={close} disabled={deleteBusy}>
{tr('取消', 'Cancel')}
</button>
<button
className="danger"
disabled={deleteBusy}
onClick={() => {
setDeleteBusy(true);
void api
.remove(dialog.project!.pcbProjectCode)
.then(
() => {
close();
setRefresh((n) => n + 1);
},
(e: unknown) => setImportError(errorText(e)),
)
.finally(() => setDeleteBusy(false));
}}
>
{deleteBusy ? tr('正在删除…', 'Deleting…') : tr('删除项目', 'Delete project')}
</button>
</footer>
</div>
) : (
<>
{dialog.kind === 'import' && (
<div className="vm-import">
<p>
{tr(
'选择原生 KiCad ZIP、目录,或原理图 / PCB 文件。',
'Choose a native KiCad ZIP, directory, schematic or board.',
)}
</p>
<label>
{tr('选择文件', 'Choose files')}
<input
type="file"
multiple
accept=".zip,.kicad_pcb,.kicad_sch,.kicad_pro"
disabled={importBusy}
onChange={(e) => void selectFiles(e.target.files)}
/>
</label>
<label>
{tr('选择目录', 'Choose directory')}
<input
type="file"
multiple
{...{ webkitdirectory: '' }}
disabled={importBusy}
onChange={(e) => void selectFiles(e.target.files)}
/>
</label>
{importBusy ? (
<p role="status">{tr('正在检查工程…', 'Checking project…')}</p>
) : (
imported && (
<>
<p>
{imported.files.length} {tr('个文件已通过检查', 'files checked')}
</p>
{(['project', 'board', 'schematic'] as const).map((kind) => {
const suffix = {
project: '.kicad_pro',
board: '.kicad_pcb',
schematic: '.kicad_sch',
}[kind];
const candidates = imported.files.filter((f) => f.name.endsWith(suffix));
return candidates.length > 1 ? (
<label key={kind}>
{tr('主入口', 'Main entry')} ({kind})
<select
value={imported.roots[kind] ?? ''}
onChange={(e) =>
setImported({
...imported,
roots: { ...imported.roots, [kind]: e.target.value },
})
}
>
{candidates.map((f) => (
<option key={f.name}>{f.name}</option>
))}
</select>
</label>
) : null;
})}
</>
)
)}
{importError && (
<p role="alert" className="vm-error">
{importError}
</p>
)}
</div>
)}
<NameForm
key={dialog.requestId}
initial={dialog.project?.name}
label={
dialog.kind === 'import'
? tr('导入并打开', 'Import and open')
: tr('确认', 'Confirm')
}
cancel={close}
submit={async (name) => {
if (dialog.kind === 'rename') {
await api.rename(dialog.project!.pcbProjectCode, name);
close();
setRefresh((n) => n + 1);
} else if (dialog.kind === 'import') {
if (!imported)
throw new Error(tr('请先选择工程文件。', 'Choose a project first.'));
await importProject(name, imported, dialog.requestId);
} else await create(name, dialog.requestId);
}}
/>
</>
)}
</Modal>
)}
</main>
);
}
+30
View File
@@ -0,0 +1,30 @@
// SPDX-License-Identifier: GPL-3.0-or-later
import { createElement } from 'react';
import { SITE_ICONS } from '../assets/site-brand/navigation.js';
export function SiteIcon({
name,
size = 18,
}: {
name: keyof typeof SITE_ICONS;
size?: number;
}): JSX.Element {
return (
<svg
className="ic"
width={size}
height={size}
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
strokeWidth="1.7"
strokeLinecap="round"
strokeLinejoin="round"
aria-hidden="true"
>
{SITE_ICONS[name].map((shape) =>
createElement(shape.tag, { ...shape.attributes, key: JSON.stringify(shape) }),
)}
</svg>
);
}
@@ -0,0 +1,77 @@
// SPDX-License-Identifier: GPL-3.0-or-later
import type { WorkspaceRuntime } from './runtime.js';
import { readValue, storageKey } from './storage.js';
import type { WorkspaceFile } from './types.js';
import { USER_DIRS } from '../fs/chooser_places.js';
/** Collect used private resources after every mounted editor has serialized. */
export function installAccountResources(runtime: WorkspaceRuntime): () => void {
return runtime.register('resource-collector', {
flush: async () => {
const text = runtime
.getFiles()
.filter((f) => /\.(?:kicad_sch|kicad_pcb|kicad_mod)$/.test(f.name))
.map((f) => new TextDecoder().decode(f.bytes))
.join('\n');
const nicknames = new Set<string>();
for (const match of text.matchAll(
/\(\s*(?:lib_id|footprint)\s+"([^":]+):|\(\s*property\s+"Footprint"\s+"([^":]+):/g,
))
nicknames.add(match[1] ?? match[2]!);
const load = async (root: string): Promise<WorkspaceFile[]> => {
try {
return (
(await readValue<WorkspaceFile[]>(
'libraries',
storageKey(runtime.ownerUserCode, root.replace(/^\//, '')),
)) ?? []
);
} catch {
runtime.storageUnavailable();
return [];
}
};
const decoder = new TextDecoder();
for (const file of await load(USER_DIRS.symbols)) {
const nickname = file.name
.split('/')
.pop()!
.replace(/\.kicad_sym$/i, '');
if (
nicknames.has(nickname) &&
/\.kicad_sym$/i.test(file.name) &&
!runtime.getFiles().some((f) => f.name === `symbols/${nickname}.kicad_sym`)
)
runtime.storeLibrary('symbols', nickname, decoder.decode(file.bytes));
}
for (const file of await load(USER_DIRS.footprints)) {
const match = file.name.match(/(?:^|\/)([^/]+)\.pretty\/([^/]+)\.kicad_mod$/i);
if (
match &&
nicknames.has(match[1]!) &&
!runtime
.getFiles()
.some((f) => f.name === `footprints/${match[1]}.pretty/${match[2]}.kicad_mod`)
)
runtime.storeLibrary('footprints', match[1]!, decoder.decode(file.bytes), match[2]);
}
const models = await load(USER_DIRS.models3d);
for (const file of runtime.getFiles()) {
if (!/\.(?:kicad_pcb|kicad_mod)$/i.test(file.name)) continue;
let content = decoder.decode(file.bytes);
for (const model of models) {
const reference = `${USER_DIRS.models3d}/${model.name}`;
const name = `models3d/account/${model.name}`;
if (!content.includes(JSON.stringify(reference))) continue;
runtime.writeFile(name, model.bytes);
content = content.replaceAll(
JSON.stringify(reference),
JSON.stringify(`\${KIPRJMOD}/${name}`),
);
}
runtime.writeTextFiles([{ name: file.name, text: content }]);
}
runtime.assertActive();
},
});
}
+331
View File
@@ -0,0 +1,331 @@
// SPDX-License-Identifier: GPL-3.0-or-later
import {
WorkspaceError,
DEFAULT_LIMITS,
copyBytes,
platformTime,
validProjectCode,
type AuthRecord,
type Capabilities,
type PcbProject,
type PcbProjectApi,
type ProjectDocument,
type SaveReceipt,
type UploadRequest,
type UploadSignature,
} from './types.js';
export function apiBase(): string {
const configured = import.meta.env.VITE_PCB_API_BASE;
if (configured) return configured.replace(/\/$/, '');
const host = location.hostname;
if (host === 'vibemake.robotquan.com') return 'https://vibemake-api.robotquan.com/api';
if (host.startsWith('dev-')) return 'https://dev-vibemake-api.robotquan.com/api';
return '/api';
}
export async function platformRequest<T>(
path: string,
token: string | null,
init: RequestInit = {},
): Promise<T> {
const headers = new Headers(init.headers);
headers.set('Accept', 'application/json');
if (token) headers.set('Authorization', `Bearer ${token}`);
if (init.body !== undefined) headers.set('Content-Type', 'application/json');
const response = await fetch(apiBase() + path, {
...init,
headers,
credentials: 'omit',
cache: 'no-store',
signal: init.signal
? AbortSignal.any([init.signal, AbortSignal.timeout(30000)])
: AbortSignal.timeout(30000),
});
const body = await response.json().catch(() => null);
if (!response.ok || !body || (body.code && body.code !== 'OK') || !Object.hasOwn(body, 'data'))
throw new WorkspaceError(
body?.code ?? 'BAD_RESPONSE',
body?.message ?? 'Request failed',
response.status,
body?.requestId ?? response.headers.get('X-Request-Id') ?? undefined,
retryDelay(response.headers.get('Retry-After')),
);
return body.data as T;
}
function retryDelay(value: string | null): number | undefined {
if (value === null) return undefined;
const delay = /^\d+$/.test(value) ? Number(value) * 1000 : Date.parse(value) - Date.now();
return Number.isFinite(delay) ? Math.max(0, delay) : undefined;
}
const path = (code: string): string => `/pcb/workspace/projects/${encodeURIComponent(code)}`;
function project(value: PcbProject): PcbProject {
if (
!value ||
!validProjectCode(value.pcbProjectCode) ||
typeof value.name !== 'string' ||
typeof value.description !== 'string' ||
(value.coverUrl !== null && typeof value.coverUrl !== 'string') ||
typeof value.hasDocument !== 'boolean' ||
!Number.isSafeInteger(value.version) ||
value.version < 0 ||
typeof value.fileName !== 'string' ||
!Number.isSafeInteger(value.sizeBytes) ||
value.sizeBytes < 0
)
throw new WorkspaceError('BAD_RESPONSE');
return {
...value,
savedAt: value.savedAt === null ? null : platformTime(value.savedAt),
createdAt: platformTime(value.createdAt),
updatedAt: platformTime(value.updatedAt),
};
}
function objectUrl(value: string): string {
let url: URL;
try {
url = new URL(value);
} catch {
throw new WorkspaceError('BAD_RESPONSE');
}
if (url.protocol !== 'https:' && !(url.protocol === 'http:' && url.origin === location.origin))
throw new WorkspaceError('BAD_RESPONSE');
if (url.username || url.password) throw new WorkspaceError('BAD_RESPONSE');
return url.href;
}
export class HttpPcbProjectApi implements PcbProjectApi {
private retryNotBefore = 0;
private uncertainCreates = new Set<string>();
constructor(
private identity: AuthRecord,
private current: () => AuthRecord | null,
private signal: AbortSignal,
) {}
private assert(): void {
const current = this.current();
if (
this.signal.aborted ||
current?.user.userCode !== this.identity.user.userCode ||
current.token !== this.identity.token
)
throw new WorkspaceError('STALE_IDENTITY');
}
private async call<T>(url: string, init?: RequestInit): Promise<T> {
this.assert();
if (Date.now() < this.retryNotBefore)
throw new WorkspaceError(
'RATE_LIMITED',
'Rate limited',
429,
undefined,
this.retryNotBefore - Date.now(),
);
try {
const value = await platformRequest<T>(url, this.identity.token, {
...init,
signal: this.signal,
});
this.assert();
return value;
} catch (error) {
this.assert();
const failure = error as WorkspaceError;
if (failure.status === 429 && failure.retryAfterMs !== undefined)
this.retryNotBefore = Date.now() + failure.retryAfterMs;
if ((error as WorkspaceError).status === 401)
window.dispatchEvent(
new CustomEvent('vm:pcb:unauthorized', { detail: this.identity.token }),
);
throw error;
}
}
async capabilities(): Promise<Capabilities> {
this.assert();
return { ...DEFAULT_LIMITS, manifestVersions: [...DEFAULT_LIMITS.manifestVersions] };
}
async list(page: number, keyword: string): ReturnType<PcbProjectApi['list']> {
const value = await this.call<Awaited<ReturnType<PcbProjectApi['list']>>>(
`/pcb/workspace/projects?${new URLSearchParams({ page: String(page), size: '20', keyword })}`,
);
if (
!value ||
!Array.isArray(value.items) ||
!Number.isSafeInteger(value.total) ||
value.total < 0 ||
!Number.isSafeInteger(value.page) ||
value.page < 1 ||
!Number.isSafeInteger(value.size) ||
value.size < 1
)
throw new WorkspaceError('BAD_RESPONSE');
return { ...value, items: value.items.map(project) };
}
async create(name: string, clientRequestId: string): Promise<PcbProject> {
this.assert();
// The published API has no create idempotency key. Do not silently repeat
// an ambiguous POST with the same form submission identifier.
if (this.uncertainCreates.has(clientRequestId)) throw new WorkspaceError('UNKNOWN_CREATION');
try {
return project(
await this.call<PcbProject>('/pcb/workspace/projects', {
method: 'POST',
body: JSON.stringify({ name, description: '' }),
}),
);
} catch (error) {
const failure = error as WorkspaceError;
if (
(!failure.status || failure.status >= 500 || failure.code === 'BAD_RESPONSE') &&
failure.code !== 'STALE_IDENTITY'
) {
this.uncertainCreates.add(clientRequestId);
throw new WorkspaceError(
'UNKNOWN_CREATION',
'Creation result unknown',
failure.status,
failure.requestId,
);
}
throw error;
}
}
async get(code: string): Promise<PcbProject> {
const value = project(await this.call<PcbProject>(path(code)));
if (value.pcbProjectCode !== code) throw new WorkspaceError('BAD_RESPONSE');
return value;
}
async rename(code: string, name: string): Promise<PcbProject> {
const value = project(
await this.call(path(code), { method: 'PATCH', body: JSON.stringify({ name }) }),
);
if (value.pcbProjectCode !== code) throw new WorkspaceError('BAD_RESPONSE');
return value;
}
async remove(code: string): Promise<void> {
await this.call(path(code), { method: 'DELETE' });
}
async document(code: string): Promise<ProjectDocument> {
const value = await this.call<Omit<ProjectDocument, 'pcbProjectCode'>>(
`${path(code)}/document`,
);
if (
!value ||
!Number.isSafeInteger(value.version) ||
value.version < 1 ||
!Number.isSafeInteger(value.sizeBytes) ||
value.sizeBytes <= 0 ||
typeof value.fileName !== 'string' ||
!value.fileName ||
value.expiresAt !== null
)
throw new WorkspaceError('BAD_RESPONSE');
objectUrl(value.downloadUrl);
return { ...value, pcbProjectCode: code };
}
async sign(code: string, request: UploadRequest): Promise<UploadSignature> {
if (
!request.fileName ||
[...request.fileName].length > 255 ||
request.fileName.includes('/') ||
request.fileName.includes('\\') ||
[...request.fileName].some((c) => c.charCodeAt(0) < 32 || c.charCodeAt(0) === 127) ||
!/\.zip$/i.test(request.fileName) ||
!Number.isSafeInteger(request.sizeBytes) ||
request.sizeBytes <= 0 ||
!Number.isSafeInteger(request.expectedVersion) ||
request.expectedVersion < 0
)
throw new WorkspaceError('PCB_INVALID_FILE');
if (request.sizeBytes > DEFAULT_LIMITS.maxArchiveBytes)
throw new WorkspaceError('PCB_FILE_TOO_LARGE');
const value = await this.call<UploadSignature>(`${path(code)}/uploads/signature`, {
method: 'POST',
body: JSON.stringify({
fileName: request.fileName,
sizeBytes: request.sizeBytes,
expectedVersion: request.expectedVersion,
}),
});
if (
!value ||
typeof value.uploadCode !== 'string' ||
!value.uploadCode ||
!value.formFields ||
typeof value.formFields !== 'object' ||
Array.isArray(value.formFields) ||
Object.values(value.formFields).some((v) => typeof v !== 'string')
)
throw new WorkspaceError('BAD_RESPONSE');
objectUrl(value.uploadUrl);
return { ...value, expiresAt: platformTime(value.expiresAt) };
}
async upload(signature: UploadSignature, bytes: Uint8Array): Promise<void> {
this.assert();
const form = new FormData();
for (const [key, value] of Object.entries(signature.formFields)) form.append(key, value);
form.append('file', new Blob([copyBytes(bytes)], { type: 'application/zip' }), 'project.zip');
const response = await fetch(objectUrl(signature.uploadUrl), {
method: 'POST',
body: form,
signal: AbortSignal.any([this.signal, AbortSignal.timeout(120000)]),
credentials: 'omit',
referrerPolicy: 'no-referrer',
});
this.assert();
if (response.status !== 200)
throw new WorkspaceError('PCB_OSS_ERROR', 'Upload failed', response.status);
}
async commit(code: string, uploadCode: string): Promise<SaveReceipt> {
const value = await this.call<SaveReceipt>(`${path(code)}/document`, {
method: 'PUT',
body: JSON.stringify({ uploadCode }),
});
if (
!value ||
value.pcbProjectCode !== code ||
!Number.isSafeInteger(value.version) ||
value.version < 1
)
throw new WorkspaceError('BAD_RESPONSE');
return { ...value, savedAt: platformTime(value.savedAt) };
}
async download(document: ProjectDocument, limits: Capabilities): Promise<Uint8Array> {
this.assert();
if (document.sizeBytes > limits.maxArchiveBytes) throw new WorkspaceError('PCB_FILE_TOO_LARGE');
const response = await fetch(objectUrl(document.downloadUrl), {
signal: AbortSignal.any([this.signal, AbortSignal.timeout(120000)]),
cache: 'no-store',
credentials: 'omit',
referrerPolicy: 'no-referrer',
});
if (!response.ok)
throw new WorkspaceError('DOWNLOAD_FAILED', 'Download failed', response.status);
const reader = response.body?.getReader();
if (!reader) throw new WorkspaceError('DOWNLOAD_FAILED');
const chunks: Uint8Array[] = [];
let size = 0;
try {
for (;;) {
const { done, value } = await reader.read();
if (done) break;
size += value.length;
if (size > document.sizeBytes || size > limits.maxArchiveBytes)
throw new WorkspaceError('PCB_FILE_TOO_LARGE');
chunks.push(value);
}
} finally {
await reader.cancel().catch(() => undefined);
}
this.assert();
const bytes = new Uint8Array(size);
let offset = 0;
for (const chunk of chunks) {
bytes.set(chunk, offset);
offset += chunk.length;
}
// The backend does not provide a ZIP hash. Verify size here, then validate
// every file against the manifest in openArchive before mounting anything.
if (size !== document.sizeBytes) throw new WorkspaceError('PCB_HASH_MISMATCH');
this.assert();
return bytes;
}
}
+46
View File
@@ -0,0 +1,46 @@
// SPDX-License-Identifier: GPL-3.0-or-later
import type { createArchive } from './archive.js';
import { WorkspaceError, type Capabilities, type NativeProject } from './types.js';
/** Each operation owns a worker so a revoked session can stop all its work. */
export function archiveOperation<T>(payload: object, signal?: AbortSignal): Promise<T> {
return new Promise((resolve, reject) => {
const worker = new Worker(new URL('./archive.worker.ts', import.meta.url), { type: 'module' });
const stop = (): void => {
worker.terminate();
signal?.removeEventListener('abort', abort);
};
const abort = (): void => {
stop();
reject(new WorkspaceError('STALE_BINDING'));
};
if (signal?.aborted) {
abort();
return;
}
signal?.addEventListener('abort', abort, { once: true });
worker.onmessage = ({ data }) => {
stop();
if (data.error) reject(new WorkspaceError(data.error.code, data.error.message));
else resolve(data.value as T);
};
worker.onerror = () => {
stop();
reject(new WorkspaceError('PCB_INVALID_ARCHIVE', 'Archive worker failed'));
};
worker.postMessage({ ...payload, id: 1 });
});
}
export const packProject = (
project: NativeProject,
build: string,
limits: Capabilities,
signal?: AbortSignal,
): ReturnType<typeof createArchive> =>
archiveOperation({ operation: 'pack', project, build, limits }, signal);
export const unpackProject = (
bytes: Uint8Array,
limits: Capabilities,
requireManifest: boolean,
signal?: AbortSignal,
): Promise<NativeProject> =>
archiveOperation({ operation: 'open', bytes, limits, requireManifest }, signal);
+360
View File
@@ -0,0 +1,360 @@
// SPDX-License-Identifier: GPL-3.0-or-later
import { Unzip, UnzipInflate, zipSync } from 'fflate';
import { parse, head } from '@ziroeda/sexpr/index.js';
import {
DEFAULT_LIMITS,
WorkspaceError,
copyBytes,
sha256,
type Capabilities,
type NativeProject,
type ProjectManifest,
type ProjectRoots,
type WorkspaceFile,
} from './types.js';
const enc = new TextEncoder();
const dec = new TextDecoder('utf-8', { fatal: true });
export const MANIFEST = 'vibemake-project.json';
export function safePath(input: string, limits: Capabilities = DEFAULT_LIMITS): string {
if (
typeof input !== 'string' ||
!input ||
input.startsWith('/') ||
input.includes('\\') ||
input.includes(':') ||
[...input].some((c) => c.charCodeAt(0) < 32 || c.charCodeAt(0) === 127)
)
throw new WorkspaceError('PCB_UNSAFE_PATH', input);
const path = input.normalize('NFC');
const parts = path.split('/');
if (parts.length > limits.maxPathDepth || parts.some((s) => !s || s === '.' || s === '..'))
throw new WorkspaceError('PCB_UNSAFE_PATH', input);
return path;
}
function transient(path: string): boolean {
return (
path
.split('/')
.some((part) => ['.git', '.history', '__MACOSX', 'node_modules'].includes(part)) ||
/(?:^|\/)(?:\.DS_Store|~.*\.lck)$|\.(?:lck|tmp|bak|kicad_prl)$|(?:^|\/)fp-info-cache$/i.test(
path,
)
);
}
export function validateFiles(
files: WorkspaceFile[],
directories: string[],
limits = DEFAULT_LIMITS,
): void {
if (files.length > limits.maxFileCount) throw new WorkspaceError('PCB_TOO_MANY_FILES');
let total = 0;
const seen = new Map<string, 'file' | 'dir'>();
for (const f of files) {
const path = safePath(f.name, limits);
const key = path.toLocaleLowerCase('en-US');
if (seen.has(key)) throw new WorkspaceError('PCB_UNSAFE_PATH', `Duplicate path: ${path}`);
seen.set(key, 'file');
total += f.bytes.length;
if (f.bytes.length > limits.maxFileBytes) throw new WorkspaceError('PCB_FILE_TOO_LARGE', path);
}
if (total > limits.maxUnpackedBytes) throw new WorkspaceError('PCB_UNPACKED_TOO_LARGE');
for (const d of directories) {
const key = safePath(d, limits).toLocaleLowerCase('en-US');
if (seen.has(key)) throw new WorkspaceError('PCB_UNSAFE_PATH', d);
seen.set(key, 'dir');
}
for (const key of seen.keys()) {
const parts = key.split('/');
for (let n = 1; n < parts.length; n++)
if (seen.get(parts.slice(0, n).join('/')) === 'file')
throw new WorkspaceError('PCB_UNSAFE_PATH', key);
}
}
export function inferRoots(files: WorkspaceFile[]): ProjectRoots {
const names = files.map((f) => f.name);
const project = names.find((n) => /\.kicad_pro$/i.test(n)) ?? null;
const stem = project?.replace(/\.kicad_pro$/i, '');
const find = (extension: string): string | null =>
names.find((n) => n === `${stem}.${extension}`) ??
names.find((n) => n.endsWith(`.${extension}`)) ??
null;
return { project, schematic: find('kicad_sch'), board: find('kicad_pcb') };
}
export function validateRoots(project: NativeProject): void {
if (
!project.roots ||
!['project', 'board', 'schematic'].every((key) => Object.hasOwn(project.roots, key))
)
throw new WorkspaceError('PCB_INVALID_MANIFEST');
if (!project.roots.board && !project.roots.schematic)
throw new WorkspaceError('PCB_INVALID_ARCHIVE', 'No native board or schematic');
const suffix = { project: '.kicad_pro', schematic: '.kicad_sch', board: '.kicad_pcb' };
for (const [kind, root] of Object.entries(project.roots)) {
if (!Object.hasOwn(suffix, kind) || (root !== null && typeof root !== 'string'))
throw new WorkspaceError('PCB_INVALID_MANIFEST');
if (root === null) continue;
const file = project.files.find((f) => f.name === root);
if (!file || !root.toLowerCase().endsWith(suffix[kind as keyof ProjectRoots]))
throw new WorkspaceError('PCB_INVALID_MANIFEST');
const text = dec.decode(file.bytes);
if (kind === 'project') {
JSON.parse(text);
} else {
try {
if (head(parse(text)) !== (kind === 'board' ? 'kicad_pcb' : 'kicad_sch')) throw new Error();
} catch {
throw new WorkspaceError('PCB_INVALID_ARCHIVE', root);
}
}
}
}
/** Only engineering wrappers are removed; paths inside the selected root stay intact. */
export function importFiles(input: WorkspaceFile[], limits = DEFAULT_LIMITS): NativeProject {
let files = input
.filter((f) => !transient(f.name) && f.name !== MANIFEST)
.map((f) => ({ name: safePath(f.name, limits), bytes: copyBytes(f.bytes) }));
validateFiles(files, [], limits);
while (
files.length &&
files.every(
(f) => f.name.includes('/') && f.name.split('/')[0] === files[0]!.name.split('/')[0],
)
) {
files = files.map((f) => ({ ...f, name: f.name.slice(f.name.indexOf('/') + 1) }));
}
const project: NativeProject = {
files,
roots: inferRoots(files),
directories: [],
libraryDependencies: [],
unresolvedDependencies: [],
};
validateRoots(project);
return project;
}
/** Streaming inflate with actual byte accounting, before allocating a full archive. */
export function unpackEntries(
bytes: Uint8Array,
limits = DEFAULT_LIMITS,
): { files: WorkspaceFile[]; directories: string[] } {
if (bytes.length > limits.maxArchiveBytes) throw new WorkspaceError('PCB_FILE_TOO_LARGE');
const files: WorkspaceFile[] = [];
const directories: string[] = [];
const seen = new Set<string>();
let total = 0;
let error: unknown;
let fileCount = 0;
let completed = 0;
const unzip = new Unzip((entry) => {
const dir = entry.name.endsWith('/');
const name = safePath(dir ? entry.name.slice(0, -1) : entry.name, limits);
const key = name.toLocaleLowerCase('en-US');
if (seen.has(key)) throw new WorkspaceError('PCB_UNSAFE_PATH', name);
seen.add(key);
if (seen.size > limits.maxFileCount + limits.maxFileCount * limits.maxPathDepth)
throw new WorkspaceError('PCB_TOO_MANY_FILES');
// Inspect Unix external attributes below too; never instantiate symlinks.
if (dir) {
directories.push(name);
return;
}
if (++fileCount > limits.maxFileCount + 1) throw new WorkspaceError('PCB_TOO_MANY_FILES');
if (entry.originalSize !== undefined && entry.originalSize > limits.maxFileBytes)
throw new WorkspaceError('PCB_FILE_TOO_LARGE');
const chunks: Uint8Array[] = [];
let size = 0;
entry.ondata = (err, chunk, final) => {
if (err) {
error = err;
return;
}
size += chunk.length;
total += chunk.length;
if (size > limits.maxFileBytes || total > limits.maxUnpackedBytes) {
entry.terminate();
throw new WorkspaceError('PCB_UNPACKED_TOO_LARGE');
}
chunks.push(chunk);
if (final) {
completed++;
const data = new Uint8Array(size);
let offset = 0;
for (const part of chunks) {
data.set(part, offset);
offset += part.length;
}
files.push({ name, bytes: data });
}
};
entry.start();
});
unzip.register(UnzipInflate);
// Central-directory attributes: a ZIP symlink is invalid even though this
// decoder only creates memory files. Count/bytes still come from inflation.
const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
let end = bytes.length - 22;
while (
end >= Math.max(0, bytes.length - 65557) &&
(view.getUint32(end, true) !== 0x06054b50 ||
end + 22 + view.getUint16(end + 20, true) !== bytes.length)
)
end--;
if (
end < 0 ||
end < bytes.length - 65557 ||
view.getUint16(end + 4, true) !== 0 ||
view.getUint16(end + 6, true) !== 0
)
throw new WorkspaceError('PCB_INVALID_ARCHIVE');
const count = view.getUint16(end + 10, true),
centralSize = view.getUint32(end + 12, true),
centralOffset = view.getUint32(end + 16, true);
if (
centralOffset + centralSize !== end ||
count > (limits.maxFileCount + 1) * (limits.maxPathDepth + 1)
)
throw new WorkspaceError('PCB_INVALID_ARCHIVE');
let offset = centralOffset,
declaredTotal = 0;
for (let index = 0; index < count; index++) {
if (
offset + 46 > end ||
view.getUint32(offset, true) !== 0x02014b50 ||
view.getUint16(offset + 8, true) & 1
)
throw new WorkspaceError('PCB_INVALID_ARCHIVE');
const mode = view.getUint32(offset + 38, true) >>> 16;
if ((mode & 0xf000) === 0xa000) throw new WorkspaceError('PCB_UNSAFE_PATH', 'Symlink');
const size = view.getUint32(offset + 24, true);
declaredTotal += size;
if (size > limits.maxFileBytes || declaredTotal > limits.maxUnpackedBytes)
throw new WorkspaceError('PCB_UNPACKED_TOO_LARGE');
offset +=
46 +
view.getUint16(offset + 28, true) +
view.getUint16(offset + 30, true) +
view.getUint16(offset + 32, true);
}
if (offset !== end) throw new WorkspaceError('PCB_INVALID_ARCHIVE');
try {
for (let at = 0; at < bytes.length; at += 16384)
unzip.push(bytes.subarray(at, at + 16384), at + 16384 >= bytes.length);
} catch (e) {
throw e instanceof WorkspaceError ? e : new WorkspaceError('PCB_INVALID_ARCHIVE');
}
if (error || completed !== fileCount || seen.size !== count)
throw new WorkspaceError('PCB_INVALID_ARCHIVE');
validateFiles(files, directories, { ...limits, maxFileCount: limits.maxFileCount + 1 });
return { files, directories };
}
export async function openArchive(
bytes: Uint8Array,
limits = DEFAULT_LIMITS,
requireManifest = true,
): Promise<NativeProject> {
const unpacked = unpackEntries(bytes, limits);
const manifestFile = unpacked.files.find((f) => f.name === MANIFEST);
if (!manifestFile) {
if (requireManifest) throw new WorkspaceError('PCB_INVALID_MANIFEST');
return importFiles(unpacked.files, limits);
}
let manifest: ProjectManifest;
try {
manifest = JSON.parse(dec.decode(manifestFile.bytes));
} catch {
throw new WorkspaceError('PCB_INVALID_MANIFEST');
}
if (manifest?.format !== 'vibemake-pcb-project' || manifest.schemaVersion !== 1)
throw new WorkspaceError('PCB_UNSUPPORTED_MANIFEST');
if (
!manifest.roots ||
!Array.isArray(manifest.files) ||
!Array.isArray(manifest.directories) ||
!Array.isArray(manifest.libraryDependencies) ||
!Array.isArray(manifest.unresolvedDependencies) ||
manifest.libraryDependencies.some(
(d) =>
!d ||
typeof d.kind !== 'string' ||
typeof d.id !== 'string' ||
typeof d.version !== 'string',
) ||
manifest.unresolvedDependencies.some(
(d) =>
d?.kind !== 'model3d' ||
typeof d.reference !== 'string' ||
typeof d.sourcePath !== 'string',
)
)
throw new WorkspaceError('PCB_INVALID_MANIFEST');
const files = unpacked.files.filter((f) => f.name !== MANIFEST);
validateFiles(files, manifest.directories, limits);
if (manifest.files.length !== files.length) throw new WorkspaceError('PCB_INVALID_MANIFEST');
const indexed = new Set<string>();
for (const record of manifest.files) {
if (!record || typeof record.path !== 'string')
throw new WorkspaceError('PCB_INVALID_MANIFEST');
const path = safePath(record.path, limits);
const file = files.find((f) => f.name === path);
if (
indexed.has(path) ||
!file ||
record.sizeBytes !== file.bytes.length ||
!/^[a-f0-9]{64}$/.test(record.sha256) ||
(await sha256(file.bytes)) !== record.sha256
)
throw new WorkspaceError('PCB_HASH_MISMATCH');
indexed.add(path);
}
const project: NativeProject = {
files,
roots: manifest.roots,
directories: manifest.directories,
libraryDependencies: manifest.libraryDependencies,
unresolvedDependencies: manifest.unresolvedDependencies ?? [],
};
validateRoots(project);
return project;
}
export async function createArchive(
project: NativeProject,
engineBuild: string,
limits = DEFAULT_LIMITS,
): Promise<{ bytes: Uint8Array; manifest: ProjectManifest; sha256: string }> {
const files = project.files.filter((f) => f.name !== MANIFEST && !transient(f.name));
validateFiles(files, project.directories, limits);
validateRoots({ ...project, files });
const manifest: ProjectManifest = {
format: 'vibemake-pcb-project',
schemaVersion: 1,
engineBuild,
roots: project.roots,
directories: project.directories,
libraryDependencies: project.libraryDependencies,
unresolvedDependencies: project.unresolvedDependencies,
files: await Promise.all(
files.map(async (f) => ({
path: f.name,
sizeBytes: f.bytes.length,
sha256: await sha256(f.bytes),
})),
),
};
const entries: Record<string, Uint8Array> = Object.create(null);
for (const f of files) entries[f.name] = copyBytes(f.bytes);
for (const directory of project.directories) entries[`${directory}/`] = new Uint8Array();
entries[MANIFEST] = enc.encode(JSON.stringify(manifest));
const bytes = zipSync(entries, { level: 6 });
if (bytes.length > limits.maxArchiveBytes) throw new WorkspaceError('PCB_FILE_TOO_LARGE');
return { bytes, manifest, sha256: await sha256(bytes) };
}
+24
View File
@@ -0,0 +1,24 @@
// SPDX-License-Identifier: GPL-3.0-or-later
import { createArchive, openArchive } from './archive.js';
import type { Capabilities, NativeProject } from './types.js';
type Message = { id: number; limits: Capabilities } & (
| { operation: 'pack'; project: NativeProject; build: string }
| { operation: 'open'; bytes: Uint8Array; requireManifest: boolean }
);
self.onmessage = async ({ data }: MessageEvent<Message>) => {
try {
const value =
data.operation === 'pack'
? await createArchive(data.project, data.build, data.limits)
: await openArchive(data.bytes, data.limits, data.requireManifest);
self.postMessage({ id: data.id, value });
} catch (error) {
self.postMessage({
id: data.id,
error: {
code: (error as { code?: string }).code ?? 'PCB_INVALID_ARCHIVE',
message: String(error),
},
});
}
};
+328
View File
@@ -0,0 +1,328 @@
// SPDX-License-Identifier: GPL-3.0-or-later
import {
createContext,
useCallback,
useContext,
useEffect,
useRef,
useState,
type ReactNode,
} from 'react';
import { platformRequest } from './api.js';
import { Modal, errorText, useTr } from './ui.js';
import { WorkspaceError, type AuthRecord, type PlatformUser } from './types.js';
export const MOCK = import.meta.env.DEV && import.meta.env.VITE_PCB_API_MODE === 'mock';
const KEY = MOCK ? 'vm.pcb.mock.auth' : 'vm.auth';
type AuthStatus = 'checking' | 'authenticated' | 'anonymous' | 'expired' | 'error';
interface AuthContextValue {
record: AuthRecord | null;
status: AuthStatus;
error: unknown;
loginOpen: boolean;
openLogin(): void;
closeLogin(): void;
verify(): Promise<void>;
login(email: string, captchaCode: string, answer: string): Promise<void>;
logout(): Promise<void>;
mockLogin(account: 'A' | 'B'): void;
current(): AuthRecord | null;
}
const Context = createContext<AuthContextValue | null>(null);
function read(): AuthRecord | null {
try {
const value = JSON.parse(localStorage.getItem(KEY) ?? 'null') as AuthRecord | null;
return value?.token && value.user?.userCode && Number.isFinite(value.expiresAt) ? value : null;
} catch {
return null;
}
}
function checkedUser(value: PlatformUser): PlatformUser {
if (!value?.userCode || typeof value.userCode !== 'string')
throw new WorkspaceError('BAD_RESPONSE');
return value;
}
export function PlatformAuthProvider({ children }: { children: ReactNode }): JSX.Element {
const [record, setRecord] = useState<AuthRecord | null>(read),
[status, setStatus] = useState<AuthStatus>('checking'),
[error, setError] = useState<unknown>(null),
[loginOpen, setLoginOpen] = useState(false);
const current = useRef(record),
generation = useRef(0);
const apply = useCallback((next: AuthRecord | null, persist = true) => {
generation.current++;
current.current = next;
setRecord(next);
if (persist) {
if (next) localStorage.setItem(KEY, JSON.stringify(next));
else localStorage.removeItem(KEY);
window.dispatchEvent(new Event('vm:pcb:auth'));
}
}, []);
const verify = useCallback(async () => {
const identity = read();
if (
identity?.token !== current.current?.token ||
identity?.user.userCode !== current.current?.user.userCode
)
apply(identity, false);
const run = ++generation.current;
if (!identity) {
setStatus('anonymous');
return;
}
setStatus('checking');
setError(null);
if (MOCK) {
setStatus('authenticated');
return;
}
if (identity.expiresAt <= Date.now()) {
setStatus('expired');
setLoginOpen(true);
return;
}
try {
const user = checkedUser(
await platformRequest<PlatformUser>('/users/me', identity.token, {
signal: AbortSignal.timeout(20000),
}),
);
if (run !== generation.current) return;
if (user.userCode !== identity.user.userCode) throw new WorkspaceError('BAD_RESPONSE');
apply({ ...identity, user }, false);
setStatus('authenticated');
} catch (e) {
if (run !== generation.current) return;
setError(e);
if ((e as WorkspaceError).status === 401) {
setStatus('expired');
setLoginOpen(true);
} else setStatus('error');
}
}, [apply]);
useEffect(() => {
void verify();
const storage = (e: StorageEvent): void => {
if (e.key === KEY || e.key === null) void verify();
};
const focus = (): void => {
const next = read();
if (next?.token !== current.current?.token || (next && next.expiresAt <= Date.now()))
void verify();
};
const unauthorized = (e: Event): void => {
if ((e as CustomEvent).detail === current.current?.token) {
setStatus('expired');
setLoginOpen(true);
}
};
window.addEventListener('storage', storage);
window.addEventListener('focus', focus);
window.addEventListener('vm:pcb:unauthorized', unauthorized);
const timer = setInterval(focus, 30000);
return () => {
generation.current++;
clearInterval(timer);
window.removeEventListener('storage', storage);
window.removeEventListener('focus', focus);
window.removeEventListener('vm:pcb:unauthorized', unauthorized);
};
}, [verify]);
const value: AuthContextValue = {
record,
status,
error,
loginOpen,
openLogin: () => setLoginOpen(true),
closeLogin: () => setLoginOpen(false),
verify,
current: () => current.current,
async login(email, captchaCode, answer) {
const run = ++generation.current;
const result = await platformRequest<{
token: string;
user: PlatformUser;
expiresIn: number;
}>('/auth/login', null, {
method: 'POST',
body: JSON.stringify({ email: email.trim(), captchaCode, captchaAnswer: answer.trim() }),
signal: AbortSignal.timeout(20000),
});
const user = checkedUser(
await platformRequest<PlatformUser>('/users/me', result.token, {
signal: AbortSignal.timeout(20000),
}),
);
if (run !== generation.current) throw new WorkspaceError('STALE_IDENTITY');
if (user.userCode !== checkedUser(result.user).userCode)
throw new WorkspaceError('BAD_RESPONSE');
apply({
token: result.token,
user,
expiresAt: Date.now() + (result.expiresIn || 86400) * 1000,
});
setStatus('authenticated');
setLoginOpen(false);
setError(null);
},
async logout() {
const identity = current.current;
if (!MOCK && identity)
await platformRequest('/auth/logout', identity.token, {
method: 'POST',
signal: AbortSignal.timeout(20000),
});
if (identity?.token !== current.current?.token) return;
apply(null);
setStatus('anonymous');
},
mockLogin(account) {
if (!MOCK) return;
apply({
token: `mock-${account}`,
user: {
userCode: `mock-${account}`,
nickname: `模拟账号 ${account}`,
email: `${account.toLowerCase()}@example.test`,
},
expiresAt: Date.now() + 86400000,
});
setStatus('authenticated');
setLoginOpen(false);
},
};
return (
<Context.Provider value={value}>
{children}
{loginOpen && <LoginDialog />}
</Context.Provider>
);
}
export function usePlatformAuth(): AuthContextValue {
const value = useContext(Context);
if (!value) throw new Error('Missing platform auth');
return value;
}
function LoginDialog(): JSX.Element {
const auth = usePlatformAuth(),
tr = useTr();
const [captcha, setCaptcha] = useState<{ captchaCode: string; image: string } | null>(null),
[email, setEmail] = useState(''),
[answer, setAnswer] = useState(''),
[busy, setBusy] = useState(false),
[error, setError] = useState('');
const request = useRef(0);
const refresh = useCallback(async () => {
const run = ++request.current;
setCaptcha(null);
setAnswer('');
try {
const value = await platformRequest<{ captchaCode: string; image: string }>(
'/auth/captcha',
null,
{ signal: AbortSignal.timeout(20000) },
);
if (request.current === run) setCaptcha(value);
} catch (e) {
if (request.current === run) setError(errorText(e));
}
}, []);
useEffect(() => {
if (!MOCK) void refresh();
return () => {
request.current++;
};
}, [refresh]);
return (
<Modal title={tr('登录 make', 'Sign in to make')} close={auth.closeLogin} busy={busy}>
{MOCK ? (
<div className="vm-form">
<p>
{tr(
'开发模拟账号,不影响主站登录。',
'Development accounts, separate from the website sign-in.',
)}
</p>
<button onClick={() => auth.mockLogin('A')}>
{tr('使用模拟账号 A', 'Use mock account A')}
</button>
<button onClick={() => auth.mockLogin('B')}>
{tr('使用模拟账号 B', 'Use mock account B')}
</button>
</div>
) : (
<form
className="vm-form"
onSubmit={(e) => {
e.preventDefault();
if (!captcha) {
void refresh();
return;
}
setBusy(true);
setError('');
void auth
.login(email, captcha.captchaCode, answer)
.catch(async (failure: unknown) => {
setError(errorText(failure));
await refresh();
})
.finally(() => setBusy(false));
}}
>
<label>
{tr('邮箱', 'Email')}
<input
type="email"
autoComplete="email"
maxLength={254}
value={email}
onChange={(e) => setEmail(e.target.value)}
required
autoFocus
disabled={busy}
placeholder="you@example.com"
/>
</label>
<label>
{tr('验证码', 'Image code')}
<span className="vm-captcha">
<input
value={answer}
onChange={(e) => setAnswer(e.target.value)}
maxLength={12}
autoComplete="off"
required
disabled={busy}
placeholder={tr('输入右侧字符', 'Enter the characters')}
/>
<button
type="button"
title={tr('换一张验证码', 'Refresh image')}
onClick={() => void refresh()}
disabled={busy}
>
{captcha ? (
<img src={captcha.image} alt={tr('图片验证码', 'Image code')} />
) : (
tr('重新获取', 'Retry')
)}
</button>
</span>
</label>
{error && (
<p className="vm-error" role="alert">
{error}
</p>
)}
<button className="primary" disabled={busy || !captcha}>
{busy ? tr('正在登录…', 'Signing in…') : tr('登录 / 注册', 'Sign in / Register')}
</button>
<p className="vm-muted">
{tr('首次登录会自动创建账号。', 'Your first sign-in creates an account.')}
</p>
</form>
)}
</Modal>
);
}
+11
View File
@@ -0,0 +1,11 @@
// SPDX-License-Identifier: GPL-3.0-or-later
import type { Route } from '../nav/route.js';
import type { WorkspaceRuntime } from './runtime.js';
import type { ReactNode } from 'react';
export interface PlatformBridge {
runtime: WorkspaceRuntime;
route: Route;
navigate: (route: Route, options?: { replace?: boolean }) => void;
manager: ReactNode;
}
@@ -0,0 +1,46 @@
// SPDX-License-Identifier: GPL-3.0-or-later
import {
InstallErrorPresenter,
InstallInfoPresenter,
InstallMessageDialogPresenter,
InstallQuestionPresenter,
} from '@ziroeda/common/confirm_ui.js';
import { installOverlayScrollbars } from '@ziroeda/common/widgets/overlay_scrollbars.js';
import { installDialogSizeHints } from '@ziroeda/common/dialog_shim.js';
import { installOutlineFontProvider } from '@ziroeda/common/font/outline_fonts.js';
import { SetFileDialog, SetSaveFileDialog } from '@ziroeda/wx/filedlg.js';
import { wxInitAllImageHandlers } from '@ziroeda/wx/wx_image.js';
import { InitPgm } from '../pgm_app.js';
import { SetPgm } from '@ziroeda/common/pgm_base.js';
import { OpenFileDialog } from '../fs/OpenFileDialog.js';
import { SaveAsDialog } from '../fs/SaveAsDialog.js';
let task: Promise<void> | undefined;
let owner: string | undefined;
export function initializeEditorEnvironment(nextOwner: string): Promise<void> {
if (owner !== nextOwner) {
SetPgm(null);
InitPgm();
owner = nextOwner;
}
task ??= (async () => {
installOverlayScrollbars();
installDialogSizeHints();
InitPgm();
InstallErrorPresenter();
InstallQuestionPresenter();
InstallInfoPresenter();
InstallMessageDialogPresenter();
SetFileDialog((props) => (
<OpenFileDialog
{...props}
kind={props.kind as Parameters<typeof OpenFileDialog>[0]['kind']}
/>
));
SetSaveFileDialog((props) => (
<SaveAsDialog {...props} kind={props.kind as Parameters<typeof SaveAsDialog>[0]['kind']} />
));
installOutlineFontProvider();
await wxInitAllImageHandlers();
})();
return task;
}
+175
View File
@@ -0,0 +1,175 @@
// SPDX-License-Identifier: GPL-3.0-or-later
import { dirLevel, FsError, FsErrorCode, type Entry, type FileSystem } from '../fs/filesystem.js';
import { USER_DIRS } from '../fs/chooser_places.js';
import { safePath } from './archive.js';
import { atomic, readValue, storageKey } from './storage.js';
import type { WorkspaceRuntime } from './runtime.js';
import { copyBytes, type WorkspaceFile } from './types.js';
/** One chooser tree, captured by a binding; never resolves another project by name. */
export function workspaceFileSystem(runtime: WorkspaceRuntime): FileSystem {
const base = runtime.internalName;
const userDirs = Object.values(USER_DIRS).map((p) => p.replace(/^\/+/, ''));
const resolve = (input: string): { root: string; rel: string; privateDir: boolean } => {
runtime.assertActive();
const path = input.replace(/^\//, '').replace(/\/$/, '');
if (!path) return { root: '', rel: '', privateDir: false };
safePath(path);
const [root = '', ...parts] = path.split('/');
if (root !== base && !userDirs.includes(root)) throw new FsError(FsErrorCode.NOT_FOUND, input);
return { root, rel: parts.join('/'), privateDir: root !== base };
};
const privateFiles = async (root: string): Promise<WorkspaceFile[]> =>
(await readValue<WorkspaceFile[]>('libraries', storageKey(runtime.ownerUserCode, root))) ?? [];
const privateDirs = async (root: string): Promise<string[]> =>
(await readValue<string[]>(
'libraries',
storageKey(runtime.ownerUserCode, root, 'directories'),
)) ?? [];
const updatePrivate = (
root: string,
edit: (
files: WorkspaceFile[],
directories: string[],
) => { files: WorkspaceFile[]; directories: string[] },
): Promise<void> =>
atomic(['libraries'], (tx, done, fail) => {
const store = tx.objectStore('libraries');
const key = storageKey(runtime.ownerUserCode, root),
dirsKey = storageKey(runtime.ownerUserCode, root, 'directories');
const files = store.get(key),
dirs = store.get(dirsKey);
dirs.onsuccess = () => {
try {
runtime.assertActive();
const next = edit(
(files.result as WorkspaceFile[] | undefined) ?? [],
(dirs.result as string[] | undefined) ?? [],
);
store.put(next.files, key);
store.put(next.directories, dirsKey);
done(undefined);
} catch (error) {
fail(error);
}
};
});
const rows = async (input: string): Promise<Entry[]> => {
const p = resolve(input);
if (!p.root)
return [base, ...userDirs].map((name) => ({
name,
path: `/${name}`,
kind: name === base ? 'project' : 'folder',
size: null,
modified: null,
}));
const files = p.privateDir ? await privateFiles(p.root) : runtime.getFiles();
const entries = dirLevel(
files.map((f) => ({ name: f.name, size: f.bytes.length, modified: null })),
p.rel,
`/${p.root}${p.rel ? `/${p.rel}` : ''}`,
);
for (const dir of p.privateDir
? await privateDirs(p.root)
: runtime.nativeProject().directories) {
const prefix = p.rel ? `${p.rel}/` : '';
if (!dir.startsWith(prefix)) continue;
const name = dir.slice(prefix.length).split('/')[0]!;
if (name && !entries.some((e) => e.name === name))
entries.push({
name,
path: `/${p.root}/${prefix}${name}`,
kind: 'folder',
size: null,
modified: null,
});
}
return entries;
};
const fs: FileSystem = {
list: rows,
async stat(path) {
if (path === '/') return { name: '', path, kind: 'folder', size: null, modified: null };
const at = path.lastIndexOf('/');
return (await rows(path.slice(0, at) || '/')).find((e) => e.path === path) ?? null;
},
async read(path) {
const p = resolve(path);
const files = p.privateDir ? await privateFiles(p.root) : runtime.getFiles();
const file = files.find((f) => f.name === p.rel);
if (!file) throw new FsError(FsErrorCode.NOT_FOUND, path);
runtime.assertActive();
return copyBytes(file.bytes);
},
async write(path, bytes) {
const p = resolve(path);
if (!p.rel) throw new FsError(FsErrorCode.NOT_IN_PROJECT, path);
if (p.privateDir) {
const copy = copyBytes(bytes);
await runtime.queueWrite(path, () =>
updatePrivate(p.root, (files, directories) => ({
files: [...files.filter((f) => f.name !== p.rel), { name: p.rel, bytes: copy }],
directories,
})),
);
} else runtime.writeFiles([{ name: p.rel, bytes }]);
},
async mkdir(path) {
const p = resolve(path);
if (p.privateDir) {
await runtime.queueWrite(path, () =>
updatePrivate(p.root, (files, directories) => ({
files,
directories: [...new Set([...directories, p.rel])],
})),
);
return;
}
runtime.addDirectory(p.rel);
},
async mkproject(path) {
throw new FsError(FsErrorCode.READ_ONLY, path, 'Use the platform New Project command');
},
async rename(path, name) {
safePath(name);
if (name.includes('/')) throw new FsError(FsErrorCode.INVALID, path);
const p = resolve(path);
if (!p.rel) throw new FsError(FsErrorCode.READ_ONLY, path);
const parent = p.rel.includes('/') ? p.rel.slice(0, p.rel.lastIndexOf('/') + 1) : '';
if (p.privateDir) {
const target = parent + name;
const move = (name: string): string =>
name === p.rel || name.startsWith(`${p.rel}/`) ? target + name.slice(p.rel.length) : name;
await runtime.queueWrite(path, () =>
updatePrivate(p.root, (files, directories) => {
if (files.some((f) => f.name === target) || directories.includes(target))
throw new FsError(FsErrorCode.INVALID, path);
return {
files: files.map((f) => ({ ...f, name: move(f.name) })),
directories: directories.map(move),
};
}),
);
return;
}
runtime.renamePath(p.rel, parent + name);
},
async remove(path) {
const p = resolve(path);
if (!p.rel) throw new FsError(FsErrorCode.READ_ONLY, path);
if (p.privateDir) {
const keep = (name: string): boolean => name !== p.rel && !name.startsWith(`${p.rel}/`);
await runtime.queueWrite(path, () =>
updatePrivate(p.root, (files, directories) => ({
files: files.filter((f) => keep(f.name)),
directories: directories.filter(keep),
})),
);
return;
}
runtime.removePath(p.rel);
},
};
return fs;
}
+320
View File
@@ -0,0 +1,320 @@
// SPDX-License-Identifier: GPL-3.0-or-later
/** Loaded through a DEV-only dynamic import. This is never a real server. */
import { openArchive } from './archive.js';
import { atomic, listValues, readValue, storageKey } from './storage.js';
import {
DEFAULT_LIMITS,
WorkspaceError,
copyBytes,
sha256,
validProjectName,
type Capabilities,
type PcbProject,
type PcbProjectApi,
type ProjectDocument,
type SaveReceipt,
type UploadRequest,
type UploadSignature,
} from './types.js';
interface MockProject extends PcbProject {
owner: string;
sha256?: string | null;
deleted?: boolean;
bytes?: Uint8Array;
}
interface MockUpload {
owner: string;
code: string;
request: UploadRequest;
signature: UploadSignature;
bytes?: Uint8Array;
receipt?: SaveReceipt;
}
export type MockFault =
| 'none'
| 'offline'
| 'confirmation-lost'
| 'expired'
| 'conflict'
| 'too-large';
export const mockFaults: { current: MockFault } = { current: 'none' };
const fail = (code: string): WorkspaceError =>
new WorkspaceError(code, code, code === 'NOT_FOUND' ? 404 : 409);
export class MockPcbProjectApi implements PcbProjectApi {
constructor(private owner: string) {}
private check(): void {
if (mockFaults.current === 'offline')
throw new WorkspaceError('OFFLINE', 'Development offline simulation');
}
async capabilities(): Promise<Capabilities> {
this.check();
return {
...DEFAULT_LIMITS,
maxArchiveBytes: mockFaults.current === 'too-large' ? 64 : DEFAULT_LIMITS.maxArchiveBytes,
};
}
async list(page: number, keyword: string): ReturnType<PcbProjectApi['list']> {
this.check();
const all = (await listValues<MockProject>('mockProjects'))
.filter(
(p) =>
p.owner === this.owner &&
!p.deleted &&
p.name.toLowerCase().includes(keyword.toLowerCase()),
)
.sort(
(a, b) =>
b.updatedAt.localeCompare(a.updatedAt) ||
a.pcbProjectCode.localeCompare(b.pcbProjectCode),
);
return {
items: all
.slice((page - 1) * 20, page * 20)
.map(({ owner: _owner, bytes: _bytes, ...p }) => p),
total: all.length,
page,
size: 20,
};
}
async create(name: string, clientRequestId: string): Promise<PcbProject> {
this.check();
if (!validProjectName(name)) throw fail('BAD_REQUEST');
const key = storageKey(this.owner, clientRequestId);
return atomic(['mockCreates', 'mockProjects'], (tx, done, reject) => {
const request = tx.objectStore('mockCreates').get(key);
request.onsuccess = () => {
const existing = request.result as { name: string; project: MockProject } | undefined;
if (existing) {
if (existing.name !== name) reject(fail('PCB_IDEMPOTENCY_CONFLICT'));
else done(existing.project);
return;
}
const now = new Date().toISOString();
const p: MockProject = {
owner: this.owner,
pcbProjectCode: `pcb_${crypto.randomUUID()}`,
name: name.trim(),
description: '',
coverUrl: null,
hasDocument: false,
version: 0,
fileName: '',
sizeBytes: 0,
sha256: null,
savedAt: null,
createdAt: now,
updatedAt: now,
};
tx.objectStore('mockProjects').put(p, storageKey(this.owner, p.pcbProjectCode));
tx.objectStore('mockCreates').put({ name, project: p }, key);
done(p);
};
});
}
private async record(code: string): Promise<MockProject> {
this.check();
const p = await readValue<MockProject>('mockProjects', storageKey(this.owner, code));
if (!p || p.owner !== this.owner || p.deleted) throw fail('NOT_FOUND');
return p;
}
async get(code: string): Promise<PcbProject> {
const { owner: _owner, bytes: _bytes, ...p } = await this.record(code);
return p;
}
async rename(code: string, name: string): Promise<PcbProject> {
this.check();
if (!validProjectName(name)) throw fail('BAD_REQUEST');
return atomic(['mockProjects'], (tx, done, reject) => {
const key = storageKey(this.owner, code);
const r = tx.objectStore('mockProjects').get(key);
r.onsuccess = () => {
const p = r.result as MockProject | undefined;
if (!p || p.deleted) {
reject(fail('NOT_FOUND'));
return;
}
const next = { ...p, name: name.trim(), updatedAt: new Date().toISOString() };
tx.objectStore('mockProjects').put(next, key);
done(next);
};
});
}
async remove(code: string): Promise<void> {
this.check();
return atomic(['mockProjects'], (tx, done, reject) => {
const key = storageKey(this.owner, code);
const r = tx.objectStore('mockProjects').get(key);
r.onsuccess = () => {
const p = r.result as MockProject | undefined;
if (!p || p.deleted) {
reject(fail('NOT_FOUND'));
return;
}
tx.objectStore('mockProjects').put({ ...p, deleted: true, bytes: undefined }, key);
done(undefined);
};
});
}
async document(code: string): Promise<ProjectDocument> {
const p = await this.record(code);
if (!p.bytes || !p.savedAt || !p.sha256) throw fail('PCB_DOCUMENT_NOT_FOUND');
return {
pcbProjectCode: code,
version: p.version,
fileName: 'project.zip',
sizeBytes: p.sizeBytes,
downloadUrl: `mock:${code}`,
expiresAt: null,
};
}
async sign(code: string, request: UploadRequest): Promise<UploadSignature> {
this.check();
const limits = await this.capabilities();
if (request.sizeBytes > limits.maxArchiveBytes) throw fail('PCB_FILE_TOO_LARGE');
const key = storageKey(this.owner, code, request.clientOperationId);
const signature: UploadSignature = {
uploadCode: request.clientOperationId,
uploadUrl: `mock:${code}`,
formFields: {},
expiresAt: new Date(Date.now() + 15 * 60 * 1000).toISOString(),
};
return atomic(['mockProjects', 'mockUploads'], (tx, done, reject) => {
const record = tx.objectStore('mockProjects').get(storageKey(this.owner, code));
record.onsuccess = () => {
const p = record.result as MockProject | undefined;
if (!p || p.deleted) {
reject(fail('NOT_FOUND'));
return;
}
const upload = tx.objectStore('mockUploads').get(key);
upload.onsuccess = () => {
const existing = upload.result as MockUpload | undefined;
if (existing) {
if (JSON.stringify(existing.request) !== JSON.stringify(request))
reject(fail('PCB_IDEMPOTENCY_CONFLICT'));
else done(existing.signature);
return;
}
if (p.version !== request.expectedVersion) {
reject(fail('PCB_VERSION_CONFLICT'));
return;
}
tx.objectStore('mockUploads').put(
{ owner: this.owner, code, request, signature } satisfies MockUpload,
key,
);
done(signature);
};
};
});
}
async upload(signature: UploadSignature, bytes: Uint8Array): Promise<void> {
this.check();
const code = signature.uploadUrl.slice(5);
await this.record(code);
const key = storageKey(this.owner, code, signature.uploadCode);
const upload = await readValue<MockUpload>('mockUploads', key);
if (!upload || upload.owner !== this.owner) throw fail('NOT_FOUND');
if (mockFaults.current === 'expired' || Date.parse(upload.signature.expiresAt) < Date.now())
throw fail('PCB_UPLOAD_EXPIRED');
if (
bytes.length !== upload.request.sizeBytes ||
(await sha256(bytes)) !== upload.request.sha256
)
throw fail('PCB_HASH_MISMATCH');
await openArchive(bytes);
if (upload.bytes && (await sha256(upload.bytes)) !== (await sha256(bytes)))
throw fail('PCB_IDEMPOTENCY_CONFLICT');
await atomic(['mockUploads'], (tx, done, reject) => {
const read = tx.objectStore('mockUploads').get(key);
read.onsuccess = () => {
const current = read.result as MockUpload | undefined;
if (!current || current.owner !== this.owner) {
reject(fail('NOT_FOUND'));
return;
}
if (!current.receipt)
tx.objectStore('mockUploads').put({ ...current, bytes: copyBytes(bytes) }, key);
done(undefined);
};
});
}
async commit(code: string, uploadCode: string): Promise<SaveReceipt> {
this.check();
const key = storageKey(this.owner, code, uploadCode);
const receipt = await atomic<SaveReceipt>(
['mockProjects', 'mockUploads'],
(tx, done, reject) => {
const pr = tx.objectStore('mockProjects').get(storageKey(this.owner, code));
pr.onsuccess = () => {
const p = pr.result as MockProject | undefined;
if (!p || p.deleted) {
reject(fail('NOT_FOUND'));
return;
}
const ur = tx.objectStore('mockUploads').get(key);
ur.onsuccess = () => {
const u = ur.result as MockUpload | undefined;
if (!u || u.owner !== this.owner) {
reject(fail('NOT_FOUND'));
return;
}
if (u.receipt) {
done(u.receipt);
return;
}
if (
mockFaults.current === 'expired' ||
Date.parse(u.signature.expiresAt) < Date.now()
) {
reject(fail('PCB_UPLOAD_EXPIRED'));
return;
}
if (!u.bytes) {
reject(fail('PCB_FILE_MISSING'));
return;
}
if (mockFaults.current === 'conflict' || p.version !== u.request.expectedVersion) {
reject(fail('PCB_VERSION_CONFLICT'));
return;
}
const savedAt = new Date().toISOString();
const result: SaveReceipt = {
pcbProjectCode: code,
version: p.version + 1,
savedAt,
};
tx.objectStore('mockProjects').put(
{
...p,
hasDocument: true,
version: result.version,
savedAt,
updatedAt: savedAt,
bytes: u.bytes,
sha256: u.request.sha256,
sizeBytes: u.bytes.length,
fileName: 'project.zip',
},
storageKey(this.owner, code),
);
tx.objectStore('mockUploads').put({ ...u, receipt: result }, key);
done(result);
};
};
},
);
if (mockFaults.current === 'confirmation-lost') {
mockFaults.current = 'none';
throw new WorkspaceError('NETWORK_ERROR', 'Simulated response lost after commit');
}
return receipt;
}
async download(document: ProjectDocument, limits: Capabilities): Promise<Uint8Array> {
const p = await this.record(document.pcbProjectCode);
if (!p.bytes || p.version !== document.version || p.sizeBytes !== document.sizeBytes)
throw fail('PCB_VERSION_CONFLICT');
if (p.bytes.length > limits.maxArchiveBytes) throw fail('PCB_FILE_TOO_LARGE');
return copyBytes(p.bytes);
}
}
+718
View File
@@ -0,0 +1,718 @@
/* VibeMake website tokens; native engineering canvases retain KiCad colors. */
.vm-platform {
--vm-bg: #07080a;
--vm-panel: #0f1114;
--vm-raised: #15181c;
--vm-line: #252a31;
--vm-text: #f3f4f6;
--vm-muted: #939ba6;
--vm-accent: #c8ff3e;
--vm-header-height: 64px;
min-height: 100%;
height: 100dvh;
display: flex;
flex-direction: column;
overflow-y: auto;
scrollbar-gutter: stable;
/* Native editor styles hide every scrollbar. The website's outer scroller
keeps browser defaults so loading an editor cannot move the shared nav. */
scrollbar-width: auto;
scrollbar-color: auto;
color-scheme: dark;
background: var(--vm-bg);
color: var(--vm-text);
font:
15px / 1.65 Sora,
"PingFang SC",
"Hiragino Sans GB",
"Microsoft YaHei",
system-ui,
sans-serif;
-webkit-font-smoothing: antialiased;
}
.vm-platform-editor {
--vm-header-height: 42px;
overflow: hidden;
scrollbar-gutter: auto;
}
.vm-platform::-webkit-scrollbar {
width: revert;
height: revert;
display: revert;
}
.vm-platform::-webkit-scrollbar-track,
.vm-platform::-webkit-scrollbar-thumb,
.vm-platform::-webkit-scrollbar-corner,
.vm-platform::-webkit-scrollbar-button {
display: revert;
}
.vm-platform *,
.vm-dialog * {
box-sizing: border-box;
}
.vm-platform button:not(:where(.ze-app button, .vm-site-shell button, .vm-cad-list button)),
.vm-platform input:not(:where(.ze-app input, .vm-cad-list input)),
.vm-platform select:not(:where(.ze-app select)),
.vm-dialog button,
.vm-dialog input {
font: inherit;
}
.vm-platform button:not(:where(.ze-app button, .vm-site-shell button, .vm-cad-list button)),
.vm-platform summary:not(:where(.ze-app summary)),
.vm-dialog button {
cursor: pointer;
}
.vm-platform button:not(:where(.ze-app button, .vm-site-shell button, .vm-cad-list button)),
.vm-files button,
.vm-dialog button {
min-height: 38px;
border: 1px solid var(--vm-line, #252a31);
border-radius: 8px;
padding: 7px 14px;
color: inherit;
background: var(--vm-panel, #0f1114);
transition:
background 0.15s,
border-color 0.15s;
}
.vm-platform button:hover:not(:where(.ze-app button, .vm-site-shell button, .vm-cad-list button)),
.vm-dialog button:hover {
background: var(--vm-raised, #15181c);
border-color: #59616d;
}
.vm-platform
button:disabled:not(:where(.ze-app button, .vm-site-shell button, .vm-cad-list button)),
.vm-dialog button:disabled {
opacity: 0.45;
cursor: wait;
}
.vm-platform .primary:not(:where(.ze-app .primary)),
.vm-dialog .primary {
background: var(--vm-accent, #c8ff3e);
color: #111607;
border-color: var(--vm-accent, #c8ff3e);
font-weight: 600;
}
.vm-platform .primary:hover:not(:where(.ze-app .primary)),
.vm-dialog .primary:hover {
background: #d8ff7a;
}
.vm-platform a:not(:where(.ze-app a, .vm-site-shell a, .vm-cad-list a)) {
color: inherit;
text-decoration: none;
}
.vm-platform :focus-visible:not(:where(.ze-app *)),
.vm-dialog :focus-visible {
outline: 2px solid #c8ff3e;
outline-offset: 3px;
}
.vm-platform input:not(:where(.ze-app input, .vm-cad-list input)),
.vm-platform select:not(:where(.ze-app select)),
.vm-dialog input {
background: #15181c;
border: 1px solid #343b45;
border-radius: 8px;
min-height: 42px;
color: #f3f4f6;
padding: 10px 12px;
}
.vm-platform input:not(:where(.ze-app input, .vm-cad-list input))::placeholder,
.vm-dialog input::placeholder {
color: #939ba6;
}
.vm-more > div {
position: absolute;
right: 0;
z-index: 40;
min-width: 200px;
padding: 8px;
background: var(--vm-panel);
border: 1px solid var(--vm-line);
border-radius: 10px;
box-shadow: 0 16px 40px #0008;
display: flex;
flex-direction: column;
gap: 4px;
}
.vm-platform.vm-cad-design .vm-projects {
width: 100%;
flex: none;
margin: 0 auto;
}
.vm-project-actions {
display: flex;
align-items: center;
justify-content: flex-end;
gap: 12px;
flex-wrap: wrap;
}
.vm-title {
display: flex;
justify-content: space-between;
align-items: center;
gap: 24px;
margin-bottom: 32px;
}
.vm-eyebrow {
font:
11px / 1.5 "JetBrains Mono",
monospace;
letter-spacing: 2px;
color: var(--vm-accent);
}
.vm-title h1 {
font-size: 28px;
margin: 8px 0;
font-weight: 600;
letter-spacing: -0.6px;
}
.vm-title small {
display: inline-block;
font:
12px "JetBrains Mono",
monospace;
color: var(--vm-muted);
background: var(--vm-raised);
padding: 4px 7px;
border: 1px solid var(--vm-line);
border-radius: 5px;
vertical-align: middle;
margin-left: 8px;
}
.vm-title p,
.vm-muted {
color: var(--vm-muted, #939ba6);
}
.vm-title p {
margin: 8px 0 0;
}
.vm-list-tools {
display: flex;
justify-content: space-between;
gap: 20px;
align-items: center;
margin-bottom: 24px;
}
.vm-search {
display: flex;
align-items: center;
gap: 12px;
border: 1px solid var(--vm-line);
background: var(--vm-panel);
border-radius: 8px;
padding-left: 14px;
}
.vm-search span {
color: var(--vm-muted);
font-size: 12px;
}
.vm-search input {
border: 0;
width: 280px;
background: transparent;
}
.vm-grid {
display: grid;
grid-template-columns: repeat(3, minmax(0, 1fr));
gap: 20px;
}
.vm-card {
min-width: 0;
background: var(--vm-panel);
border: 1px solid var(--vm-line);
border-radius: 12px;
overflow: hidden;
transition: border-color 0.15s;
}
.vm-card:hover {
border-color: #4a5636;
}
.vm-card .vm-card-open {
width: 100%;
padding: 24px;
border: 0;
border-radius: 0;
text-align: left;
background: transparent;
position: relative;
}
.vm-card-icon {
display: flex;
align-items: center;
justify-content: center;
width: 48px;
height: 48px;
font-size: 30px;
color: var(--vm-accent);
background: #c8ff3e0d;
border: 1px solid #c8ff3e22;
border-radius: 10px;
margin-bottom: 24px;
}
.vm-card-tag {
position: absolute;
right: 24px;
top: 30px;
color: var(--vm-muted);
font:
11px "JetBrains Mono",
monospace;
letter-spacing: 1px;
}
.vm-card h2 {
font-size: 16px;
font-weight: 500;
margin: 0 0 8px;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.vm-card p {
color: var(--vm-muted);
font-size: 12px;
margin: 0;
}
.vm-card footer {
display: flex;
justify-content: space-between;
align-items: center;
padding: 10px 16px;
border-top: 1px solid var(--vm-line);
gap: 6px;
}
.vm-card footer button {
border: 0;
background: transparent;
padding: 4px 7px;
font-size: 12px;
}
.vm-card footer > div {
display: flex;
gap: 2px;
}
.vm-platform .danger-text,
.vm-dialog .danger-text {
color: #ff9696;
}
.vm-dialog .danger {
color: #ffb5b5;
border-color: #a94d4d;
}
.vm-empty {
text-align: center;
margin: 0 auto;
padding: 90px 28px;
max-width: 800px;
}
.vm-empty h1 {
font-size: 30px;
font-weight: 600;
}
.vm-empty h2 {
font-size: 22px;
font-weight: 500;
}
.vm-empty p {
color: var(--vm-muted);
margin: 14px auto 26px;
}
.vm-empty button {
margin: 0 5px;
}
.vm-empty-mark {
color: var(--vm-accent);
font-size: 48px;
}
.vm-pagination {
margin-top: 32px;
display: flex;
justify-content: center;
gap: 20px;
align-items: center;
color: var(--vm-muted);
}
.vm-skeleton {
min-height: 230px;
background: linear-gradient(100deg, #0f1114 30%, #191c21 50%, #0f1114 70%);
background-size: 250% 100%;
animation: vm-shimmer 1.8s infinite;
}
@keyframes vm-shimmer {
to {
background-position: -250% 0;
}
}
.vm-dialog {
--vm-line: #252a31;
--vm-panel: #0f1114;
--vm-raised: #15181c;
--vm-text: #f3f4f6;
--vm-muted: #939ba6;
--vm-accent: #c8ff3e;
background: #0f1114;
color: #f3f4f6;
border: 1px solid #343b45;
border-radius: 14px;
padding: 0;
width: min(540px, calc(100vw - 40px));
max-height: calc(100vh - 60px);
box-shadow: 0 30px 100px #000b;
font:
14px / 1.6 Sora,
"PingFang SC",
system-ui,
sans-serif;
}
.vm-dialog::backdrop {
background: #000a;
backdrop-filter: blur(5px);
}
.vm-dialog header {
display: flex;
align-items: center;
justify-content: space-between;
border-bottom: 1px solid #252a31;
padding: 18px 24px;
}
.vm-dialog h2 {
font-size: 18px;
margin: 0;
font-weight: 500;
}
.vm-dialog header button {
border: 0;
background: transparent;
font-size: 22px;
padding: 0 9px;
}
.vm-form {
padding: 24px;
display: flex;
flex-direction: column;
gap: 20px;
}
.vm-form p {
margin: 0;
}
.vm-form label {
display: flex;
flex-direction: column;
gap: 8px;
}
.vm-form footer {
display: flex;
justify-content: flex-end;
gap: 10px;
flex-wrap: wrap;
}
.vm-captcha {
display: flex;
gap: 12px;
}
.vm-captcha input {
min-width: 0;
flex: 1;
}
.vm-captcha button {
width: 122px;
padding: 0;
overflow: hidden;
}
.vm-captcha img {
display: block;
width: 100%;
height: 42px;
object-fit: contain;
background: white;
}
.vm-error {
color: #ffabab;
}
.vm-import {
padding: 20px 24px 0;
}
.vm-import label {
display: block;
margin: 10px 0;
}
.vm-import input {
display: block;
width: 100%;
margin-top: 6px;
}
.vm-mock {
min-height: 38px;
display: flex;
gap: 16px;
padding: 4px 24px;
align-items: center;
justify-content: center;
background: #2e2514;
color: #f5d992;
font-size: 12px;
}
.vm-mock strong {
font-weight: 500;
}
.vm-mock button {
min-height: 28px;
padding: 2px 8px;
font-size: 12px;
}
.vm-mock label {
display: flex;
gap: 8px;
align-items: center;
}
.vm-mock select {
min-height: 28px;
padding: 2px 8px;
max-width: 240px;
}
.vm-notice,
.vm-warning {
display: flex;
align-items: center;
gap: 12px;
padding: 10px 24px;
background: #20271a;
color: #daefbb;
font-size: 13px;
}
.vm-notice {
justify-content: space-between;
}
.vm-notice button {
min-height: 26px;
padding: 0 8px;
background: transparent;
}
.vm-warning {
background: #302714;
color: #f1d497;
flex-wrap: wrap;
}
.vm-warning h2 {
font-size: 16px;
}
.vm-warning p {
width: 100%;
}
.vm-warning label {
display: block;
width: 100%;
}
.vm-save-blocked {
display: flex;
flex-shrink: 0;
align-items: center;
gap: 12px;
padding: 12px 20px;
border-bottom: 1px solid #80602b;
border-left: 4px solid #f4c56a;
background: #302714;
color: #f7d998;
font-size: 14px;
line-height: 1.6;
}
.vm-save-blocked > svg {
flex-shrink: 0;
}
.vm-save-blocked > div {
flex: 1;
min-width: 0;
}
.vm-save-blocked strong {
display: block;
font-weight: 600;
}
.vm-save-blocked p {
margin: 2px 0 0;
}
.vm-save-blocked button {
flex-shrink: 0;
}
.vm-workbench {
flex: 1;
min-height: 0;
display: flex;
flex-direction: column;
}
.vm-mock ~ .vm-workbench {
min-height: 0;
}
.vm-view-tabs {
display: flex;
gap: 4px;
}
.vm-cad-design .vm-site-shell .vm-view-tabs button.selected {
background: var(--surface-2);
color: var(--accent);
}
.vm-save-status {
margin-left: auto;
font-size: 12px;
white-space: nowrap;
color: var(--vm-muted);
}
.vm-save-status.saved {
color: var(--vm-accent);
}
.vm-save-status.blocked {
color: #f4c56a;
}
.vm-save-status.failed,
.vm-save-status.conflict {
color: #ffabab;
}
.vm-more {
position: relative;
}
.vm-more summary {
padding: 4px 9px;
border-radius: 3px;
color: var(--muted);
font-size: 14px;
list-style: none;
white-space: nowrap;
}
.vm-more summary::-webkit-details-marker {
display: none;
}
.vm-more summary:hover {
background: var(--surface-2);
color: var(--text);
}
.vm-more > div {
top: 45px;
max-height: 70vh;
overflow: auto;
}
.vm-more button {
min-height: 34px;
padding: 4px 9px;
font-size: 14px;
text-align: left;
border: 0;
border-radius: 5px;
background: transparent;
}
.vm-more button:hover {
background: var(--vm-raised);
}
.vm-more hr {
width: 100%;
border: 0;
border-top: 1px solid var(--vm-line);
}
.vm-engine {
flex: 1;
min-height: 0;
overflow: hidden;
position: relative;
/* Keep native toolbars below website menus and account/input masks. */
isolation: isolate;
background: var(--vm-bg);
}
.vm-engine .ze-app {
height: 100%;
}
.vm-engine .ze-frame {
max-height: 100%;
}
.vm-engine .ze-frame-3d {
/* The website owns the viewport; the viewer fills only its editor area. */
position: absolute;
}
/* Website navigation reduces the native frame's available height. Keep the
full appearance controls reachable when a short desktop viewport compresses it. */
.vm-engine .ze-rightdock {
overflow-y: auto;
}
.vm-engine .ze-rightdock > .ze-panel.grow {
min-height: 300px;
flex-shrink: 0;
}
.vm-loading {
display: grid;
place-items: center;
min-height: 220px;
color: var(--vm-muted);
}
.vm-files {
padding: 34px;
height: 100%;
overflow: auto;
}
.vm-files h1 {
margin: 8px 0;
font-size: 24px;
}
.vm-file-add {
display: block;
margin: 24px 0;
}
.vm-file-add input {
margin-left: 12px;
}
.vm-file-list > div {
display: flex;
gap: 12px;
padding: 8px 0;
align-items: center;
border-bottom: 1px solid var(--vm-line);
}
.vm-file-list > div > button:first-child {
flex: 1;
text-align: left;
font:
12px "JetBrains Mono",
monospace;
background: transparent;
border: 0;
overflow-wrap: anywhere;
}
.vm-file-list span {
color: var(--vm-muted);
font:
12px "JetBrains Mono",
monospace;
}
.vm-file-list button {
font-size: 12px;
}
.vm-desktop-mask,
.vm-auth-mask {
position: fixed;
inset: var(--vm-header-height) 0 0;
z-index: 900;
background: #07080aef;
backdrop-filter: blur(6px);
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
padding: 40px;
text-align: center;
}
.vm-desktop-mask {
z-index: 1000;
}
.vm-desktop-mask h1 {
font-size: 26px;
}
.vm-desktop-mask p {
max-width: 540px;
color: var(--vm-muted);
}
@media (max-width: 1100px) {
.vm-grid {
grid-template-columns: repeat(2, minmax(0, 1fr));
}
}
@media (prefers-reduced-motion: reduce) {
.vm-platform * {
animation: none;
transition: none;
}
}
+100
View File
@@ -0,0 +1,100 @@
// SPDX-License-Identifier: GPL-3.0-or-later
import type { MissingResource, NativeProject } from './types.js';
const decoder = new TextDecoder();
function folder(path: string): string {
return path.includes('/') ? path.slice(0, path.lastIndexOf('/') + 1) : '';
}
function normalize(path: string): string | null {
if (path.startsWith('/') || /^[A-Za-z]:/.test(path)) return null;
const parts: string[] = [];
for (const item of path.replace(/\\/g, '/').split('/')) {
if (item === '..') {
if (!parts.length) return null;
parts.pop();
} else if (item && item !== '.') parts.push(item);
}
return parts.join('/');
}
export function resolveReference(source: string, reference: string): string | null {
if (reference.startsWith('${KIPRJMOD}/'))
return normalize(reference.slice('${KIPRJMOD}/'.length));
if (reference.includes('${') || /^\w+:/.test(reference)) return null;
return normalize(folder(source) + reference);
}
function relative(source: string, target: string): string {
const from = folder(source).split('/').filter(Boolean),
to = target.split('/');
while (from.length && to.length && from[0] === to[0]) {
from.shift();
to.shift();
}
return [...from.map(() => '..'), ...to].join('/');
}
const refs = /(\(\s*(?:model|uri|file)\s+|\(\s*property\s+"Sheetfile"\s+)("(?:\\.|[^"\\])*")/g;
/** Only native path-bearing fields are changed; placements and geometry survive. */
export function rewriteReferences(
text: string,
source: string,
nextSource: string,
move: (path: string) => string,
): string {
if (/\.kicad_pro$/i.test(source)) {
const data: unknown = JSON.parse(text);
const visit = (value: unknown): void => {
if (!value || typeof value !== 'object') return;
for (const [key, item] of Object.entries(value)) {
if (typeof item === 'string' && /^(?:page_layout_descr_file|drawing_sheet)$/i.test(key)) {
const absolute = resolveReference(source, item);
if (absolute)
(value as Record<string, unknown>)[key] = item.startsWith('${KIPRJMOD}/')
? `\${KIPRJMOD}/${move(absolute)}`
: relative(nextSource, move(absolute));
} else visit(item);
}
};
visit(data);
return JSON.stringify(data, null, 2);
}
return text.replace(refs, (all, prefix: string, quoted: string) => {
let reference: string;
try {
reference = JSON.parse(quoted);
} catch {
return all;
}
const absolute = resolveReference(source, reference);
if (!absolute) return all;
const destination = move(absolute);
if (destination === absolute && folder(source) === folder(nextSource)) return all;
return (
prefix +
JSON.stringify(
reference.startsWith('${KIPRJMOD}/')
? `\${KIPRJMOD}/${destination}`
: relative(nextSource, destination),
)
);
});
}
export function missingModels(project: NativeProject): MissingResource[] {
const result: MissingResource[] = [],
names = new Set(project.files.map((f) => f.name));
for (const file of project.files) {
if (!/\.(kicad_pcb|kicad_mod)$/i.test(file.name)) continue;
for (const match of decoder.decode(file.bytes).matchAll(/\(\s*model\s+("(?:\\.|[^"\\])*")/g)) {
let reference: string;
try {
reference = JSON.parse(match[1]!);
} catch {
continue;
}
if (/^\$\{KICAD\d*_3DMODEL_DIR\}\//.test(reference)) continue;
const resolved = resolveReference(file.name, reference),
rootResolved = reference.startsWith('${KIPRJMOD}/') ? resolved : normalize(reference);
if ((resolved && names.has(resolved)) || (rootResolved && names.has(rootResolved))) continue;
if (!result.some((r) => r.sourcePath === file.name && r.reference === reference))
result.push({ kind: 'model3d', sourcePath: file.name, reference });
}
}
return result;
}
+78
View File
@@ -0,0 +1,78 @@
// SPDX-License-Identifier: GPL-3.0-or-later
import type { Route } from '../nav/route.js';
import { safePath } from './archive.js';
import { WorkspaceError, validProjectCode, type NativeProject } from './types.js';
export interface WorkspaceRoute {
code: string | null;
editor: Route;
}
const views = new Set(['pcb', 'schematic', 'symbols', 'footprints']);
const tools = new Set(['calculator', 'drawing-sheet', 'image-converter', 'gerber']);
export function validateWorkspaceFile(route: WorkspaceRoute, project: NativeProject): void {
const editor = route.editor;
if (editor.kind !== 'project' && editor.kind !== 'tool') return;
if (!editor.file) return;
const suffix =
editor.kind === 'tool'
? editor.tool === 'drawing-sheet'
? '.kicad_wks'
: null
: (
{
pcb: '.kicad_pcb',
schematic: '.kicad_sch',
symbols: '.kicad_sym',
footprints: '.kicad_mod',
manager: null,
} as const
)[editor.view];
if (
!suffix ||
!editor.file.toLowerCase().endsWith(suffix) ||
!project.files.some((f) => f.name === editor.file)
)
throw new WorkspaceError('NOT_FOUND', `工程文件不存在或与编辑器不匹配: ${editor.file}`);
}
export function parseWorkspaceRoute(input: string, base = '/pcb/'): WorkspaceRoute {
const url = new URL(input, 'https://workspace.test');
const prefix = base.endsWith('/') ? base : `${base}/`;
if (!url.pathname.startsWith(prefix)) throw new Error('Unknown PCB route');
const tail = url.pathname.slice(prefix.length).replace(/\/$/, '');
if (!tail) return { code: null, editor: { kind: 'home' } };
const parts = tail.split('/').map(decodeURIComponent);
const [p, code, view, child] = parts;
if (p !== 'p' || !validProjectCode(code) || parts.length > 4)
throw new Error('Invalid PCB route');
const file = url.searchParams.get('f');
if (file) safePath(file);
if (view === 'tools' && child && tools.has(child))
return {
code,
editor: {
kind: 'tool',
tool: child as Extract<Route, { kind: 'tool' }>['tool'],
...(file ? { file } : {}),
},
};
if ((view && !views.has(view)) || (child && (view !== 'pcb' || child !== '3d')))
throw new Error('Unknown editor');
return {
code,
editor: {
kind: 'project',
uid: code,
view: (view ?? 'manager') as Extract<Route, { kind: 'project' }>['view'],
...(file ? { file } : {}),
...(child ? { child: '3d' as const } : {}),
},
};
}
export function workspaceHref(route: WorkspaceRoute, base = '/pcb/'): string {
if (!route.code) return base;
const root = `${base}p/${encodeURIComponent(route.code)}/`;
const editor = route.editor;
if (editor.kind === 'tool')
return `${root}tools/${editor.tool}${editor.file ? `?${new URLSearchParams({ f: editor.file })}` : ''}`;
if (editor.kind !== 'project') return root;
return `${root}${editor.view === 'manager' ? '' : editor.view}${editor.child ? '/3d' : ''}${editor.file ? `?${new URLSearchParams({ f: editor.file })}` : ''}`;
}
+675
View File
@@ -0,0 +1,675 @@
// SPDX-License-Identifier: GPL-3.0-or-later
import type {
ProjectSnapshotHost,
ProjectSnapshotParticipant,
} from '@ziroeda/common/project_snapshot.js';
import { safePath, validateFiles } from './archive.js';
import { packProject } from './archive-client.js';
import { missingModels, rewriteReferences } from './resources.js';
import { atom, head, isList, list, parse, serialize, str } from '@ziroeda/sexpr/index.js';
import { childNamed } from '@ziroeda/sexpr/query.js';
import {
removeValue,
readValue,
storageKey,
writeValue,
type DraftRecord,
type PendingSave,
} from './storage.js';
import {
WorkspaceError,
copyBytes,
equalBytes,
type Capabilities,
type NativeProject,
type PcbProject,
type PcbProjectApi,
type SaveReceipt,
type WorkspaceFile,
} from './types.js';
export type SavePhase =
| 'never'
| 'dirty'
| 'preparing'
| 'uploading'
| 'confirming'
| 'saved'
| 'blocked'
| 'failed'
| 'conflict';
export interface RuntimeState {
revision: number;
acknowledgedRevision: number;
phase: SavePhase;
inputLocked: boolean;
error: unknown;
storageWarning: boolean;
}
export interface CapturedProject {
project: NativeProject;
revision: number;
snapshotId: string;
}
export class WorkspaceRuntime implements ProjectSnapshotHost {
readonly sessionId = crypto.randomUUID();
readonly bindingId = crypto.randomUUID();
readonly localRecordId = crypto.randomUUID();
readonly scope: string;
readonly abort = new AbortController();
readonly participants = new Map<string, ProjectSnapshotParticipant>();
private files = new Map<string, Uint8Array>();
private listeners = new Set<() => void>();
private draftTimer: ReturnType<typeof setTimeout> | undefined;
private draftSequence = 0;
private saveTask: Promise<void> | null = null;
private captureTask: Promise<CapturedProject> | null = null;
private writeTail: Promise<unknown> = Promise.resolve();
private writes = new Map<string, Promise<void>>();
private pending: PendingSave | null = null;
private externalLock = false;
private currentState: RuntimeState;
private projectData: Omit<NativeProject, 'files'>;
private sourceDraft?: DraftRecord;
baseVersion: number;
command?: (action: 'open' | 'new' | 'save-as' | 'download') => void;
constructor(
readonly ownerUserCode: string,
public metadata: PcbProject,
project: NativeProject,
public api: PcbProjectApi,
readonly limits: Capabilities,
readonly build: string,
draft?: DraftRecord,
) {
this.sourceDraft = draft;
this.scope = `${ownerUserCode}:${metadata.pcbProjectCode}:${this.bindingId}`;
this.baseVersion = draft?.baseVersion ?? metadata.version;
for (const file of project.files) this.files.set(safePath(file.name), copyBytes(file.bytes));
const { files: _files, ...data } = project;
this.projectData = structuredClone(data);
this.projectData.unresolvedDependencies = missingModels(project);
this.currentState = {
revision: draft?.revision ?? 0,
acknowledgedRevision: draft?.acknowledgedRevision ?? 0,
phase:
draft && draft.revision > draft.acknowledgedRevision
? 'dirty'
: metadata.hasDocument
? 'saved'
: 'never',
inputLocked: false,
error: null,
storageWarning: false,
};
}
get code(): string {
return this.metadata.pcbProjectCode;
}
get internalName(): string {
return (
this.projectData.roots.project ??
this.projectData.roots.board ??
this.projectData.roots.schematic ??
'project'
)
.split('/')
.pop()!
.replace(/\.[^.]+$/, '');
}
get roots(): NativeProject['roots'] {
return { ...this.projectData.roots };
}
get unresolvedDependencies(): NativeProject['unresolvedDependencies'] {
return structuredClone(this.projectData.unresolvedDependencies);
}
relativePath(path: string): string {
const prefix = `/${this.internalName}/`;
return safePath(path.startsWith(prefix) ? path.slice(prefix.length) : path, this.limits);
}
adoptPending(pending: PendingSave): void {
if (pending.ownerUserCode !== this.ownerUserCode || pending.pcbProjectCode !== this.code)
throw new WorkspaceError('STALE_BINDING');
// Revision numbers belong to a session. Recovered acknowledgements may not
// clear edits made in this new session or another tab.
this.pending = structuredClone(pending);
}
getSnapshot = (): RuntimeState => this.currentState;
subscribe = (listener: () => void): (() => void) => {
this.listeners.add(listener);
return () => this.listeners.delete(listener);
};
private emit(patch: Partial<RuntimeState> = {}): void {
this.currentState = { ...this.currentState, ...patch };
for (const listener of this.listeners) listener();
}
assertActive(): void {
if (this.abort.signal.aborted) throw new WorkspaceError('STALE_BINDING');
}
/** Synchronous native mount listeners enqueue writes which snapshots must await. */
queueWrite(key: string, operation: () => Promise<void>): Promise<void> {
this.assertActive();
const task = this.writeTail
.catch(() => undefined)
.then(async () => {
this.assertActive();
await operation();
this.assertActive();
});
this.writeTail = task;
this.writes.set(key, task);
void task.then(
() => {
if (this.writes.get(key) === task) this.writes.delete(key);
},
() => this.emit({ storageWarning: true }),
);
return task;
}
setLocked(value: boolean): void {
this.externalLock = value;
this.emit({ inputLocked: value });
}
storageUnavailable(): void {
this.emit({ storageWarning: true });
}
get dirty(): boolean {
return (
!this.metadata.hasDocument ||
this.currentState.revision > this.currentState.acknowledgedRevision ||
[...this.participants.values()].some((p) => p.isDirty?.())
);
}
get hasPending(): boolean {
return this.pending !== null;
}
register(key: string, participant: ProjectSnapshotParticipant): () => void {
this.assertActive();
this.participants.set(key, participant);
return () => {
if (this.participants.get(key) === participant) this.participants.delete(key);
};
}
modified = (): void => {
if (this.abort.signal.aborted) return;
const phase = ['preparing', 'uploading', 'confirming'].includes(this.currentState.phase)
? this.currentState.phase
: 'dirty';
this.emit({ revision: this.currentState.revision + 1, phase });
clearTimeout(this.draftTimer);
this.draftTimer = setTimeout(() => {
void this.persistDraft(true);
}, 1000);
};
getFiles(): WorkspaceFile[] {
this.assertActive();
return [...this.files].map(([name, bytes]) => ({ name, bytes: copyBytes(bytes) }));
}
nativeProject(): NativeProject {
return { ...structuredClone(this.projectData), files: this.getFiles() };
}
getTextFiles(): { name: string; text: string; bytes: Uint8Array }[] {
const dec = new TextDecoder();
return this.getFiles().map((file) => ({ ...file, text: dec.decode(file.bytes) }));
}
writeFiles(files: WorkspaceFile[]): void {
this.assertActive();
const next = new Map(this.files);
for (const file of files) next.set(safePath(file.name, this.limits), file.bytes);
validateFiles(
[...next].map(([name, bytes]) => ({ name, bytes })),
this.projectData.directories,
this.limits,
);
let changed = false;
for (const file of files) {
const path = safePath(file.name, this.limits);
const prior = this.files.get(path);
if (prior && equalBytes(prior, file.bytes)) continue;
this.files.set(path, copyBytes(file.bytes));
changed = true;
}
if (changed) this.modified();
}
writeTextFiles(files: { name: string; text: string }[]): void {
this.writeFiles(files.map((f) => ({ name: f.name, bytes: new TextEncoder().encode(f.text) })));
}
addDirectory(path: string): void {
this.assertActive();
const name = safePath(path);
if (!this.projectData.directories.includes(name)) {
this.projectData.directories.push(name);
this.modified();
}
}
removePath(path: string): void {
this.assertActive();
const name = safePath(path);
for (const [kind, root] of Object.entries(this.projectData.roots))
if (root === name || root?.startsWith(`${name}/`))
throw new WorkspaceError('ROOT_FILE', `Cannot delete active ${kind}`);
for (const key of this.files.keys())
if (key === name || key.startsWith(`${name}/`)) this.files.delete(key);
this.projectData.directories = this.projectData.directories.filter(
(d) => d !== name && !d.startsWith(`${name}/`),
);
this.modified();
}
renamePath(from: string, to: string): void {
this.assertActive();
const source = safePath(from),
destination = safePath(to);
if (source === destination) return;
if (destination.startsWith(`${source}/`)) throw new WorkspaceError('PCB_UNSAFE_PATH');
const move = (path: string): string =>
path === source
? destination
: path.startsWith(`${source}/`)
? destination + path.slice(source.length)
: path;
if (
![...this.files.keys(), ...this.projectData.directories].some(
(n) => n === source || n.startsWith(`${source}/`),
)
)
throw new WorkspaceError('NOT_FOUND');
if (this.files.has(destination) || this.projectData.directories.includes(destination))
throw new WorkspaceError('PCB_UNSAFE_PATH');
const next = this.getFiles().map((file) => ({
name: move(file.name),
bytes:
/\.(?:kicad_pro|kicad_sch|kicad_pcb|kicad_mod)$|(?:^|\/)(?:sym|fp|design-block)-lib-table$/.test(
file.name,
)
? new TextEncoder().encode(
rewriteReferences(
new TextDecoder().decode(file.bytes),
file.name,
move(file.name),
move,
),
)
: file.bytes,
}));
const directories = this.projectData.directories.map(move);
validateFiles(next, directories, this.limits);
this.files = new Map(next.map((f) => [f.name, f.bytes]));
this.projectData.directories = directories;
for (const key of ['project', 'board', 'schematic'] as const) {
const root = this.projectData.roots[key];
if (root) this.projectData.roots[key] = move(root);
}
this.projectData.unresolvedDependencies = missingModels(this.nativeProject());
this.modified();
}
setRoots(roots: NativeProject['roots']): void {
this.assertActive();
this.projectData.roots = { ...roots };
this.modified();
}
writeFile(path: string, bytes: Uint8Array): void {
this.writeFiles([{ name: path, bytes }]);
}
storeLibrary(
kind: 'symbols' | 'footprints',
nickname: string,
text: string,
itemName?: string,
): void {
const id = safePath(nickname || 'Project');
if (id.includes('/')) throw new WorkspaceError('PCB_UNSAFE_PATH');
const name =
kind === 'symbols'
? `symbols/${id}.kicad_sym`
: `footprints/${id}.pretty/${safePath(itemName || 'Footprint')}.kicad_mod`;
const tableName = kind === 'symbols' ? 'sym-lib-table' : 'fp-lib-table';
const root = kind === 'symbols' ? 'sym_lib_table' : 'fp_lib_table';
const prior = this.files.get(tableName);
const ast = prior ? parse(new TextDecoder().decode(prior)) : list(atom(root));
const rows = ast.items.filter((node) => {
if (!isList(node) || head(node) !== 'lib') return true;
const value = childNamed(node, 'name')?.items[1];
return !value || value.kind === 'list' || value.value !== id;
});
const uri = `\${KIPRJMOD}/${kind === 'symbols' ? name : `footprints/${id}.pretty`}`;
rows.push(
list(
atom('lib'),
list(atom('name'), str(id)),
list(atom('type'), str('KiCad')),
list(atom('uri'), str(uri)),
list(atom('options'), str('')),
list(atom('descr'), str('')),
),
);
this.writeTextFiles([
{ name, text },
{ name: tableName, text: serialize(list(...rows)) },
]);
}
updateMissing(resources: NativeProject['unresolvedDependencies']): void {
this.projectData.unresolvedDependencies = resources;
}
private assertSnapshotReady(): void {
if ([...this.participants.values()].some((p) => p.isBusy?.()))
throw new WorkspaceError('SNAPSHOT_BUSY');
}
async capture(localOnly = false): Promise<CapturedProject> {
if (this.captureTask) return this.captureTask;
this.captureTask = (async () => {
this.assertActive();
if (this.externalLock && !localOnly) throw new WorkspaceError('UNAUTHORIZED');
// A command can stay active until the user presses Esc. Never hide that
// prerequisite behind a preparation spinner; keep the editor interactive
// and report it immediately. Local drafts retry on their next idle tick.
this.assertSnapshotReady();
this.emit({ inputLocked: true });
try {
const priority = (key: string): number =>
key === 'resource-collector' ? 2 : key === 'app-frames' ? 1 : 0;
const ordered = [...this.participants.entries()].sort(
([a], [b]) => priority(a) - priority(b),
);
await Promise.all(this.writes.values());
for (const [, participant] of ordered) {
await participant.flush();
await Promise.all(this.writes.values());
this.assertActive();
}
const project = this.nativeProject();
project.unresolvedDependencies = missingModels(project);
this.projectData.unresolvedDependencies = project.unresolvedDependencies;
validateFiles(project.files, project.directories, this.limits);
return { project, revision: this.currentState.revision, snapshotId: crypto.randomUUID() };
} finally {
if (!this.abort.signal.aborted) this.emit({ inputLocked: this.externalLock });
}
})();
try {
return await this.captureTask;
} finally {
this.captureTask = null;
}
}
async persistDraft(flush = false): Promise<void> {
if (this.abort.signal.aborted) return;
const sequence = ++this.draftSequence;
try {
const captured = flush
? await this.capture(true)
: { project: this.nativeProject(), revision: this.currentState.revision };
const draft: DraftRecord = {
...captured.project,
ownerUserCode: this.ownerUserCode,
pcbProjectCode: this.code,
sessionId: this.sessionId,
baseVersion: this.baseVersion,
revision: captured.revision,
acknowledgedRevision: this.currentState.acknowledgedRevision,
updatedAt: Date.now(),
};
if (sequence !== this.draftSequence || this.abort.signal.aborted) return;
await writeValue('drafts', storageKey(this.ownerUserCode, this.code, this.sessionId), draft);
if (this.sourceDraft) {
await removeValue(
'drafts',
storageKey(this.ownerUserCode, this.code, this.sourceDraft.sessionId),
);
this.sourceDraft = undefined;
}
} catch (error) {
if ((error as WorkspaceError).code === 'SNAPSHOT_BUSY' && !this.abort.signal.aborted) {
clearTimeout(this.draftTimer);
this.draftTimer = setTimeout(() => {
void this.persistDraft(true);
}, 1000);
}
if ((error as WorkspaceError).code !== 'SNAPSHOT_BUSY' && !this.abort.signal.aborted)
this.emit({ storageWarning: true });
}
}
private async persistPending(): Promise<void> {
if (!this.pending) return;
try {
await writeValue(
'pending',
storageKey(this.ownerUserCode, this.code, this.pending.request.clientOperationId),
this.pending,
);
} catch {
this.emit({ storageWarning: true });
}
}
private async acknowledge(pending: PendingSave, receipt: SaveReceipt): Promise<void> {
this.assertActive();
if (
receipt.pcbProjectCode !== this.code ||
!pending.signature?.uploadCode ||
receipt.version !== pending.request.expectedVersion + 1
)
throw new WorkspaceError('BAD_RESPONSE');
this.baseVersion = receipt.version;
this.metadata = {
...this.metadata,
hasDocument: true,
version: receipt.version,
savedAt: receipt.savedAt,
updatedAt: receipt.savedAt,
sizeBytes: pending.bytes.length,
fileName: pending.request.fileName,
};
this.pending = null;
const sameSession = pending.sessionId === this.sessionId;
const acknowledged = sameSession ? pending.revision : this.currentState.acknowledgedRevision;
this.emit({
acknowledgedRevision: Math.max(this.currentState.acknowledgedRevision, acknowledged),
phase: this.currentState.revision > acknowledged ? 'dirty' : 'saved',
error: null,
});
await removeValue(
'pending',
storageKey(this.ownerUserCode, this.code, pending.request.clientOperationId),
).catch(() => this.emit({ storageWarning: true }));
await writeValue('cache', storageKey(this.ownerUserCode, this.code, receipt.version), {
ownerUserCode: this.ownerUserCode,
pcbProjectCode: this.code,
version: receipt.version,
sha256: pending.request.sha256,
bytes: pending.bytes,
}).catch(() => this.emit({ storageWarning: true }));
if (!sameSession) {
const key = storageKey(this.ownerUserCode, this.code, pending.sessionId);
const draft = await readValue<DraftRecord>('drafts', key).catch(() => undefined);
if (draft && draft.baseVersion === pending.request.expectedVersion) {
await writeValue('drafts', key, {
...draft,
baseVersion: receipt.version,
acknowledgedRevision: Math.max(draft.acknowledgedRevision, pending.revision),
}).catch(() => this.emit({ storageWarning: true }));
}
}
if (sameSession || this.currentState.revision > 0) await this.persistDraft();
}
save = (): Promise<void> => {
if (this.saveTask) return this.saveTask;
this.saveTask = this.performSave().finally(() => {
this.saveTask = null;
});
return this.saveTask;
};
private async performSave(): Promise<void> {
try {
this.assertActive();
if (this.externalLock) throw new WorkspaceError('UNAUTHORIZED');
if (!this.pending) {
// Do not enter "preparing" unless a new snapshot can actually start.
// Confirming an existing upload does not require a new snapshot.
this.assertSnapshotReady();
this.emit({ phase: 'preparing', error: null });
const captured = await this.capture();
const packed = await packProject(
captured.project,
this.build,
await this.api.capabilities(),
this.abort.signal,
);
this.assertActive();
this.pending = {
ownerUserCode: this.ownerUserCode,
pcbProjectCode: this.code,
sessionId: this.sessionId,
snapshotId: captured.snapshotId,
revision: captured.revision,
bytes: packed.bytes,
request: {
fileName: 'project.zip',
sizeBytes: packed.bytes.length,
sha256: packed.sha256,
expectedVersion: this.baseVersion,
clientOperationId: crypto.randomUUID(),
archiveFormat: 'vibemake-pcb-project+zip',
manifestVersion: 1,
},
createdAt: Date.now(),
};
await this.persistPending();
}
for (let attempt = 0; attempt < 2; attempt++) {
const p: PendingSave = this.pending!;
const retryingUpload = Boolean(p.signature);
this.emit({ phase: 'uploading' });
if (!p.signature) {
p.signature = await this.api.sign(this.code, p.request);
this.assertActive();
await this.persistPending();
}
// Only a recovered/retried batch needs probing first. A fresh batch
// uploads before confirming, as required by the backend contract.
if (retryingUpload)
try {
this.emit({ phase: 'confirming' });
const receipt = await this.api.commit(this.code, p.signature.uploadCode);
await this.acknowledge(p, receipt);
return;
} catch (error) {
this.assertActive();
const code = (error as WorkspaceError).code;
if (['PCB_UPLOAD_EXPIRED', 'PCB_FILE_SIZE_MISMATCH'].includes(code) && attempt === 0) {
await removeValue(
'pending',
storageKey(this.ownerUserCode, this.code, p.request.clientOperationId),
).catch(() => undefined);
this.pending = {
...p,
request: { ...p.request, clientOperationId: crypto.randomUUID() },
signature: undefined,
};
await this.persistPending();
continue;
}
if (code !== 'PCB_FILE_MISSING') throw error;
}
this.emit({ phase: 'uploading' });
let uploadError: unknown;
try {
await this.api.upload(p.signature, p.bytes);
} catch (error) {
uploadError = error;
}
this.assertActive();
this.emit({ phase: 'confirming' });
try {
const receipt = await this.api.commit(this.code, p.signature.uploadCode);
await this.acknowledge(p, receipt);
return;
} catch (error) {
if (
['PCB_UPLOAD_EXPIRED', 'PCB_FILE_SIZE_MISMATCH'].includes(
(error as WorkspaceError).code,
) &&
attempt === 0
) {
await this.abandonPending();
this.pending = {
...p,
request: { ...p.request, clientOperationId: crypto.randomUUID() },
signature: undefined,
};
await this.persistPending();
continue;
}
if (uploadError && (error as WorkspaceError).code === 'PCB_FILE_MISSING')
throw uploadError;
throw error;
}
}
} catch (error) {
if (!this.abort.signal.aborted)
this.emit({
phase:
(error as WorkspaceError).code === 'SNAPSHOT_BUSY'
? 'blocked'
: (error as WorkspaceError).code === 'PCB_VERSION_CONFLICT'
? 'conflict'
: 'failed',
error,
});
throw error;
}
}
async discardDraft(): Promise<void> {
await removeValue('drafts', storageKey(this.ownerUserCode, this.code, this.sessionId));
if (this.sourceDraft) {
await removeValue(
'drafts',
storageKey(this.ownerUserCode, this.code, this.sourceDraft.sessionId),
);
this.sourceDraft = undefined;
}
}
async abandonPending(): Promise<void> {
if (this.pending)
await removeValue(
'pending',
storageKey(this.ownerUserCode, this.code, this.pending.request.clientOperationId),
);
this.pending = null;
}
async resolveModel(
missing: NativeProject['unresolvedDependencies'][number],
file: File,
): Promise<void> {
await this.capture();
this.assertActive();
if (file.size > this.limits.maxFileBytes) throw new WorkspaceError('PCB_FILE_TOO_LARGE');
let name = `models3d/${safePath(file.name)}`;
if (this.files.has(name)) name = `models3d/${crypto.randomUUID()}-${file.name}`;
const bytes = new Uint8Array(await file.arrayBuffer());
this.assertActive();
const source = this.files.get(missing.sourcePath);
if (!source) throw new WorkspaceError('NOT_FOUND');
const text = new TextDecoder()
.decode(source)
.replace(/(\(\s*model\s+)("(?:\\.|[^"\\])*")/g, (all, prefix: string, quoted: string) => {
try {
return JSON.parse(quoted) === missing.reference
? prefix + JSON.stringify(`\${KIPRJMOD}/${name}`)
: all;
} catch {
return all;
}
});
this.writeFiles([
{ name, bytes },
{ name: missing.sourcePath, bytes: new TextEncoder().encode(text) },
]);
this.projectData.unresolvedDependencies = missingModels(this.nativeProject());
}
revoke(): void {
clearTimeout(this.draftTimer);
this.abort.abort();
this.participants.clear();
this.listeners.clear();
this.files.clear();
}
}
+59
View File
@@ -0,0 +1,59 @@
/* Layout integration only. All navigation metrics come from the website's
synchronized navigation.css, not a second PCB navigation theme. */
.vm-site-shell {
flex: none;
position: sticky;
top: 0;
z-index: 50;
height: var(--nav);
background: var(--bg);
}
.vm-site-shell .site-account {
position: relative;
}
.vm-site-shell .user-pop {
position: absolute;
top: calc(100% + 8px);
right: 0;
}
.vm-site-shell .nav-user .avatar {
width: 28px;
height: 28px;
font-size: 12px;
}
.vm-site-shell .who small {
overflow-wrap: anywhere;
}
.vm-site-shell .nav-links {
white-space: nowrap;
}
/* CAD's editor header is fixed on the standalone CAD page. PCB places the same
compact header in its flex workspace so notices do not cover the document. */
.vm-cad-design .vm-site-shell.cad-editor {
height: var(--nav);
overflow: visible;
}
.vm-cad-design .vm-site-shell.cad-editor .nav {
position: relative;
inset: auto;
}
/* Keep the main site's desktop metrics at full width. On the narrow desktop
range above the existing 820px editing limit, collapse secondary actions
before allowing Chinese menu labels to wrap or the account to leave screen. */
@media (min-width: 821px) and (max-width: 1100px) {
.vm-site-shell:not(.cad-editor) .nav-inner {
gap: 24px;
padding: 0 20px;
}
.vm-site-shell .nav-search span,
.vm-site-shell .nav-search kbd,
.vm-site-shell .nav-actions > .site-publish {
display: none;
}
.vm-site-shell .nav-search {
width: 40px;
height: 40px;
padding: 0;
justify-content: center;
}
}
+167
View File
@@ -0,0 +1,167 @@
// SPDX-License-Identifier: GPL-3.0-or-later
import type { NativeProject, SaveReceipt, UploadRequest, UploadSignature } from './types.js';
export type StoreName =
| 'drafts'
| 'cache'
| 'pending'
| 'libraries'
| 'mockProjects'
| 'mockUploads'
| 'mockCreates';
const stores: StoreName[] = [
'drafts',
'cache',
'pending',
'libraries',
'mockProjects',
'mockUploads',
'mockCreates',
];
let database: Promise<IDBDatabase> | undefined;
function open(): Promise<IDBDatabase> {
database ??= new Promise((resolve, reject) => {
const request = indexedDB.open('vm.pcb', 1);
request.onupgradeneeded = () => {
for (const name of stores)
if (!request.result.objectStoreNames.contains(name)) request.result.createObjectStore(name);
};
request.onsuccess = () => {
const db = request.result;
db.onversionchange = () => {
db.close();
database = undefined;
};
resolve(db);
};
request.onerror = () => {
database = undefined;
reject(request.error);
};
request.onblocked = () => {
database = undefined;
reject(new Error('PCB storage upgrade is blocked'));
};
});
return database;
}
export function storageKey(...parts: (string | number)[]): string {
return JSON.stringify(parts);
}
export async function readValue<T>(store: StoreName, key: string): Promise<T | undefined> {
const db = await open();
return new Promise((resolve, reject) => {
const tx = db.transaction(store, 'readonly');
const request = tx.objectStore(store).get(key);
let result: T | undefined;
request.onsuccess = () => {
result = request.result as T | undefined;
};
tx.oncomplete = () => resolve(result);
tx.onabort = () => reject(tx.error ?? new Error('Storage read aborted'));
tx.onerror = () => reject(tx.error);
});
}
export async function listValues<T>(store: StoreName): Promise<T[]> {
const db = await open();
return new Promise((resolve, reject) => {
const tx = db.transaction(store, 'readonly');
const request = tx.objectStore(store).getAll();
let result: T[] = [];
request.onsuccess = () => {
result = request.result as T[];
};
tx.oncomplete = () => resolve(result);
tx.onabort = () => reject(tx.error);
tx.onerror = () => reject(tx.error);
});
}
export async function writeValue<T>(store: StoreName, key: string, value: T): Promise<void> {
const db = await open();
return new Promise((resolve, reject) => {
const tx = db.transaction(store, 'readwrite');
tx.objectStore(store).put(value, key);
tx.oncomplete = () => resolve();
tx.onabort = () => reject(tx.error ?? new Error('Storage write aborted'));
tx.onerror = () => reject(tx.error);
});
}
export async function removeValue(store: StoreName, key: string): Promise<void> {
const db = await open();
return new Promise((resolve, reject) => {
const tx = db.transaction(store, 'readwrite');
tx.objectStore(store).delete(key);
tx.oncomplete = () => resolve();
tx.onabort = () => reject(tx.error);
tx.onerror = () => reject(tx.error);
});
}
/** All reads and writes happen inside one IDB transaction, including mock CAS. */
export async function atomic<T>(
names: StoreName[],
operation: (
tx: IDBTransaction,
done: (result: T) => void,
fail: (error: unknown) => void,
) => void,
): Promise<T> {
const db = await open();
return new Promise((resolve, reject) => {
const tx = db.transaction(names, 'readwrite');
let result: T;
let failure: unknown;
tx.oncomplete = () => resolve(result);
tx.onabort = () => reject(failure ?? tx.error ?? new Error('Transaction aborted'));
tx.onerror = () => reject(failure ?? tx.error);
const fail = (error: unknown): void => {
failure = error;
tx.abort();
};
try {
operation(
tx,
(value) => {
result = value;
},
fail,
);
} catch (error) {
fail(error);
}
});
}
export interface DraftRecord extends NativeProject {
ownerUserCode: string;
pcbProjectCode: string;
sessionId: string;
baseVersion: number;
revision: number;
acknowledgedRevision: number;
updatedAt: number;
}
export interface PendingSave {
ownerUserCode: string;
pcbProjectCode: string;
sessionId: string;
snapshotId: string;
revision: number;
request: UploadRequest;
signature?: UploadSignature;
bytes: Uint8Array;
createdAt: number;
receipt?: SaveReceipt;
}
export const listDrafts = async (owner: string, code: string): Promise<DraftRecord[]> =>
(await listValues<DraftRecord>('drafts'))
.filter(
(d) =>
d.ownerUserCode === owner &&
d.pcbProjectCode === code &&
d.revision > d.acknowledgedRevision,
)
.sort((a, b) => b.updatedAt - a.updatedAt);
export const listPending = async (owner: string, code: string): Promise<PendingSave[]> =>
(await listValues<PendingSave>('pending'))
.filter((p) => p.ownerUserCode === owner && p.pcbProjectCode === code)
.sort((a, b) => a.createdAt - b.createdAt);
+170
View File
@@ -0,0 +1,170 @@
// SPDX-License-Identifier: GPL-3.0-or-later
/** Platform identity and native project contracts; no dependency on Supabase. */
export interface PlatformUser {
userCode: string;
email?: string;
nickname?: string;
avatarUrl?: string;
}
export interface AuthRecord {
token: string;
user: PlatformUser;
expiresAt: number;
}
export interface WorkspaceFile {
name: string;
bytes: Uint8Array;
}
export interface ProjectRoots {
project: string | null;
schematic: string | null;
board: string | null;
}
export interface MissingResource {
kind: 'model3d';
sourcePath: string;
reference: string;
}
export interface ProjectManifest {
format: 'vibemake-pcb-project';
schemaVersion: 1;
engineBuild: string;
roots: ProjectRoots;
directories: string[];
files: { path: string; sizeBytes: number; sha256: string }[];
libraryDependencies: { kind: string; id: string; version: string }[];
unresolvedDependencies: MissingResource[];
}
export interface NativeProject {
files: WorkspaceFile[];
roots: ProjectRoots;
directories: string[];
libraryDependencies: ProjectManifest['libraryDependencies'];
unresolvedDependencies: MissingResource[];
}
export interface PcbProject {
pcbProjectCode: string;
name: string;
description: string;
coverUrl: string | null;
hasDocument: boolean;
version: number;
fileName: string;
sizeBytes: number;
savedAt: string | null;
createdAt: string;
updatedAt: string;
}
export interface Capabilities {
archiveFormat: 'vibemake-pcb-project+zip';
manifestVersions: number[];
maxArchiveBytes: number;
maxUnpackedBytes: number;
maxFileBytes: number;
maxFileCount: number;
maxPathDepth: number;
downloadMode: 'signed' | 'public';
}
export const DEFAULT_LIMITS: Capabilities = {
archiveFormat: 'vibemake-pcb-project+zip',
manifestVersions: [1],
// The backend has no capabilities endpoint. ZIP upload defaults to 256 MiB;
// the remaining limits protect this browser's archive parser independently.
maxArchiveBytes: 256 * 1024 * 1024,
maxUnpackedBytes: 512 * 1024 * 1024,
maxFileBytes: 256 * 1024 * 1024,
maxFileCount: 2000,
maxPathDepth: 16,
downloadMode: 'public',
};
/** Hash and operation/format identifiers are local transaction data, not API fields. */
export interface UploadRequest {
fileName: string;
sizeBytes: number;
sha256: string;
expectedVersion: number;
clientOperationId: string;
archiveFormat: 'vibemake-pcb-project+zip';
manifestVersion: 1;
}
export interface UploadSignature {
uploadCode: string;
uploadUrl: string;
formFields: Record<string, string>;
expiresAt: string;
}
export interface SaveReceipt {
pcbProjectCode: string;
version: number;
savedAt: string;
}
export interface ProjectDocument {
/** Added locally by the adapter; the document response does not repeat the code. */
pcbProjectCode: string;
version: number;
fileName: string;
sizeBytes: number;
downloadUrl: string;
expiresAt: null;
}
export interface PcbProjectApi {
capabilities(): Promise<Capabilities>;
list(
page: number,
keyword: string,
): Promise<{ items: PcbProject[]; page: number; size: number; total: number }>;
create(name: string, clientRequestId: string): Promise<PcbProject>;
get(code: string): Promise<PcbProject>;
rename(code: string, name: string): Promise<PcbProject>;
remove(code: string): Promise<void>;
document(code: string): Promise<ProjectDocument>;
sign(code: string, request: UploadRequest): Promise<UploadSignature>;
upload(signature: UploadSignature, bytes: Uint8Array): Promise<void>;
commit(code: string, uploadCode: string): Promise<SaveReceipt>;
download(document: ProjectDocument, limits: Capabilities): Promise<Uint8Array>;
}
export class WorkspaceError extends Error {
constructor(
public code: string,
message = code,
public status = 0,
public requestId?: string,
public retryAfterMs?: number,
) {
super(message);
this.name = 'WorkspaceError';
}
}
/** Business timestamps without an offset are Asia/Shanghai, never browser-local time. */
export function platformTime(value: string): string {
if (typeof value !== 'string' || !value) throw new WorkspaceError('BAD_RESPONSE');
const zoned = /(?:Z|[+-]\d{2}:\d{2})$/i.test(value) ? value : `${value.replace(' ', 'T')}+08:00`;
const date = new Date(zoned);
if (!Number.isFinite(date.valueOf())) throw new WorkspaceError('BAD_RESPONSE');
return date.toISOString();
}
export function validProjectCode(value: unknown): value is string {
return (
typeof value === 'string' &&
value.length > 0 &&
value !== '.' &&
value !== '..' &&
![...value].some((c) => c.charCodeAt(0) < 32 || c.charCodeAt(0) === 127)
);
}
export function validProjectName(value: string): boolean {
const name = value.trim();
return (
[...name].length > 0 &&
[...name].length <= 100 &&
![...name].some((c) => c.charCodeAt(0) < 32 || c.charCodeAt(0) === 127)
);
}
export const copyBytes = (bytes: Uint8Array): Uint8Array<ArrayBuffer> => new Uint8Array(bytes);
export const equalBytes = (a: Uint8Array, b: Uint8Array): boolean =>
a.length === b.length && a.every((v, i) => v === b[i]);
export async function sha256(bytes: Uint8Array): Promise<string> {
return [...new Uint8Array(await crypto.subtle.digest('SHA-256', copyBytes(bytes)))]
.map((v) => v.toString(16).padStart(2, '0'))
.join('');
}
+339
View File
@@ -0,0 +1,339 @@
// SPDX-License-Identifier: GPL-3.0-or-later
import {
createContext,
useContext,
useEffect,
useId,
useRef,
useState,
type ReactNode,
} from 'react';
import { getUiLanguage } from '@ziroeda/common/i18n.js';
export type Locale = 'zh' | 'en';
const Language = createContext<Locale>('zh');
const ModalBusy = createContext<(busy: boolean) => void>(() => {});
export const LanguageProvider = Language.Provider;
export function useTr(): (zh: string, en: string) => string {
const locale = useContext(Language);
return (zh, en) => (locale === 'en' ? en : zh);
}
export function SaveBlockedNotice({
retry,
disabled = false,
}: {
retry: () => void;
disabled?: boolean;
}): JSX.Element {
const tr = useTr();
return (
<div className="vm-save-blocked" role="alert" aria-atomic="true">
<svg
width="22"
height="22"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
strokeWidth="1.8"
strokeLinecap="round"
strokeLinejoin="round"
aria-hidden="true"
>
<path d="M10.3 3.9 2.2 18a2 2 0 0 0 1.7 3h16.2a2 2 0 0 0 1.7-3L13.7 3.9a2 2 0 0 0-3.4 0Z" />
<path d="M12 9v4M12 17h.01" />
</svg>
<div>
<strong>
{tr('本次尚未保存:当前操作未结束', 'Not saved: an editing operation is still active')}
</strong>
<p>
{tr(
'请先完成放置、拖动、布线或关闭对话框;也可在编辑区按 Esc 退出当前工具(布线时可能需按两次),然后重新保存。',
'Finish placement, dragging or routing, or close the dialog. You can also press Esc in the editor to exit the active tool (routing may need two presses), then save again.',
)}
</p>
</div>
<button type="button" onClick={retry} disabled={disabled}>
{tr('重新保存', 'Retry save')}
</button>
</div>
);
}
export function Modal({
title,
children,
close,
busy = false,
}: {
title: string;
children: ReactNode;
close: () => void;
busy?: boolean;
}): JSX.Element {
const ref = useRef<HTMLDialogElement>(null);
const id = useId();
const tr = useTr();
const [formBusy, setFormBusy] = useState(false);
useEffect(() => {
const dialog = ref.current!;
const previous = document.activeElement as HTMLElement | null;
dialog.showModal();
return () => {
dialog.close();
previous?.focus();
};
}, []);
return (
<dialog
ref={ref}
className="vm-dialog"
aria-labelledby={id}
onCancel={(e) => {
e.preventDefault();
if (!busy && !formBusy) close();
}}
onKeyDown={(e) => e.stopPropagation()}
>
<header>
<h2 id={id}>{title}</h2>
<button
type="button"
disabled={busy || formBusy}
onClick={close}
aria-label={tr('关闭', 'Close')}
>
×
</button>
</header>
<ModalBusy.Provider value={setFormBusy}>{children}</ModalBusy.Provider>
</dialog>
);
}
export function NameForm({
initial = '',
submit,
cancel,
label,
}: {
initial?: string;
submit: (name: string) => Promise<void>;
cancel: () => void;
label: string;
}): JSX.Element {
const [name, setName] = useState(initial),
[busy, setBusy] = useState(false),
[error, setError] = useState('');
const tr = useTr();
const setModalBusy = useContext(ModalBusy);
useEffect(() => {
setModalBusy(busy);
return () => setModalBusy(false);
}, [busy, setModalBusy]);
return (
<form
className="vm-form"
onSubmit={(event) => {
event.preventDefault();
const value = name.trim();
if (
!value ||
[...value].length > 100 ||
[...value].some((c) => c.charCodeAt(0) < 32 || c.charCodeAt(0) === 127)
) {
setError(
tr(
'名称须为 1~100 个字符,且不含控制字符。',
'Use 1–100 characters without control characters.',
),
);
return;
}
setBusy(true);
setError('');
void submit(value).catch((e: unknown) => {
setError(errorText(e));
setBusy(false);
});
}}
>
<label>
{tr('项目名称', 'Project name')}
<input
value={name}
onChange={(e) => setName(e.target.value)}
autoFocus
required
maxLength={200}
disabled={busy}
/>
</label>
{error && (
<p role="alert" className="vm-error">
{error}
</p>
)}
<footer>
<button type="button" onClick={cancel} disabled={busy}>
{tr('取消', 'Cancel')}
</button>
<button className="primary" disabled={busy}>
{busy ? tr('处理中…', 'Working…') : label}
</button>
</footer>
</form>
);
}
const errors: Record<string, string> = {
OFFLINE: '当前离线,请恢复网络后重试。',
STALE_BINDING: '工程会话已更换。',
STALE_IDENTITY: '账号已变化,请重试。',
UNAUTHORIZED: '请重新登录后继续。',
PCB_VERSION_CONFLICT: '云端已有新版本。当前设计已保留,请下载副本、另存新项目或重新加载云端。',
PCB_DOCUMENT_NOT_FOUND: '此项目尚未保存设计。',
NOT_FOUND: '项目不存在或已被删除。',
PCB_HASH_MISMATCH: '工程校验失败,请重新下载或导入。',
PCB_INVALID_ARCHIVE: '工程文件损坏或缺少原生设计文件。',
PCB_INVALID_MANIFEST: '工程清单不合法。',
PCB_UNSUPPORTED_MANIFEST: '暂不支持此工程格式版本。',
PCB_UNSAFE_PATH: '工程包含不合法或重复的文件路径。',
PCB_FILE_TOO_LARGE: '文件超过容量限制。',
PCB_UNPACKED_TOO_LARGE: '解压后的工程超过容量限制。',
PCB_TOO_MANY_FILES: '工程文件过多。',
SNAPSHOT_BUSY: '请先完成当前放置、拖动、布线或对话框操作,再保存。',
PCB_UPLOAD_EXPIRED: '上传凭证已过期,请重试。',
PCB_OSS_ERROR: '工程上传失败,请重试。',
PCB_INVALID_FILE: 'ZIP 文件名、格式或大小不合法,请检查后重试。',
PCB_FILE_MISSING: '上传对象尚未找到,工程和批次已保留,请重试保存。',
PCB_FILE_SIZE_MISMATCH: '上传文件大小不符,请重试上传。',
REQUEST_TOO_LARGE: '请求超过服务端容量限制。',
RATE_LIMITED: '操作过于频繁,请稍后重试。',
PCB_STORAGE_UNAVAILABLE: 'PCB 云存储暂不可用,工程已保留,请稍后重试。',
PCB_STORAGE_UNSAFE: 'PCB 云存储配置不完整,工程已保留,请联系管理员。',
PCB_CODE_BUSY: '服务暂忙,输入已保留,请稍后重试。',
REDIS_UNAVAILABLE: '服务暂不可用,输入已保留,请稍后重试。',
BAD_RESPONSE: '接口返回的数据不完整,请重试;当前工程已保留。',
UNKNOWN_CREATION: '未能确认新建结果。请关闭弹窗并刷新列表核对,避免重复创建项目。',
UNKNOWN_CONFIRMATION: '确认响应未收到,设计和保存批次已保留。请重试确认。',
};
// Async workflow messages keep stable source text in state. Resolve the visible
// copy when rendering so changing language does not recreate a project session.
const messages: Record<string, string> = {
页面发生错误: 'A page error occurred',
'请先保留当前页面。再次打开时可恢复已落盘草稿,最后尚未序列化的操作可能无法恢复。':
'Keep this page open first. Saved local drafts can be restored when reopening, but the last unserialized operations may not be recoverable.',
下载当前已序列化副本: 'Download the current serialized copy',
重新加载: 'Reload',
重新加载云端: 'Reload cloud',
'将放弃当前未保存修改。请先下载需要保留的副本。':
'This discards current unsaved changes. Download a copy first if you need to keep them.',
放弃并重新加载: 'Discard and reload',
离开当前工程: 'Leave this project',
'当前工程有尚未保存到云端的修改。': 'This project has changes that have not been saved to cloud.',
保存并离开: 'Save and leave',
放弃修改并离开: 'Discard changes and leave',
继续编辑: 'Keep editing',
'保存期间有新的修改,请再次保存后离开。':
'New edits were made during saving. Save again before leaving.',
'该工程有待确认保存,请先重试确认,或下载副本后重新加载云端。':
'A save is awaiting confirmation. Retry it, or download a copy before reloading cloud.',
'账号已验证,但云端已有新版本。当前设计已保留;保存时将检查版本冲突。':
'Your account is verified, but cloud has a newer version. Your design is preserved; saving will check for conflicts.',
'本机存储不可用,草稿恢复功能暂不可用。':
'Local storage is unavailable. Draft recovery is currently unavailable.',
有待确认的保存: 'A save is awaiting confirmation',
'上一次保存尚未收到确认。请先确认原批次,避免生成重复版本。':
'The last save has no confirmation yet. Confirm the original upload before creating another version.',
重试确认原保存: 'Retry the original confirmation',
下载待确认工程副本: 'Download the pending project copy',
返回项目列表: 'Back to projects',
发现本机草稿: 'Local draft found',
恢复本机草稿: 'Restore local draft',
使用云端设计: 'Use cloud design',
创建空白设计: 'Create a blank design',
返回列表: 'Back to projects',
此项目尚未保存设计: 'This project has no saved design',
'当前设备没有可恢复的工程文件。可以创建空白工程,或返回列表。':
'No recoverable design exists on this device. Create a blank project or return to the list.',
创建空白工程: 'Create blank project',
'已取消新建工程。': 'Project creation was cancelled.',
'已导入,尚未保存到云端。': 'Imported. The design has not been saved to cloud yet.',
'工程已创建,尚未保存到云端。': 'Project created. The design has not been saved to cloud yet.',
'资源已加入工程,尚未保存到云端。':
'Resources added. These changes have not been saved to cloud yet.',
删除工程文件: 'Delete project file',
删除: 'Delete',
取消: 'Cancel',
'文件名不能包含路径分隔符。': 'The filename cannot contain path separators.',
'无法加载模板或示例,请重试。': 'Could not load templates or examples. Try again.',
'目录格式不正确。': 'The catalog format is invalid.',
'请选择工程。': 'Choose a project.',
'资源响应缺少内容。': 'The resource response has no content.',
'当前离线,请恢复网络后重试。': 'You are offline. Reconnect and try again.',
'工程会话已更换。': 'The project session has changed.',
'账号已变化,请重试。': 'Your account has changed. Try again.',
'请重新登录后继续。': 'Sign in again to continue.',
'云端已有新版本。当前设计已保留,请下载副本、另存新项目或重新加载云端。':
'Cloud has a newer version. Your design is preserved. Download a copy, save as a new project, or reload cloud.',
'此项目尚未保存设计。': 'This project has no saved design.',
'项目不存在或已被删除。': 'The project does not exist or has been deleted.',
'工程校验失败,请重新下载或导入。': 'Project verification failed. Download or import it again.',
'工程文件损坏或缺少原生设计文件。': 'The project is damaged or missing native design files.',
'工程清单不合法。': 'The project manifest is invalid.',
'暂不支持此工程格式版本。': 'This project format version is not supported.',
'工程包含不合法或重复的文件路径。': 'The project contains invalid or duplicate file paths.',
'文件超过容量限制。': 'A file exceeds the size limit.',
'解压后的工程超过容量限制。': 'The unpacked project exceeds the size limit.',
'工程文件过多。': 'The project contains too many files.',
'请先完成当前放置、拖动、布线或对话框操作,再保存。':
'Finish the current placement, drag, routing, or dialog before saving.',
'上传凭证已过期,请重试。': 'The upload signature has expired. Try again.',
'工程上传失败,请重试。': 'Project upload failed. Try again.',
'ZIP 文件名、格式或大小不合法,请检查后重试。': 'The ZIP filename, format, or size is invalid.',
'上传对象尚未找到,工程和批次已保留,请重试保存。':
'The uploaded object was not found. Your project and batch are preserved. Retry saving.',
'上传文件大小不符,请重试上传。': 'The uploaded file size does not match. Retry uploading.',
'请求超过服务端容量限制。': 'The request exceeds the server limit.',
'操作过于频繁,请稍后重试。': 'Too many requests. Try again later.',
'PCB 云存储暂不可用,工程已保留,请稍后重试。':
'PCB cloud storage is unavailable. Your project is preserved. Try again later.',
'PCB 云存储配置不完整,工程已保留,请联系管理员。':
'PCB storage configuration is incomplete. Your project is preserved. Contact the administrator.',
'服务暂忙,输入已保留,请稍后重试。':
'The service is busy. Your input is preserved. Try again later.',
'服务暂不可用,输入已保留,请稍后重试。':
'The service is unavailable. Your input is preserved. Try again later.',
'接口返回的数据不完整,请重试;当前工程已保留。':
'The API response is incomplete. Your project is preserved. Retry the request.',
'未能确认新建结果。请关闭弹窗并刷新列表核对,避免重复创建项目。':
'The create result is unknown. Close this dialog and refresh the project list before creating another project.',
'确认响应未收到,设计和保存批次已保留。请重试确认。':
'No confirmation was received. Your design and upload are preserved. Retry confirmation.',
'操作失败,请重试。': 'The operation failed. Try again.',
};
export function messageText(text: string): string {
if (getUiLanguage() !== 'en') return text;
const file = /^确定删除 (.+)?$/u.exec(text);
return messages[text] ?? (file ? `Delete ${file[1]}?` : text);
}
export function errorText(error: unknown): string {
if (
error instanceof Error &&
'code' in error &&
error.code === 'RATE_LIMITED' &&
'retryAfterMs' in error &&
typeof error.retryAfterMs === 'number'
)
return getUiLanguage() === 'en'
? `Too many requests. Retry in ${Math.ceil(error.retryAfterMs / 1000)} seconds.`
: `操作过于频繁,请在 ${Math.ceil(error.retryAfterMs / 1000)} 秒后重试。`;
if (error instanceof Error && 'code' in error)
return messageText(errors[String(error.code)] ?? error.message);
return messageText(error instanceof Error ? error.message : '操作失败,请重试。');
}
export function downloadBytes(bytes: Uint8Array, name: string): void {
const url = URL.createObjectURL(new Blob([new Uint8Array(bytes)], { type: 'application/zip' }));
const link = document.createElement('a');
link.href = url;
link.download = name;
link.click();
setTimeout(() => URL.revokeObjectURL(url), 1000);
}
+14 -1
View File
@@ -1959,7 +1959,11 @@ export const toolbarSlice = (app: ToolbarApp): SettingsSlice => `${app}-toolbars
export const sliceStorageKey = (slice: SettingsSlice): string => settingsStorageKey(slice);
/** Where any settings file lives in localStorage, synced slice or not. */
export const settingsStorageKey = (filename: string): string => `ziroeda.${filename}`;
let platformSettingsOwner: string | null = null;
export const settingsStorageKey = (filename: string): string =>
platformSettingsOwner
? `vm.pcb.preferences.${encodeURIComponent(platformSettingsOwner)}.${filename}`
: `ziroeda.${filename}`;
/**
* Apply every correction newer than `from` to one stored eeschema settings
@@ -2551,6 +2555,15 @@ const TOOLBAR_SLICES = new Map<SettingsSlice, ToolbarApp>(
* notification the editors re-render through (useSyncExternalStore).
*/
export class SettingsManager {
/** Platform preferences are local and scoped to the verified account. */
setPlatformOwner(owner: string): void {
if (platformSettingsOwner === owner) return;
platformSettingsOwner = owner;
this.manager.Load();
this.m_toolbars = this.readToolbars();
this.stamps = {};
this.notify();
}
/** The `SETTINGS_MANAGER` the files are registered with; `PGM_BASE` adopts it. */
readonly manager: SETTINGS_MANAGER;
private readonly files: SliceFiles;
+6 -4
View File
@@ -1,7 +1,7 @@
// SPDX-License-Identifier: GPL-3.0-or-later
// Copyright (C) 2026 ZiroEDA and contributors.
import { createContext, useContext, useEffect, useRef, useState, type ReactNode } from 'react';
import { useAuth } from '../auth/AuthProvider.js';
import { useOptionalAuth } from '../auth/AuthProvider.js';
import { createProjectSyncTransport } from './createProjectSyncTransport.js';
import type {
EditorKind,
@@ -43,6 +43,7 @@ export function ProjectSyncProvider({
projectUid,
view,
children,
disabled = false,
}: {
/** Null or empty when no project is open; nothing connects. */
projectName: string | null | undefined;
@@ -52,8 +53,9 @@ export function ProjectSyncProvider({
/** Which editor the user is actually looking at right now. */
view: EditorKind;
children: ReactNode;
disabled?: boolean;
}): React.JSX.Element {
const { session } = useAuth();
const session = useOptionalAuth()?.session;
const displayName = session?.user.email ?? null;
const userId = session?.user.id ?? null;
@@ -65,7 +67,7 @@ export function ProjectSyncProvider({
viewRef.current = view;
useEffect(() => {
if (!projectName) {
if (disabled || !projectName) {
setTransport(null);
return undefined;
}
@@ -78,7 +80,7 @@ export function ProjectSyncProvider({
setTransport(null);
t.disconnect();
};
}, [projectName, projectUid, userId, displayName]);
}, [projectName, projectUid, userId, displayName, disabled]);
// A switch between editors is a re-announcement, never a reconnect. The
// sheet path is left to the schematic editor, which is the only thing that
+4 -1
View File
@@ -4,9 +4,12 @@
/** Shared VibeMake home link for the project manager and every editor menubar. */
import type { JSX } from 'react';
import logoUrl from '../assets/vibemake-logo.png';
import { projectSnapshotHost } from '@ziroeda/common/project_snapshot.js';
// Keep the shared editor-frame prop contract; the brand now always opens the main site.
export function HomeLink(_props: { onClick?: () => void }): JSX.Element {
export function HomeLink(_props: { onClick?: () => void }): JSX.Element | null {
// The platform shell owns the project-list logo and its unsaved-change guard.
if (projectSnapshotHost()) return null;
return (
<a
className="ze-home-link ze-home-brand"
+44 -18
View File
@@ -85,9 +85,8 @@ export default defineConfig({
* toolbar's 472 icons are all under it — so 799 KB of base64 SVG sat in
* the entry chunk, downloaded and parsed before the sign-in screen could
* paint, for icons nothing shows until an editor frame does. As files
* they are hashed and immutable, precached by the worker, and fetched by
* a frame when it first paints — which is at idle, since the frames warm
* behind the manager (App.tsx, `warmFrames`). The entry drops by half.
* they are hashed and immutable and fetched when a frame first paints.
* The platform list never warms editor frames. The entry drops by half.
*/
assetsInlineLimit: 0,
},
@@ -106,6 +105,18 @@ export default defineConfig({
*/
worker: { format: 'es' },
plugins: [
{
name: 'pcb-production-mode',
configResolved(config) {
// React explicitly includes these even when excluded above. The alias
// is application source and must share i18n with the rest of the app.
config.optimizeDeps.include = config.optimizeDeps.include?.filter(
(id) => id !== 'react/jsx-runtime' && id !== 'react/jsx-dev-runtime',
);
if (config.command === 'build' && config.env.VITE_PCB_API_MODE === 'mock')
throw new Error('PCB mock mode is development-only. Build with real API mode.');
},
},
react(),
/**
* The app is installed, not fetched.
@@ -115,9 +126,9 @@ export default defineConfig({
* `max-age=0, must-revalidate` unless told otherwise (that is now
* vercel.json's job) — and an editor nobody had opened yet was fetched the
* moment they first asked for it, behind a "Loading the board editor..."
* overlay. This service worker precaches every built chunk on the first
* visit, so the second launch, and every editor in it, comes off disk with
* no request at all, and the app works with the network down.
* overlay. The platform precaches only its small shell. Native editors,
* libraries and kernels load on demand; authenticated data and project
* archives never belong in the service worker cache.
*
* `prompt`, not `autoUpdate`: a new deploy is *installed* in the background
* but *activates* only once every tab of the old build is closed — the way
@@ -133,14 +144,14 @@ export default defineConfig({
manifest: {
name: 'VibeMake PCB',
short_name: 'VibeMake PCB',
description: '基于浏览器的原理图与 PCB 设计工具,项目保存在本地,兼容 KiCad 文件。',
description: 'VibeMake 原理图与 PCB 设计工作区,支持工程保存与 KiCad 原生文件。',
start_url: APP_BASE,
scope: APP_BASE,
display: 'standalone',
// The chrome the shell paints while the first chunk loads. Matches the
// mark's own ground in favicon.svg and the dark shell in ui/shell.css.
background_color: '#0b0c0e',
theme_color: '#0b0c0e',
background_color: '#07080a',
theme_color: '#07080a',
icons: [
{ src: 'icons/icon-192.png', sizes: '192x192', type: 'image/png' },
{ src: 'icons/icon-512.png', sizes: '512x512', type: 'image/png' },
@@ -161,9 +172,10 @@ export default defineConfig({
// below, not up front.
globPatterns: [
'index.html',
'vibemake-mark.svg',
'brand/*',
'icons/*.png',
'assets/**/*.{js,css,png,svg}',
'assets/index-*.js',
'assets/index-*.css',
],
// ...with one exception, for the same reason: the DRC worker carries
// the whole engine, every test provider and the board parser, and at
@@ -171,13 +183,11 @@ export default defineConfig({
// It is fetched the first time someone runs a DRC, and cached then
// (runtimeCaching below), rather than by everyone who opens the site.
globIgnores: ['assets/drc_worker-*.js'],
// index.js alone is 1.7 MB; workbox's default 2 MiB cap would otherwise
// quietly skip the one file that matters most.
// Keep an explicit upper bound even if the shell grows in a future build.
maximumFileSizeToCacheInBytes: 4 * 1024 * 1024,
// Every app route (/p/<uid>/pcb, /demo/<id>) is index.html, as
// vercel.json's rewrite already says. Serving it from the precache is
// what makes a cold-start with no network still paint the launcher.
// Only the /pcb/ application scope uses this navigation fallback.
navigateFallback: 'index.html',
navigateFallbackDenylist: [/\/api\//, /\.zip(?:\?|$)/],
runtimeCaching: [
{
// WASM kernels are hashed like every other asset, so cache-first is
@@ -219,10 +229,26 @@ export default defineConfig({
]
: []),
],
server: { port: 5173 },
server: {
port: 5173,
proxy: {
'/api': {
target: process.env.API_TARGET || 'https://dev-vibemake-api.robotquan.com',
changeOrigin: true,
configure(proxy) {
proxy.on('proxyReq', (request) => {
request.removeHeader('origin');
request.removeHeader('referer');
});
},
},
},
},
// zstd-wasm locates zstd.wasm next to its own module via import.meta.url;
// pre-bundling would move the JS into .vite/deps without the wasm, so serve
// the package as-is (production builds handle new URL(..., import.meta.url)
// natively and copy the asset).
optimizeDeps: { exclude: ['@bokuweb/zstd-wasm'] },
// Prebundling the aliased JSX runtime would embed a second i18n singleton.
// Keep it as source so language changes reach both native tools and the shell.
optimizeDeps: { exclude: ['@bokuweb/zstd-wasm', 'react/jsx-runtime', 'react/jsx-dev-runtime'] },
});
Binary file not shown.

After

Width:  |  Height:  |  Size: 57 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 104 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 39 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 122 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 42 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 41 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 70 KiB

+59
View File
@@ -0,0 +1,59 @@
# PCB 后端接口接入说明
更新日期:2026-11-05。接口依据为本次提供的 `frontend-pcb-workspace(1).md`。本文描述前端接入实现;旧的后端实施建议不再作为接口契约。
## 本地运行与环境
在相邻的 `vibemake` 目录运行 `node scripts/server.mjs`,通过 `http://127.0.0.1:8091/pcb/` 访问。启动脚本默认以真实接口模式启动独立 PCB Vite 服务,`/api` 沿用主站的 dev 后端代理。更换后端使用 `API_TARGET=https://后端域名 node scripts/server.mjs`。
单独开发 PCB 时运行 `pnpm -C designer dev`;其 `/api` 也代理至 dev 后端,可通过 `API_TARGET` 覆盖。不同端口的 localStorage 不共享,所以统一登录必须在同一个主站源地址下验收,不能混用 localhost 与 127.0.0.1。
只有显式运行 `PCB_API_MODE=mock node scripts/server.mjs` 或 `pnpm -C designer dev:mock` 才启用本机模拟。模拟账号使用独立键,不覆盖主站 `vm.auth`。生产构建禁止模拟模式,接口故障不会回退模拟。
`VITE_PCB_API_BASE` 留空时按主站域名选择 dev/prod API;自建环境可显式设为 `/api` 并配置反向代理。此变量是公开的构建配置,不是服务端运行时配置。前端不存储 OSS RAM 密钥。
## 已对齐的接口
统一登录复用 `/auth/captcha`、`/auth/login`、`/auth/logout`、`/users/me`。存储格式仍为 `vm.auth={token,user,expiresAt}`;有身份时先验证 `/users/me`。业务请求携带 Bearer;直传、下载均不携带平台 Token 或 Cookie。401 保留当前工程并要求重新验证账号,超时、断网和 5xx 不清空身份。
工作空间前缀为 `/api/pcb/workspace/projects`:
| 操作 | 方法和路径 | 请求或返回 |
| --- | --- | --- |
| 分页搜索 | GET 空路径 | `page,size=20,keyword`,关键词最多 100 字符 |
| 创建 | POST 空路径 | `{name,description:""}` |
| 详情 | GET `/{code}` | 项目对象,保留 coverUrl |
| 重命名 | PATCH `/{code}` | `{name}`,不改内部文件名与文件版本 |
| 删除 | DELETE `/{code}` | data 为 null |
| 签名 | POST `/{code}/uploads/signature` | 仅 `{fileName,sizeBytes,expectedVersion}` |
| 确认 | PUT `/{code}/document` | 仅 `{uploadCode}`;回执仅要求项目编码、version、savedAt |
| 打开 | GET `/{code}/document` | 普通 downloadUrl、expiresAt=null、version、fileName、sizeBytes |
所有业务响应解析 `{code,message,data,requestId}`,不缓存。无时区的业务时间按 `+08:00` 解析。项目编码按不透明字符串处理,不依赖数据库 ID 或显示名称。
不请求 `/pcb/workspace/capabilities`,因为后端契约没有该接口。不向服务器发送 clientRequestId、clientOperationId、sha256、archiveFormat 或 manifestVersion,也不要求这些字段出现在签名、回执或 document 中。本地事务仍保留操作标识和 ZIP hash,用于草稿、缓存和恢复,与后端字段分开。
现有页面保留新建、导入、搜索、重命名、删除;本轮没有增加封面编辑器。coverUrl 随项目元数据保留,工程保存和重命名不清空封面。将来新增封面 UI 时使用文档中的公共封面上传流程,不混用 PCB ZIP 签名接口。
## 保存、失败和重开
1. 在安全操作边界刷新各编辑器、等待文件写队列、捕获不可变快照。
2. 原始字节与原生目录整体打包,加入前端 manifest。第一次保存前已有项目编码,上传失败不重建项目。
3. 申请签名,FormData 原样加入所有 formFields,最后追加 application/zip 文件;不手动设置 multipart Content-Type。
4. OSS POST 成功要求 HTTP 200,不解析 JSON。随后用原 uploadCode 确认,收到合法回执才更新已保存 revision。上传期间的新修改继续显示未保存。
5. 确认超时或上传结果不明,保留原 ZIP 和批次,下次先确认原批次;仅明确缺文件时重传。明确过期或大小不符时为原快照重新申请。发生版本冲突保留本地工程,不自动更换基础版本覆盖。
6. 重开先处理待确认批次,再读取 document、下载、校验大小、受限解压、校验 manifest 和全部文件 hash,成功后才挂载。编辑基础版本取 document.version,不能使用此前详情的 version。普通下载地址 403 按故障处理,不当作临时签名过期无限重取。
服务器不解析 ZIP,也不返回 ZIP SHA-256;工程可编辑性、归档路径和条目完整性由前端验证。manifest 是前端归档格式,不是额外的服务端契约。缺少外部模型仍可保存,缺少原生设计或内部 hash 不一致则不能加载。重开可继续编辑,跨会话不恢复旧 Undo/Redo 栈。
浏览器当前限制:ZIP 256 MiB(与文档默认一致)、单文件 256 MiB、解压总量 512 MiB、2000 文件、路径深度 16。后端可独立返回更低限额的 413;上调后端配置不会自动提高浏览器限制。这些限额不代表所有大小的工程均已完成性能验收。
429 读取 Retry-After 并阻止冷却期内再次请求,不自动重放写操作;其他文档错误码保留 requestId 并显示可操作的错误提示。文档未提供创建幂等键,创建响应不明时要求先刷新列表核对,不把再次 POST 宣称为幂等重试。
## 验证与部署
接口测试见 `qa/unittests/designer/pcb_http_api.test.ts`,认证测试见 `pcb_platform_auth.test.tsx`,原生往返和模拟事务测试见 `pcb_platform.test.ts`。HTTP 测试使用与文档一致的最小服务端响应,覆盖 Bearer 隔离、multipart、上海时间、无服务端 hash 的下载、document 基础版本、未知确认恢复、并发冲突、限流与账号切换。
构建仍为 `pnpm -C designer build`,产物独立挂载到主站 `/pcb/`;主站打包脚本可收录该目录。服务器保留 `/pcb/p/...` 的 SPA 回退及正确的 API 环境、OSS/CDN POST/GET CORS。此次不修改业务后端、数据库、Bucket ACL 或服务器部署配置。
真实账号、真实 OSS 和跨设备往返需单独联调;本地契约测试不能代替这些验收。
+246
View File
@@ -0,0 +1,246 @@
# VibeMake PCB 项目工作空间:后端实施要求
日期:2026-11-04。
状态:历史接口建议,已由 2026-11-05 提供的 `frontend-pcb-workspace(1).md` 替代。当前前端接入以 [实际接口接入说明](./pcb-api-integration.md) 为准。下文 capabilities、服务端 hash/manifest 校验、创建幂等字段及私有签名下载均为当时建议,不是现有后端能力,也不是当前前端的接口要求。本轮未修改或部署业务后端。
## 1. 业务边界与复用范围
PCB 与主站、CAD 使用同一平台账号和 Bearer 身份。PCB 内提供同款邮箱和图片验证码弹窗,调用 GET /api/auth/captcha、POST /api/auth/login、POST /api/auth/logout、GET /api/users/me。登录请求为 {email,captchaCode,captchaAnswer},响应为 {token,user,expiresIn};共享 vm.auth={token,user,expiresAt},expiresAt 为毫秒。账号服务继续由平台维护,不新增 PCB 用户表、密码、Supabase 账号、恢复密钥或跨项目映射。
PCB 项目独立建模和独立接口,不复用 /api/workspace/projects 或 CAD 项目记录。PCB 原理图、子页、板文件、设置、自定义库和工程资源组成一个工程;保存时一次确认整个工程。
本期不提供团队、邀请、发布社区、历史列表/版本恢复、回收站或管理后台接口。version 仅用于保存并发检查;它不是新增的历史管理产品。
接口命名参考当前 CAD /api/cad/workspace/projects。PCB 文件采用原生 KiCad 工程 ZIP,不使用 CAD 的 .sc 或早期 OpenCAD 的 DWG/DXF。
## 2. 通用约定
- API 前缀:/api/pcb/workspace。核心项目路径为 /projects。
- 所有接口必须平台鉴权。ownerUserCode 从已验证身份取得,不接受请求体指定归属。
- pcbProjectCode、uploadCode 为不透明业务字符串;项目编码使用 1 至 120 个字母、数字、下划线或连字符,客户端 encodeURIComponent。不暴露数据库 ID,不强制为 UUID。
- 前端为创建和上传分别生成稳定 clientRequestId / clientOperationId;后端需按本文实现幂等,不能只忽略这些字段。
- 成功 HTTP 200,使用当前主站信封 {code:"OK",message:"",data:...,requestId:"..."};失败同时保留对应 HTTP 状态与稳定业务 code。
- 分页参数 page、size、keyword;默认 size=20,最大 100。名称 trim 后 1~100 个 Unicode 字符,描述最多 2000 字符,同名允许。
- 文件大小为原始字节整数,hash 为 64 位小写 SHA-256。时间必须采用 ISO 8601,包含 Z 或明确的 +08:00 等时区,不返回无时区字符串。
- 账号/项目/签名/下载信息响应 Cache-Control:no-store。业务 API 支持主站前端域名的 CORS;错误不通过泄漏他人项目存在性区分权限。
## 3. 接口清单
核心八个接口与当前 CAD 风格一致;另提供一个能力端点,避免归档上限和格式版本仅写死在前端:
| 方法 | 路径 | 用途 |
| --- | --- | --- |
| GET | /api/pcb/workspace/capabilities | 归档格式、大小和文件数限制、读取模式 |
| GET | /api/pcb/workspace/projects | 个人 PCB 项目分页 |
| POST | /api/pcb/workspace/projects | 新建项目元数据,支持创建幂等 |
| GET | /api/pcb/workspace/projects/{pcbProjectCode} | 工程元数据 |
| PATCH | /api/pcb/workspace/projects/{pcbProjectCode} | 改名称/描述 |
| DELETE | /api/pcb/workspace/projects/{pcbProjectCode} | 删除,阻止一切后续写入 |
| POST | /api/pcb/workspace/projects/{pcbProjectCode}/uploads/signature | 为不可变 ZIP 申请上传批次 |
| PUT | /api/pcb/workspace/projects/{pcbProjectCode}/document | 校验并原子提交同一批次;重复确认查询原回执 |
| GET | /api/pcb/workspace/projects/{pcbProjectCode}/document | 当前已确认文件及其同一快照版本 |
本方案没有另设 complete/status 接口。确认超时重试同一 PUT document;如果后端采用异步校验,则必须另行明确 VERIFYING、状态查询和客户端轮询协议,不能保持当前成功回执形状却提前返回“保存成功”。
### 3.1 capabilities
建议的初始限制如下,属于待压测的配置起点,不能据此声称现有浏览器或服务器已经通过大工程验收:
{
"archiveFormat": "vibemake-pcb-project+zip",
"manifestVersions": [1],
"maxArchiveBytes": 52428800,
"maxUnpackedBytes": 209715200,
"maxFileBytes": 52428800,
"maxFileCount": 2000,
"maxPathDepth": 16,
"downloadMode": "signed"
}
ZIP 50 MiB、解压总量 200 MiB 只是初始建议;服务端和前端共同限额。后续上调需要测量峰值内存、worker 拷贝、ZIP 解析和上传时长,不直接沿用 CAD 256 MiB 的单文件上限。
### 3.2 项目 CRUD
POST 请求:
{
"name": "控制板",
"description": "",
"clientRequestId": "<客户端创建请求标识>"
}
同一 owner + clientRequestId 重试返回同一个项目;若请求标识相同但名称/描述不一致,返回幂等参数冲突。标识与响应应跨短期网络重试保留。PATCH 不修改文件版本,不改 ZIP 内部名称,不触发项目文件重新上传。
项目对象:
{
"pcbProjectCode": "<不透明项目编码>",
"name": "控制板",
"description": "",
"hasDocument": false,
"version": 0,
"fileName": "",
"sizeBytes": 0,
"sha256": null,
"savedAt": null,
"createdAt": "2026-11-04T10:00:00+08:00",
"updatedAt": "2026-11-04T10:00:00+08:00"
}
新项目没有云文件,hasDocument=false、version=0;前端据此在浏览器创建原生工程,首次确认保存才产生 document。创建成功后页面退出导致空项目遗留允许保留,不伪造文件已保存。
GET 列表返回 {items,page,size,total},只含本人未删除工程,按 updatedAt 倒序并以稳定主键作为相同时间的次序。GET 详情与 PATCH 返回项目对象,DELETE 返回 null。
### 3.3 上传签名
POST 请求:
{
"fileName": "project.zip",
"sizeBytes": 123456,
"sha256": "<整个ZIP的SHA-256>",
"expectedVersion": 0,
"clientOperationId": "<当前不可变快照的上传操作标识>",
"archiveFormat": "vibemake-pcb-project+zip",
"manifestVersion": 1
}
expectedVersion 必须是 JSON 非负整数;sizeBytes 必须非零且不超限。上传前也验证 owner、工程未删除和基础版本,但最终以确认时的事务校验为准。
相同 owner/project/clientOperationId 与相同请求指纹,重复签名返回同一 uploadCode 和有效的授权信息;参数不一致返回 PCB_IDEMPOTENCY_CONFLICT。不能把“超时重试签名”解释为多个独立文件版本。
签名响应:
{
"uploadCode": "<批次编码>",
"clientOperationId": "<原操作标识>",
"uploadUrl": "<OSS签名POST地址>",
"formFields": {
"<签名字段>": "<值>"
},
"expiresAt": "<明确截止时间>"
}
表单字段按现有 OSS 签名机制返回,前端原样加入 FormData,最后 append file。POST 不带平台 Authorization、Cookie,不手设 multipart Content-Type,也不自行覆盖 ACL、key、policy。
签名建议有效 15 分钟,服务端校验批次截止时间。临时对象键由服务端生成,包含环境/用户/工程/批次的不透明标识;文件名不参与决定路径。每个批次禁止覆盖,确保验证期间和确认后不能被签名再次改写。
### 3.4 确认保存与幂等
PUT 请求:{uploadCode:"<批次编码>"}。
成功回执:
{
"pcbProjectCode": "<项目编码>",
"uploadCode": "<已确认批次>",
"clientOperationId": "<原操作标识>",
"version": 1,
"sha256": "<已验证ZIP的SHA-256>",
"savedAt": "<服务器确认时间>"
}
处理要求:
1. 根据鉴权身份定位批次及项目,校验归属、期限、文件元数据和项目状态。
2. 已 COMMITTED 的同一批次返回首次回执,不重复增加 version;即使项目后来有新版,也返回原批次回执而不是覆盖成最新版。
3. 对象未完整上传时返回 PCB_FILE_MISSING,不更新项目指针。OSS 上传响应丢失时,已存在正确对象应允许正常确认。
4. 服务端读取并实际校验对象大小、SHA-256、ZIP/manifest 结构、条目边界和引用入口,不信任客户端提交的 hash 或扩展名。
5. 对暂存对象做不可变固化,或使用已确保禁止覆盖的不可变对象;数据库最终引用的字节必须就是已校验的字节。不能先验后允许同 key 再上传。
6. 事务内锁定或 CAS 更新工程:当前 version 必须等于 expectedVersion,且没有 deleted。成功后 version+1、替换当前 document 指针、记录 savedAt 和批次 COMMITTED 回执。
7. 两个同时使用同一 expectedVersion 的保存只有一个成功。另一个返回 PCB_VERSION_CONFLICT;不得按客户端时间戳决定覆盖。
8. 数据库提交失败时不返回成功;已上传的孤立对象稍后清理。确认成功但 HTTP 响应丢失时,重试同一 uploadCode 找回同一回执。
客户端仅在明确收到缺文件、大小不符或过期这类终态后,才可退役原批次,为同一快照生成新的 clientOperationId 申请替代批次;未知结果一直查询原批次。旧批次替代后也不可绕过 version CAS 再提交。
同一 uploadCode 已确认且项目仍存在时重复确认不受原上传有效期影响。幂等回执不能随着签名过期立即丢失。项目删除后统一拒绝继续写入,旧页面不可借已确认批次恢复工程。
### 3.5 当前 document 读取
返回:
{
"pcbProjectCode": "<项目编码>",
"version": 1,
"fileName": "project.zip",
"sizeBytes": 123456,
"sha256": "<整个ZIP的SHA-256>",
"archiveFormat": "vibemake-pcb-project+zip",
"manifestVersion": 1,
"downloadUrl": "<短期读取地址>",
"expiresAt": "<签名到期时间>",
"savedAt": "<服务器确认时间>"
}
version、文件引用、hash 必须来自同一个已确认快照;前端不能把先前 GET 项目详情的版本拼到后来下载的文件上。尚未保存返回 PCB_DOCUMENT_NOT_FOUND;详情明确为空工程时,前端提示“此项目尚未保存设计”,用户选择创建空白或返回列表,不能自动把空板当作恢复成功。
推荐 downloadMode=signed:工程对象私有,GET document 验证 owner 后签发短期单对象 GET。下载过期可重新取 document;若 version/hash 已变化则重新处理新云版本,不能混用地址与版本。
当前 CAD 的实际约定是普通 OSS/CDN 地址和 expiresAt=null。若 PCB 采用 public 模式复用现有基础设施,capabilities 必须返回 public、expiresAt=null,并明确持有直链可访问、删除项目不能撤销直链。平台接口的 owner 校验不会自动改变 Bucket/CDN 的读权限。本方案推荐 PCB 私有读取;不把该能力假设为现有 CAD 已具备。
## 4. 归档内容和校验
归档是 ZIP,根目录唯一的 vibemake-project.json:
- format=vibemake-pcb-project,schemaVersion=1,engineBuild 为编辑器构建标识。
- roots 为 {project,schematic,board},各值为相对路径或 null,至少有一个支持的原生设计入口。
- files 为所有原生/资源条目的 path、原始 sizeBytes、原始 SHA-256,不包含 manifest 自身。
- directories 为必要空目录;libraryDependencies 为明确的公共库标识/版本,不包含用户 token 或绝对凭据 URL。
- unresolvedDependencies 为 [{kind:"model3d",sourcePath:"project.kicad_pcb",reference:"missing.step"}]。缺失外部模型允许保存,后端不得因该列表非空拒绝已有设计;缺少主设计、非法路径或 hash 不匹配仍然拒绝。
- 每个被列出的文件必须存在,ZIP 实际设计/资源条目必须在 manifest 中;不接受偷偷附带不在索引中的其他文件。
服务器应限制实际解压量和实际文件数,不能只相信 ZIP central directory 的 size。限制单文件、路径深度和处理时长,按配置防止异常膨胀。前端也做相同校验,但不替代服务端。
路径以 / 分隔,拒绝绝对路径、盘符、..、空段、NUL、控制字符、规范化后重复路径、文件目录冲突和符号链接;跨平台兼容时还需处理大小写折叠冲突。不要把条目按不可信名称直接解压到服务器任意目录。
不执行 ZIP 内脚本、制造文件或库内容;后端不解析并重写 KiCad 几何,不更新网络、不自动布线、不转 STL/STEP/GLB。检查归档结构和存储完整性不等于保证第三方 CAD 特性无损。
嵌入的原生文件保持原字节,禁止把所有文件都当 UTF-8 文本重编码。自定义模型、图片等二进制必须保留。不要将整个 ZIP 再转 base64 放进 JSON。
## 5. 建议存储模型
可按现有框架/数据库调整命名,不要求为本期增加完整的版本管理模块:
| 表 | 主要字段与约束 |
| --- | --- |
| pcb_workspace_projects | 内部 id、pcb_project_code、owner_user_code、name、description、version、当前 object key/size/hash、archive/manifest 版本、saved_at、created_at、updated_at、deleted_at;业务编码唯一 |
| pcb_workspace_uploads | upload_code、project_id、owner、client_operation_id、expected_version、请求指纹、临时/最终 key、size/hash、expires_at、state、确认 version/saved_at/receipt;owner/project/operation 唯一 |
| 创建幂等记录 | owner/client_request_id 唯一、请求指纹与 project_id;可复用现有幂等基础设施 |
确认后工程只暴露当前版本;旧对象保留/回收与幂等事务分开,不增加历史查询页面。删除使用 tombstone 或等价状态,阻止未完成上传之后把项目重新写回来;默认不做离线排队删除。
对象路径前缀独立,例如环境根下 pcb-workspace/,不混入社区公开资源或 CAD 工程目录。可复用同一 OSS 连接和现有签名服务,不要求另建云厂商账户。
临时/失败对象允许后台过期清理;必须排除当前工程引用、已确认批次所需对象和验证中的对象。历史对象保留策略另行配置,不在本期默默删除旧文件或提供恢复承诺。
## 6. 错误码
| HTTP / code | 前端处理 |
| --- | --- |
| 400 BAD_REQUEST / PCB_INVALID_ARCHIVE / PCB_INVALID_MANIFEST / PCB_UNSAFE_PATH | 保留工程,指出包/路径/参数问题 |
| 401 UNAUTHORIZED | 锁住当前工程、保留草稿,重新登录并重新核对身份 |
| 404 NOT_FOUND | 不存在/非本人/已删除,停止该项目写入;不显示他人信息 |
| 404 PCB_DOCUMENT_NOT_FOUND | 仅空项目进入新建原生工程流程 |
| 409 PCB_VERSION_CONFLICT | 保留修改;下载、另存或用户确认后重开;不自动覆盖 |
| 409 PCB_FILE_MISSING / PCB_FILE_SIZE_MISMATCH / PCB_UPLOAD_EXPIRED | 根据明确结果保留原 bytes 后重试对应阶段 |
| 409 PCB_IDEMPOTENCY_CONFLICT | 停止自动重试,检查相同请求标识是否被不同内容复用 |
| 422 PCB_HASH_MISMATCH / PCB_UNSUPPORTED_MANIFEST | 不提交,保留设计和副本 |
| 413 PCB_FILE_TOO_LARGE / PCB_UNPACKED_TOO_LARGE / PCB_TOO_MANY_FILES | 前端显示实际限制,保持设计 |
| 429 RATE_LIMITED | 保留快照,按 Retry-After 延后重试 |
| 502 PCB_OSS_ERROR | 保留批次,重试确认或读取 |
| 503 PCB_STORAGE_UNAVAILABLE | 提示存储未配置,不回退成本机模拟成功 |
下载对象存储返回 403 与平台 401 不混淆:前者可能为签名过期/CORS/对象访问配置问题,不清平台登录态。真实离线、5xx 和普通超时均不当作退出登录。
## 7. 部署与联调责任
后端:数据库迁移、PCB 模块、权限/CAS/幂等、OSS 配置与 ZIP 校验;不部署前端编辑器运行服务。PCB_MAX_ARCHIVE_BYTES 等归档限制和独立存储开关通过环境配置,名称按后端约定统一。
前端:独立 designer 构建、同源 /pcb/、身份适配、快照/归档、签名直传、确认/恢复。所有大小/hash 在原生 bytes 和最终 ZIP 上按约定计算。
OSS:允许 VibeMake dev/prod 域名 POST/GET/HEAD/OPTIONS 所需 CORS;签名表单条件匹配实际大小/类型/禁止覆盖要求;私有读取模式下确保可签名读取。公共符号/封装/模型库单独配置,不把用户 ZIP 放进公共库分发路径。
验收必须使用真实账号和对象存储,至少验证:A 保存、B 同账号打开续编、A 读取 B 新版;另一账号不得读写;保存确认断网重试不多一个版本;并发只有一个提交;删除后旧保存不能复活;ZIP/manifest/hash 不匹配不推进版本。
本机 mock 只用于前端开发,必须有醒目标识且显式启用,不作为 dev/prod 的默认 API 回退。不把模拟服务成功当作真实服务器已完成。
+157
View File
@@ -0,0 +1,157 @@
# VibeMake PCB 前端实施与交付说明
更新日期:2026-11-05。基于 7e01147 实施。真实接口接入以 [当前接入说明](./pcb-api-integration.md) 为准。
配套:[历史后端接口建议](./pcb-backend-requirements.md)、[验证记录与截图](./pcb-verification.md)。后续已调整主站同源入口和开发启动模式;CAD 与业务后端功能代码未改。本文件描述已经实现的前端和仍需真实服务联调的边界。
## 1. 独立应用与页面
PCB 保持独立仓库、独立 pnpm/Vite 构建。发布 `designer/dist` 到主站同源 `/pcb/`,不合并主站业务代码。主站、CAD、PCB 各自维护项目数据,只共享账号和品牌。
| 地址 | 内容 |
| --- | --- |
| `/pcb/` | 我的 PCB 项目,搜索、20 项分页、新建、导入、重命名、删除 |
| `/pcb/p/{code}/` | 当前工程文件管理 |
| `/pcb/p/{code}/pcb` | PCB 编辑 |
| `/pcb/p/{code}/schematic` | 原理图编辑 |
| `/pcb/p/{code}/pcb/3d` | 三维查看 |
| `/pcb/p/{code}/symbols` | 符号编辑 |
| `/pcb/p/{code}/footprints` | 封装编辑 |
| `/pcb/p/{code}/tools/{tool}` | calculator、drawing-sheet、image-converter、gerber |
`?f=` 为经过校验的工程相对路径,禁止绝对路径和目录穿越。刷新和直接访问根据项目编码加载,停用旧最近项目回退。项目名允许重复,重命名只改显示名称,不改文件与引用。新建生成稳定内部名称 `project.kicad_pro/.kicad_sch/.kicad_pcb`,先建立本机草稿,首次手动保存后才产生云设计。
原生 ZIP、目录、单独板文件和原理图通过导入校验后创建平台项目,多入口工程可选择主文件。模板和示例走同一创建流程。其他格式转换保留在专业 PCB 编辑器的 File > Import > Non-KiCad Board File,转换结果写入当前工程。
首次进入默认 PCB;没有板文件的工程进入原理图。另一浏览器打开只有元数据的项目会提示“此项目尚未保存设计”,由用户选择创建空白或返回列表,不伪装成已恢复设计。
## 2. 统一视觉与登录
网站外壳采用受控 Logo 副本、Sora、中文系统字体、JetBrains Mono,以及 `#07080a` 背景、`#0f1114/#15181c` 面板、`#c8ff3e` 主色。导航 64px、列表最大宽度 1240px。专业画布、工具栏、图层、坐标遵循已有编辑器规则。弹窗约束焦点,提交时锁定关闭,保留加载、错误、重试、空状态反馈。页面按 ui-ux-pro-max 的焦点和反馈指导检查,视觉以现有网站为准。
新增页面默认中文,可切换英文。专业编辑器继续使用已有翻译系统,语言切换不会重建文档。宽度不超过 820px、手机和平板显示电脑端提示;编辑中缩窄只遮罩与锁定,不卸载文档。
真实模式读取主站 `vm.auth={token,user,expiresAt}`,`expiresAt` 为毫秒时间戳。PCB 内提供同款邮箱、图片验证码登录弹窗:
| 接口 | 前端用途 |
| --- | --- |
| GET `/api/auth/captcha` | 图片及验证码编码 |
| POST `/api/auth/login` | `{email,captchaCode,captchaAnswer}` |
| GET `/api/users/me` | 验证身份后加载工作区 |
| POST `/api/auth/logout` | 退出共享账号 |
同一用户 token 更新后保留工程并重新验证;过期锁输入、保留文档和草稿。网络与 5xx 显示故障,不清空账号。切换用户取消旧请求、保存原账号草稿、销毁旧工程与私有资源挂载。工程异步响应按 owner、binding、session 和请求代次隔离。
平台入口不启动旧 Supabase 身份、恢复密钥、设置云同步、项目云同步、分享或协作任务。旧匿名/加密工程不自动认领,需从原环境导出再显式导入。
## 3. 工程文件与快照
主要实现位于 `designer/src/platform/`:
| 文件 | 职责 |
| --- | --- |
| `auth.tsx`、`api.ts` | 共享身份、真实接口、签名直传 |
| `ProjectList.tsx`、`PlatformApp.tsx` | 列表、路由、工作区、离开保护 |
| `runtime.ts` | 唯一工程绑定、revision、保存事务、草稿 |
| `filesystem.ts`、`account-resources.ts` | 原生工具读写、账号私有资源收集 |
| `archive.ts`、`archive.worker.ts` | 受限 ZIP、manifest、SHA-256 |
| `storage.ts`、`mock-api.ts` | 平台 IndexedDB、模拟接口 |
| `EditorHost.tsx` | 懒加载编辑环境与工程挂载 |
原理图、PCB、符号、封装和图纸注册可等待的快照参与者。快照在安全命令边界暂时锁输入,等待原生序列化、文件写队列和资源收集,复制完整 byte 文件集,随后解锁。工程文件按完整相对路径定位,两个目录下同名子页保持独立。
云格式为原生文件集合加 manifest 的完整 ZIP,根目录不包显示名称:
```text
vibemake-project.json
project.kicad_pro
project.kicad_sch
project.kicad_pcb
project.kicad_dru
sheets/...
symbols/...
footprints/...
models3d/...
images/...
```
manifest v1 实际字段如下,hash 示例须替换为文件原始字节的真实 SHA-256:
```json
{
"format": "vibemake-pcb-project",
"schemaVersion": 1,
"engineBuild": "build identifier",
"roots": {"project":"project.kicad_pro","schematic":"project.kicad_sch","board":"project.kicad_pcb"},
"directories": ["sheets"],
"files": [{"path":"project.kicad_pcb","sizeBytes":1234,"sha256":"64 lowercase hex characters"}],
"libraryDependencies": [],
"unresolvedDependencies": [{"kind":"model3d","sourcePath":"project.kicad_pcb","reference":"missing.step"}]
}
```
实际清单包含全部设计与资源,排除 manifest 自身、锁、临时文件、旧历史和可再生缓存。二进制保持原字节,不使用扩展名白名单过滤工程。前端导入校验路径、大小、数量、重复、文件目录冲突、符号链接、manifest 版本和 hash,校验原生主文件语法。现有后端仅存储 ZIP 并核验上传对象大小,不解压、解析或校验可编辑性。
已使用的本机私有符号/封装收集到工程并更新库表,私有模型复制到工程相对路径。偏好和用户库按账号留本机,不新增个人云库产品。
## 4. 保存、草稿与恢复
手动保存、Ctrl/Cmd+S、保存并离开触发完整云保存。自动保存只在空闲 1 秒及安全命令边界写本机 byte 草稿,不打 ZIP、不上传。
保存状态为尚未保存或有修改,进入正在准备、上传、确认,然后显示已保存、仍有新修改、失败或冲突。保存并发触发复用同一任务。上传期间可继续编辑,只确认快照 revision,后续编辑不会被清成已保存。本机序列化成功也不会清除云端脏状态。
流程为捕获快照、worker 打 ZIP 与本地 hash、持久化待确认事务、申请签名、上传、PUT 确认,核对回执项目/version 后更新已确认 revision。服务端不回传操作标识、批次或 hash,原 uploadCode 由本地保存任务绑定。确认响应丢失保持原 ZIP 和批次,重试原确认;明确过期或大小不符才申请替代批次。冲突不覆盖,提供下载、另存新项目、明确放弃后重载。
数据库 `vm.pcb` 分开保存草稿、已确认缓存、待确认批次、本机用户库和模拟服务数据。草稿按账号、项目、标签页 session 隔离。重开先处理未知确认,再从同一次 document 响应下载并验证完整 ZIP;发现草稿时展示时间和基础版本供选择。
恢复后已有元件、走线、属性仍为原生可编辑对象。旧 Undo/Redo 不跨会话恢复,新操作正常撤销重做。离开有保存并离开、放弃并离开、继续编辑;保存失败停留。浏览器关闭使用原生提示并尽力写草稿,不承诺关闭时云上传完成。存储不可用保留当前内存并提示云保存或下载。
## 5. 三维资源
缺少外部模型允许保存。模型路径、偏移、旋转、缩放留在原生设计;已有模型 bytes 入 ZIP,缺失项进入 `unresolvedDependencies` 并持续提示数量。文件管理提供补选,复制到 `models3d/`、修正引用、标记修改。三维读取支持 bytes,私有缓存按工程挂载和内容 hash 隔离。
缺少主设计文件、损坏归档或不合法路径仍阻止打开或保存。模型缺失提示不能掩盖工程损坏。
## 6. 本地启动与正式构建
```sh
pnpm install
pnpm -C designer dev:mock --host 127.0.0.1
```
打开 `http://127.0.0.1:5173/pcb/`。模拟账号 A/B、模拟项目和 ZIP 只在当前浏览器 IndexedDB,持续显示开发标识,身份键为 `vm.pcb.mock.auth`,不覆盖真实 `vm.auth`。故障开关包括离线、确认响应丢失、签名过期、版本冲突、容量超限。
```sh
pnpm -C designer build
pnpm -C designer preview --host 127.0.0.1
```
正式构建仅真实接口。`VITE_PCB_API_MODE=mock` 或 `vite build --mode mock` 会拒绝构建,真实 API 失败不回退模拟。产物 `designer/dist`,base `/pcb/`。`VITE_PCB_API_BASE=/api` 使用同源代理,其他配置见 `designer/.env.example`。不要把 secret 放入 VITE 前缀变量。
列表和登录不初始化原生编辑环境;三维、DRC 和其他工具按需加载。PWA 仅预缓存轻量入口及品牌资源,不缓存账号接口、工程 ZIP、签名地址,也不强制刷新编辑页面。
## 7. 服务器挂载
以下示例假设主站静态根为 `/srv/vibemake`,将 `designer/dist` 内容发布到其 `pcb/` 子目录。路径按服务器实际情况调整。
```nginx
root /srv/vibemake;
location = /pcb { return 301 /pcb/; }
location = /pcb/index.html { add_header Cache-Control "no-cache"; }
location = /pcb/sw.js { add_header Cache-Control "no-cache"; }
location ^~ /pcb/assets/ {
try_files $uri =404;
add_header Cache-Control "public, max-age=31536000, immutable";
}
location /pcb/ { try_files $uri $uri/ /pcb/index.html; }
```
保留主站 `/api/` 代理,业务 API 失败返回 JSON,不能回退 index.html。字体、公共符号、封装、模板、示例和模型服务需在目标环境验证可达。对象存储放开前端源的 POST/GET CORS;Bearer 仅发业务 API,不送 OSS。使用 HTTPS 提供 secure context 和 SHA-256。旧构建 hash 资源保留一段时间,避免打开中的旧页面找不到懒加载 chunk。
主站入口已接入独立 PCB,同源 `/pcb/` 不再使用旧 iframe;开发启动默认使用真实接口,模拟需显式开启。线上仍需发布新产物并联调主站导航、登录共享、刷新、CSP 和对象存储 CORS。不同端口不能作为共享登录验收。
## 8. 验证边界
新增 `qa/unittests/designer/pcb_platform.test.ts` 覆盖原生设计与二进制往返、子页同名路径、归档攻击与篡改、缺失模型、账号隔离、幂等确认、并发冲突、保存期间编辑、未知结果恢复和文件写队列。浏览器模拟验收覆盖登录、新建、草稿恢复、保存、确认丢失重试及从列表重开后读取设计属性。
真实账号与跨设备存储需后端完成后验收:浏览器 A 保存,B 同账号打开、继续修改保存,A 再读取新版;不同账号禁止读写。大工程容量、全部第三方格式转换、完整制造输出及各浏览器 GPU 表现需要专门回归,不能由模拟测试推断通过。
+125
View File
@@ -0,0 +1,125 @@
# PCB 前端交付验证记录
## 2026-11-05:按已发布后端文档接入真实接口
当前接口契约和运行方式见 [PCB API 接入说明](./pcb-api-integration.md)。本节只记录本轮实际验证,不将测试用 HTTP 响应当作真实 OSS 服务。
- `pcb_http_api.test.ts` 14 项、`pcb_platform_auth.test.tsx` 3 项、既有 `pcb_platform.test.ts` 11 项,共 28 项通过。
- 覆盖文档规定的最小 JSON 字段、平台 Bearer、OSS 不携带平台凭证、multipart 字段及字节、无时区上海时间、无服务端 hash 的 ZIP 校验和重开、同源共享登录、401 与断网区分、429 冷却、账号变化后的延迟响应、重复确认、OSS 响应丢失、签名过期/大小不符后的替代批次和版本冲突。
- `pnpm -C designer typecheck`、本轮新增/修改模块的 Biome 检查、两个仓库 `git diff --check` 通过。
- 独立 Vite 生产构建通过,产物写入 `/tmp/vibemake-pcb-real-build.xokcwi`,未覆盖既有主站或 PCB 部署产物。仍有既有 OCCT 浏览器模块及大 chunk 提示;PWA 预缓存 24 项。显式 mock 生产构建按预期被拒绝。
- 一次扩大回归运行 12 个文件、162 项:159 通过,`ui_font_tokens.test.ts` 的 3 项字体统计失败,指向本轮未修改的 `assets/site-brand` 品牌样式。没有为适配接口而改动字体样式或放宽断言。
- QA 类型检查仍有既有 3 个诊断:`dialog_about.test.tsx` 两处旧 reportBug 参数和 `viewer3d_chrome.test.ts` 一处隐式 any。本轮新测试没有额外类型诊断。
- 8091 主站开发服务已重启为真实接口模式;未登录请求 `/api/pcb/workspace/projects` 收到 dev 后端 401/UNAUTHORIZED、JSON 信封及 Cache-Control:no-store。
- 实际浏览器打开 `/pcb/`,确认无模拟标识;点击登录后真实邮箱/图片验证码弹窗能加载验证码。没有代用户解答验证码、登录或创建远端项目。
尚未完成真实账号下的 OSS 上传/确认、跨设备打开和服务端双标签并发联调;这些需要实际账号及启用后的存储环境,不能由上述契约测试推断通过。
---
日期:2026-11-04。环境:macOS、Node/pnpm、本地浏览器、开发模拟接口。基于 `7e01147` 的 PCB 仓库实施。
配套:[实施与部署](./pcb-integration-plan.md)、[后端接口要求](./pcb-backend-requirements.md)。模拟接口持久化到浏览器 IndexedDB,本记录没有把它当作真实云服务或跨设备验收。
## 自动检查
| 检查 | 结果 | 范围和限制 |
| --- | --- | --- |
| 相关测试 | 10 个文件、148 项通过 | 平台 11 项,以及原生保存、子页路径、旧任务隔离、设置、PWA 和界面契约 |
| 正式构建 | `pnpm -C designer build` 通过 | 包含 designer TypeScript 检查,产物 `designer/dist`,base `/pcb/` |
| 模拟包保护 | 预期拒绝构建 | `VITE_PCB_API_MODE=mock pnpm -C designer exec vite build` 返回开发模式禁止生产构建 |
| 新增模块格式和 lint | 通过 | `designer/src/platform`、两个公共快照模块、平台测试 |
| Hook 依赖 | 平台无诊断 | 修改范围全量扫描与原基线一致,既有 53 个警告没有增加;未使用依赖自动修复 |
| 仓库 biome | 9 个错误 | 与原基线相同的 9 个既有格式错误,没有新增错误 |
| 递归类型检查 | 未全绿 | 产品包通过;QA 有 3 个既有错误,详见下文 |
| 递归测试 | 未全绿 | 1544 个文件通过、34 个失败、9 个跳过;22666 项通过、87 项失败、757 项跳过 |
| 差异空白检查 | 通过 | `git diff --check` |
可重复运行相关测试:
```sh
pnpm -C qa exec vitest run \
unittests/designer/pcb_platform.test.ts \
unittests/designer/pcb_frame_needs_pgm.test.ts \
unittests/designer/project_sync_provider.test.ts \
unittests/designer/reload_keeps_edits.test.ts \
unittests/designer/settings_cloud_sync.test.ts \
unittests/designer/sw_update.test.ts \
unittests/designer/ui_font_tokens.test.ts \
unittests/eeschema/sheet_edit.test.ts \
unittests/designer/menu_ellipsis.test.ts \
unittests/common/wx_controls_ratchet.test.ts
```
平台用例实际解析并序列化 KiCad 原生文件,验证完整 ZIP 二次往返、图片/模型二进制、走线宽度、过孔钻孔、封装位置、区域间距和原理图属性。另覆盖同名子页、路径攻击、hash 篡改、缺失模型、账号隔离、同名项目、创建/确认幂等、并发冲突、删除后保存、安全命令边界、异步文件写队列、保存中新修改和未知确认恢复。
### 变异验证
把实现中的确认 revision 临时改为当前最新 revision,designer 类型检查通过,`only acknowledges` 用例按预期失败。再单独把该用例中“上传期间继续编辑后仍有未保存修改”的期望改为 false,用例也按预期失败。QA 类型检查仍只有同样的 3 个既有错误,无新增类型诊断;因此 QA 整体编译不能记为通过。两次变异都核对修改已生效,随后用补丁还原,平台 11 项及相关 148 项重新通过。
### 仓库既有失败
QA 类型错误:
- `qa/unittests/common/dialog_about.test.tsx:173`、`:184` 仍传入组件已不接受的 `reportBug`。
- `qa/unittests/designer/viewer3d_chrome.test.ts:276` 存在隐式 any。
递归测试中,多项旧测试直接使用 URL.pathname 读取含中文的工作区路径,把百分号编码当成文件路径,导致 ENOENT。其余失败涉及既有 About、Linux libm 对照、计算器、制造输出、界面常量统计、旧 SW 根路径断言及源码映射规则。
另将原提交提取到纯 ASCII 临时路径进行基线对照,结果为 1562 个文件通过、15 个失败、9 个跳过,23157 项通过、28 项失败、755 项跳过。该目录没有工作区 Git 元信息,且路径不同,两个总数不能作为逐项回归差值;对照只用于确认既有失败和路径依赖。本轮没有修改制造内核或将失败断言改成当前输出。
## 浏览器实际操作
| 操作 | 观察结果 |
| --- | --- |
| 模拟账号 A 新建空工程 | 生成原生主文件,进入 PCB,显示尚未保存 |
| 修改原生页面属性、模拟确认丢失、重试 | 保留工程和原批次,重试后显示已保存 |
| 返回列表并重新打开 | 已保存属性恢复,仍可进入原生属性编辑 |
| Arduino_Uno 模板创建非空工程 | 板框、焊盘、封装、飞线加载,首次保存成功 |
| 重开 Arduino 工程并修改标题 | 新修改标为未保存;“保存并离开”成功返回列表 |
| 再次重开并检查 Title | 恢复 `Arduino saved and reopened`,表单仍可编辑 |
| 三维查看 | 从已恢复工程加载板体、钻孔、焊盘和丝印;外部模型转换有现有 WRL 提示,未据此宣称全部模型成功 |
| 中英文切换 | 列表、网站外壳、原生菜单与保存/离开交互切换,不重建当前文档 |
| 切换模拟 A/B | B 不显示 A 项目,切回 A 后可见原项目 |
| 编辑中宽度缩至 820px | 显示电脑端遮罩,画布仍挂载;恢复宽度后继续编辑 |
界面按 ui-ux-pro-max 的弹窗焦点、输入锁、加载反馈和可达操作指导检查,品牌颜色以 VibeMake/CAD 为准。修正了网站菜单被原生工具栏覆盖、三维视图占据网站导航区域和窄桌面外观面板不能滚动的问题。
截图:
- [项目列表](./assets/pcb-project-list.jpg)
- [保存后重开的 PCB](./assets/pcb-editor-reopened.jpg)
- [重开后的三维视图](./assets/pcb-3d-reopened.jpg)
- [再次编辑保存后恢复的原生属性](./assets/pcb-reopened-properties.jpg)
## 主站导航对齐
PCB 导航从 `vibemake/css/style.css` 同步导航、按钮、头像和账号弹出层样式,并复用主站的本地 Sora / JetBrains Mono 字体、四档 Logo、菜单配置、SVG 图标和头像配色。React 外壳仅接入 PCB 的登录、语言和离开保护回调。
主站品牌调整后,在 PCB 仓库运行 `pnpm -C designer sync:site-navigation`;源目录不在默认相邻位置时使用 `pnpm -C designer sync:site-navigation /绝对路径/vibemake`。同步后的资源随 PCB 仓库独立构建,构建和部署不依赖主站源码目录。生成资源位于 `designer/src/assets/site-brand` 和 `designer/public/brand`,不应手工修改生成样式。
浏览器对照主站默认 1280px 视口:Logo 均为 112×42,导航内容最大宽度 1240、左右内边距 40,菜单间距 30;六项菜单的坐标、14px 字号、23.1px 行高及字体栈一致。PCB 当前项使用主站的白色文字和 4px 荧光绿圆点。账号为同款 36px 胶囊按钮。
窄桌面保留字体尺寸,通过折叠次要操作防止菜单换行及账号溢出;英文长菜单使用同款折叠菜单。导航中的社区搜索、发布入口前往主站页面,并经过现有工程离开保护。PCB 不运行主站业务脚本。
本轮针对变更执行类型检查、构建、格式与 Hook 检查、11 项平台测试,以及浏览器账号菜单、Escape 焦点恢复、语言切换和工程导航检查。上文记录的全仓既有失败不据此标记为解决。
截图:[对齐主站后的项目列表](./assets/pcb-navigation-aligned.jpg)。
## CAD 列表与编辑器栏对齐
项目列表直接使用从 `vibemake/css/cad.css` 同步的样式,复用 `cad-main`、标题、独立搜索框、卡片预览区、图标操作按钮及分页。同步脚本同时保存主站的标题字体规则、按钮禁用规则和 SVG 图标。列表的外层只处理 React flex 布局,保留 CAD 的 1240px 最大宽度和 `48px 40px 72px` 内边距。
编辑页复用同一个账号组件,以 CAD 的 42px 顶部栏、92×34 Logo、32px 保存图标呈现。移除全站菜单、项目名称、语言入口和原生“文件”左侧的旧 Logo。新 Logo 点击后经过现有离开保护返回项目列表;工程内工具、视图切换和保存入口仍可使用。旧独立入口保留原有 HomeLink,平台模式由外层统一提供 Logo。
浏览器实际打开已保存的非空 PCB,确认以上元素和尺寸、PCB 选中状态、账号菜单无语言入口、Escape 关闭菜单,以及 Logo 返回列表。编辑器加载前后,列表的字体、卡片和顶部位置保持一致。类型检查、11 项平台测试、变更文件格式检查、Hook 依赖检查及生产构建通过。构建仍有既有 OCCT 浏览器模块和大体积 chunk 提示。
截图:[CAD 同款项目列表](./assets/pcb-cad-style-list.jpg)、[紧凑编辑器顶部栏](./assets/pcb-cad-style-editor.jpg)。
## 尚需真实环境验收
前端真实适配已实现,业务后端和主站/CAD 功能代码未改动。真实环境还需验证同源 `vm.auth`、邮箱和图片验证码接口、OSS 签名/CORS、服务端 hash 与归档校验、账号权限以及跨浏览器持久化。
最终联调流程:主站登录后进入 `/pcb/`,浏览器 A 保存,浏览器 B 以同一账号打开并继续修改保存,A 重新读取新版;另一账号不得读取或覆盖该工程。断网、冲突、删除后保存和确认响应丢失也须在真实服务验证。
大工程峰值内存、全部第三方格式转换、完整制造输出和不同浏览器 GPU 表现尚未逐项回归。当前模拟验收不覆盖这些范围。发布配置及资源挂载由服务器联调阶段完成,本轮没有执行服务器部署。
+19 -10
View File
@@ -4,9 +4,8 @@
/**
* Multi-sheet project helpers, mirroring KiCad's SCH_SHEET_LIST hierarchy walk:
* the root schematic references sub-sheets through their "Sheetfile" field, each
* of which is another .kicad_sch document. Files are keyed by basename, KiCad
* projects normally keep all sheets beside the .kicad_pro, and relative paths
* resolve to the same basename.
* of which is another .kicad_sch document. Documents are keyed by project-relative
* path, so identically named sheets in different directories stay distinct.
*/
import type { Schematic, SchSheet } from './types.js';
@@ -23,11 +22,21 @@ export function sheetName(sheet: SchSheet): string {
return sheet.fields.find((f) => f.key === 'Sheetname')?.value ?? '';
}
/** The "Sheetfile" field as a basename ("sub/dir/amp.kicad_sch" -> "amp.kicad_sch"). */
export function sheetFile(sheet: SchSheet): string {
/** Resolve Sheetfile relative to the containing schematic, within the project. */
export function sheetFile(sheet: SchSheet, parentFile = ''): string {
const raw = sheet.fields.find((f) => f.key === 'Sheetfile')?.value ?? '';
const idx = Math.max(raw.lastIndexOf('/'), raw.lastIndexOf('\\'));
return idx === -1 ? raw : raw.slice(idx + 1);
if (!raw || raw.startsWith('/') || /^[A-Za-z]:/.test(raw)) return '';
const path = raw.startsWith('${KIPRJMOD}/')
? raw.slice('${KIPRJMOD}/'.length)
: parentFile.slice(0, Math.max(0, parentFile.lastIndexOf('/') + 1)) + raw;
const parts: string[] = [];
for (const part of path.replace(/\\/g, '/').split('/')) {
if (part === '..') {
if (!parts.length) return '';
parts.pop();
} else if (part && part !== '.') parts.push(part);
}
return parts.join('/');
}
export interface SheetTreeNode {
@@ -118,7 +127,7 @@ function buildSheetList(
// command addresses, so it is taken before the sort.
const sheets = doc.sheets.map((sh, i) => ({ sh, i })).sort((a, b) => byPosition(a.sh, b.sh));
for (const { sh, i } of sheets) {
const child = sheetFile(sh);
const child = sheetFile(sh, file);
if (child === '') continue;
// Append this sheet symbol's uuid (falling back to its index) so each
// instance of a shared file gets its own path.
@@ -308,8 +317,8 @@ export function findRootFile(docs: ReadonlyMap<string, Schematic>, proName?: str
if (docs.has(want)) return want;
}
const referenced = new Set<string>();
for (const doc of docs.values()) {
for (const sh of doc.sheets) referenced.add(sheetFile(sh));
for (const [file, doc] of docs) {
for (const sh of doc.sheets) referenced.add(sheetFile(sh, file));
}
for (const file of docs.keys()) {
if (!referenced.has(file)) return file;
+2
View File
@@ -58,6 +58,8 @@ function basename(p: string): string {
export function findProjectPro(files: readonly RawFile[], proBase?: string): RawFile | undefined {
const want = proBase ? `${proBase}.kicad_pro`.toLowerCase() : null;
if (want) {
const exact = files.find((f) => f.name.toLowerCase() === want);
if (exact) return exact;
const pinned = files.find(
(f) => PRO_RE.test(f.name) && basename(f.name).toLowerCase() === want,
);
+35 -11
View File
@@ -1,4 +1,6 @@
// SPDX-License-Identifier: GPL-3.0-or-later
import { projectSnapshotHost } from '@ziroeda/common/project_snapshot.js';
import { useProjectSnapshot } from '@ziroeda/common/use_project_snapshot.js';
// Copyright (C) 2026 ZiroEDA and contributors.
// Portions derived from KiCad, copyright The KiCad Developers. See NOTICE.md.
import type { HOSTED_LIBRARY } from '@ziroeda/common/libraries/library_manager.js';
@@ -3653,7 +3655,7 @@ export function SchematicEditor({
);
let parsed = 0;
for (const f of files) {
const base = f.name.split('/').pop()!.split('\\').pop()!;
const base = f.name.replace(/\\/g, '/');
if (/\.kicad_pro$/i.test(base)) {
// Prefer the active project's .kicad_pro (rootPro) so the editor and
// the launcher tree open the same root sheet. Absent that, fall back
@@ -3744,7 +3746,7 @@ export function SchematicEditor({
if (pageRepair.repaired) setLoadRepairedMessage(LOAD_REPAIRED_MESSAGE);
project.current = { docs, root };
// Home-page tree clicks land on the clicked sheet, else the root.
const startBase = startFile?.split('/').pop()?.split('\\').pop();
const startBase = startFile?.replace(/\\/g, '/');
const start = startBase && docs.has(startBase) ? startBase : root;
const wantRoot = proName?.replace(/\.kicad_pro$/i, '.kicad_sch');
if (wantRoot && !docs.has(wantRoot) && start === root)
@@ -3851,6 +3853,12 @@ export function SchematicEditor({
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [projectMetaKey, rootPro, openNonce, shown]);
const snapshotHost = useRef(projectSnapshotHost()).current;
useProjectSnapshot(
'schematic-safety',
{ flush: () => {}, isBusy: () => !(schFrameRef.current?.ToolStackIsEmpty() ?? true) },
unsaved ? doc : undefined,
);
// Serialize the project's sheets (current sheet + resident others) for autosave.
const serializeSheets = useCallback((): PickedFile[] => {
if (!doc) return [];
@@ -3860,12 +3868,13 @@ export function SchematicEditor({
for (const [file, d] of docs) {
try {
files.push({ name: file, text: serializeSchematic(d) });
} catch {
} catch (error) {
if (snapshotHost) throw error;
/* skip a bad sheet */
}
}
return files;
}, [doc, currentFile]);
}, [doc, currentFile, snapshotHost]);
// Autosave: once edits settle, hand the sheets up (App debounces the write to
// IndexedDB). Fires on sheet switch/load too, re-saving identical content.
@@ -3885,9 +3894,10 @@ export function SchematicEditor({
registerAutosaveFlush(() => {
const files = serializeSheets();
if (files.length) onProjectChange?.(files);
if (snapshotHost) setUnsaved(false);
});
return () => registerAutosaveFlush(null);
}, [registerAutosaveFlush, onProjectChange, serializeSheets]);
}, [registerAutosaveFlush, onProjectChange, serializeSheets, snapshotHost]);
// Switch the visible sheet (KiCad's Enter Sheet / hierarchy navigation): stash
// the edited current sheet back into the project, swap in the target document
@@ -3960,7 +3970,10 @@ export function SchematicEditor({
* editor.
*/
const [openDlgOpen, setOpenDlgOpen] = useState(false);
const promptOpen = useCallback(() => setOpenDlgOpen(true), []);
const promptOpen = useCallback(() => {
if (snapshotHost) snapshotHost.command?.('open');
else setOpenDlgOpen(true);
}, [snapshotHost]);
// Doc edits mark the title dirty; the flag clears after the app's coalesced
// autosave window (1.2 s) has taken the change. Mount / file switches skip.
@@ -3985,7 +3998,7 @@ export function SchematicEditor({
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [doc]);
const save = useCallback(() => {
const save = useCallback(async () => {
// Not inside a setDoc updater. A state updater must be pure — StrictMode
// runs it twice, which here meant persisting twice or firing two downloads
// — and it must not be where the work is decided: the document is read from
@@ -4006,7 +4019,12 @@ export function SchematicEditor({
// Save writes into the project's file manager (cloud storage); a local
// copy can be downloaded from there (or via Save a Copy). This is the
// path that also commits the Local History point.
void onSaveFiles([{ name: currentFile, text }]);
try {
await onSaveFiles([{ name: currentFile, text }]);
} catch (error) {
setInfoBar(`Could not save: ${error instanceof Error ? error.message : String(error)}`);
return;
}
} else if (onPersistFiles && currentFile !== DEFAULT_FILE) {
onPersistFiles([{ name: currentFile, text }]);
} else {
@@ -4038,10 +4056,11 @@ export function SchematicEditor({
const enc = new TextEncoder();
const dec = new TextDecoder();
const fs = new MEMORY_FILESYSTEM();
for (const f of rawFiles) fs.Write(f.name, enc.encode(f.text));
for (const f of rawFiles) fs.Write(f.name, f.bytes ?? enc.encode(f.text));
fs.SetWriteListener((aRel, aData) => {
const text = dec.decode(aData);
onPersistFiles?.([{ name: aRel, text }]);
if (snapshotHost) snapshotHost.writeFile(aRel, aData);
else onPersistFiles?.([{ name: aRel, text, bytes: aData }]);
// (TRANSITIONAL, with the mirror) the live project wrote its project file
// (SETTINGS_MANAGER::SaveProject): the window's copy and the Schematic Setup read from it
// follow the file, the one thing both models read, so neither writes over the other.
@@ -4063,7 +4082,7 @@ export function SchematicEditor({
schFrameRef.current?.Prj().DesignBlockLibs().AsyncLoad();
designBlocksPane.RefreshLibs();
return unmount;
}, [rawFiles, projectName, onPersistFiles, rootPro, designBlocksPane]);
}, [rawFiles, projectName, onPersistFiles, rootPro, designBlocksPane, snapshotHost]);
const liveMirrorRef = useRef<LIVE_SCHEMATIC_MIRROR | null>(null);
const inEditLiveRef = useRef(false);
const adoptLiveScreensRef = useRef<(aScreens: Iterable<SCH_SCREEN>) => void>(() => {});
@@ -4884,6 +4903,10 @@ export function SchematicEditor({
const onTopAction = useCallback(
(id: string) => {
if (snapshotHost && id === 'save') {
void snapshotHost.save().catch(() => undefined);
return;
}
// the canvas-editing actions run on the frame's TOOL_MANAGER (TRANSITIONAL, W2).
const galAction = schToolbarAction(id);
const galMgr = schFrameRef.current?.GetToolManager();
@@ -5024,6 +5047,7 @@ export function SchematicEditor({
selection,
runRescueSymbols,
runLiveAction,
snapshotHost,
],
);
@@ -1,4 +1,7 @@
// SPDX-License-Identifier: GPL-3.0-or-later
import { projectSnapshotHost } from '@ziroeda/common/project_snapshot.js';
import { useProjectSnapshot } from '@ziroeda/common/use_project_snapshot.js';
import { SCH_IO_KICAD_SEXPR_LIB_CACHE } from '../sch_io/kicad_sexpr/sch_io_kicad_sexpr_lib_cache.js';
// Copyright (C) 2026 ZiroEDA and contributors.
// Portions derived from KiCad, copyright The KiCad Developers. See NOTICE.md.
/**
@@ -296,7 +299,7 @@ export function SymbolEditor({
const symRightBar = app.useToolbarEntries('symbol_editor', 'RIGHT', SYM_DEFAULT_TOOLBARS);
/** Anything the frame changed: re-read it. */
const [, repaint] = useReducer((n: number) => n + 1, 0);
const [snapshotRevision, repaint] = useReducer((n: number) => n + 1, 0);
// ----- window state -----------------------------------------------------------
const [session, setSession] = useState<ReadonlySet<string>>(
@@ -1191,6 +1194,11 @@ export function SymbolEditor({
/** A top-toolbar or right-toolbar button, or a menu row: its action or the window's own. */
const onAction = useCallback(
(id: string) => {
const host = projectSnapshotHost();
if (host && (id === 'save' || id === 'saveAll')) {
void host.save().catch(() => undefined);
return;
}
switch (id) {
case 'openPreferences':
setPrefsOpen(true);
@@ -1253,6 +1261,32 @@ export function SymbolEditor({
// ----- title -----------------------------------------------------------------------
const modified = frame.GetScreen()?.IsContentModified() === true;
const snapshotHost = useRef(projectSnapshotHost()).current;
useProjectSnapshot(
'symbols',
{
isDirty: () => frame.HasLibModifications() || frame.GetScreen()?.IsContentModified() === true,
isBusy: () => !frame.ToolStackIsEmpty(),
flush: async () => {
if (!snapshotHost) return;
if (frame.IsSymbolFromSchematic() && frame.GetScreen()?.IsContentModified()) {
if (!(await frame.saveCurrentSymbol()))
throw new Error('Could not write symbol back to schematic');
}
for (const nickname of libManager.GetLibraryNames()) {
if (!libManager.IsLibraryModified(nickname)) continue;
snapshotHost.storeLibrary(
'symbols',
nickname,
SCH_IO_KICAD_SEXPR_LIB_CACHE.FormatLibrary(libManager.EnumerateSymbols(nickname)),
);
libManager.ClearLibraryModified(nickname);
}
frame.GetScreen()?.SetContentModified(false);
},
},
snapshotRevision,
);
const symTitle = symFrameTitle(
{
hasSymbol: symbol !== null,
+19 -1
View File
@@ -1,4 +1,6 @@
// SPDX-License-Identifier: GPL-3.0-or-later
import { projectSnapshotHost } from '@ziroeda/common/project_snapshot.js';
import { useProjectSnapshot } from '@ziroeda/common/use_project_snapshot.js';
// Copyright (C) 2026 ZiroEDA and contributors.
// Portions derived from KiCad, copyright The KiCad Developers. See NOTICE.md.
/**
@@ -275,7 +277,7 @@ export function PlEditorFrameWindow({
const recent = useFileHistory(recentFiles);
/** Re-render the chrome: wx repaints its widgets on its own. */
const [, repaint] = useReducer((n: number) => n + 1, 0);
const [snapshotRevision, repaint] = useReducer((n: number) => n + 1, 0);
/**
* `IFACE::OnKifaceStart` + `CreateKiWindow( FRAME_PL_EDITOR )`: the settings
@@ -755,6 +757,22 @@ export function PlEditorFrameWindow({
),
);
const snapshotHost = useRef(projectSnapshotHost()).current;
useProjectSnapshot(
'drawing-sheet',
{
isDirty: () => attached && frame.IsContentModified(),
isBusy: () => !frame.ToolStackIsEmpty(),
flush: () => {
if (!snapshotHost || !attached || !frame.IsContentModified()) return;
const path = frame.GetCurrentFileName();
const name = path ? (snapshotHost.relativePath?.(path) ?? path) : 'drawing-sheet.kicad_wks';
snapshotHost.writeFile(name, new TextEncoder().encode(PlDataModel().SaveInString()));
frame.GetScreen()?.SetContentModified(false);
},
},
snapshotRevision,
);
// This editor has no autosave: stop an accidental close of a modified sheet.
useUnsavedGuard(attached && frame.IsContentModified());
+29 -1
View File
@@ -1,4 +1,7 @@
// SPDX-License-Identifier: GPL-3.0-or-later
import { projectSnapshotHost } from '@ziroeda/common/project_snapshot.js';
import { useProjectSnapshot } from '@ziroeda/common/use_project_snapshot.js';
import { FormatFootprintForLibrary } from './pcb_io/kicad_sexpr/pcb_io_kicad_sexpr.js';
// Copyright (C) 2026 ZiroEDA and contributors.
// Portions derived from KiCad, copyright The KiCad Developers. See NOTICE.md.
/**
@@ -361,7 +364,7 @@ export function FootprintEditFrame({
rightBarRef.current = fpRightBar;
/** Anything the frame changed: re-read it. */
const [, repaint] = useReducer((n: number) => n + 1, 0);
const [snapshotRevision, repaint] = useReducer((n: number) => n + 1, 0);
// ----- window state -----------------------------------------------------------
// The sketch modes are `fpedit.json`'s, which the frame's settings object is loaded from below.
@@ -1141,6 +1144,11 @@ export function FootprintEditFrame({
const onMenuAction = useCallback(
(id: string) => {
const host = projectSnapshotHost();
if (host && id === 'save') {
void host.save().catch(() => undefined);
return;
}
switch (id) {
case 'newLibrary':
// PCB_BASE_EDIT_FRAME::CreateNewLibrary: LibraryFileBrowser with the new-library
@@ -1261,6 +1269,26 @@ export function FootprintEditFrame({
});
const modified = frame.IsContentModified();
const snapshotHost = useRef(projectSnapshotHost()).current;
useProjectSnapshot(
'footprints',
{
isDirty: () => frame.IsContentModified(),
isBusy: () => !frame.ToolStackIsEmpty(),
flush: () => {
const footprint = frame.GetBoard()?.Footprints()[0];
if (!snapshotHost || !footprint || !frame.IsContentModified()) return;
snapshotHost.storeLibrary(
'footprints',
footprint.GetFPID().GetLibNickname() || 'Project',
FormatFootprintForLibrary(footprint),
footprint.GetFPID().GetLibItemName() || 'Footprint',
);
frame.GetScreen()?.SetContentModified(false);
},
},
snapshotRevision,
);
useDocumentTitle('footprints', formatTitle(FP_FRAME_NAME, title, false));
useUnsavedGuard(modified);
+2
View File
@@ -3658,6 +3658,8 @@ function basename(p: string): string {
export function findProjectPro(files: readonly RawFile[], proBase?: string): RawFile | undefined {
const want = proBase ? `${proBase}.kicad_pro`.toLowerCase() : null;
if (want) {
const exact = files.find((f) => f.name.toLowerCase() === want);
if (exact) return exact;
const pinned = files.find(
(f) => PRO_RE.test(f.name) && basename(f.name).toLowerCase() === want,
);
+37 -3
View File
@@ -1,4 +1,6 @@
// SPDX-License-Identifier: GPL-3.0-or-later
import { projectSnapshotHost } from '@ziroeda/common/project_snapshot.js';
import { useProjectSnapshot } from '@ziroeda/common/use_project_snapshot.js';
// Copyright (C) 2026 ZiroEDA and contributors.
// Portions derived from KiCad, copyright The KiCad Developers. See NOTICE.md.
/**
@@ -1116,7 +1118,7 @@ export function PcbEditor({
projectName?: string;
/** The open project's files (name + text), lets the 3D viewer resolve
* ${KIPRJMOD}/relative model references to project-bundled files. */
projectFiles?: { name: string; text: string }[];
projectFiles?: { name: string; text: string; bytes?: Uint8Array }[];
/** Base name of the active `.kicad_pro` (scopes multi-project folders). */
rootPro?: string;
/** Persist project files immediately (Board Setup writes the `.kicad_pro`
@@ -2777,9 +2779,11 @@ export function PcbEditor({
* (`MAIL_IMPORT_FILE` -> `importFile`, pcb_edit_frame.cpp), as upstream's two
* callers share OpenProjectFiles.
*/
const platformImportBusy = useRef(false);
const importNonKicadFile = (aPath: string, aBytes: Uint8Array): void => {
const frame = frameRef.current;
if (!frame) return;
platformImportBusy.current = true;
void frame
.ImportNonKicadBoard(
aPath,
@@ -2840,7 +2844,10 @@ export function PcbEditor({
setInfoBarError(
`Error loading PCB '${aPath}'.\n${e instanceof Error ? e.message : String(e)}`,
),
);
)
.finally(() => {
platformImportBusy.current = false;
});
};
// `MAIL_IMPORT_FILE`, delivered once: after this frame's own open has
@@ -3128,14 +3135,31 @@ export function PcbEditor({
// every drop froze the editor for that long. An edit landing while the
// text is being built aborts it (the effect's cleanup); the next quiet
// second starts over.
const snapshotHost = useRef(projectSnapshotHost()).current;
const serializationEpoch = useRef(0);
useProjectSnapshot(
'pcb-safety',
{
flush: () => {
if (snapshotHost) saveProjectLocalSettings();
},
isBusy: () =>
platformImportBusy.current ||
loading !== null ||
!(frameRef.current?.ToolStackIsEmpty() ?? true),
isDirty: () => dirtyRef.current,
},
dirty ? boardSettingsRev : undefined,
);
useEffect(() => {
if (!dirty || !onBoardChange) return;
const epoch = ++serializationEpoch.current;
let cancelled = false;
const id = setTimeout(async () => {
const brd = boardRef.current;
if (!brd) return;
const text = await FormatBoardAsync(brd.k, yieldToEventLoop, () => cancelled);
if (cancelled || text === null) return;
if (cancelled || text === null || epoch !== serializationEpoch.current) return;
onBoardChange(text);
setDirty(false);
}, 1000);
@@ -3154,11 +3178,13 @@ export function PcbEditor({
useEffect(() => {
if (!registerAutosaveFlush) return;
registerAutosaveFlush(() => {
serializationEpoch.current++;
const brd = boardRef.current;
// Not dirty means the last serialization already reached the host, and
// re-serializing a large board on every tab hide is not free.
if (!brd || !dirtyRef.current || !onBoardChange) return;
onBoardChange(FormatBoard(brd.k));
dirtyRef.current = false;
setDirty(false);
});
return () => registerAutosaveFlush(null);
@@ -6316,6 +6342,14 @@ export function PcbEditor({
};
const onTopAction = (id: string): void => {
if (snapshotHost && id === 'save') {
void snapshotHost.save().catch(() => undefined);
return;
}
if (snapshotHost && id === 'saveCopy') {
snapshotHost.command?.('download');
return;
}
switch (id) {
case 'save':
// Save writes into the project's file manager (cloud storage); users
+3 -1
View File
@@ -679,6 +679,9 @@ importers:
fake-indexeddb:
specifier: ^6.2.5
version: 6.2.5
fflate:
specifier: ^0.8.3
version: 0.8.3
happy-dom:
specifier: ^20.11.6
version: 20.11.6
@@ -2779,7 +2782,6 @@ packages:
glob@11.1.0:
resolution: {integrity: sha512-vuNwKSaKiqm7g0THUBu2x7ckSs3XJLXE+2ssL7/MfTGPLLcrJQ/4Uq1CjPTtO5cCIiRxqvN6Twy1qOwhL0Xjcw==}
engines: {node: 20 || >=22}
deprecated: Old versions of glob are not supported, and contain widely publicized security vulnerabilities, which have been fixed in the current version. Please update. Support for old versions may be purchased (at exorbitant rates) by contacting i@izs.me
hasBin: true
glob@13.0.6:
+1
View File
@@ -42,6 +42,7 @@
"@types/react": "^18.3.31",
"@types/react-dom": "^18.3.7",
"fake-indexeddb": "^6.2.5",
"fflate": "^0.8.3",
"happy-dom": "^20.11.6",
"react": "^18.3.1",
"react-dom": "^18.3.1"
+84
View File
@@ -0,0 +1,84 @@
// @vitest-environment happy-dom
// SPDX-License-Identifier: GPL-3.0-or-later
import { cleanup, fireEvent, render } from '@testing-library/react';
import { useState } from 'react';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { jsx, jsxs, jsxDEV } from '@ziroeda/common/jsx-runtime.js';
import { setUiLanguage } from '@ziroeda/common/i18n.js';
beforeEach(() => {
setUiLanguage('简体中文');
});
afterEach(() => {
cleanup();
vi.restoreAllMocks();
setUiLanguage('English');
});
describe('localized JSX child identity', () => {
it.each([
'jsxs',
'jsxDEV',
] as const)('%s preserves static siblings without requiring list keys', (runtime) => {
const errors = vi.spyOn(console, 'error').mockImplementation(() => {});
const props = {
children: [jsx('span', { children: 'Save' }), jsx('span', { children: 'Cancel' })],
};
const { container } = render(
runtime === 'jsxs' ? jsxs('header', props) : jsxDEV('nav', props, undefined, true),
);
expect(container.textContent).toBe('保存取消');
expect(errors).not.toHaveBeenCalled();
});
it('still warns when a dynamic list is missing keys', () => {
const errors = vi.spyOn(console, 'error').mockImplementation(() => {});
render(
jsx('ol', {
children: ['first', 'second'].map((name) => jsx('li', { children: name })),
}),
);
expect(
errors.mock.calls.some(([message]) =>
String(message).includes('Each child in a list should have a unique "key" prop'),
),
).toBe(true);
});
it('still validates dynamic lists nested among static siblings', () => {
const errors = vi.spyOn(console, 'error').mockImplementation(() => {});
render(
jsxs('ul', {
children: [
jsx('li', { children: 'fixed' }),
['first', 'second'].map((name) => jsx('li', { children: name })),
],
}),
);
expect(
errors.mock.calls.some(([message]) =>
String(message).includes('Each child in a list should have a unique "key" prop'),
),
).toBe(true);
});
it('keeps keyed row state attached to its identity after reordering', () => {
const errors = vi.spyOn(console, 'error').mockImplementation(() => {});
function Row({ code }: { code: string }): JSX.Element {
const [count, setCount] = useState(0);
return jsx('button', {
'aria-label': code,
onClick: () => setCount(count + 1),
children: `${code}: ${count}`,
});
}
const list = (codes: string[]) =>
jsx('section', { children: codes.map((code) => jsx(Row, { code }, code)) });
const view = render(list(['project-a', 'project-b']));
fireEvent.click(view.getByRole('button', { name: 'project-a' }));
view.rerender(list(['project-b', 'project-a']));
expect(view.getByRole('button', { name: 'project-a' }).textContent).toBe('project-a: 1');
expect(view.getByRole('button', { name: 'project-b' }).textContent).toBe('project-b: 0');
expect(errors).not.toHaveBeenCalled();
});
});
@@ -43,7 +43,10 @@ const AREAS = [
/** The wx layer itself. */
const EXEMPT = (aRel: string): boolean =>
aRel.startsWith('external/wx/') || aRel === 'common/dialog_shim.tsx';
aRel.startsWith('external/wx/') ||
aRel === 'common/dialog_shim.tsx' ||
// The VibeMake website shell intentionally uses web dialogs, while engineering tools use wx.
aRel.startsWith('designer/src/platform/');
const KINDS = {
button: /<button\b/g,
@@ -1061,6 +1061,8 @@ function scan(): Site[] {
(function walk(dir: string) {
for (const entry of readdirSync(dir)) {
const p = join(dir, entry);
// VibeMake's website shell follows its own brand tokens; native frames keep GTK parity.
if (p === join(SRC, 'platform')) continue;
if (statSync(p).isDirectory()) walk(p);
else if (/\.(css|tsx|ts)$/.test(p)) files.push(p);
}
@@ -56,6 +56,8 @@ function* codeLines(): Generator<{ where: string; line: string }> {
for (const rel of SOURCE_DIRS) {
for (const full of walk(ROOT + rel)) {
// The platform website uses VibeMake copy; this convention governs native editors.
if (full.startsWith(`${ROOT}designer/src/platform/`)) continue;
const src = readFileSync(full, 'utf8');
// Both spellings. `'\\u2026'` is the same character to the user and
// invisible to a search for the glyph — six sites were written that way
@@ -69,12 +69,20 @@ describe('PCB_EDIT_FRAME needs the PGM_BASE before its first SetBoard', () => {
});
describe('PGM_BASE::InitPgm runs at program start, before any frame', () => {
it('main.tsx installs it before the app renders', () => {
const main = readFileSync(resolve(process.cwd(), '../designer/src/main.tsx'), 'utf8');
it('initializes the lazy engineering environment before mounting a frame', () => {
const main = readFileSync(
resolve(process.cwd(), '../designer/src/platform/editor-environment.tsx'),
'utf8',
);
const host = readFileSync(
resolve(process.cwd(), '../designer/src/platform/EditorHost.tsx'),
'utf8',
);
const init = main.indexOf('InitPgm();');
const render = main.indexOf('createRoot(');
const render = host.indexOf('<App platform={bridge}');
expect(init).toBeGreaterThan(0);
expect(init).toBeLessThan(render);
expect(host.indexOf('initializeEditorEnvironment(runtime.ownerUserCode)')).toBeLessThan(render);
expect(host).toContain('ready ?');
});
it('is installed once, and the PCB editor builds on the same object', async () => {
+441
View File
@@ -0,0 +1,441 @@
// SPDX-License-Identifier: GPL-3.0-or-later
import 'fake-indexeddb/auto';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { HttpPcbProjectApi, platformRequest } from '@ziroeda/designer/src/platform/api.js';
import { createArchive, importFiles, openArchive } from '@ziroeda/designer/src/platform/archive.js';
import { WorkspaceRuntime } from '@ziroeda/designer/src/platform/runtime.js';
import { listPending } from '@ziroeda/designer/src/platform/storage.js';
import { parseWorkspaceRoute, workspaceHref } from '@ziroeda/designer/src/platform/routes.js';
import {
DEFAULT_LIMITS,
platformTime,
type AuthRecord,
type PcbProject,
type SaveReceipt,
type UploadRequest,
} from '@ziroeda/designer/src/platform/types.js';
vi.mock('@ziroeda/designer/src/platform/archive-client.js', async () => {
const archive = await import('@ziroeda/designer/src/platform/archive.js');
return { packProject: archive.createArchive, unpackProject: archive.openArchive };
});
const fetcher = vi.fn<typeof fetch>();
const time = '2026-11-05T12:30:00';
const project = (): PcbProject => ({
pcbProjectCode: 'pcb:opaque-code',
name: '控制板',
description: '',
coverUrl: null,
hasDocument: false,
version: 0,
fileName: '',
sizeBytes: 0,
savedAt: null,
createdAt: time,
updatedAt: time,
});
const reply = (data: unknown, status = 200, code = 'OK', headers: Record<string, string> = {}) =>
new Response(JSON.stringify({ code, message: code, data, requestId: 'request-1' }), {
status,
headers,
});
const identity = (): AuthRecord => ({
token: 'platform-token',
user: { userCode: crypto.randomUUID() },
expiresAt: Date.now() + 86400000,
});
function client(record = identity()) {
const controller = new AbortController();
const current = { value: record as AuthRecord | null };
const api = new HttpPcbProjectApi(record, () => current.value, controller.signal);
return { api, current, controller, record };
}
const request = (sizeBytes = 3): UploadRequest => ({
fileName: 'project.zip',
sizeBytes,
expectedVersion: 0,
sha256: 'a'.repeat(64),
clientOperationId: crypto.randomUUID(),
archiveFormat: 'vibemake-pcb-project+zip',
manifestVersion: 1,
});
const signature = () => ({
uploadCode: 'batch-1',
uploadUrl: 'https://bucket.example.test/',
expiresAt: '2026-11-05T12:45:00',
formFields: {
key: 'vibemake_dev/pcb-projects/p/b/project.zip',
policy: 'opaque-policy',
Signature: 'opaque-signature',
},
});
beforeEach(() => {
vi.stubGlobal('location', { hostname: '127.0.0.1', origin: 'http://127.0.0.1:8091' });
vi.stubGlobal('window', new EventTarget());
vi.stubGlobal('fetch', fetcher);
fetcher.mockReset();
});
afterEach(() => {
vi.unstubAllGlobals();
vi.useRealTimers();
});
describe('published PCB workspace HTTP contract', () => {
it('uses the eight documented project endpoints without a capabilities request or undocumented POST fields', async () => {
const { api } = client();
expect((await api.capabilities()).maxArchiveBytes).toBe(268435456);
expect(fetcher).not.toHaveBeenCalled();
fetcher.mockResolvedValueOnce(reply(project()));
const created = await api.create('控制板', 'local-create-id');
expect(created.createdAt).toBe('2026-11-05T04:30:00.000Z');
expect(JSON.parse(String(fetcher.mock.calls[0]![1]?.body))).toEqual({
name: '控制板',
description: '',
});
fetcher.mockResolvedValueOnce(reply({ items: [project()], total: 1, page: 2, size: 20 }));
expect((await api.list(2, '控制')).total).toBe(1);
expect(String(fetcher.mock.calls[1]![0])).toContain('page=2&size=20&keyword=');
fetcher.mockResolvedValueOnce(reply(project()));
await api.get(created.pcbProjectCode);
fetcher.mockResolvedValueOnce(reply({ ...project(), name: '新名字' }));
expect((await api.rename(created.pcbProjectCode, '新名字')).name).toBe('新名字');
fetcher.mockResolvedValueOnce(reply(signature()));
const signed = await api.sign(created.pcbProjectCode, request());
expect(signed.expiresAt).toBe('2026-11-05T04:45:00.000Z');
expect(JSON.parse(String(fetcher.mock.calls[4]![1]?.body))).toEqual({
fileName: 'project.zip',
sizeBytes: 3,
expectedVersion: 0,
});
fetcher.mockResolvedValueOnce(
reply({ pcbProjectCode: created.pcbProjectCode, version: 1, savedAt: time }),
);
expect(await api.commit(created.pcbProjectCode, signed.uploadCode)).toEqual({
pcbProjectCode: created.pcbProjectCode,
version: 1,
savedAt: '2026-11-05T04:30:00.000Z',
});
expect(JSON.parse(String(fetcher.mock.calls[5]![1]?.body))).toEqual({ uploadCode: 'batch-1' });
fetcher.mockResolvedValueOnce(reply(null));
await api.remove(created.pcbProjectCode);
for (const [url, init] of fetcher.mock.calls) {
expect(String(url)).toMatch(/^\/api\/pcb\/workspace\/projects/);
expect(init?.cache).toBe('no-store');
expect(new Headers(init?.headers).get('Authorization')).toBe('Bearer platform-token');
}
const route = parseWorkspaceRoute('/pcb/p/pcb%3Aopaque-code/pcb');
expect(route.code).toBe(created.pcbProjectCode);
expect(workspaceHref(route)).toBe('/pcb/p/pcb%3Aopaque-code/pcb');
});
it('uploads all signed fields unchanged, with a ZIP file last and no platform credentials or JSON parsing', async () => {
const { api } = client();
fetcher.mockResolvedValueOnce(new Response('', { status: 200 }));
await api.upload(signature(), new Uint8Array([0, 128, 255]));
const [url, init] = fetcher.mock.calls[0]!;
expect(url).toBe(signature().uploadUrl);
expect(init?.credentials).toBe('omit');
expect(init?.headers).toBeUndefined();
const entries = [...(init!.body as FormData).entries()];
expect(entries.slice(0, -1)).toEqual(Object.entries(signature().formFields));
expect(entries.at(-1)?.[0]).toBe('file');
const file = entries.at(-1)![1] as File;
expect(file.type).toBe('application/zip');
expect(new Uint8Array(await file.arrayBuffer())).toEqual(new Uint8Array([0, 128, 255]));
});
it('reads a public document without server-only hashes and uses its version instead of stale project metadata', async () => {
const { api } = client();
const native = importFiles([
{ name: 'main.kicad_pcb', bytes: new TextEncoder().encode('(kicad_pcb)') },
{ name: 'models3d/a.step', bytes: new Uint8Array([0, 255, 128]) },
]);
const packed = await createArchive(native, 'test');
fetcher.mockResolvedValueOnce(reply({ ...project(), hasDocument: true, version: 1 }));
const metadata = await api.get(project().pcbProjectCode);
fetcher.mockResolvedValueOnce(
reply({
downloadUrl: 'https://cdn.example.test/project.zip',
expiresAt: null,
version: 2,
fileName: 'project.zip',
sizeBytes: packed.bytes.length,
}),
);
const document = await api.document(metadata.pcbProjectCode);
fetcher.mockResolvedValueOnce(new Response(new Uint8Array(packed.bytes)));
const opened = await openArchive(await api.download(document, DEFAULT_LIMITS));
expect(opened.files.find((f) => f.name === 'models3d/a.step')?.bytes).toEqual(
new Uint8Array([0, 255, 128]),
);
const init = fetcher.mock.calls[2]![1]!;
expect(init.credentials).toBe('omit');
expect(init.headers).toBeUndefined();
const runtime = new WorkspaceRuntime(
'user',
{ ...metadata, version: document.version },
opened,
api,
DEFAULT_LIMITS,
'test',
);
expect(runtime.baseVersion).toBe(2);
runtime.writeFile('notes.txt', new Uint8Array([99]));
expect(runtime.dirty).toBe(true);
runtime.revoke();
});
it('rejects truncated downloads, non-HTTPS storage URLs and malformed signatures', async () => {
const { api } = client();
const document = {
pcbProjectCode: 'p',
version: 1,
fileName: 'project.zip',
sizeBytes: 3,
downloadUrl: 'https://cdn.example.test/project.zip',
expiresAt: null,
} as const;
fetcher.mockResolvedValueOnce(new Response(new Uint8Array([1])));
await expect(api.download(document, DEFAULT_LIMITS)).rejects.toMatchObject({
code: 'PCB_HASH_MISMATCH',
});
fetcher.mockResolvedValueOnce(
reply({ ...signature(), uploadUrl: 'http://untrusted.example.test/' }),
);
await expect(api.sign('p', request())).rejects.toMatchObject({ code: 'BAD_RESPONSE' });
fetcher.mockResolvedValueOnce(reply({ ...signature(), formFields: [] }));
await expect(api.sign('p', request())).rejects.toMatchObject({ code: 'BAD_RESPONSE' });
await expect(api.sign('p', { ...request(), expectedVersion: 1.5 })).rejects.toMatchObject({
code: 'PCB_INVALID_FILE',
});
});
it('surfaces 401 without clearing identity and ignores stale account responses', async () => {
const { api, current, record } = client();
const unauthorized = vi.fn();
window.addEventListener('vm:pcb:unauthorized', unauthorized);
fetcher.mockResolvedValueOnce(reply(null, 401, 'UNAUTHORIZED'));
await expect(api.get('p')).rejects.toMatchObject({
code: 'UNAUTHORIZED',
requestId: 'request-1',
});
expect(current.value).toBe(record);
expect(unauthorized).toHaveBeenCalledOnce();
fetcher.mockImplementationOnce(async () => {
current.value = identity();
return reply(project());
});
await expect(api.get('p')).rejects.toMatchObject({ code: 'STALE_IDENTITY' });
});
it('honors Retry-After without automatically replaying a write request', async () => {
vi.useFakeTimers();
const { api } = client();
fetcher.mockResolvedValueOnce(reply(null, 429, 'RATE_LIMITED', { 'Retry-After': '5' }));
await expect(api.commit('p', 'u')).rejects.toMatchObject({
code: 'RATE_LIMITED',
retryAfterMs: 5000,
});
await expect(api.commit('p', 'u')).rejects.toMatchObject({ code: 'RATE_LIMITED' });
expect(fetcher).toHaveBeenCalledOnce();
vi.advanceTimersByTime(5000);
fetcher.mockResolvedValueOnce(reply({ pcbProjectCode: 'p', version: 1, savedAt: time }));
await expect(api.commit('p', 'u')).resolves.toHaveProperty('version', 1);
});
it('does not assume backend create idempotency after an unknown POST result', async () => {
const { api } = client();
fetcher.mockRejectedValueOnce(new TypeError('connection lost'));
await expect(api.create('控制板', 'form-1')).rejects.toMatchObject({
code: 'UNKNOWN_CREATION',
});
await expect(api.create('控制板', 'form-1')).rejects.toMatchObject({
code: 'UNKNOWN_CREATION',
});
expect(fetcher).toHaveBeenCalledOnce();
});
it('normalizes Shanghai timestamps while preserving explicit offsets and reports server fault codes', async () => {
expect(platformTime('2026-11-05 12:30:00')).toBe('2026-11-05T04:30:00.000Z');
expect(platformTime('2026-11-05T04:30:00Z')).toBe('2026-11-05T04:30:00.000Z');
for (const [status, code] of [
[404, 'PCB_DOCUMENT_NOT_FOUND'],
[409, 'PCB_VERSION_CONFLICT'],
[503, 'PCB_STORAGE_UNAVAILABLE'],
] as const) {
fetcher.mockResolvedValueOnce(reply(null, status, code));
await expect(
platformRequest('/pcb/workspace/projects', 'platform-token'),
).rejects.toMatchObject({ code, status });
}
});
});
describe('real HTTP save and recovery', () => {
function server() {
const { api, record } = client();
const metadata = project();
const archive = { bytes: undefined as Uint8Array | undefined };
let saved: SaveReceipt | undefined;
let loseConfirmation = false;
let uploads = 0;
let signs = 0;
const commitCodes: string[] = [];
fetcher.mockImplementation(async (input, init) => {
const url = String(input);
if (url.endsWith('/uploads/signature')) {
signs++;
return reply({ ...signature(), uploadCode: `batch-${signs}` });
}
if (url === signature().uploadUrl) {
uploads++;
archive.bytes = new Uint8Array(
await ((init!.body as FormData).get('file') as File).arrayBuffer(),
);
return new Response('', { status: 200 });
}
if (url.endsWith('/document') && init?.method === 'PUT') {
commitCodes.push(JSON.parse(String(init.body)).uploadCode);
if (!archive.bytes) return reply(null, 409, 'PCB_FILE_MISSING');
saved ??= { pcbProjectCode: metadata.pcbProjectCode, version: 1, savedAt: time };
if (loseConfirmation) {
loseConfirmation = false;
throw new TypeError('response lost');
}
return reply(saved);
}
throw new Error(`Unexpected request: ${url}`);
});
const native = importFiles([
{ name: 'main.kicad_pcb', bytes: new TextEncoder().encode('(kicad_pcb)') },
]);
const runtime = new WorkspaceRuntime(
record.user.userCode,
metadata,
native,
api,
DEFAULT_LIMITS,
'test',
);
return {
api,
metadata,
runtime,
record,
archive,
commitCodes,
native,
loseNextConfirmation() {
loseConfirmation = true;
},
counts() {
return { uploads, signs };
},
};
}
it('accepts a minimal real receipt and acknowledges only the snapshot uploaded', async () => {
const s = server();
const upload = s.api.upload.bind(s.api);
s.api.upload = async (sig, bytes) => {
s.runtime.writeFile('late.bin', new Uint8Array([255]));
await upload(sig, bytes);
};
try {
await s.runtime.save();
expect(s.runtime.getSnapshot().phase).toBe('dirty');
expect(s.runtime.baseVersion).toBe(1);
expect(s.counts()).toEqual({ uploads: 1, signs: 1 });
expect(s.commitCodes).toEqual(['batch-1']);
expect((await openArchive(s.archive.bytes!)).files.some((f) => f.name === 'late.bin')).toBe(
false,
);
} finally {
s.runtime.revoke();
}
});
it('recovers a lost confirmation with the original batch, without uploading again or incrementing twice', async () => {
const s = server();
s.runtime.modified();
s.loseNextConfirmation();
await expect(s.runtime.save()).rejects.toThrow('response lost');
const pending = await listPending(s.record.user.userCode, s.metadata.pcbProjectCode);
expect(pending).toHaveLength(1);
s.runtime.revoke();
const recovered = new WorkspaceRuntime(
s.record.user.userCode,
s.metadata,
s.native,
s.api,
DEFAULT_LIMITS,
'test',
);
try {
recovered.adoptPending(pending[0]!);
await recovered.save();
expect(recovered.baseVersion).toBe(1);
expect(s.counts()).toEqual({ uploads: 1, signs: 1 });
expect(s.commitCodes).toEqual(['batch-1', 'batch-1']);
expect(await listPending(s.record.user.userCode, s.metadata.pcbProjectCode)).toHaveLength(0);
} finally {
recovered.revoke();
}
});
it('keeps local design and batch on a version conflict', async () => {
const s = server();
const fetchSaved = fetcher.getMockImplementation()!;
fetcher.mockImplementation(async (url, init) =>
String(url).endsWith('/document')
? reply(null, 409, 'PCB_VERSION_CONFLICT')
: fetchSaved(url, init),
);
try {
await expect(s.runtime.save()).rejects.toMatchObject({ code: 'PCB_VERSION_CONFLICT' });
expect(s.runtime.getSnapshot().phase).toBe('conflict');
expect(s.runtime.baseVersion).toBe(0);
expect(s.runtime.hasPending).toBe(true);
expect(s.runtime.nativeProject().files).toHaveLength(1);
} finally {
s.runtime.revoke();
}
});
it('confirms the original batch when the OSS upload response disappears after storing the ZIP', async () => {
const s = server();
const upload = s.api.upload.bind(s.api);
s.api.upload = async (signed, bytes) => {
await upload(signed, bytes);
throw new TypeError('upload response lost');
};
try {
await s.runtime.save();
expect(s.runtime.getSnapshot().phase).toBe('saved');
expect(s.counts()).toEqual({ uploads: 1, signs: 1 });
expect(s.commitCodes).toEqual(['batch-1']);
} finally {
s.runtime.revoke();
}
});
it.each([
'PCB_UPLOAD_EXPIRED',
'PCB_FILE_SIZE_MISMATCH',
])('replaces the batch only after an explicit %s response, preserving the snapshot', async (code) => {
const s = server();
const fetchSaved = fetcher.getMockImplementation()!;
let rejected = false;
fetcher.mockImplementation(async (url, init) => {
if (String(url).endsWith('/document') && !rejected) {
rejected = true;
return reply(null, 409, code);
}
return fetchSaved(url, init);
});
try {
await s.runtime.save();
expect(s.runtime.baseVersion).toBe(1);
expect(s.counts()).toEqual({ uploads: 2, signs: 2 });
expect(s.commitCodes).toEqual(['batch-2']);
expect(await listPending(s.record.user.userCode, s.metadata.pcbProjectCode)).toHaveLength(0);
} finally {
s.runtime.revoke();
}
});
});
+424
View File
@@ -0,0 +1,424 @@
// SPDX-License-Identifier: GPL-3.0-or-later
import 'fake-indexeddb/auto';
import { readFileSync } from 'node:fs';
import { describe, it, expect, beforeEach, vi } from 'vitest';
import { zipSync, unzipSync, strToU8 } from 'fflate';
import {
createArchive,
openArchive,
importFiles,
safePath,
} from '@ziroeda/designer/src/platform/archive.js';
import {
DEFAULT_LIMITS,
type NativeProject,
type UploadRequest,
} from '@ziroeda/designer/src/platform/types.js';
import { MockPcbProjectApi, mockFaults } from '@ziroeda/designer/src/platform/mock-api.js';
import { WorkspaceRuntime } from '@ziroeda/designer/src/platform/runtime.js';
import { listDrafts, listPending } from '@ziroeda/designer/src/platform/storage.js';
import { missingModels, rewriteReferences } from '@ziroeda/designer/src/platform/resources.js';
import {
parseWorkspaceRoute,
workspaceHref,
validateWorkspaceFile,
} from '@ziroeda/designer/src/platform/routes.js';
import { workspaceFileSystem } from '@ziroeda/designer/src/platform/filesystem.js';
import { ParseBoard, FormatBoard } from '@ziroeda/pcbnew/pcb_io/kicad_sexpr/pcb_io_kicad_sexpr.js';
import { PCB_VIA } from '@ziroeda/pcbnew/pcb_track.js';
import { parse } from '@ziroeda/sexpr';
import { readSchematic, serializeSchematic } from '@ziroeda/eeschema';
import { buildSheetTree, findRootFile } from '@ziroeda/eeschema/project.js';
import { getPageSettings, setPageSettingsCommand } from '@ziroeda/eeschema/tools/page_settings.js';
vi.mock('@ziroeda/designer/src/platform/archive-client.js', async () => {
const archive = await import('@ziroeda/designer/src/platform/archive.js');
return { packProject: archive.createArchive, unpackProject: archive.openArchive };
});
const bytes = (text: string): Uint8Array => new TextEncoder().encode(text);
const decode = (data: Uint8Array): string => new TextDecoder().decode(data);
const fixture = (): NativeProject =>
importFiles([
{ name: 'main.kicad_pro', bytes: bytes('{"meta":{"version":3}}') },
{
name: 'main.kicad_pcb',
bytes: readFileSync(
new URL('../../data/zone_fill/hatchsmall_kicad_cli.kicad_pcb', import.meta.url),
),
},
{
name: 'main.kicad_sch',
bytes: readFileSync(
new URL('../../data/eeschema/sexpr_1006/v1006.kicad_sch', import.meta.url),
),
},
{
name: 'sub.kicad_sch',
bytes: readFileSync(new URL('../../data/eeschema/sexpr_1006/sub.kicad_sch', import.meta.url)),
},
{ name: 'models3d/custom.step', bytes: new Uint8Array([0, 128, 255, 17, 0, 192]) },
{ name: 'images/logo.png', bytes: new Uint8Array([137, 80, 78, 71, 0, 255]) },
]);
const signatureRequest = async (
native = fixture(),
expectedVersion = 0,
): Promise<{ bytes: Uint8Array; request: UploadRequest }> => {
const archive = await createArchive(native, 'test');
return {
bytes: archive.bytes,
request: {
fileName: 'project.zip',
sizeBytes: archive.bytes.length,
sha256: archive.sha256,
expectedVersion,
clientOperationId: crypto.randomUUID(),
archiveFormat: 'vibemake-pcb-project+zip',
manifestVersion: 1,
},
};
};
beforeEach(() => {
mockFaults.current = 'none';
});
describe('PCB native archive and path boundaries', () => {
it('preserves binary resources and native designs through save, reload and a second edit', async () => {
const native = fixture();
native.directories = ['empty'];
const archive = await createArchive(native, 'build-test');
const opened = await openArchive(archive.bytes);
for (const file of native.files)
expect(opened.files.find((f) => f.name === file.name)?.bytes).toEqual(
new Uint8Array(file.bytes),
);
expect(opened.directories).toEqual(['empty']);
const sch = readSchematic(
parse(decode(opened.files.find((f) => f.name === 'main.kicad_sch')!.bytes)),
);
const changed = setPageSettingsCommand({
...getPageSettings(sch),
title: 'reopened and edited',
}).apply(sch);
const saved = serializeSchematic(changed);
expect(readSchematic(parse(saved)).titleBlock?.title).toBe('reopened and edited');
const pcb = ParseBoard(decode(opened.files.find((f) => f.name === 'main.kicad_pcb')!.bytes));
pcb.GetTitleBlock().SetTitle('board edited after reopen');
const track = pcb.Tracks().find((item) => !(item instanceof PCB_VIA))!;
const width = track.GetWidth() + 10000;
track.SetWidth(width);
const via = pcb.Tracks().find((item) => item instanceof PCB_VIA) as PCB_VIA;
const drill = via.GetDrillValue() + 5000;
via.SetDrill(drill);
const footprint = pcb.Footprints()[0]!;
const position = { x: footprint.GetPosition().x + 100000, y: footprint.GetPosition().y };
footprint.SetPosition(position);
const zone = pcb.Zones()[0]!;
zone.SetLocalClearance(250000);
const count = pcb.Tracks().length;
expect(FormatBoard(pcb)).toContain('(kicad_pcb');
expect(ParseBoard(FormatBoard(pcb)).Tracks().length).toBe(count);
expect(ParseBoard(FormatBoard(pcb)).GetTitleBlock().GetTitle()).toBe(
'board edited after reopen',
);
const edited = {
...opened,
files: opened.files.map((file) =>
file.name === 'main.kicad_pcb' ? { ...file, bytes: bytes(FormatBoard(pcb)) } : file,
),
};
const secondOpen = await openArchive((await createArchive(edited, 'build-test')).bytes);
const continued = ParseBoard(
decode(secondOpen.files.find((f) => f.name === 'main.kicad_pcb')!.bytes),
);
expect(
continued
.Tracks()
.find((t) => t.m_Uuid === track.m_Uuid)
?.GetWidth(),
).toBe(width);
expect(
(continued.Tracks().find((item) => item.m_Uuid === via.m_Uuid) as PCB_VIA).GetDrillValue(),
).toBe(drill);
expect(
continued
.Footprints()
.find((f) => f.m_Uuid === footprint.m_Uuid)
?.GetPosition(),
).toEqual(position);
expect(
continued
.Zones()
.find((z) => z.m_Uuid === zone.m_Uuid)
?.GetLocalClearance(),
).toBe(250000);
});
it('rejects traversal, normalized collisions, truncated archives and tampered manifests', async () => {
for (const path of ['../x', '/x', 'a/../../x', 'a\\x', 'a//x', 'C:x'])
expect(() => safePath(path)).toThrow();
expect(() =>
importFiles([
{ name: 'a.kicad_pcb', bytes: bytes('(kicad_pcb)') },
{ name: 'A.kicad_pcb', bytes: bytes('(kicad_pcb)') },
]),
).toThrow();
const archive = await createArchive(fixture(), 'test');
await expect(openArchive(archive.bytes.slice(0, -1))).rejects.toThrow();
const entries = unzipSync(archive.bytes);
entries['models3d/custom.step'] = new Uint8Array([12]);
await expect(openArchive(zipSync(entries))).rejects.toMatchObject({
code: 'PCB_HASH_MISMATCH',
});
await expect(
openArchive(zipSync({ '../bad.kicad_pcb': strToU8('(kicad_pcb)') }), DEFAULT_LIMITS, false),
).rejects.toMatchObject({ code: 'PCB_UNSAFE_PATH' });
});
it('retains distinct same-name hierarchy documents', () => {
const sheet = (name: string, id: string): string =>
`(sheet (at 10 10) (size 20 20) (uuid "${id}") (property "Sheetname" "${id}" (at 10 10 0)) (property "Sheetfile" "${name}" (at 10 30 0)))`;
const sch = (extra = '') =>
readSchematic(
parse(
`(kicad_sch (version 20250114) (generator "eeschema") (uuid "root") (paper "A4") (lib_symbols) ${extra})`,
),
);
const docs = new Map([
['root.kicad_sch', sch(sheet('a/same.kicad_sch', 'a') + sheet('b/same.kicad_sch', 'b'))],
['a/same.kicad_sch', sch()],
['b/same.kicad_sch', sch()],
]);
expect(findRootFile(docs)).toBe('root.kicad_sch');
expect(buildSheetTree(docs, 'root.kicad_sch').children.map((s) => s.file)).toEqual([
'a/same.kicad_sch',
'b/same.kicad_sch',
]);
});
it('warns about missing models, keeps placement data and rewrites relative paths', async () => {
const native = fixture();
native.files.push({
name: 'parts/local.kicad_mod',
bytes: bytes('(footprint "test" (model "../missing.step" (offset (xyz 1 2 3))))'),
});
const missing = missingModels(native);
expect(missing).toContainEqual({
kind: 'model3d',
sourcePath: 'parts/local.kicad_mod',
reference: '../missing.step',
});
native.unresolvedDependencies = missing;
const reopened = await openArchive((await createArchive(native, 'test')).bytes);
expect(reopened.unresolvedDependencies).toEqual(missing);
expect(
rewriteReferences(
'(model "../models3d/custom.step" (offset (xyz 1 2 3)))',
'parts/a.kicad_mod',
'deep/parts/a.kicad_mod',
(p) => p,
),
).toBe('(model "../../models3d/custom.step" (offset (xyz 1 2 3)))');
});
it('uses project code and validated relative paths in deep links', () => {
const route = parseWorkspaceRoute('/pcb/p/pcb_123/schematic?f=a%2Fsame.kicad_sch');
expect(workspaceHref(route)).toBe('/pcb/p/pcb_123/schematic?f=a%2Fsame.kicad_sch');
expect(() => parseWorkspaceRoute('/pcb/p/pcb_123/pcb?f=..%2Fsecret')).toThrow();
expect(() =>
validateWorkspaceFile(
parseWorkspaceRoute('/pcb/p/pcb_123/pcb?f=missing.kicad_pcb'),
fixture(),
),
).toThrow();
expect(() =>
validateWorkspaceFile(parseWorkspaceRoute('/pcb/p/pcb_123/pcb?f=main.kicad_sch'), fixture()),
).toThrow();
});
});
describe('mock persistence and save transactions', () => {
it('rejects an active tool immediately without locking, preparing or uploading, and saves after it ends', async () => {
const owner = crypto.randomUUID(),
api = new MockPcbProjectApi(owner),
p = await api.create('Safe boundary', crypto.randomUUID());
const runtime = new WorkspaceRuntime(owner, p, fixture(), api, DEFAULT_LIMITS, 'test');
const sign = vi.spyOn(api, 'sign');
const phases: string[] = [];
runtime.subscribe(() => phases.push(runtime.getSnapshot().phase));
let busy = true;
const flush = vi.fn(async () => {
expect(runtime.getSnapshot().inputLocked).toBe(true);
runtime.writeFile('command-result.bin', new Uint8Array([7]));
});
runtime.register('tool', {
isBusy: () => busy,
flush,
});
// No clock advancement: this must reject before waiting for a command or
// starting network work, even when the tool remains active indefinitely.
vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] });
try {
await expect(runtime.capture()).rejects.toMatchObject({ code: 'SNAPSHOT_BUSY' });
await expect(runtime.save()).rejects.toMatchObject({ code: 'SNAPSHOT_BUSY' });
await expect(runtime.save()).rejects.toMatchObject({ code: 'SNAPSHOT_BUSY' });
expect(runtime.getSnapshot()).toMatchObject({ phase: 'blocked', inputLocked: false });
expect(phases).not.toContain('preparing');
expect(flush).not.toHaveBeenCalled();
expect(sign).not.toHaveBeenCalled();
expect(runtime.dirty).toBe(true);
busy = false;
await runtime.save();
expect(flush).toHaveBeenCalledOnce();
expect(sign).toHaveBeenCalledOnce();
expect(runtime.getSnapshot()).toMatchObject({
phase: 'saved',
inputLocked: false,
error: null,
});
const document = await api.document(p.pcbProjectCode);
const opened = await openArchive(await api.download(document, DEFAULT_LIMITS));
expect(opened.files.find((f) => f.name === 'command-result.bin')?.bytes).toEqual(
new Uint8Array([7]),
);
} finally {
runtime.revoke();
vi.useRealTimers();
}
});
it('awaits concurrent private writes and rejects a snapshot when a native write failed', async () => {
const owner = crypto.randomUUID(),
api = new MockPcbProjectApi(owner),
p = await api.create('Libraries', crypto.randomUUID());
const runtime = new WorkspaceRuntime(owner, p, fixture(), api, DEFAULT_LIMITS, 'test');
const fs = workspaceFileSystem(runtime);
await Promise.all([
fs.write('/Symbols/One.kicad_sym', bytes('one')),
fs.write('/Symbols/Two.kicad_sym', bytes('two')),
]);
expect((await fs.list('/Symbols')).map((entry) => entry.name).sort()).toEqual([
'One.kicad_sym',
'Two.kicad_sym',
]);
let resolve!: () => void;
const gate = new Promise<void>((done) => {
resolve = done;
});
const write = runtime.queueWrite('delayed', async () => {
await gate;
runtime.writeFile('delayed.bin', new Uint8Array([255]));
});
const capture = runtime.capture();
resolve();
await write;
expect((await capture).project.files.find((f) => f.name === 'delayed.bin')?.bytes).toEqual(
new Uint8Array([255]),
);
await expect(
runtime.queueWrite('broken', async () => {
throw new Error('disk full');
}),
).rejects.toThrow('disk full');
await expect(runtime.capture()).rejects.toThrow('disk full');
runtime.revoke();
});
it('isolates owners, allows duplicate names, retries creation and confirmation idempotently', async () => {
const owner = crypto.randomUUID(),
api = new MockPcbProjectApi(owner);
const id = crypto.randomUUID(),
p = await api.create('Duplicate', id);
expect((await api.create('Duplicate', id)).pcbProjectCode).toBe(p.pcbProjectCode);
const other = await api.create('Duplicate', crypto.randomUUID());
expect(other.pcbProjectCode).not.toBe(p.pcbProjectCode);
await expect(
new MockPcbProjectApi(crypto.randomUUID()).get(p.pcbProjectCode),
).rejects.toMatchObject({ code: 'NOT_FOUND' });
const packed = await signatureRequest(),
sig = await api.sign(p.pcbProjectCode, packed.request);
await api.upload(sig, packed.bytes);
mockFaults.current = 'confirmation-lost';
await expect(api.commit(p.pcbProjectCode, sig.uploadCode)).rejects.toThrow();
const receipt = await api.commit(p.pcbProjectCode, sig.uploadCode);
expect(receipt.version).toBe(1);
expect(await api.sign(p.pcbProjectCode, packed.request)).toEqual(sig);
expect(await api.commit(p.pcbProjectCode, sig.uploadCode)).toEqual(receipt);
expect((await new MockPcbProjectApi(owner).document(p.pcbProjectCode)).version).toBe(1);
});
it('commits one of two concurrent versions and rejects saves to a deleted project', async () => {
const api = new MockPcbProjectApi(crypto.randomUUID()),
p = await api.create('Race', crypto.randomUUID());
const a = await signatureRequest(),
b = await signatureRequest();
const sa = await api.sign(p.pcbProjectCode, a.request),
sb = await api.sign(p.pcbProjectCode, b.request);
await api.upload(sa, a.bytes);
await api.upload(sb, b.bytes);
const outcomes = await Promise.allSettled([
api.commit(p.pcbProjectCode, sa.uploadCode),
api.commit(p.pcbProjectCode, sb.uploadCode),
]);
expect(outcomes.filter((o) => o.status === 'fulfilled')).toHaveLength(1);
expect(outcomes.filter((o) => o.status === 'rejected')).toHaveLength(1);
await api.remove(p.pcbProjectCode);
await expect(api.commit(p.pcbProjectCode, sa.uploadCode)).rejects.toMatchObject({
code: 'NOT_FOUND',
});
});
it('deduplicates saves and only acknowledges the snapshot uploaded, preserving later edits', async () => {
const api = new MockPcbProjectApi(crypto.randomUUID()),
p = await api.create('Runtime', crypto.randomUUID());
const runtime = new WorkspaceRuntime(
crypto.randomUUID(),
p,
fixture(),
api,
DEFAULT_LIMITS,
'test',
);
runtime.modified();
const upload = api.upload.bind(api);
api.upload = async (signature, data) => {
runtime.writeFile('late.bin', new Uint8Array([99]));
await upload(signature, data);
};
const save = runtime.save();
expect(runtime.save()).toBe(save);
await save;
expect(runtime.dirty).toBe(true);
const doc = await api.document(p.pcbProjectCode),
opened = await openArchive(await api.download(doc, DEFAULT_LIMITS));
expect(opened.files.some((f) => f.name === 'late.bin')).toBe(false);
api.upload = upload;
await runtime.save();
expect(runtime.dirty).toBe(false);
expect((await api.document(p.pcbProjectCode)).version).toBe(2);
runtime.revoke();
});
it('recovers an unknown confirmation without duplicating a version or leaving a false dirty draft', async () => {
const owner = crypto.randomUUID(),
api = new MockPcbProjectApi(owner),
p = await api.create('Recover', crypto.randomUUID());
const runtime = new WorkspaceRuntime(owner, p, fixture(), api, DEFAULT_LIMITS, 'test');
runtime.modified();
await runtime.persistDraft();
mockFaults.current = 'confirmation-lost';
await expect(runtime.save()).rejects.toThrow();
const records = await listPending(owner, p.pcbProjectCode);
expect(records).toHaveLength(1);
runtime.revoke();
const recovery = new WorkspaceRuntime(
owner,
await api.get(p.pcbProjectCode),
fixture(),
api,
DEFAULT_LIMITS,
'test',
);
recovery.adoptPending(records[0]!);
const flush = vi.fn();
recovery.register('active-tool', { isBusy: () => true, flush });
await recovery.save();
// Retrying an existing upload only confirms its immutable snapshot. An
// active tool must not prevent that acknowledgement or flush new edits.
expect(flush).not.toHaveBeenCalled();
expect((await api.get(p.pcbProjectCode)).version).toBe(1);
expect(await listPending(owner, p.pcbProjectCode)).toHaveLength(0);
expect(await listDrafts(owner, p.pcbProjectCode)).toHaveLength(0);
recovery.revoke();
});
});
@@ -0,0 +1,98 @@
// @vitest-environment happy-dom
// SPDX-License-Identifier: GPL-3.0-or-later
import { act, cleanup, render, waitFor } from '@testing-library/react';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import {
PlatformAuthProvider,
usePlatformAuth,
MOCK,
} from '@ziroeda/designer/src/platform/auth.js';
let auth: ReturnType<typeof usePlatformAuth>;
function Probe(): null {
auth = usePlatformAuth();
return null;
}
const user = { userCode: 'platform-user', email: 'test@example.test', nickname: '测试用户' };
const record = () => ({ token: 'shared-platform-token', user, expiresAt: Date.now() + 86400000 });
const fetcher = vi.fn<typeof fetch>();
const reply = (data: unknown, status = 200, code = 'OK') =>
new Response(JSON.stringify({ code, message: code, data, requestId: 'auth-request' }), {
status,
});
beforeEach(() => {
localStorage.clear();
fetcher.mockReset();
vi.stubGlobal('fetch', fetcher);
});
afterEach(() => {
cleanup();
vi.unstubAllGlobals();
localStorage.clear();
});
const mount = () =>
render(
<PlatformAuthProvider>
<Probe />
</PlatformAuthProvider>,
);
describe('PCB real shared platform authentication', () => {
it('recognizes the main website vm.auth record and verifies /users/me with the same token', async () => {
expect(MOCK).toBe(false);
localStorage.setItem('vm.auth', JSON.stringify(record()));
fetcher.mockResolvedValueOnce(reply(user));
mount();
await waitFor(() => expect(auth.status).toBe('authenticated'));
expect(auth.record?.user.userCode).toBe(user.userCode);
expect(String(fetcher.mock.calls[0]![0])).toMatch(/\/api\/users\/me$/);
expect(new Headers(fetcher.mock.calls[0]![1]?.headers).get('Authorization')).toBe(
'Bearer shared-platform-token',
);
});
it('signs in with email and captcha, verifies identity, and writes the main website format', async () => {
mount();
await waitFor(() => expect(auth.status).toBe('anonymous'));
fetcher.mockResolvedValueOnce(reply({ token: 'new-platform-token', user, expiresIn: 3600 }));
fetcher.mockResolvedValueOnce(reply(user));
await act(async () => {
await auth.login(' test@example.test ', 'captcha-id', ' abcd ');
});
const [url, init] = fetcher.mock.calls[0]!;
expect(String(url)).toMatch(/\/api\/auth\/login$/);
expect(JSON.parse(String(init?.body))).toEqual({
email: 'test@example.test',
captchaCode: 'captcha-id',
captchaAnswer: 'abcd',
});
const saved = JSON.parse(localStorage.getItem('vm.auth')!);
expect(saved).toMatchObject({ token: 'new-platform-token', user });
expect(saved.expiresAt).toBeGreaterThan(Date.now() + 3590000);
expect(localStorage.getItem('vm.pcb.mock.auth')).toBeNull();
fetcher.mockResolvedValueOnce(reply(null));
await act(async () => {
await auth.logout();
});
expect(String(fetcher.mock.calls[2]![0])).toMatch(/\/api\/auth\/logout$/);
expect(localStorage.getItem('vm.auth')).toBeNull();
});
it('preserves identity on service failure and locks for reauthentication on 401', async () => {
const shared = record();
localStorage.setItem('vm.auth', JSON.stringify(shared));
fetcher.mockRejectedValueOnce(new TypeError('offline'));
mount();
await waitFor(() => expect(auth.status).toBe('error'));
expect(auth.record?.token).toBe(shared.token);
expect(JSON.parse(localStorage.getItem('vm.auth')!).token).toBe(shared.token);
fetcher.mockResolvedValueOnce(reply(null, 401, 'UNAUTHORIZED'));
// Opening the expired-session dialog fetches a new public captcha.
fetcher.mockResolvedValueOnce(
reply({ captchaCode: 'captcha-id', image: 'data:image/png;base64,' }),
);
await act(async () => {
await auth.verify();
});
expect(auth.status).toBe('expired');
expect(auth.loginOpen).toBe(true);
expect(auth.record?.token).toBe(shared.token);
});
});

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