686 lines
41 KiB
JavaScript
686 lines
41 KiB
JavaScript
import { esc, icon, renderShell } from '../layout.js';
|
|
import { auth, getMe, logout } from '../api.js';
|
|
import { openLogin } from '../auth-dialog.js';
|
|
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, 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');
|
|
const store = new DraftStore(), session = crypto.randomUUID();
|
|
let api, bridge, project, binding, saver, boundUser = null, state = {}, epoch = 0, page = 1, query = '', total = 0;
|
|
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');
|
|
function context() { return { epoch, client: api, owner: boundUser, binding }; }
|
|
async function agentRevision(value) {
|
|
const revision = String(value ?? '');
|
|
if (!revision) throw cadError('BAD_RESPONSE');
|
|
// The bridge revision includes visibility state; the Agent API allows only 128 characters.
|
|
return sha256(new TextEncoder().encode(revision));
|
|
}
|
|
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 && !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;
|
|
header.dataset.cadEditor = 'true';
|
|
const logo = header.querySelector('.nav-logo');
|
|
logo.href = CAD.list;
|
|
logo.setAttribute('aria-label', t('list'));
|
|
logo.addEventListener('click', (event) => {
|
|
event.preventDefault();
|
|
navigate(CAD.list);
|
|
});
|
|
header.querySelector('.nav-inner > .nav-links')?.remove();
|
|
const left = document.createElement('div');
|
|
left.className = 'cad-appbar-left';
|
|
left.innerHTML = '<span class="cad-appbar-divider" aria-hidden="true"></span><nav class="nav-links cad-engine-menus" aria-label="' + esc(t('file')) + '"><button type="button" data-engine-menu="file">' + esc(t('file')) + '</button></nav>'
|
|
+ '<button type="button" class="icon-btn cad-appbar-icon" data-history="undo" aria-label="' + esc(t('undo')) + '" title="' + esc(t('undo')) + '">' + icon('undo', 18) + '</button>'
|
|
+ '<button type="button" class="icon-btn cad-appbar-icon" data-history="redo" aria-label="' + esc(t('redo')) + '" title="' + esc(t('redo')) + '">' + icon('redo', 18) + '</button>';
|
|
logo.after(left);
|
|
const actions = header.querySelector('.nav-actions');
|
|
actions.querySelector('.nav-search')?.remove();
|
|
actions.querySelectorAll('[data-publish], .nav-menu').forEach((node) => node.remove());
|
|
header.querySelector('.sheet')?.remove();
|
|
const menus = document.createElement('nav');
|
|
menus.className = 'nav-links cad-engine-menus cad-editor-utility';
|
|
menus.setAttribute('aria-label', t('help'));
|
|
menus.innerHTML = '<button type="button" class="icon-btn cad-appbar-icon" data-engine-menu="preferences" aria-label="' + esc(t('preferences')) + '" title="' + esc(t('preferences')) + '">' + icon('gear', 18) + '</button>'
|
|
+ '<button type="button" class="icon-btn cad-appbar-icon" data-engine-menu="help" aria-label="' + esc(t('help')) + '" title="' + esc(t('help')) + '">' + icon('help', 18) + '</button>';
|
|
actions.prepend(menus);
|
|
const authSlot = actions.querySelector('[data-auth]');
|
|
authSlot?.classList.remove('hide-sm');
|
|
const saveStatus = document.createElement('span');
|
|
saveStatus.className = 'cad-save-state';
|
|
saveStatus.dataset.state = saveState;
|
|
saveStatus.setAttribute('role', 'status');
|
|
saveStatus.textContent = t(saveState);
|
|
const saveButton = document.createElement('button');
|
|
saveButton.className = 'icon-btn cad-appbar-icon';
|
|
saveButton.type = 'button';
|
|
saveButton.dataset.save = '';
|
|
saveButton.innerHTML = icon('save', 18);
|
|
saveButton.setAttribute('aria-label', t('save'));
|
|
saveButton.title = t('save');
|
|
saveButton.disabled = !binding || authLocked || openingProject || recovering || recoveryPending;
|
|
if (authSlot) {
|
|
actions.insertBefore(saveStatus, authSlot);
|
|
} else {
|
|
actions.append(saveStatus);
|
|
}
|
|
left.append(saveButton);
|
|
header.addEventListener('click', (event) => {
|
|
const button = event.target.closest('[data-engine-menu]');
|
|
if (!button || !bridge) return;
|
|
bridge.showMenu(button.dataset.engineMenu).catch(showError);
|
|
});
|
|
left.querySelectorAll('[data-history]').forEach((button) => button.addEventListener('click', async () => {
|
|
if (authLocked || button.disabled) return;
|
|
try {
|
|
await window.solidcraft.execute(button.dataset.history === 'undo' ? 'edit.undo' : 'edit.redo', {});
|
|
state = await bridge.getState();
|
|
drawHeader();
|
|
} catch (error) { showError(error); }
|
|
}));
|
|
saveButton.addEventListener('click', () => save().catch(showError));
|
|
}
|
|
function drawHeader() {
|
|
if (editor) {
|
|
// The engine owns the full-height split. Match its measured column in the HTML bar,
|
|
// including after a divider drag or a CAD UI zoom change. Older engines keep their inset.
|
|
const fullHeight = state.assistant?.fullHeight === true;
|
|
const fraction = Number(state.assistant?.panelFraction);
|
|
const assistantWidth = fullHeight && state.assistant?.open && Number.isFinite(fraction)
|
|
? Math.max(0, Math.min(0.5, fraction)) * 100 : 0;
|
|
document.body.classList.toggle('cad-full-height', fullHeight);
|
|
document.body.style.setProperty('--cad-assistant-width', `${assistantWidth}%`);
|
|
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 || 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 || 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)); }
|
|
}
|
|
const assistant = header.querySelector('[data-engine-menu="assistant"]');
|
|
if (assistant) {
|
|
assistant.hidden = !assistantAvailable || state.assistant?.enabled === false || state.assistant?.toolbar === false;
|
|
assistant.disabled = authLocked || !binding || !viewportReady || modalCount > 0;
|
|
assistant.setAttribute('aria-pressed', String(!!state.assistant?.open));
|
|
}
|
|
document.title = project ? project.name + ' — ' + CAD.product : CAD.product;
|
|
} else {
|
|
document.title = t('projects') + ' — ' + CAD.product;
|
|
}
|
|
const description = locale() === 'zh' ? 'VibeMake CAD 在线参数化建模、草图、材质与渲染。' : 'VibeMake CAD for online parametric modeling, sketches, materials and rendering.';
|
|
const meta = document.querySelector('meta[name="description"]'); if (meta) meta.content = description;
|
|
const socialTitle = document.querySelector('meta[property="og:title"]'); if (socialTitle) socialTitle.content = CAD.product;
|
|
const socialDescription = document.querySelector('meta[property="og:description"]'); if (socialDescription) socialDescription.content = description;
|
|
}
|
|
function status(key, error) {
|
|
saveState = key; drawHeader();
|
|
if (key === 'coverFailed' || key === 'coverUnavailable') {
|
|
notice(t(key) + (error?.requestId ? ` (${error.requestId})` : ''));
|
|
return;
|
|
}
|
|
if (error && error.code !== 'STALE_IDENTITY' && error.code !== 'STALE_BINDING') showError(error);
|
|
}
|
|
function showError(error) {
|
|
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(); }
|
|
}
|
|
function message(key, hint, action, actionLabel = 'retry') {
|
|
main.hidden = false;
|
|
main.innerHTML = `<section class="cad-state">${icon('cube', 48)}<h1>${esc(t(key))}</h1>${hint ? `<p>${esc(t(hint))}</p>` : ''}${action ? `<button class="btn btn-primary" data-action>${esc(t(actionLabel))}</button>` : ''}</section>`;
|
|
main.querySelector('[data-action]')?.addEventListener('click', action);
|
|
}
|
|
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;
|
|
leaving = true; signingOut = true; authLocked = true; updateLock(); await clearAssistant();
|
|
try { await logout(); } catch { /* a rejected logout still clears this browser's identity */ }
|
|
auth.clear(); signingOut = false;
|
|
if (editor) location.assign('/cad/'); else { authLocked = true; drawHeader(); message('loginRequired', 'loginHint', signIn, 'signIn'); }
|
|
}
|
|
function updateLock() {
|
|
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');
|
|
if (blocker) {
|
|
blocker.hidden = !(!desktopAllowed() && viewportReady);
|
|
if (!blocker.hidden) blocker.innerHTML = `<div class="cad-state"><h2>${esc(t('expand'))}</h2><p>${esc(t('protected'))}</p></div>`;
|
|
}
|
|
}
|
|
async function bindAssistant() {
|
|
if (!assistantAvailable || !binding || !boundUser) return;
|
|
const ctx = context();
|
|
assistantRequest?.abort(); assistantRequest = new AbortController();
|
|
const capabilityRequest = assistantRequest;
|
|
if (window.__VIBEMAKE_CAD__) window.__VIBEMAKE_CAD__.agentChat = null;
|
|
let capabilities = null;
|
|
try {
|
|
capabilities = await api.aiCapabilities(capabilityRequest.signal);
|
|
assertContext(ctx, true);
|
|
} catch (error) {
|
|
if (error.code === 'STALE_IDENTITY' || error.code === 'STALE_BINDING') throw error;
|
|
if (error.name !== 'AbortError') notice(errorText(error));
|
|
} finally {
|
|
if (assistantRequest === capabilityRequest) assistantRequest = null;
|
|
}
|
|
if (capabilityRequest.signal.aborted) return;
|
|
assertContext(ctx, true);
|
|
const client = api, engine = bridge, documentContext = context();
|
|
const host = window.__VIBEMAKE_CAD__;
|
|
if (host) {
|
|
host.agentChat = capabilities?.enabled ? async (requestBody, signal, onStart) => {
|
|
assertContext(documentContext, true);
|
|
const current = await engine.getState();
|
|
const documentRevision = await agentRevision(current.revision);
|
|
assertContext(documentContext, true);
|
|
const request = {
|
|
...requestBody,
|
|
cadProjectCode: project.id,
|
|
context: { ...requestBody.context, documentRevision },
|
|
};
|
|
return client.aiChat(request, signal, () => {
|
|
assertContext(documentContext, true);
|
|
onStart?.();
|
|
});
|
|
} : null;
|
|
}
|
|
await bridge.setAgentContext({
|
|
userId: boundUser,
|
|
projectId: project.id,
|
|
binding,
|
|
sessionId: session,
|
|
documentSessionCode: session,
|
|
aiCapabilities: capabilities,
|
|
});
|
|
assertContext(ctx, true);
|
|
}
|
|
async function clearAssistant() {
|
|
assistantRequest?.abort(); assistantRequest = null;
|
|
if (typeof bridge?.setAgentContext === 'function') await bridge.setAgentContext(null).catch(() => {});
|
|
if (window.__VIBEMAKE_CAD__) window.__VIBEMAKE_CAD__.agentChat = null;
|
|
}
|
|
async function validateIdentity() {
|
|
if (!auth.token) return false;
|
|
const token = auth.token;
|
|
const user = await getMe();
|
|
if (auth.token !== token) throw cadError('STALE_IDENTITY');
|
|
if (!user?.userCode) throw cadError('BAD_RESPONSE');
|
|
auth.setUser(user); return true;
|
|
}
|
|
async function boot() {
|
|
if (booting) return;
|
|
booting = true; const current = ++epoch;
|
|
try {
|
|
if (!desktopAllowed()) { message('desktop', 'desktopHint', () => location.assign('/'), 'home'); return; }
|
|
stage('identity'); drawHeader();
|
|
if (!(await validateIdentity())) {
|
|
authLocked = true; updateLock(); message('loginRequired', 'loginHint', signIn, 'signIn');
|
|
await openLogin({ locale: locale() });
|
|
if (!auth.token || !(await validateIdentity())) return;
|
|
}
|
|
if (current !== epoch) return;
|
|
api = new CadApi();
|
|
if (current !== epoch) return;
|
|
authLocked = false; authToken = auth.token;
|
|
if (boundUser && boundUser !== userId()) { await releaseAccount(); location.replace('/cad/'); return; }
|
|
boundUser = userId();
|
|
if (editor && binding) {
|
|
saver.api = api; saver.closed = false;
|
|
await bindAssistant(); updateLock();
|
|
if (saver.operation) await saver.save();
|
|
drawHeader(); main.hidden = true; return;
|
|
}
|
|
if (editor) await openEditor(current); else await loadList();
|
|
} catch (error) {
|
|
if (current !== epoch) return;
|
|
if (error.code === 'STALE_IDENTITY') { setTimeout(boot, 0); return; }
|
|
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 { openingProject = false; booting = false; drawHeader(); updateLock(); if (restartBoot) { restartBoot = false; setTimeout(boot, 0); } }
|
|
}
|
|
async function loadList() {
|
|
if (!api || authLocked) return;
|
|
request?.abort(); request = new AbortController(); const control = request, current = epoch, client = api;
|
|
main.innerHTML = `<section><div class="cad-heading"><div><p class="cad-eyebrow">VIBEMAKE CAD</p><h1>${esc(t('projects'))}</h1></div><button class="btn btn-primary" data-new>${icon('plus')} ${esc(t('new'))}</button></div>
|
|
<label class="cad-search">${icon('search')}<input type="search" maxlength="200" aria-label="${esc(t('search'))}" placeholder="${esc(t('search'))}" value="${esc(query)}"></label><div data-results aria-live="polite"><div class="cad-state">${esc(t('loading'))}</div></div></section>`;
|
|
main.querySelector('[data-new]').addEventListener('click', newProject);
|
|
let timer;
|
|
main.querySelector('input').addEventListener('input', (event) => { query = [...event.target.value].slice(0, 200).join(''); clearTimeout(timer); timer = setTimeout(() => { page = 1; fetchResults(); }, 300); });
|
|
async function fetchResults() {
|
|
if (request !== control) return;
|
|
const q = query, requestedPage = page;
|
|
try {
|
|
const result = await client.list({ keyword: q, page: requestedPage, pageSize: 20 }, control.signal);
|
|
if (current !== epoch || request !== control || q !== query || requestedPage !== page) return;
|
|
total = result.total;
|
|
if (!result.items.length && page > 1) { page--; return fetchResults(); }
|
|
const target = main.querySelector('[data-results]');
|
|
target.innerHTML = result.items.length ? `<div class="cad-grid">${result.items.map((p) => `<article class="cad-card"><div class="cad-card-art" aria-hidden="true">${p.coverUrl ? `<img src="${esc(p.coverUrl)}" alt="" loading="lazy" decoding="async" referrerpolicy="no-referrer">` : icon('cube', 52)}</div><div class="cad-card-body"><h2>${esc(p.name)}</h2><small>${p.lastSavedAt ? `${esc(t('savedAt'))} ${esc(new Date(p.lastSavedAt).toLocaleString(locale() === 'zh' ? 'zh-CN' : 'en'))}` : esc(t('noSave'))}</small><div class="cad-card-actions"><a class="btn btn-sm" href="${projectUrl(p.id)}">${esc(t('open'))}</a><button class="btn btn-sm" data-rename="${esc(p.id)}" aria-label="${esc(t('rename'))}">${icon('edit')}</button><button class="btn btn-sm" data-delete="${esc(p.id)}" aria-label="${esc(t('delete'))}">${icon('trash')}</button></div></div></article>`).join('')}</div><nav class="cad-pagination" aria-label="Pagination"><button class="btn btn-sm" data-prev ${page === 1 ? 'disabled' : ''}>${esc(t('previous'))}</button><span>${page} / ${Math.max(1, Math.ceil(total / 20))}</span><button class="btn btn-sm" data-next ${page * 20 >= total ? 'disabled' : ''}>${esc(t('next'))}</button></nav>`
|
|
: `<section class="cad-state">${icon('cube', 48)}<h2>${esc(t(query ? 'noResults' : 'empty'))}</h2><p>${esc(t('emptyHint'))}</p></section>`;
|
|
target.querySelectorAll('.cad-card-art img').forEach((image) => {
|
|
const fallback = () => { image.parentElement.innerHTML = icon('cube', 52); };
|
|
image.addEventListener('error', fallback, { once: true });
|
|
if (image.complete && !image.naturalWidth) fallback();
|
|
});
|
|
target.querySelector('[data-prev]')?.addEventListener('click', () => { page--; fetchResults(); });
|
|
target.querySelector('[data-next]')?.addEventListener('click', () => { page++; fetchResults(); });
|
|
target.querySelectorAll('[data-rename]').forEach((button) => button.addEventListener('click', async () => {
|
|
const item = result.items.find((p) => p.id === button.dataset.rename), name = await nameDialog(item.name);
|
|
if (!name) return;
|
|
try { client.assertIdentity(); if (current !== epoch) return; await client.rename(item.id, name); await fetchResults(); } catch (error) { showError(error); }
|
|
}));
|
|
target.querySelectorAll('[data-delete]').forEach((button) => button.addEventListener('click', async () => {
|
|
if (await choose(t('delete'), t('deleteAsk'), [['delete', t('delete')], ['cancel', t('cancel'), true]]) !== 'delete') return;
|
|
button.disabled = true; try { client.assertIdentity(); if (current !== epoch) return; await client.delete(button.dataset.delete); await fetchResults(); } catch (error) { showError(error); button.disabled = false; }
|
|
}));
|
|
} catch (error) { if (current !== epoch || control !== request || error.name === 'AbortError') return; showError(error); const target = main.querySelector('[data-results]'); if (target) { target.textContent = errorText(error); const retry = document.createElement('button'); retry.className = 'btn'; retry.textContent = t('retry'); retry.onclick = fetchResults; target.append(retry); } }
|
|
}
|
|
await fetchResults();
|
|
}
|
|
async function newProject() {
|
|
const ctx = context();
|
|
if (editor && !(await guard())) return;
|
|
const name = await nameDialog(t('untitled')); if (!name) return;
|
|
const client = ctx.client;
|
|
try {
|
|
assertContext(ctx, editor);
|
|
const created = await client.create(name);
|
|
assertContext(ctx, editor);
|
|
leaving = true;
|
|
location.assign(projectUrl(created.id));
|
|
} catch (error) { showError(error); }
|
|
}
|
|
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 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; }
|
|
check();
|
|
const engineReady = await bridge.ready(); check();
|
|
assistantAvailable = engineReady.capabilities?.assistant === true && typeof bridge.setAgentContext === 'function';
|
|
if (!assistantAvailable) notice(t('assistantUpdate'));
|
|
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();
|
|
}
|
|
recovering = true; viewportReady = true; viewport.style.visibility = ''; main.hidden = true;
|
|
unsubscribe?.(); unsubscribe = bridge.subscribe(onEngineState);
|
|
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;
|
|
state = next;
|
|
if (!saver?.active && !['conflict', 'failed', 'expired', 'unavailable', 'pending'].includes(saveState)) {
|
|
saveState = project?.version ? (next.dirty ? 'dirty' : saver?.pendingCover ? 'coverFailed' : saver?.coverUnavailable ? 'coverUnavailable' : 'saved') : 'never';
|
|
}
|
|
drawHeader();
|
|
if (next.intent && !authLocked && modalCount === 0) hostIntent(next.intent).catch(showError);
|
|
if (next.locale && next.locale !== locale() && !next.fontFailed && !recovering) { setLocale(next.locale); drawHeader(); }
|
|
}
|
|
async function save() {
|
|
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;
|
|
try { result = await saver.save(); }
|
|
catch (error) { if (error.code === 'SNAPSHOT_BUSY' && state.pendingMoves) await bridge.requestSave(); throw error; }
|
|
assertContext(ctx, true);
|
|
state = await bridge.getState();
|
|
status(state.dirty ? 'dirty' : result.coverPending ? 'coverFailed' : result.coverUnavailable ? 'coverUnavailable' : 'saved');
|
|
if (result.coverPending) notice(t('coverFailed'));
|
|
else if (result.coverUnavailable) notice(t('coverUnavailable'));
|
|
else if (!draftWarning) notice('');
|
|
return result;
|
|
}
|
|
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, 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({ 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 = () => {
|
|
blocked = true; recoveryPending = true; status('pending'); notice(t('pending'));
|
|
const button = document.createElement('button'); button.className = 'btn'; button.textContent = t('retry');
|
|
button.onclick = () => (binding ? restoreLocal() : boot()).catch(showError);
|
|
document.querySelector('#cad-notice').append(button);
|
|
if (!binding) message('pending', null, boot);
|
|
};
|
|
let resolvingJournal = true, readingDrafts = false, showConflict = false;
|
|
try {
|
|
const journals = await store.list(boundUser, project.id, 'operation');
|
|
assertContext(ctx, true);
|
|
for (const journal of journals.reverse()) {
|
|
if (journal.user !== ctx.owner || journal.projectId !== project.id) throw cadError('BAD_DESIGN');
|
|
if (!Number.isSafeInteger(journal.request?.sizeBytes)) {
|
|
if (!(journal.bytes instanceof Uint8Array)) throw cadError('BAD_DESIGN');
|
|
await store.put(boundUser, project.id, journal.session || session, 'draft', {
|
|
bytes: journal.bytes,
|
|
snapshotId: journal.snapshotId || crypto.randomUUID(),
|
|
baseVersion: Number.isSafeInteger(journal.request?.expectedVersion) ? journal.request.expectedVersion : project.version,
|
|
origin: 'legacy-save-recovery',
|
|
});
|
|
await store.remove(journal.key, journal.snapshotId);
|
|
continue;
|
|
}
|
|
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;
|
|
project.version = journal.request.expectedVersion; project.headVersion = project.version;
|
|
saver = makeSaver();
|
|
main.hidden = true; updateLock();
|
|
try {
|
|
await saver.resume(journal);
|
|
assertContext(ctx, true);
|
|
state = await bridge.getState();
|
|
} catch (error) {
|
|
showError(error);
|
|
if (['HEAD_CONFLICT', 'CAD_VERSION_CONFLICT'].includes(error.code)) {
|
|
const latest = await api.get(project.id);
|
|
project.version = latest.version; project.headVersion = latest.version;
|
|
state = await bridge.getState(); showConflict = true;
|
|
return { restored: true };
|
|
}
|
|
if (saver.operation) { pending(); return { restored: true, blocked: true }; }
|
|
}
|
|
} else {
|
|
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 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();
|
|
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();
|
|
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;
|
|
const ctx = context(), target = project, client = api, name = await nameDialog(target.name); if (!name) return;
|
|
try { assertContext(ctx, true); const renamed = await client.rename(target.id, name); assertContext(ctx, true); if (project === target) { project.name = renamed.name; drawHeader(); } }
|
|
catch (error) { showError(error); }
|
|
}
|
|
async function guard() {
|
|
if (!binding || leaving) return true;
|
|
const ctx = context(), target = project.id;
|
|
const snapshot = await bridge.getState();
|
|
if (!snapshot.dirty && !saver?.operation && !recoveryPending) return true;
|
|
const choice = await choose(t('leave'), t('leaveHint'), [['save', t('saveLeave'), true], ['discard', t('discardLeave')], ['stay', t('stay')]]);
|
|
if (choice === 'discard') {
|
|
const previous = discardedDraft, discarded = { binding: ctx.binding, revision: snapshot.revision, pending: true };
|
|
try {
|
|
assertContext(ctx, true);
|
|
discardedDraft = discarded;
|
|
// Finish any earlier write before deleting; page-hide autosave must not recreate it.
|
|
await draftTask;
|
|
assertContext(ctx, true);
|
|
const drafts = await store.list(ctx.owner, target, 'draft');
|
|
assertContext(ctx, true);
|
|
for (const value of drafts) await store.remove(value.key, value.snapshotId);
|
|
assertContext(ctx, true);
|
|
discarded.pending = false;
|
|
return true;
|
|
} catch (error) {
|
|
if (discardedDraft === discarded) discardedDraft = previous;
|
|
if (['STALE_IDENTITY', 'STALE_BINDING'].includes(error.code)) showError(error); else storageWarning();
|
|
return false;
|
|
}
|
|
}
|
|
if (choice === 'save') try { await save(); return !(await bridge.getState()).dirty && !saver.operation; } catch (error) { showError(error); }
|
|
return false;
|
|
}
|
|
async function navigate(url) { if (await guard()) { leaving = true; location.assign(url); } }
|
|
async function downloadCopy() {
|
|
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; }
|
|
copying = true; const ctx = context(); let snapshot;
|
|
try {
|
|
const name = await nameDialog(project.name); if (!name) return;
|
|
assertContext(ctx, true);
|
|
snapshot = await bridge.createSnapshot({ includeCover: true }); const originalBinding = binding, owner = boundUser;
|
|
const destination = await api.create(name); if (originalBinding !== binding || owner !== userId()) throw cadError('STALE_BINDING');
|
|
// Dedicated destination coordinator uses the captured snapshot, never ACKs the original document.
|
|
const copyBridge = { createSnapshot: async () => snapshot, getState: () => bridge.getState(), acknowledgeSave: async () => {}, releaseSnapshot: async () => {} };
|
|
const copySaver = new SaveCoordinator({ api, bridge: copyBridge, store, user: owner, project: destination, binding, session: session + ':copy', onState: (key) => { if (key !== 'saved') notice(t(key)); }, onStorageError: storageWarning });
|
|
await copySaver.save(); assertContext(ctx, true);
|
|
copying = false;
|
|
const latest = await bridge.getState();
|
|
if (latest.revision === snapshot.revision || await guard()) { leaving = true; location.assign(projectUrl(destination.id)); }
|
|
} finally { copying = false; if (snapshot) await bridge.releaseSnapshot(snapshot.snapshotId); }
|
|
}
|
|
async function openNative() {
|
|
const ctx = context();
|
|
if (!(await guard())) return;
|
|
const input = document.createElement('input'); input.type = 'file'; input.accept = '.sc,.solidcraft';
|
|
input.addEventListener('change', async () => {
|
|
const file = input.files?.[0]; if (!file) return;
|
|
if (file.size <= 0 || file.size > CAD.maxSourceBytes) { showError(cadError('SOURCE_TOO_LARGE')); return; }
|
|
try {
|
|
const bytes = new Uint8Array(await file.arrayBuffer());
|
|
assertContext(ctx, true);
|
|
// Validation has no effect on the active document, even when parsing fails.
|
|
await bridge.validateProject(bytes);
|
|
const name = await nameDialog(file.name.replace(/\.(sc|solidcraft)$/i, '')); if (!name) return;
|
|
assertContext(ctx, true);
|
|
const next = await ctx.client.create(name); assertContext(ctx, true);
|
|
await store.put(ctx.owner, next.id, session, 'draft', { snapshotId: crypto.randomUUID(), bytes, baseVersion: 0, origin: 'native-import' });
|
|
assertContext(ctx, true);
|
|
leaving = true; location.assign(projectUrl(next.id));
|
|
} catch (error) { showError(error); }
|
|
}, { once: true }); input.click();
|
|
}
|
|
async function conflictDialog() {
|
|
if (modalCount || recovering) return;
|
|
const answer = await choose(t('conflict'), t('conflictHint'), [['new', t('saveAs'), true], ['copy', t('copy')], ['reload', t('reload')], ['stay', t('stay')]]);
|
|
if (answer === 'new') await saveAs(); else if (answer === 'copy') await downloadCopy();
|
|
else if (answer === 'reload') { leaving = true; location.reload(); }
|
|
}
|
|
async function hostIntent(intent) {
|
|
if (intent === 'save') return save(); if (intent === 'saveAs') return saveAs(); if (intent === 'new') return newProject();
|
|
if (intent === 'open') return openNative(); if (intent === 'download') return downloadCopy();
|
|
}
|
|
function showFontError(error) {
|
|
if (error.code !== 'FONT_UNAVAILABLE') return;
|
|
message('font', null, async () => { try { await bridge?.setLocale(locale()); if (bridge) await bridge.ready(); await boot(); } catch (err) { showError(err); } });
|
|
const button = document.createElement('button'); button.className = 'btn'; button.textContent = t('english');
|
|
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();
|
|
}
|
|
async function authChanged() {
|
|
if (signingOut) return;
|
|
if (booting) {
|
|
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(); await bridge?.cancelOpenProject?.().catch(() => {});
|
|
if (!auth.token) {
|
|
authToken = null; authLocked = true; updateLock(); status('expired');
|
|
await clearAssistant();
|
|
await draft();
|
|
if (!editor || !binding) message('loginRequired', 'loginHint', signIn, 'signIn');
|
|
await openLogin({ locale: locale() }); if (auth.token) boot();
|
|
} else if (boundUser && userId() !== boundUser) {
|
|
authLocked = true; updateLock(); await clearAssistant(); await releaseAccount(); leaving = true; location.replace('/cad/');
|
|
} else boot();
|
|
}
|
|
auth.onChange(authChanged);
|
|
window.__vibemakeCadSignIn = () => signIn();
|
|
window.__vibemakeCadSignOut = () => signOut();
|
|
window.__vibemakeCadNavigate = (url) => navigate(url);
|
|
window.addEventListener('vm:modal', (event) => { modalCount = Math.max(0, modalCount + (event.detail.open ? 1 : -1)); updateLock(); });
|
|
window.addEventListener('storage', (event) => { if (event.key === LOCALE_KEY && event.newValue) { setLocale(event.newValue, false); drawHeader(); bridge?.setLocale(locale()).then(() => bridge.ready()).catch(showFontError); if (!editor) loadList(); } });
|
|
window.addEventListener('keydown', (event) => {
|
|
if (!editor || modalCount || authLocked || !binding || !desktopAllowed() || event.target.closest('input, textarea, select, [contenteditable=true]')) return;
|
|
if (!(event.ctrlKey || event.metaKey)) return;
|
|
const key = event.key.toLowerCase();
|
|
if (!['s', 'n', 'o'].includes(key)) return;
|
|
event.preventDefault(); event.stopImmediatePropagation();
|
|
hostIntent(key === 's' ? (event.shiftKey ? 'saveAs' : 'save') : key === 'n' ? 'new' : 'open').catch(showError);
|
|
}, true);
|
|
window.addEventListener('beforeunload', (event) => { if (!leaving && binding && (state.dirty || saver?.operation || copying || recoveryPending)) { event.preventDefault(); event.returnValue = ''; } });
|
|
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', () => {
|
|
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 (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; request?.abort(); bridge?.cancelOpenProject?.().catch(() => {}); message('desktop', 'desktopHint', () => location.assign('/'), 'home'); } });
|
|
initEditorHeader();
|
|
setLocale(locale(), false); drawHeader(); boot();
|