diff --git a/.gitignore b/.gitignore index c69042b..11c14ed 100644 --- a/.gitignore +++ b/.gitignore @@ -9,3 +9,7 @@ sandbox/node_modules/ # Generated simulation bundles and local upload/preview exports. /play/ /deliverables/ +# Generated CAD engine files installed from the SolidCraft Web package. +/cad/_assets/ +/cad/engine.json +/cad/sw.js diff --git a/README.md b/README.md index 9691011..d0e9c76 100644 --- a/README.md +++ b/README.md @@ -18,6 +18,23 @@ npm run build:walking 生成 `/play/robots/index.html`(Robot Package 通用运行器)和 `/play/microduck/index.html`(旧版 Microduck 包)。两者由本站提供,按详情接口选择;关闭弹窗会释放仿真。修改沙盒后再次执行 `npm run build:walking`;`npm run build` 会自动构建并收录。默认暂停,点击开始后按住键盘 / 触摸方向键运动,松开停止。来源记录见 `sandbox/NOTICE`。 +### CAD Web engine + +Build the engine with `./build.sh` in the SolidCraft repository. Then run these commands from the VibeMake project root: + +```bash +unzip -o ../solidcraft-main/dist/vibemake-cad-engine.zip -d . +npm run dev +``` + +The archive already contains a `cad/` directory. Merge it into the project root so that `cad/engine.json`, `cad/sw.js` and `cad/_assets//` sit beside the existing `cad/editor/`. Do not extract it into `cad/cad/` or replace the whole existing `cad/` directory. No CAD engine path environment variable is needed. Restart the development server after installing a new engine. + +`npm run build` and `npm run build:dev` validate the engine installed in `cad/` and include its current assets in the site ZIP. If no engine is installed, the build reports that the engine must be deployed separately. Engine binaries are generated files and are not committed to this repository. + +The site registers `/cad/worker.js`, which imports the engine package's `/cad/sw.js` and supplies the update activation protocol, including for older engine packages. The refresh action first runs the unsaved-changes guard, activates the waiting worker, and then reloads. Update notices compare the published engine build with the running build, rather than treating every waiting worker as a new editor version. Login state, IndexedDB drafts, and other applications' caches are retained. + +Deploy the site changes (including `cad/worker.js` and `js/cad/`) once with this fix; replacing only the engine ZIP cannot repair the old site's refresh handler. Serve `/cad/engine.json`, `/cad/sw.js`, `/cad/worker.js`, the editor HTML, and `js/cad/` with `Cache-Control: no-cache` (or `no-store`). Only `/cad/_assets//` should use long-lived immutable caching. The development server already applies these cache policies. Update regressions: `node --test tests/cad/engine-updates.browser.mjs`. + ### 项目装配与行走资源 社区详情读取后端实际上传绑定: @@ -53,6 +70,8 @@ node scripts/server.mjs # http://localhost:8091 后端接口数据(/api 转发到 dev 后端;线上也用这个服务器,按域名自动选 dev / 正式后端) # http://127.0.0.1:8091 本地演示数据(最早的完整样子,作参考) # /pcb/ 同源代理到相邻的 ziro-designer-main/designer,默认使用真实后端,无需手动打开 5173 端口 +# AI 自动绘板默认连接本机 127.0.0.1:8000:先在相邻仓库 backend/.env.local 配置 DeepSeek 密钥与 KiCad 路径,再运行 backend/start.sh +# PCB_API_TARGET=http://其他服务器:8000 node scripts/server.mjs 可覆盖 AI 绘板后台地址 # PCB_API_MODE=mock node scripts/server.mjs 显式启用开发模拟(独立存储,不共用主站账号) ``` diff --git a/assets/brand/make-cad.svg b/assets/brand/make-cad.svg new file mode 100644 index 0000000..00e851a --- /dev/null +++ b/assets/brand/make-cad.svg @@ -0,0 +1,12 @@ + + make CAD + + + + + + + + + + diff --git a/cad.html b/cad.html index 97a0b8f..9bf262c 100644 --- a/cad.html +++ b/cad.html @@ -1,6 +1,8 @@ + + 我的 CAD 项目 — VibeMake CAD diff --git a/cad/editor/index.html b/cad/editor/index.html index 7a54982..c76c49c 100644 --- a/cad/editor/index.html +++ b/cad/editor/index.html @@ -1,6 +1,8 @@ + + VibeMake CAD diff --git a/cad/worker.js b/cad/worker.js new file mode 100644 index 0000000..374f7ba --- /dev/null +++ b/cad/worker.js @@ -0,0 +1,7 @@ +// The site owns the activation protocol; engine packages own the asset allowlist. +// Imported-script changes are checked with updateViaCache: 'none'. +importScripts('/cad/sw.js'); +self.addEventListener('message', (event) => { + if (event.data?.type === 'SKIP_WAITING') event.waitUntil(self.skipWaiting()); +}); +self.addEventListener('activate', (event) => event.waitUntil(self.clients.claim())); diff --git a/js/cad/api.js b/js/cad/api.js index f7f539b..56a3e22 100644 --- a/js/cad/api.js +++ b/js/cad/api.js @@ -1,5 +1,6 @@ import { auth, API_BASE, ApiError } from '../api.js'; import { locale } from './i18n.js'; +import { CAD, validStepFilename, validNativeFilename } from './config.js'; import { cadAgentRateLimiter } from './agent-rate-limit.js'; export { auth, ApiError }; @@ -34,9 +35,17 @@ function shanghaiTime(value) { function projectRecord(value) { const record = value?.project ?? value; - if (!record || typeof record.cadProjectCode !== 'string' || !record.cadProjectCode) throw cadError('BAD_RESPONSE'); + if (!record || typeof record.cadProjectCode !== 'string' || !record.cadProjectCode + || typeof record.hasDocument !== 'boolean' || !Number.isSafeInteger(record.version) || record.version < 0 + || (!record.hasDocument && record.version !== 0) || (record.hasDocument && record.version === 0) + || (record.workspaceProjectCode != null && (typeof record.workspaceProjectCode !== 'string' || !record.workspaceProjectCode))) throw cadError('BAD_RESPONSE'); + if (record.initialStep != null && (typeof record.initialStep !== 'object' || Array.isArray(record.initialStep) + || typeof record.initialStep.downloadUrl !== 'string' || typeof record.initialStep.fileName !== 'string' + || !Number.isSafeInteger(record.initialStep.sizeBytes))) throw cadError('BAD_RESPONSE'); return { ...record, + workspaceProjectCode: record.workspaceProjectCode ?? null, + initialStep: record.initialStep ?? null, coverUrl: projectCoverUrl(record.coverUrl), id: record.cadProjectCode, cadProjectCode: record.cadProjectCode, @@ -164,13 +173,20 @@ export class CadApi { return { ...result, items: result.items.map(projectRecord), page: result.page, size: result.size }; } + async openWorkspaceProject(projectCode, signal) { + if (typeof projectCode !== 'string' || !projectCode || projectCode.length > 128) throw cadError('BAD_PROJECT'); + const project = projectRecord(await this.call('/workspace/projects/' + id(projectCode) + '/cad-project', { method: 'POST', signal })); + if (project.workspaceProjectCode !== projectCode) throw cadError('BAD_RESPONSE'); + return project; + } + async create(name, description = '', coverUrl) { if (coverUrl != null && coverUrl !== '' && !projectCoverUrl(coverUrl)) throw cadError('BAD_COVER'); return projectRecord(await this.call(PROJECTS, { method: 'POST', body: { name, description, ...(coverUrl === undefined ? {} : { coverUrl }) } })); } - async get(project) { - return projectRecord(await this.call(PROJECTS + '/' + id(project))); + async get(project, signal) { + return projectRecord(await this.call(PROJECTS + '/' + id(project), { signal })); } async rename(project, name) { @@ -208,10 +224,10 @@ export class CadApi { return this.call(PROJECTS + '/' + id(project), { method: 'DELETE' }); } - async document(project) { - const value = await this.call(PROJECTS + '/' + id(project) + '/document'); - if (!value || !Number.isSafeInteger(value.version) || !Number.isSafeInteger(value.sizeBytes) - || typeof value.downloadUrl !== 'string' || typeof value.fileName !== 'string') throw cadError('BAD_RESPONSE'); + async document(project, signal) { + const value = await this.call(PROJECTS + '/' + id(project) + '/document', { signal }); + if (!value || !Number.isSafeInteger(value.version) || value.version <= 0 || !Number.isSafeInteger(value.sizeBytes) + || typeof value.downloadUrl !== 'string' || !validNativeFilename(value.fileName)) throw cadError('BAD_RESPONSE'); return { ...value, savedAt: shanghaiTime(value.savedAt) }; } @@ -257,7 +273,8 @@ export async function downloadSource(file, maxBytes, progress = () => {}, signal if (!response.ok) throw cadError(response.status === 403 ? 'DOWNLOAD_FORBIDDEN' : 'DOWNLOAD_FAILED'); if (!response.body) { const bytes = new Uint8Array(await response.arrayBuffer()); - if (bytes.byteLength !== size || bytes.byteLength > maxBytes) throw cadError('BAD_DESIGN'); + if (bytes.byteLength > maxBytes) throw cadError('SOURCE_TOO_LARGE'); + if (bytes.byteLength !== size) throw cadError('BAD_DESIGN'); progress(bytes.byteLength, size); return bytes; } @@ -269,7 +286,8 @@ export async function downloadSource(file, maxBytes, progress = () => {}, signal const { done, value } = await reader.read(); if (done) break; total += value.byteLength; - if (total > size || total > maxBytes) throw cadError('SOURCE_TOO_LARGE'); + if (total > maxBytes) throw cadError('SOURCE_TOO_LARGE'); + if (total > size) throw cadError('BAD_DESIGN'); chunks.push(value); progress(total, size); } @@ -289,7 +307,7 @@ export async function downloadSource(file, maxBytes, progress = () => {}, signal export async function uploadSource(signature, bytes, fileName, signal) { const authorization = signatureRecord(signature); - if (typeof fileName !== 'string' || !/^[^\\/:\u0000-\u001f\u007f]+\.sc$/i.test(fileName)) throw cadError('BAD_FILE_NAME'); + if (!validNativeFilename(fileName)) throw cadError('BAD_FILE_NAME'); const body = new FormData(); for (const [key, value] of Object.entries(authorization.formFields)) body.append(key, value); body.append('file', new Blob([bytes], { type: 'application/octet-stream' }), fileName); @@ -303,3 +321,11 @@ export async function uploadSource(signature, bytes, fileName, signal) { }); if (!response.ok) throw cadError('UPLOAD_FAILED'); } + +export function initialStepSource(value) { + if (!value || !validStepFilename(value.fileName)) throw cadError('BAD_STEP_FILE'); + if (!Number.isSafeInteger(value.sizeBytes) || value.sizeBytes <= 0 || value.sizeBytes > CAD.maxStepSourceBytes) throw cadError('STEP_TOO_LARGE'); + if (typeof value.downloadUrl !== 'string' || !value.downloadUrl.trim()) throw cadError('BAD_STEP_FILE'); + storageUrl(value.downloadUrl); + return value; +} diff --git a/js/cad/app.js b/js/cad/app.js index 2e83a74..1d7a451 100644 --- a/js/cad/app.js +++ b/js/cad/app.js @@ -5,9 +5,10 @@ import { CAD, desktopAllowed, projectUrl, filename } from './config.js'; import { locale, setLocale, t, errorText, LOCALE_KEY } from './i18n.js'; import { CadApi, userId, cadError, downloadSource, sha256 } from './api.js'; import { DraftStore } from './drafts.js'; +import { openProjectSource } from './opening.js'; import { SaveCoordinator } from './save.js'; import { choose, nameDialog } from './dialog.js'; -import { loadEngine, downloadBytes } from './engine.js'; +import { loadEngine, prepareEngineRefresh, downloadBytes } from './engine.js'; const editor = document.body.dataset.cadPage === 'editor'; renderShell('cad', { footer: false, assistant: false, search: !editor }); const main = document.querySelector('#cad-main'), header = document.querySelector('body > header.nav'), viewport = document.querySelector('#cad-viewport'); @@ -16,6 +17,7 @@ let api, bridge, project, binding, saver, boundUser = null, state = {}, epoch = let request, booting = false, restartBoot = false, modalCount = 0, authLocked = true, viewportReady = false, saveState = 'never', draftTask = null, unsubscribe; let leaving = false, signingOut = false, authToken = null, lastDraftRevision = null, draftWarning = false, recovering = false, recoveryPending = false, copying = false; let discardedDraft = null; +let refreshingEngine = false, openingProject = false, importWarnings = []; let assistantAvailable = false; let assistantRequest; const projectId = new URLSearchParams(location.search).get('project'); @@ -30,7 +32,15 @@ function assertContext(value, document = false) { value.client?.assertIdentity(); if (value.epoch !== epoch || value.owner !== boundUser || (document && value.binding !== binding)) throw cadError('STALE_BINDING'); } -function notice(text) { const el = document.querySelector('#cad-notice'); el.textContent = text; el.hidden = !text; } +function notice(text) { + const el = document.querySelector('#cad-notice'); el.textContent = text; el.hidden = !text && !importWarnings.length; + if (importWarnings.length) { + const details = document.createElement('details'), summary = document.createElement('summary'), list = document.createElement('ul'); + details.dataset.importWarnings = ''; summary.textContent = t('stepWarnings'); + for (const warning of importWarnings) { const item = document.createElement('li'); item.textContent = String(warning); list.append(item); } + details.append(summary, list); el.append(details); + } +} function storageWarning() { draftWarning = true; notice(t('storage')); } function initEditorHeader() { if (!editor || !header) return; @@ -73,7 +83,7 @@ function initEditorHeader() { saveButton.innerHTML = icon('save', 18); saveButton.setAttribute('aria-label', t('save')); saveButton.title = t('save'); - saveButton.disabled = !binding || authLocked; + saveButton.disabled = !binding || authLocked || openingProject || recovering || recoveryPending; if (authSlot) { actions.insertBefore(saveStatus, authSlot); } else { @@ -108,11 +118,11 @@ function drawHeader() { const saveStatus = header.querySelector('.cad-save-state'); const saveButton = header.querySelector('[data-save]'); if (saveStatus) { saveStatus.dataset.state = saveState; saveStatus.textContent = t(saveState); } - if (saveButton) { saveButton.disabled = !binding || authLocked; saveButton.title = t('save'); saveButton.setAttribute('aria-label', t('save')); } + if (saveButton) { saveButton.disabled = !binding || authLocked || openingProject || recovering || recoveryPending; saveButton.title = t('save'); saveButton.setAttribute('aria-label', t('save')); } header.querySelector('[data-engine-menu="file"]').textContent = t('file'); const undo = header.querySelector('[data-history="undo"]'), redo = header.querySelector('[data-history="redo"]'); - if (undo) { undo.disabled = authLocked || !state.canUndo; undo.title = t('undo'); undo.setAttribute('aria-label', t('undo')); } - if (redo) { redo.disabled = authLocked || !state.canRedo; redo.title = t('redo'); redo.setAttribute('aria-label', t('redo')); } + if (undo) { undo.disabled = authLocked || openingProject || recovering || recoveryPending || !state.canUndo; undo.title = t('undo'); undo.setAttribute('aria-label', t('undo')); } + if (redo) { redo.disabled = authLocked || openingProject || recovering || recoveryPending || !state.canRedo; redo.title = t('redo'); redo.setAttribute('aria-label', t('redo')); } for (const key of ['assistant', 'preferences', 'help']) { const button = header.querySelector('[data-engine-menu="' + key + '"]'); if (button) { button.title = t(key); button.setAttribute('aria-label', t(key)); } @@ -141,7 +151,7 @@ function status(key, error) { if (error && error.code !== 'STALE_IDENTITY' && error.code !== 'STALE_BINDING') showError(error); } function showError(error) { - if (['STALE_IDENTITY', 'STALE_BINDING', 'AbortError'].includes(error?.code || error?.name)) return; + if (['STALE_IDENTITY', 'STALE_BINDING', 'OPEN_CANCELLED', 'AbortError'].includes(error?.code || error?.name)) return; notice(errorText(error)); if (['HEAD_CONFLICT', 'CAD_VERSION_CONFLICT'].includes(error.code)) conflictDialog(); if ([403, 404, 410].includes(error.status)) { status('unavailable'); authLocked = true; updateLock(); draft(); } @@ -151,7 +161,15 @@ function message(key, hint, action, actionLabel = 'retry') { main.innerHTML = `
${icon('cube', 48)}

${esc(t(key))}

${hint ? `

${esc(t(hint))}

` : ''}${action ? `` : ''}
`; main.querySelector('[data-action]')?.addEventListener('click', action); } -function stage(key, progress) { message(key); const p = main.querySelector('h1'); if (progress) p.textContent += ` ${progress}`; } +function stage(key, progress) { + message(key, null, openingProject ? cancelOpening : null, 'cancel'); + const p = main.querySelector('h1'); if (progress) p.textContent += ` ${progress}`; +} +async function cancelOpening() { + ++epoch; request?.abort(); + await bridge?.cancelOpenProject?.().catch(() => {}); + openingProject = false; updateLock(); message('openCancelled', null, boot); +} async function signIn() { await openLogin({ locale: locale() }); if (!authLocked && !binding && editor) boot(); } async function signOut() { if (!(await guard())) return; @@ -161,7 +179,7 @@ async function signOut() { if (editor) location.assign('/cad/'); else { authLocked = true; drawHeader(); message('loginRequired', 'loginHint', signIn, 'signIn'); } } function updateLock() { - const locked = authLocked || recovering || recoveryPending || modalCount > 0 || !desktopAllowed() || !viewportReady; + const locked = authLocked || openingProject || recovering || recoveryPending || refreshingEngine || modalCount > 0 || !desktopAllowed() || !viewportReady; if (viewport) { viewport.inert = locked; viewport.style.pointerEvents = locked ? 'none' : ''; } bridge?.setInteractionLocked(locked).catch(() => {}); const blocker = document.querySelector('#cad-blocker'); @@ -260,7 +278,7 @@ async function boot() { if (error.status === 401) { authLocked = true; message('loginRequired', 'loginHint', signIn, 'signIn'); setTimeout(signIn, 0); return; } if (binding) showError(error); else if (error.code === 'FONT_UNAVAILABLE') showFontError(error); else { message('error', null, boot); showError(error); } - } finally { booting = false; drawHeader(); updateLock(); if (restartBoot) { restartBoot = false; setTimeout(boot, 0); } } + } finally { openingProject = false; booting = false; drawHeader(); updateLock(); if (restartBoot) { restartBoot = false; setTimeout(boot, 0); } } } async function loadList() { if (!api || authLocked) return; @@ -316,36 +334,50 @@ async function newProject() { } async function openEditor(current) { if (typeof projectId !== 'string' || !projectId || projectId.length > 128) throw cadError('NOT_FOUND'); + openingProject = true; updateLock(); importWarnings = []; notice(''); + request?.abort(); request = new AbortController(); const control = request, client = api; + const check = () => { client.assertIdentity(); if (current !== epoch || control.signal.aborted) throw cadError('STALE_BINDING'); }; stage('metadata'); - project = await api.get(projectId); - let source = null; - try { source = await api.document(projectId); } - catch (error) { if (error.code !== 'CAD_DOCUMENT_NOT_FOUND') throw error; } - if (current !== epoch) return; - project.version = source?.version ?? project.version ?? 0; - project.headVersion = project.version; + project = await client.get(projectId, control.signal); check(); stage('engine'); viewport.hidden = false; viewport.style.visibility = 'hidden'; try { bridge = await loadEngine(); } catch (error) { if (error.code === 'FONT_UNAVAILABLE') { bridge = window.vibemakeCad; showFontError(error); } throw error; } - if (current !== epoch) return; - const engineReady = await bridge.ready(); + check(); + const engineReady = await bridge.ready(); check(); assistantAvailable = engineReady.capabilities?.assistant === true && typeof bridge.setAgentContext === 'function'; if (!assistantAvailable) notice(t('assistantUpdate')); - let bytes = null; - if (source) { - stage('download'); - bytes = await downloadSource(source, CAD.maxSourceBytes, (received, size) => stage('download', Math.round(received / size * 100) + '%')); + const progress = bridge.subscribe((next) => { + if (current !== epoch || !next.opening) return; + const key = next.opening.phase === 'preparing' ? 'stepPreparing' : 'stepImport'; + const { done, total } = next.opening; + stage(key, total > 0 ? `${Math.min(done, total)} / ${total}` : null); + }); + let result; + try { + result = await openProjectSource({ api: client, bridge, project, signal: control.signal, assertCurrent: check, + onStage: stage, recover: () => restoreLocal({ preflight: true }) }); + } finally { progress(); } + check(); + if (result.blocked && !binding) return; + if (result.opened) { + saver?.dispose(); binding = result.opened.binding; project.version = result.version; project.headVersion = result.version; + saver = makeSaver(); } - if (current !== epoch) return; - stage('rebuild'); - const result = await bridge.openProject({ projectId, bytes, saved: !!source }); - if (current !== epoch) { await bridge.releaseProject(); return; } - binding = result.binding; recovering = true; viewportReady = true; viewport.style.visibility = ''; main.hidden = true; + recovering = true; viewportReady = true; viewport.style.visibility = ''; main.hidden = true; unsubscribe?.(); unsubscribe = bridge.subscribe(onEngineState); - saver = makeSaver(); state = await bridge.getState(); saveState = source ? 'saved' : 'never'; drawHeader(); updateLock(); - await restoreLocal(); - await saver.restoreCover(); - await bindAssistant(); state = await bridge.getState(); drawHeader(); + state = await bridge.getState(); check(); + saveState = recoveryPending ? 'pending' : saver?.conflicted ? 'conflict' : project.version ? (state.dirty ? 'dirty' : 'saved') : 'never'; + if (result.kind !== 'recovery') importWarnings = result.warnings || []; + if (!result.blocked) notice(draftWarning ? t('storage') : ''); + drawHeader(); updateLock(); + if (result.kind === 'native') await restoreLocal(); + else recovering = false; + if (importWarnings.length && !recoveryPending) notice(''); + check(); + if (result.kind === 'step') await draft(); + await saver.restoreCover(); check(); + await bindAssistant(); check(); state = await bridge.getState(); drawHeader(); } + function makeSaver() { return new SaveCoordinator({ api, bridge, store, user: boundUser, project, binding, session, onState: status, onStorageError: storageWarning }); } function onEngineState(next) { if (next.binding !== binding) return; @@ -358,7 +390,7 @@ function onEngineState(next) { if (next.locale && next.locale !== locale() && !next.fontFailed && !recovering) { setLocale(next.locale); drawHeader(); } } async function save() { - if (authLocked || !saver) throw cadError('UNAUTHORIZED'); + if (authLocked || openingProject || recovering || !saver) throw cadError('UNAUTHORIZED'); if (copying) throw cadError('SAVE_IN_PROGRESS'); if (recoveryPending) throw cadError('PENDING_SAVE'); const ctx = context(); let result; @@ -376,28 +408,32 @@ function draft() { if (leaving || recovering || !bridge || !binding || !boundUser || draftTask || !state.dirty || !state.snapshotAvailable || state.revision === lastDraftRevision) return draftTask; if (discardedDraft?.binding === binding && (discardedDraft.pending || discardedDraft.revision === state.revision)) return; const engine = bridge, oldBinding = binding, owner = boundUser, target = project.id, version = project.version, revision = state.revision; + const origin = project.initialStep && version === 0 ? 'step-import' : undefined, warnings = [...importWarnings]; draftTask = (async () => { let snapshot; try { snapshot = await engine.createSnapshot(); if (snapshot.binding !== oldBinding) return; - await store.put(owner, target, session, 'draft', { snapshotId: snapshot.snapshotId, bytes: snapshot.bytes, baseVersion: version, revision: snapshot.revision, binding: oldBinding }); + await store.put(owner, target, session, 'draft', { snapshotId: snapshot.snapshotId, bytes: snapshot.bytes, baseVersion: version, revision: snapshot.revision, binding: oldBinding, origin, importWarnings: warnings }); if (oldBinding === binding) lastDraftRevision = revision; } catch (error) { if (error.code !== 'SNAPSHOT_BUSY') storageWarning(); } finally { if (snapshot) await engine.releaseSnapshot(snapshot.snapshotId); } })().finally(() => { draftTask = null; }); return draftTask; } -async function restoreLocal() { - if (recovering && recoveryPending) return; +async function restoreLocal({ preflight = false } = {}) { + if (recovering && recoveryPending) return { blocked: true }; + const originalBinding = binding; let blocked = false; recovering = true; recoveryPending = false; const ctx = context(); updateLock(); + const decide = (...args) => choose(...args, { signal: request?.signal }); const pending = () => { - recoveryPending = true; status('pending'); notice(t('pending')); + blocked = true; recoveryPending = true; status('pending'); notice(t('pending')); const button = document.createElement('button'); button.className = 'btn'; button.textContent = t('retry'); - button.onclick = () => restoreLocal().catch(showError); + button.onclick = () => (binding ? restoreLocal() : boot()).catch(showError); document.querySelector('#cad-notice').append(button); + if (!binding) message('pending', null, boot); }; - let resolvingJournal = true, showConflict = false; + let resolvingJournal = true, readingDrafts = false, showConflict = false; try { const journals = await store.list(boundUser, project.id, 'operation'); assertContext(ctx, true); @@ -414,10 +450,11 @@ async function restoreLocal() { await store.remove(journal.key, journal.snapshotId); continue; } - if (await choose(t('pending'), t('draftHint'), [['restore', t('restore'), true], ['cancel', t('stay')]]) === 'restore') { - assertContext(ctx, true); + const decision = await decide(t('pending'), t('draftHint'), [['restore', t('restore'), true], ['cancel', t('stay')]]); + assertContext(ctx, true); + if (decision === 'restore') { const opened = await bridge.openProject({ projectId: project.id, bytes: journal.bytes, saved: false }); - saver.dispose(); binding = opened.binding; ctx.binding = binding; + saver?.dispose(); binding = opened.binding; ctx.binding = binding; project.version = journal.request.expectedVersion; project.headVersion = project.version; saver = makeSaver(); main.hidden = true; updateLock(); @@ -431,37 +468,55 @@ async function restoreLocal() { const latest = await api.get(project.id); project.version = latest.version; project.headVersion = latest.version; state = await bridge.getState(); showConflict = true; - return; + return { restored: true }; } - if (saver.operation) { pending(); return; } + if (saver.operation) { pending(); return { restored: true, blocked: true }; } } } else { - pending(); return; + pending(); return { blocked: true }; } } resolvingJournal = false; + readingDrafts = true; const drafts = await store.list(boundUser, project.id, 'draft'); + readingDrafts = false; assertContext(ctx, true); if (drafts.length) { const value = drafts[0]; const decision = value.origin === 'native-import' && project.version === 0 ? 'restore' - : await choose(t('draft'), t('draftHint'), [['restore', t('restore'), true], ['discard', t('discard')], ['cancel', t('stay')]]); + : await decide(t('draft'), t('draftHint'), [['restore', t('restore'), true], ['discard', t('discard')], ['cancel', t('stay')]]); assertContext(ctx, true); if (decision === 'restore') { const opened = await bridge.openProject({ projectId: project.id, bytes: value.bytes, saved: false }); - saver.dispose(); binding = opened.binding; ctx.binding = binding; saver = makeSaver(); + saver?.dispose(); binding = opened.binding; ctx.binding = binding; saver = makeSaver(); if (value.baseVersion !== project.version) { saver.conflicted = true; status('conflict'); } else status('dirty'); + importWarnings = Array.isArray(value.importWarnings) ? value.importWarnings : []; lastDraftRevision = null; state = await bridge.getState(); + assertContext(ctx, true); + try { await store.rebindDraft(value.key, value.snapshotId, { binding, revision: state.revision }); } + catch { storageWarning(); } } else if (decision === 'discard') for (const d of drafts) await store.remove(d.key); + else if (preflight) { blocked = true; recoveryPending = true; message('draft', null, boot, 'restore'); } } state = await bridge.getState(); } catch (error) { if (resolvingJournal) { showError(error); if (!['STALE_IDENTITY', 'STALE_BINDING'].includes(error.code)) pending(); } - else storageWarning(); + else { + storageWarning(); + if (preflight) { + // A known pending save is always blocking. Only an unreadable draft list, + // after pending saves were resolved, may be explicitly skipped. + const proceed = readingDrafts && await decide(t('storage'), t('draftReadFailed'), + [['retry', t('retry'), true], ['continue', t('continueWithoutDrafts')]]) === 'continue'; + assertContext(ctx, true); + if (!proceed) { blocked = true; recoveryPending = true; message('draft', 'storage', boot); } + } + } } finally { recovering = false; updateLock(); if (showConflict) setTimeout(() => conflictDialog(), 0); } + return { restored: !!binding && binding !== originalBinding, blocked }; } async function renameCurrent() { if (!project) return; @@ -500,8 +555,9 @@ async function guard() { } async function navigate(url) { if (await guard()) { leaving = true; location.assign(url); } } async function downloadCopy() { - const snapshot = await bridge.createSnapshot(); - try { downloadBytes(snapshot.bytes, filename(project.name)); } finally { await bridge.releaseSnapshot(snapshot.snapshotId); } + const ctx = context(), engine = bridge, name = filename(project.name); + const snapshot = await engine.createSnapshot({ forLocalDownload: true }); + try { assertContext(ctx, true); downloadBytes(snapshot.bytes, name); } finally { await engine.releaseSnapshot(snapshot.snapshotId); } } async function saveAs() { if (copying || saver?.active) { notice(t('verifying')); return; } @@ -558,6 +614,7 @@ function showFontError(error) { button.onclick = async () => { setLocale('en', false); if (bridge) await bridge.setLocale('en'); await boot(); }; main.querySelector('section').append(button); } async function releaseAccount() { + request?.abort(); await bridge?.cancelOpenProject?.().catch(() => {}); await clearAssistant(); await draft(); saver?.dispose(); unsubscribe?.(); binding = null; viewportReady = false; await bridge?.releaseProject(); project = null; state = {}; recoveryPending = false; updateLock(); @@ -565,11 +622,11 @@ async function releaseAccount() { async function authChanged() { if (signingOut) return; if (booting) { - if (api && (api.token !== auth.token || api.user !== userId())) { ++epoch; authLocked = true; restartBoot = true; updateLock(); await clearAssistant(); } + if (api && (api.token !== auth.token || api.user !== userId())) { ++epoch; request?.abort(); authLocked = true; restartBoot = true; updateLock(); await bridge?.cancelOpenProject?.().catch(() => {}); if (!binding) await bridge?.releaseProject(); await clearAssistant(); } return; } if (auth.token === authToken && userId() === boundUser) return; - ++epoch; request?.abort(); + ++epoch; request?.abort(); await bridge?.cancelOpenProject?.().catch(() => {}); if (!auth.token) { authToken = null; authLocked = true; updateLock(); status('expired'); await clearAssistant(); @@ -598,15 +655,31 @@ window.addEventListener('beforeunload', (event) => { if (!leaving && binding && window.addEventListener('offline', () => { if (editor && binding) status('offline'); }); window.addEventListener('online', () => { if (binding && saveState === 'offline') status(state.dirty ? 'dirty' : project.version ? 'saved' : 'never'); }); window.addEventListener('vm:cad:update', () => { - const banner = document.querySelector('#cad-notice'); banner.textContent = ''; + if (refreshingEngine) return; + notice(''); + const banner = document.querySelector('#cad-notice'); const label = document.createElement('span'); label.textContent = t('update'); const refresh = document.createElement('button'); refresh.className = 'btn'; refresh.textContent = t('refresh'); - refresh.addEventListener('click', async () => { if (await guard()) { leaving = true; location.reload(); } }); - banner.append(label, refresh); banner.hidden = false; + refresh.addEventListener('click', async () => { + if (refresh.disabled) return; + refresh.disabled = true; + try { + if (!(await guard())) return; + refreshingEngine = true; updateLock(); refresh.textContent = t('preparing'); + await prepareEngineRefresh(); + leaving = true; location.reload(); + } catch { + label.textContent = t('updateFailed'); banner.replaceChildren(label, refresh); banner.hidden = false; + } + finally { + if (!leaving) { refreshingEngine = false; updateLock(); refresh.disabled = false; refresh.textContent = t('refresh'); } + } + }); + banner.prepend(label, refresh); banner.hidden = false; }); document.addEventListener('visibilitychange', () => { if (document.hidden) draft(); }); setInterval(draft, 30000); setInterval(() => { if (authToken && !auth.token) authChanged(); }, 5000); -matchMedia('(max-width: 820px)').addEventListener('change', () => { updateLock(); if (!viewportReady && !desktopAllowed()) { ++epoch; message('desktop', 'desktopHint', () => location.assign('/'), 'home'); } }); +matchMedia('(max-width: 820px)').addEventListener('change', () => { updateLock(); if (!viewportReady && !desktopAllowed()) { ++epoch; request?.abort(); bridge?.cancelOpenProject?.().catch(() => {}); message('desktop', 'desktopHint', () => location.assign('/'), 'home'); } }); initEditorHeader(); setLocale(locale(), false); drawHeader(); boot(); diff --git a/js/cad/config.js b/js/cad/config.js index b31bfaa..54ef805 100644 --- a/js/cad/config.js +++ b/js/cad/config.js @@ -1,4 +1,4 @@ -export const CAD = Object.freeze({ product: 'VibeMake CAD', list: '/cad/', editor: '/cad/editor/', bridgeVersion: 1, maxSourceBytes: 256 * 1024 * 1024, +export const CAD = Object.freeze({ product: 'VibeMake CAD', list: '/cad/', editor: '/cad/editor/', bridgeVersion: 1, maxSourceBytes: 256 * 1024 * 1024, maxStepSourceBytes: 500 * 1024 * 1024, links: Object.freeze({ home: '/', help: null, feedback: null, releases: null }), engineManifest: '/cad/engine.json' }); export const projectUrl = (id) => `${CAD.editor}?project=${encodeURIComponent(id)}`; export function desktopAllowed() { @@ -8,3 +8,14 @@ export function desktopAllowed() { } export function validName(value) { const s = value.trim(); return [...s].length >= 1 && [...s].length <= 100 && !/[\u0000-\u001f\u007f]/.test(s); } export function filename(name) { return (name.replace(/[\\/:*?"<>|\u0000-\u001f\u007f]/g, '_').slice(0, 100).replace(/^\.+/, '') || 'design') + '.sc'; } +export function validNativeFilename(value) { + return typeof value === 'string' && value.length > 3 && [...value].length <= 255 && /\.sc$/i.test(value) + && !/[\\/:\u0000-\u001f\u007f-\u009f]/.test(value); +} + +export function validStepFilename(value) { + return typeof value === 'string' && [...value].length <= 1024 && /\.(step|stp)$/i.test(value) + && !/[\\/\u0000-\u001f\u007f-\u009f]/.test(value); +} +export const workspaceCadEditable = (project, sha = null) => project?.repoStatus === 'READY' + && typeof project.stepMainUrl === 'string' && !!project.stepMainUrl.trim() && !sha; diff --git a/js/cad/dialog.js b/js/cad/dialog.js index 2d33ce1..5b0fd80 100644 --- a/js/cad/dialog.js +++ b/js/cad/dialog.js @@ -2,11 +2,14 @@ import { openModal } from '../auth-dialog.js'; import { esc } from '../layout.js'; import { t } from './i18n.js'; import { validName } from './config.js'; -export function choose(title, description, choices) { +export function choose(title, description, choices, { signal } = {}) { + if (signal?.aborted) return Promise.resolve(null); return new Promise((resolve) => { const m = openModal({ title, closeLabel: t('cancel'), body: `

${esc(description)}

${choices.map(([id, label, primary]) => ``).join('')}
` }); let answer = null; - m.onClose = () => resolve(answer); + const abort = () => m.close(); + m.onClose = () => { signal?.removeEventListener('abort', abort); resolve(answer); }; + signal?.addEventListener('abort', abort, { once: true }); m.el.querySelectorAll('[data-choice]').forEach((button) => button.addEventListener('click', () => { answer = button.dataset.choice; m.close(); })); queueMicrotask(() => m.el.querySelector('button[data-choice]')?.focus()); }); diff --git a/js/cad/drafts.js b/js/cad/drafts.js index 4c88333..7d40d03 100644 --- a/js/cad/drafts.js +++ b/js/cad/drafts.js @@ -1,6 +1,15 @@ // Binary drafts and save journals never contain tokens or signed URLs. +function coveredRevision(revision, saved) { + if (typeof revision !== 'string' || typeof saved !== 'string' || !revision || !saved) return false; + if (revision === saved) return true; + const before = typeof revision === 'string' && /^(\d{1,20}):/.exec(revision); + const after = typeof saved === 'string' && /^(\d{1,20}):/.exec(saved); + // Revision counters only order changes within one binding. Equal counters with + // different visibility state may represent a later change and must survive. + return !!before && !!after && BigInt(before[1]) < BigInt(after[1]); +} export class DraftStore { - constructor(indexed = globalThis.indexedDB) { this.indexed = indexed; } + constructor(indexed = globalThis.indexedDB) { this.indexed = indexed; this.acknowledged = new Map(); } async database() { if (!this.indexed) throw new Error('IndexedDB unavailable'); this.db ??= new Promise((resolve, reject) => { @@ -20,7 +29,11 @@ export class DraftStore { } key(user, project, session, kind) { return JSON.stringify([user, project, session, kind]); } put(user, project, session, kind, value) { - return this.transaction('readwrite', (store) => store.put({ key: this.key(user, project, session, kind), user, project, session, kind, updatedAt: Date.now(), ...value })); + return this.transaction('readwrite', (store) => { + const saved = value.binding && this.acknowledged.get(JSON.stringify([user, project, value.binding])); + if (kind === 'draft' && saved && coveredRevision(value.revision, saved)) return; + store.put({ key: this.key(user, project, session, kind), user, project, session, kind, updatedAt: Date.now(), ...value }); + }); } async list(user, project, kind) { return this.transaction('readonly', (store, done) => { const req = store.getAll(); req.onsuccess = () => done(req.result.filter((r) => r.user === user && r.project === project && (!kind || r.kind === kind)).sort((a, b) => b.updatedAt - a.updatedAt)); }); @@ -28,9 +41,16 @@ export class DraftStore { remove(key, snapshotId) { return this.transaction('readwrite', (store) => { const request = store.get(key); request.onsuccess = () => { if (request.result && (!snapshotId || request.result.snapshotId === snapshotId)) store.delete(key); }; }); } + rebindDraft(key, snapshotId, baseline) { + return this.transaction('readwrite', (store) => { const request = store.get(key); request.onsuccess = () => { + const record = request.result; + if (record?.kind === 'draft' && record.snapshotId === snapshotId) store.put({ ...record, ...baseline }); + }; }); + } clearAcknowledged(user, project, snapshotId, baseline) { + if (baseline?.binding && baseline.revision) this.acknowledged.set(JSON.stringify([user, project, baseline.binding]), baseline.revision); return this.transaction('readwrite', (store) => { const request = store.openCursor(); request.onsuccess = () => { const cursor = request.result; if (!cursor) return; const r = cursor.value; - if (r.user === user && r.project === project && (r.snapshotId === snapshotId || (r.kind === 'draft' && baseline?.binding && r.binding === baseline.binding && r.revision === baseline.revision))) cursor.delete(); cursor.continue(); }; }); + if (r.user === user && r.project === project && (r.snapshotId === snapshotId || (r.kind === 'draft' && baseline?.binding && r.binding === baseline.binding && coveredRevision(r.revision, baseline.revision)))) cursor.delete(); cursor.continue(); }; }); } } diff --git a/js/cad/engine.js b/js/cad/engine.js index 27f987e..c2d29f6 100644 --- a/js/cad/engine.js +++ b/js/cad/engine.js @@ -1,7 +1,7 @@ import { CAD } from './config.js'; import { cadError } from './api.js'; import { locale } from './i18n.js'; -let engine; +let engine, workerRegistration; export function loadEngine() { return engine ??= start().catch((error) => { engine = null; throw error; }); } @@ -20,17 +20,62 @@ async function start() { while (!window.vibemakeCad) { if (performance.now() > deadline) throw cadError('ENGINE_TIMEOUT'); await new Promise((r) => setTimeout(r, 30)); } await window.vibemakeCad.ready(); if ('serviceWorker' in navigator) { - navigator.serviceWorker.register('/cad/sw.js', { scope: '/cad/', updateViaCache: 'none' }).then((registration) => { - const notify = () => window.dispatchEvent(new CustomEvent('vm:cad:update')); + workerRegistration = navigator.serviceWorker.register('/cad/worker.js', { scope: '/cad/', updateViaCache: 'none' }).then((registration) => { + let notifiedBuild; + const notify = async () => { + try { + const response = await fetch(CAD.engineManifest, { cache: 'no-store' }); + if (!response.ok) return; + const latest = await response.json(); + // A waiting cache worker does not mean the running engine is outdated. + if (typeof latest.buildId !== 'string' || !/^[a-zA-Z0-9_-]+$/.test(latest.buildId) || latest.buildId === manifest.buildId || latest.buildId === notifiedBuild) return; + notifiedBuild = latest.buildId; + window.dispatchEvent(new CustomEvent('vm:cad:update')); + } catch { /* An unavailable update check must not interrupt editing. */ } + }; if (registration.waiting) notify(); - registration.addEventListener('updatefound', () => { - const worker = registration.installing; + const watch = (worker) => { worker?.addEventListener('statechange', () => { if (worker.state === 'installed' && navigator.serviceWorker.controller) notify(); }); - }); - }).catch(() => { /* Editor remains usable when static caching is unavailable. */ }); + }; + watch(registration.installing); + registration.addEventListener('updatefound', () => watch(registration.installing)); + return registration; + }).catch(() => null); // Editor remains usable when static caching is unavailable. } return window.vibemakeCad; } + +function waitForWorker(worker, states, timeout) { + return new Promise((resolve) => { + const finish = (result) => { + clearTimeout(timer); + worker.removeEventListener('statechange', changed); + resolve(result); + }; + const changed = () => { + if (states.includes(worker.state)) finish(true); + else if (worker.state === 'redundant') finish(false); + }; + const timer = setTimeout(() => finish(false), timeout); + worker.addEventListener('statechange', changed); + changed(); + }); +} + +// Called only after the editor has completed its unsaved-changes guard. +export async function prepareEngineRefresh() { + if (!('serviceWorker' in navigator)) return; + const registration = await (workerRegistration || navigator.serviceWorker.getRegistration('/cad/')); + if (!registration || registration.scope !== new URL('/cad/', location.href).href) return; + await registration.update(); + if (registration.installing && !await waitForWorker(registration.installing, ['installed', 'activated'], 10000)) throw cadError('ENGINE_UPDATE_FAILED'); + const worker = registration.waiting; + if (!worker) return; + const activated = waitForWorker(worker, ['activated'], 2000); + worker.postMessage({ type: 'SKIP_WAITING' }); + if (!await activated) throw cadError('ENGINE_UPDATE_FAILED'); +} + export function downloadBytes(bytes, name) { const url = URL.createObjectURL(new Blob([bytes], { type: 'application/octet-stream' })); const link = document.createElement('a'); link.href = url; link.download = name; link.click(); diff --git a/js/cad/i18n.js b/js/cad/i18n.js index 1cc593d..f3c4dc9 100644 --- a/js/cad/i18n.js +++ b/js/cad/i18n.js @@ -1,6 +1,12 @@ // Product strings live here, separate from engine message IDs. const messages = { assistant: ['助手', 'Assistant'], assistantUpdate: ['当前编辑器引擎未包含助手,请更新引擎后刷新。', 'This editor engine does not include the assistant. Update the engine, then refresh.'], + stepDownload: ['下载初始 STEP…', 'Downloading initial STEP…'], stepImport: ['导入 STEP…', 'Importing STEP…'], + stepPreparing: ['准备模型视图…', 'Preparing model view…'], openCancelled: ['已取消打开项目', 'Project opening cancelled'], + stepWarnings: ['STEP 导入存在警告,请检查模型后再保存(展开详情)', 'STEP import has warnings. Check the model before saving (show details)'], + stepInvalid: ['STEP 文件无法导入或没有可用模型,请重试或检查源文件。', 'STEP could not be imported or contains no usable model. Retry or check the source file.'], + stepTooLarge: ['初始 STEP 超过 500 MiB 上限。', 'Initial STEP exceeds the 500 MiB limit.'], + stepEngineUpdate: ['当前引擎不支持云端 STEP 导入,请检查并刷新编辑器。', 'This engine does not support cloud STEP import. Check for updates and refresh the editor.'], projects: ['我的 CAD 项目', 'My CAD projects'], new: ['新建项目', 'New project'], search: ['搜索项目名称', 'Search project names'], untitled: ['未命名项目', 'Untitled project'], open: ['打开', 'Open'], rename: ['重命名', 'Rename'], delete: ['删除', 'Delete'], deleteAsk: ['删除这个项目?此操作不能从列表中撤销。', 'Delete this project? This cannot be undone from the list.'], @@ -22,7 +28,7 @@ const messages = { unavailable: ['项目已删除或无权限', 'Project deleted or access denied'], error: ['暂时无法完成,请重试。', 'Unable to complete. Please retry.'], incompatible: ['工程格式或后端能力不兼容,请联系管理员。', 'Design format or backend capability is incompatible. Contact your administrator.'], quota: ['项目容量已达上限,请联系管理员。', 'Project storage quota reached. Contact your administrator.'], - tooLarge: ['工程超过允许的大小。请下载本地副本。', 'Design exceeds the size limit. Download a local copy.'], + tooLarge: ['工程超过 256 MiB 云端上限,当前设计已保留。请通过文件菜单下载工程副本。', 'Design exceeds the 256 MiB cloud limit. Your design is preserved. Download a design copy from the File menu.'], invalidFile: ['工程损坏、包含外部依赖或格式不受支持,原工程已保留。', 'Invalid or unsupported design or external dependencies. Your current design is intact.'], desktop: ['请在电脑端使用 VibeMake CAD', 'Use VibeMake CAD on a desktop'], desktopHint: ['CAD 需要鼠标、键盘及宽于 820px 的窗口。', 'CAD needs a mouse, keyboard and a window wider than 820px.'], expand: ['请扩大窗口以继续编辑', 'Widen the window to continue editing'], protected: ['你的编辑会话已保留。', 'Your editing session is preserved.'], @@ -32,6 +38,8 @@ const messages = { conflictHint: ['另一窗口已更新云端版本。保留当前设计,另存新项目或下载副本;重新加载会丢弃当前修改。', 'Another window updated the cloud version. Save a new project or download your current design. Reloading discards your changes.'], draft: ['发现本机草稿', 'Local draft found'], draftHint: ['恢复此设备上的未保存设计?云端更新过时,恢复后会保留冲突保护。', 'Restore this device’s unsaved design? A newer cloud version will keep conflict protection.'], restore: ['恢复草稿', 'Restore draft'], discard: ['放弃草稿', 'Discard draft'], storage: ['本机草稿不可用,请及时保存或下载副本。', 'Local drafts unavailable. Save or download a copy regularly.'], + draftReadFailed: ['未完成保存事务已检查,但无法读取本机草稿。重试,或继续导入初始模型;继续不会删除已有草稿。', 'Pending saves were checked, but local drafts could not be read. Retry, or continue loading the initial model. Existing drafts will not be deleted.'], + continueWithoutDrafts: ['继续加载模型', 'Continue loading model'], snapshotBusy: ['请先完成当前交互,或在文件菜单选择保存以处理组件移动。', 'Finish the current interaction, or use File > Save to resolve component moves.'], pending: ['上次保存结果未知。重试会确认同一上传批次,不会创建重复版本。', 'The previous save result is unknown. Retrying confirms the same upload batch without creating a duplicate version.'], font: ['中文字体加载失败。请重试,或临时使用英文。', 'Chinese font failed to load. Retry, or temporarily use English.'], @@ -40,6 +48,7 @@ const messages = { metadataConflict: ['名称已在另一窗口修改,请刷新后重试。', 'The name changed in another window. Refresh and retry.'], update: ['编辑器有新版本。请保存后刷新。', 'An editor update is available. Save before refreshing.'], refresh: ['检查并刷新', 'Refresh'], + updateFailed: ['更新检查失败,当前设计已保留,请重试。', 'The update check failed. Your current design is preserved. Please retry.'], engineMissing: ['编辑器资源缺失,请联系管理员或重试。', 'Editor resources are missing. Contact your administrator or retry.'], uploadExpired: ['保存事务已过期,当前设计已保留,请重新保存。', 'The save transaction expired. Your design is preserved. Save again.'], downloadForbidden: ['无法读取工程文件,请联系管理员检查 OSS/CDN 访问权限和跨域配置。', 'Cannot read the design file. Ask your administrator to check OSS/CDN access and CORS settings.'], @@ -60,6 +69,7 @@ export function errorText(error) { const keys = { HEAD_CONFLICT: 'conflict', CAD_VERSION_CONFLICT: 'conflict', METADATA_CONFLICT: 'metadataConflict', PROJECT_DELETED: 'unavailable', NOT_FOUND: 'unavailable', FORBIDDEN: 'unavailable', UNAUTHORIZED: 'expired', FORMAT_UNSUPPORTED: 'incompatible', UNSUPPORTED_FORMAT: 'incompatible', SOURCE_TOO_LARGE: 'tooLarge', TOO_LARGE: 'tooLarge', SNAPSHOT_BUSY: 'snapshotBusy', BAD_DESIGN: 'invalidFile', RATE_LIMITED: 'rateLimit', PENDING_SAVE: 'pending', FONT_UNAVAILABLE: 'font', + BAD_STEP_FILE: 'stepInvalid', STEP_IMPORT_FAILED: 'stepInvalid', STEP_EMPTY_MODEL: 'stepInvalid', STEP_TOO_LARGE: 'stepTooLarge', STEP_ENGINE_UPDATE: 'stepEngineUpdate', ENGINE_MISSING: 'engineMissing', UPLOAD_EXPIRED: 'uploadExpired', SAVE_IN_PROGRESS: 'verifying', QUOTA_EXCEEDED: 'quota', INVALID_SOURCE_FILE: 'invalidFile', CHECKSUM_MISMATCH: 'invalidFile', EXTERNAL_DEPENDENCIES_UNSUPPORTED: 'invalidFile', UNSUPPORTED_FORMAT_VERSION: 'incompatible', SAVE_UNAVAILABLE: 'pending', UPLOAD_NOT_READY: 'pending', UPLOAD_AUTH_EXPIRED: 'uploadExpired', diff --git a/js/cad/opening.js b/js/cad/opening.js new file mode 100644 index 0000000..c3bb6dd --- /dev/null +++ b/js/cad/opening.js @@ -0,0 +1,49 @@ +// The cloud document is authoritative; initial STEP is only an unsaved bootstrap source. +import { CAD } from './config.js'; +import { cadError, downloadSource, initialStepSource } from './api.js'; + +export async function openProjectSource({ api, bridge, project, signal, onStage = () => {}, assertCurrent = () => {}, + recover = async () => ({}), downloader = downloadSource }) { + const check = () => { signal?.throwIfAborted(); assertCurrent(); }; + const download = async (source, maxBytes, stage) => { + check(); onStage(stage); + let bytes; + try { + bytes = await downloader(source, maxBytes, (done, total) => { + check(); onStage(stage, Math.round(done / total * 100) + '%'); + }, signal); + } catch (error) { + if (stage === 'stepDownload' && error.code === 'SOURCE_TOO_LARGE') throw cadError('STEP_TOO_LARGE'); + throw error; + } + check(); return bytes; + }; + check(); + if (project.hasDocument) { + const source = await api.document(project.id, signal); + check(); + const bytes = await download(source, CAD.maxSourceBytes, 'download'); + onStage('rebuild'); + const opened = await bridge.openProject({ projectId: project.id, bytes, saved: true }); + check(); + return { opened, version: source.version, kind: 'native' }; + } + const recovery = await recover(); + check(); + if (recovery.restored || recovery.blocked) return { ...recovery, kind: 'recovery' }; + if (project.initialStep) { + const source = initialStepSource(project.initialStep); + const capabilities = await bridge.ready(); + check(); + if (capabilities.capabilities?.stepImport !== true || typeof bridge.openProjectFromStep !== 'function' + || typeof bridge.cancelOpenProject !== 'function') throw cadError('STEP_ENGINE_UPDATE'); + const bytes = await download(source, CAD.maxStepSourceBytes, 'stepDownload'); + onStage('stepImport'); + const opened = await bridge.openProjectFromStep({ projectId: project.id, bytes, fileName: source.fileName }); + check(); + return { opened, version: 0, kind: 'step', warnings: opened.warnings || [] }; + } + const opened = await bridge.openProject({ projectId: project.id, bytes: null, saved: false }); + check(); + return { opened, version: 0, kind: 'empty' }; +} diff --git a/js/layout.js b/js/layout.js index 0c7c44f..e4f1399 100644 --- a/js/layout.js +++ b/js/layout.js @@ -96,11 +96,14 @@ export function renderShell(active, { overlay = false, footer = true, assistant if (existing) return bindShell(existing, overlay, footer, assistant, search); const nav = document.createElement('header'); nav.className = `nav${overlay ? ' overlay' : ''}`; + const logoImage = active === 'cad' && document.body.dataset.cadPage === 'editor' + ? 'make CAD' + : 'make'; // 工作台(studio)页面不滚动、没有滚动条,其他页面有。给导航补上滚动条宽度,切换页面时 logo 和按钮不会左右跳 if (overlay) nav.style.paddingRight = `${scrollbarWidth()}px`; nav.innerHTML = `