fix(scene): persist editor and battery profiles in Core

This commit is contained in:
DCCONSTRUCTIONS
2026-11-10 01:08:00 +03:00
parent 7595bea07c
commit cd34b6ce1a
18 changed files with 581 additions and 91 deletions
@@ -1,3 +1,4 @@
import {legacyRecord,profileClient} from '../roverScene/profileClient';
import {defaultChargeGradient} from '../roverScene/chargeGradient';
import r04 from './r04.json';
import {defaultScene,parseScene,type SceneDocument} from '../roverScene/sceneDocument';
@@ -8,27 +9,16 @@ export function defaultBatteryScene():SceneDocument {
return {...defaultScene(),schema:'missioncore.battery-scene/v1',model:'catl-r04/v1',
materials:{...structuredClone(r04.materials),'bms/cells':{...structuredClone(r04.materials['bms/cells']),color:'#050505',emissiveIntensity:0,chargeGradient:defaultChargeGradient()}},assignments:{},objects:{...r04.objects}};
}
function database():Promise<IDBDatabase>{return new Promise((resolve,reject)=>{
const request=indexedDB.open('missioncore-battery-scenes',1);
request.onupgradeneeded=()=>request.result.createObjectStore('scenes');
request.onsuccess=()=>resolve(request.result);request.onerror=()=>reject(request.error);
request.onblocked=()=>reject(new Error('Хранилище батареи занято другим окном.'));
});}
async function save(id:string,document:SceneDocument){const db=await database();try{await new Promise<void>((resolve,reject)=>{
const tx=db.transaction('scenes','readwrite');tx.objectStore('scenes').put(document,id);
tx.oncomplete=()=>resolve();tx.onerror=()=>reject(tx.error);tx.onabort=()=>reject(tx.error);
});}finally{db.close();}}
export function batterySceneProfile(seedKey?:string):SceneDocumentProfile {
return {defaults:defaultBatteryScene,write:save,filename:'battery-r04-scene.json',read:async id=>{
const db=await database();let raw:unknown;try{raw=await new Promise((resolve,reject)=>{
const request=db.transaction('scenes').objectStore('scenes').get(id);
request.onsuccess=()=>resolve(request.result);request.onerror=()=>reject(request.error);
});}finally{db.close();}
const clients=new Map<string,ReturnType<typeof profileClient<SceneDocument>>>();
const client=(id:string)=>{let c=clients.get(id);if(!c){c=profileClient<SceneDocument>('battery',id);clients.set(id,c);}return c;};
return {defaults:defaultBatteryScene,write:(id,doc)=>client(id).write(doc),filename:'battery-r04-scene.json',read:async id=>{
const raw=await client(id).read(async()=>{const old=await legacyRecord('missioncore-battery-scenes','scenes',id);return old?parseScene(old,defaultBatteryScene):null;});
if(raw)return parseScene(raw,defaultBatteryScene);
const seed=seedKey?await readScene(seedKey):null;
const doc=defaultBatteryScene();
if(seed){doc.postFx=structuredClone(seed.postFx);doc.cameraAutoRotate=seed.cameraAutoRotate;doc.cameraZoomStrength=seed.cameraZoomStrength;}
// Copy once. Subsequent rover edits and battery edits have separate owners.
await save(id,doc);return doc;
// Defaults remain in memory until an explicit edit. Never overwrite a failed read.
return doc;
}};
}
@@ -1,14 +1,23 @@
import {useCallback,useEffect,useState} from 'react';
import {useCallback,useEffect,useMemo,useRef,useState} from 'react';
import {SceneHistory,historyCommand} from '../roverScene/sceneHistory';
import {profileClient} from '../roverScene/profileClient';
import {batteryAppearanceKey,defaultBatteryAppearance,parseBatteryAppearance,type BatteryAppearance} from './appearance';
async function legacy(id:string){const raw=localStorage.getItem(batteryAppearanceKey(id));return raw?parseBatteryAppearance(JSON.parse(raw)):null;}
export function useBatteryAppearance(id:string,active:boolean){
const [error,setError]=useState('');
const [history]=useState(()=>{let profile=defaultBatteryAppearance();try{const raw=localStorage.getItem(batteryAppearanceKey(id));if(raw)profile=parseBatteryAppearance(JSON.parse(raw));}catch{/* Keep the usable default if the local profile is unavailable. */}return new SceneHistory(profile);});
const [value,setValue]=useState(history.present);
const publish=useCallback(()=>{setValue(history.present);try{localStorage.setItem(batteryAppearanceKey(id),JSON.stringify(history.present));window.dispatchEvent(new CustomEvent('missioncore:battery-ui',{detail:id}));setError('');}catch{setError('Не удалось сохранить настройки батареи на этом компьютере.');}},[history,id]);
const update=useCallback((next:BatteryAppearance)=>{if(JSON.stringify(next)!==JSON.stringify(history.present)){history.update(next);publish();}},[history,publish]);
const undo=useCallback(()=>{if(history.undo())publish();},[history,publish]);
const redo=useCallback(()=>{if(history.redo())publish();},[history,publish]);
const [error,setError]=useState(''),[ready,setReady]=useState(false);
const client=useMemo(()=>profileClient<BatteryAppearance>('battery-ui',id),[id]);
const history=useMemo(()=>new SceneHistory(defaultBatteryAppearance()),[id]);
const [value,setValue]=useState(history.present),loaded=useRef(false);
const pending=useRef<BatteryAppearance|null>(null),timer=useRef<ReturnType<typeof setTimeout>|null>(null);
const flush=useCallback(()=>{if(timer.current)clearTimeout(timer.current);const next=pending.current;if(!next)return;pending.current=null;
void client.write(next).then(()=>{window.dispatchEvent(new CustomEvent('missioncore:battery-ui',{detail:id}));setError('');}).catch(e=>setError(e instanceof Error?e.message:'Не удалось сохранить оформление батареи.'));
},[client,id]);
useEffect(()=>{let cancelled=false;loaded.current=false;setReady(false);setError('');client.read(()=>legacy(id)).then(raw=>{if(!cancelled){const next=raw?parseBatteryAppearance(raw):defaultBatteryAppearance();history.reset(next);setValue(next);loaded.current=true;setReady(true);}}).catch(e=>{if(!cancelled)setError(e instanceof Error?e.message:'Не удалось прочитать оформление батареи.');});return()=>{cancelled=true;loaded.current=false;flush();};},[client,history,id,flush]);
useEffect(()=>{window.addEventListener('pagehide',flush);return()=>window.removeEventListener('pagehide',flush);},[flush]);
const publish=useCallback(()=>{setValue(history.present);pending.current=history.present;if(timer.current)clearTimeout(timer.current);timer.current=setTimeout(flush,300);},[history,flush]);
const update=useCallback((next:BatteryAppearance)=>{if(!loaded.current){setError('Дождитесь загрузки профиля.');return;}if(JSON.stringify(next)!==JSON.stringify(history.present)){history.update(next);publish();}},[history,publish]);
const undo=useCallback(()=>{if(loaded.current&&history.undo())publish();},[history,publish]);
const redo=useCallback(()=>{if(loaded.current&&history.redo())publish();},[history,publish]);
useEffect(()=>{
if(!active)return;
const begin=()=>history.begin(),end=()=>history.end();
@@ -17,18 +26,18 @@ export function useBatteryAppearance(id:string,active:boolean){
window.addEventListener('keydown',key,true);window.addEventListener('keyup',up,true);window.addEventListener('pointerdown',begin,true);window.addEventListener('pointerup',end);window.addEventListener('pointercancel',end);window.addEventListener('blur',end);
return()=>{end();window.removeEventListener('keydown',key,true);window.removeEventListener('keyup',up,true);window.removeEventListener('pointerdown',begin,true);window.removeEventListener('pointerup',end);window.removeEventListener('pointercancel',end);window.removeEventListener('blur',end);};
},[active,history,undo,redo]);
return {value,update,undo,redo,canUndo:history.canUndo,canRedo:history.canRedo,error,setError};
return {value,ready,update,undo,redo,canUndo:history.canUndo,canRedo:history.canRedo,error,setError};
}
/** Read-only subscribers update immediately when this battery's design is edited. */
/** Read-only subscribers share the persistent Core profile, across browsers. */
export function useBatteryAppearanceValue(id:string|undefined){
const [value,setValue]=useState(defaultBatteryAppearance);
useEffect(()=>{
const read=()=>{try{const raw=id&&localStorage.getItem(batteryAppearanceKey(id));setValue(raw?parseBatteryAppearance(JSON.parse(raw)):defaultBatteryAppearance());}catch{setValue(defaultBatteryAppearance());}};
let cancelled=false;
const read=()=>{if(!id){setValue(defaultBatteryAppearance());return;}void profileClient<BatteryAppearance>('battery-ui',id).read(()=>legacy(id)).then(raw=>{if(!cancelled)setValue(raw?parseBatteryAppearance(raw):defaultBatteryAppearance());}).catch(()=>{/* Retain the current indicator on a temporary Core disconnect. */});};
const local=(event:Event)=>{if((event as CustomEvent).detail===id)read();};
const external=(event:StorageEvent)=>{if(!event.key||event.key===(id&&batteryAppearanceKey(id)))read();};
read();window.addEventListener('missioncore:battery-ui',local);window.addEventListener('storage',external);
return()=>{window.removeEventListener('missioncore:battery-ui',local);window.removeEventListener('storage',external);};
read();window.addEventListener('missioncore:battery-ui',local);window.addEventListener('focus',read);
return()=>{cancelled=true;window.removeEventListener('missioncore:battery-ui',local);window.removeEventListener('focus',read);};
},[id]);
return value;
}
@@ -0,0 +1,14 @@
import {useEffect,useMemo,useState} from 'react';
import {profileClient} from '../roverScene/profileClient';
import {batteryViewHeight,batteryViewHeightKey} from './viewHeight';
type View={schema:'missioncore.battery-view/v1';height:number};
export function useBatteryView(id:string){
const client=useMemo(()=>profileClient<View>('battery-view',id),[id]);
const [height,setHeight]=useState(()=>batteryViewHeight(null,window.innerHeight));
const [ready,setReady]=useState(false),[error,setError]=useState('');
useEffect(()=>{let cancelled=false;setReady(false);setError('');void client.read(async()=>{
const raw=localStorage.getItem(batteryViewHeightKey(id));return raw?{schema:'missioncore.battery-view/v1',height:batteryViewHeight(raw,window.innerHeight)}:null;
}).then(value=>{if(!cancelled){setHeight(batteryViewHeight(JSON.stringify(value),window.innerHeight));setReady(true);}}).catch(e=>{if(!cancelled)setError(e.message);});return()=>{cancelled=true;};},[client,id]);
const commitHeight=(value:number)=>{if(!ready)return;void client.write({schema:'missioncore.battery-view/v1',height:value}).then(()=>setError('')).catch(e=>setError(e.message));};
return {height,setHeight,commitHeight,ready,error,setError};
}
@@ -1,17 +1,17 @@
import {parseEnvironmentProfile,prepareEnvironmentSave,validEnvironmentId,type StoredEnvironmentProfile} from './environmentProfiles';
import {legacyRecord,profileClient} from './profileClient';
const eventName='missioncore:environment-profiles';
function database():Promise<IDBDatabase>{return new Promise((resolve,reject)=>{const r=indexedDB.open('missioncore-environment-profiles',1);r.onupgradeneeded=()=>r.result.createObjectStore('profiles',{keyPath:'id'});r.onsuccess=()=>resolve(r.result);r.onerror=()=>reject(r.error);r.onblocked=()=>reject(new Error('Хранилище профилей занято другим окном.'));});}
type Library={schema:'missioncore.environment-library/v1';profiles:StoredEnvironmentProfile[]};
function records(raw:unknown[]):StoredEnvironmentProfile[]{return raw.map((r:any)=>{if(!validEnvironmentId(r?.id)||r.id==='nodedc'||!Number.isInteger(r.revision)||r.revision<1)throw new Error('Не удалось прочитать библиотеку профилей.');return {...parseEnvironmentProfile(r),id:r.id,revision:r.revision};});}
export async function readEnvironmentProfiles():Promise<StoredEnvironmentProfile[]>{
const db=await database();try{return await new Promise((resolve,reject)=>{const r=db.transaction('profiles').objectStore('profiles').getAll();r.onsuccess=()=>{try{resolve(records(r.result));}catch(e){reject(e);}};r.onerror=()=>reject(r.error);});}finally{db.close();}
async function library(){
const client=profileClient<Library>('environments','shared');
const value=await client.read(async()=>{const raw=await legacyRecord('missioncore-environment-profiles','profiles');return Array.isArray(raw)&&raw.length?{schema:'missioncore.environment-library/v1',profiles:records(raw)}:null;});
return {client,profiles:records(value?.profiles??[])};
}
export async function readEnvironmentProfiles():Promise<StoredEnvironmentProfile[]>{return (await library()).profiles;}
export async function saveEnvironmentProfile(profile:StoredEnvironmentProfile,expectedRevision:number|null):Promise<StoredEnvironmentProfile>{
const db=await database();let saved:StoredEnvironmentProfile;
try{saved=await new Promise((resolve,reject)=>{
const tx=db.transaction('profiles','readwrite'),store=tx.objectStore('profiles'),r=store.getAll();let next:StoredEnvironmentProfile,error:unknown;
r.onsuccess=()=>{try{next=prepareEnvironmentSave(records(r.result),profile,expectedRevision);store.put(next);}catch(e){error=e;tx.abort();}};
tx.oncomplete=()=>resolve(next);tx.onabort=()=>reject(error??tx.error);tx.onerror=()=>reject(error??tx.error);
});}finally{db.close();}
const {client,profiles}=await library(),saved=prepareEnvironmentSave(profiles,profile,expectedRevision);
await client.write({schema:'missioncore.environment-library/v1',profiles:[...profiles.filter(p=>p.id!==saved.id),saved]});
window.dispatchEvent(new Event(eventName));
if(typeof BroadcastChannel!=='undefined'){const channel=new BroadcastChannel(eventName);channel.postMessage('changed');channel.close();}
return saved;
@@ -0,0 +1,35 @@
/** Durable JSON authority. A legacy browser record is only a one-time migration input. */
export type ProfileKind='battery'|'rover'|'battery-ui'|'battery-view'|'environments';
type Stored<T>={revision:number;document:T|null};
export function profileClient<T>(kind:ProfileKind,owner:string){
let revision:number|undefined;
let queue=Promise.resolve();
const url=`/api/v1/scene-profiles/${kind}?owner=${encodeURIComponent(owner)}`;
async function request(method='GET',body?:unknown):Promise<Stored<T>>{
const response=await fetch(url,{method,cache:'no-store',headers:{'Content-Type':'application/json'},...(body?{body:JSON.stringify(body),keepalive:JSON.stringify(body).length<60000}:{})});
if(!response.ok){let message='Не удалось загрузить или сохранить профиль в Mission Core.';try{const value=await response.json();if(typeof value.detail==='string')message=value.detail;}catch{}throw new Error(message);}
const result=await response.json();if(!Number.isInteger(result.revision)||!Object.hasOwn(result,'document'))throw new Error('Неверный ответ хранилища профилей.');return result;
}
async function read(legacy?:()=>Promise<T|null>):Promise<T|null>{
let value=await request();
if(value.document===null&&legacy){const old=await legacy();if(old!==null){
try{value=await request('PUT',{document:old,expected_revision:0});}
catch(error){const winner=await request();if(winner.document===null)throw error;value=winner;}
}}
revision=value.revision;return value.document;
}
function write(document:T):Promise<void>{
const next=queue.catch(()=>{}).then(async()=>{
if(revision===undefined)throw new Error('Профиль ещё не загружен. Сохранение отменено.');
const value=await request('PUT',{document,expected_revision:revision});revision=value.revision;
});queue=next;return next;
}
return {read,write};
}
export async function legacyRecord(database:string,store:string,key?:string):Promise<unknown>{
if(typeof indexedDB==='undefined'||typeof indexedDB.databases!=='function')return null;
const databases=await indexedDB.databases();if(!databases.some(d=>d.name===database))return null;
const db=await new Promise<IDBDatabase>((resolve,reject)=>{const r=indexedDB.open(database);r.onupgradeneeded=()=>{r.transaction?.abort();reject(new Error('Старое хранилище исчезло.'));};r.onsuccess=()=>resolve(r.result);r.onerror=()=>reject(r.error);});
try{if(!db.objectStoreNames.contains(store))return null;return await new Promise((resolve,reject)=>{const s=db.transaction(store,'readonly').objectStore(store),r=key===undefined?s.getAll():s.get(key);r.onsuccess=()=>resolve(r.result??null);r.onerror=()=>reject(r.error);});}finally{db.close();}
}
@@ -1,22 +1,13 @@
import type {SceneDocument} from './sceneDocument';
import {loadStoredScene} from './sceneMigration';
// Retain the original storage slot so upgrades preserve operator materials and environment.
import {legacyRecord,profileClient} from './profileClient';
const key=(vehicle:string)=>`${vehicle}:dcd006-v020-materials-v2`;
function database():Promise<IDBDatabase>{return new Promise((resolve,reject)=>{const r=indexedDB.open('missioncore-rover-scenes',1);r.onupgradeneeded=()=>r.result.createObjectStore('scenes');r.onerror=()=>reject(r.error);r.onblocked=()=>reject(new Error('Хранилище сцены занято другим окном.'));r.onsuccess=()=>resolve(r.result);});}
export async function readScene(vehicle:string):Promise<SceneDocument|null>{
const db=await database();try{
const raw=await new Promise<unknown>((resolve,reject)=>{const r=db.transaction('scenes').objectStore('scenes').get(key(vehicle));r.onerror=()=>reject(r.error);r.onsuccess=()=>resolve(r.result);});
if(!raw)return null;
const result=loadStoredScene(raw);
if(result.updated)await new Promise<void>((resolve,reject)=>{
const tx=db.transaction('scenes','readwrite'),store=tx.objectStore('scenes');
if(result.restoredEnvironment)store.put(raw,`${key(vehicle)}:before-environment-v2`);
store.put(result.document,key(vehicle));tx.oncomplete=()=>resolve();tx.onabort=()=>reject(tx.error);tx.onerror=()=>reject(tx.error);
});
return result.document;
}finally{db.close();}
export function roverSceneProfile(){
const clients=new Map<string,ReturnType<typeof profileClient<SceneDocument>>>();
const client=(id:string)=>{let c=clients.get(id);if(!c){c=profileClient<SceneDocument>('rover',id);clients.set(id,c);}return c;};
return {read:async(id:string)=>{const value=await client(id).read(async()=>{const raw=await legacyRecord('missioncore-rover-scenes','scenes',key(id));return raw?loadStoredScene(raw).document:null;});return value?loadStoredScene(value).document:null;},write:(id:string,doc:SceneDocument)=>client(id).write(doc)};
}
export async function saveScene(vehicle:string,document:SceneDocument):Promise<void>{const db=await database();try{await new Promise<void>((resolve,reject)=>{const tx=db.transaction('scenes','readwrite');tx.objectStore('scenes').put(document,key(vehicle));tx.oncomplete=()=>resolve();tx.onabort=()=>reject(tx.error);tx.onerror=()=>reject(tx.error);});}finally{db.close();}}
export async function readScene(vehicle:string):Promise<SceneDocument|null>{return roverSceneProfile().read(vehicle);}
export async function textureFromFile(file:File):Promise<{name:string;data:string}>{
if(!['image/png','image/jpeg','image/webp'].includes(file.type)||file.size>8_000_000)throw new Error('Выберите PNG, JPEG или WebP до 8 МБ.');
const bitmap=await createImageBitmap(file);try{if(bitmap.width>4096||bitmap.height>4096)throw new Error('Максимальный размер текстуры — 4096 × 4096.');}finally{bitmap.close();}
@@ -1,32 +1,44 @@
import type {CameraState} from './cameraState';
import {useCallback,useEffect,useRef,useState} from 'react';
import {useCallback,useEffect,useMemo,useRef,useState} from 'react';
import {defaultScene,parseScene,type SceneDocument} from './sceneDocument';
import {SceneHistory} from './sceneHistory';
import {readScene,saveScene} from './sceneStorage';
import {roverSceneProfile} from './sceneStorage';
let writes=Promise.resolve();
const enqueue=(vehicle:string,doc:SceneDocument,write=saveScene)=>{const next=writes.catch(()=>{}).then(()=>write(vehicle,doc));writes=next;return next;};
export type SceneDocumentProfile={defaults:()=>SceneDocument;read:(id:string)=>Promise<SceneDocument|null>;write:typeof saveScene;filename:string};
type Write=(id:string,doc:SceneDocument)=>Promise<void>;
const enqueue=(id:string,doc:SceneDocument,write:Write)=>{const next=writes.catch(()=>{}).then(()=>write(id,doc));writes=next;return next;};
export type SceneDocumentProfile={defaults:()=>SceneDocument;read:(id:string)=>Promise<SceneDocument|null>;write:Write;filename:string};
export function useSceneDocument(vehicle:string,profile?:SceneDocumentProfile){
const defaults=profile?.defaults??defaultScene,read=profile?.read??readScene,write=profile?.write??saveScene;
const storage=useMemo(()=>profile??{...roverSceneProfile(),defaults:defaultScene,filename:'rover-scene.json'},[profile]);
const {defaults,read,write}=storage;
const [document,setDocument]=useState(defaults),[ready,setReady]=useState(false),[revision,setRevision]=useState(0);
const [saveState,setSaveState]=useState<'loading'|'saved'|'saving'|'error'>('loading'),[error,setError]=useState('');
const latest=useRef({document,revision,vehicle,write});latest.current={document,revision,vehicle,write};
const loaded=useRef(false),savedRevision=useRef(0),history=useRef(new SceneHistory(document));
const pendingCamera=useRef<CameraState|null>(null);
const savedRevision=useRef(0),history=useRef(new SceneHistory(document));
const latest=useRef({document,revision,vehicle,write,ready});latest.current={document,revision,vehicle,write,ready};
const publish=useCallback(()=>{setDocument(history.current.present);setRevision(v=>v+1);setSaveState('saving');},[]);
const undo=useCallback(()=>{pendingCamera.current=null;if(history.current.undo())publish();},[publish]);
const redo=useCallback(()=>{pendingCamera.current=null;if(history.current.redo())publish();},[publish]);
const beginGesture=useCallback(()=>history.current.begin(),[]),endGesture=useCallback(()=>history.current.end(),[]);
useEffect(()=>{let cancelled=false;read(vehicle).then(value=>{if(!cancelled){const doc=value??defaults();history.current.reset(doc);setDocument(doc);setSaveState('saved');}}).catch(()=>{if(!cancelled){setError('Не удалось прочитать сохранённую сцену. Изменения можно экспортировать в JSON.');setSaveState('error');}}).finally(()=>{if(!cancelled)setReady(true);});return()=>{cancelled=true;};},[vehicle,profile]);
const update=useCallback((fn:(doc:SceneDocument)=>SceneDocument)=>{if(history.current.update(fn(history.current.present)))publish();},[publish]);
const recordCamera=useCallback((camera:CameraState,commit=false)=>{pendingCamera.current=camera;if(commit){pendingCamera.current=null;update(doc=>JSON.stringify(doc.camera)===JSON.stringify(camera)?doc:{...doc,camera});}},[update]);
const undo=useCallback(()=>{if(!loaded.current)return;pendingCamera.current=null;if(history.current.undo())publish();},[publish]);
const redo=useCallback(()=>{if(!loaded.current)return;pendingCamera.current=null;if(history.current.redo())publish();},[publish]);
const beginGesture=useCallback(()=>{if(loaded.current)history.current.begin();},[]),endGesture=useCallback(()=>history.current.end(),[]);
useEffect(()=>{
let cancelled=false;loaded.current=false;pendingCamera.current=null;savedRevision.current=0;
setReady(false);setRevision(0);setSaveState('loading');setError('');
read(vehicle).then(value=>{if(!cancelled){const doc=value??defaults();history.current.reset(doc);setDocument(doc);loaded.current=true;setReady(true);setSaveState('saved');}}).catch(e=>{if(!cancelled){setError(e instanceof Error?e.message:'Не удалось прочитать сохранённую сцену.');setSaveState('error');}});
return()=>{cancelled=true;loaded.current=false;};
},[vehicle,storage,read,defaults]);
const update=useCallback((fn:(doc:SceneDocument)=>SceneDocument)=>{if(loaded.current&&history.current.update(fn(history.current.present)))publish();},[publish]);
const recordCamera=useCallback((camera:CameraState,commit=false)=>{if(!loaded.current)return;pendingCamera.current=camera;if(commit){pendingCamera.current=null;update(doc=>JSON.stringify(doc.camera)===JSON.stringify(camera)?doc:{...doc,camera});}},[update]);
useEffect(()=>{
if(!ready||revision===0)return;
let cancelled=false;const timer=setTimeout(()=>{enqueue(vehicle,document,write).then(()=>{savedRevision.current=revision;if(!cancelled)setSaveState('saved');}).catch(()=>{if(!cancelled){setSaveState('error');setError('Не удалось сохранить сцену на этом компьютере. Экспортируйте JSON, чтобы сохранить изменения.');}});},400);
let cancelled=false;const timer=setTimeout(()=>{enqueue(vehicle,document,write).then(()=>{savedRevision.current=revision;if(!cancelled)setSaveState('saved');}).catch(e=>{if(!cancelled){setSaveState('error');setError(e instanceof Error?e.message:'Не удалось сохранить сцену. Экспортируйте JSON, чтобы сохранить изменения.');}});},400);
return()=>{cancelled=true;clearTimeout(timer);};
},[ready,revision,vehicle,document,write]);
useEffect(()=>()=>{const v=latest.current;if(pendingCamera.current||v.revision>savedRevision.current)void enqueue(v.vehicle,pendingCamera.current?{...v.document,camera:pendingCamera.current}:v.document,v.write).catch(()=>{});},[]);
const importDocument=async(file:File)=>{try{if(file.size>32_000_000)throw new Error('Файл сцены больше 32 МБ.');const next=parseScene(JSON.parse(await file.text()),defaults);pendingCamera.current=null;update(()=>next);}catch(e){setError(e instanceof Error?e.message:'Не удалось загрузить сцену.');}};
const exportDocument=()=>{const blob=new Blob([JSON.stringify(pendingCamera.current?{...document,camera:pendingCamera.current}:document,null,2)],{type:'application/json'});const url=URL.createObjectURL(blob);const a=globalThis.document.createElement('a');a.href=url;a.download=profile?.filename??'rover-scene.json';a.click();setTimeout(()=>URL.revokeObjectURL(url),1000);};
useEffect(()=>{
const flush=()=>{const v=latest.current;if(v.ready&&(pendingCamera.current||v.revision>savedRevision.current))void enqueue(v.vehicle,pendingCamera.current?{...v.document,camera:pendingCamera.current}:v.document,v.write).catch(()=>{});};
const hidden=()=>{if(globalThis.document.visibilityState==='hidden')flush();};
window.addEventListener('pagehide',flush);globalThis.document.addEventListener('visibilitychange',hidden);
return()=>{flush();window.removeEventListener('pagehide',flush);globalThis.document.removeEventListener('visibilitychange',hidden);};
},[]);
const importDocument=async(file:File)=>{try{if(!ready)throw new Error('Дождитесь загрузки профиля.');if(file.size>32_000_000)throw new Error('Файл сцены больше 32 МБ.');const next=parseScene(JSON.parse(await file.text()),defaults);pendingCamera.current=null;update(()=>next);}catch(e){setError(e instanceof Error?e.message:'Не удалось загрузить сцену.');}};
const exportDocument=()=>{const blob=new Blob([JSON.stringify(pendingCamera.current?{...document,camera:pendingCamera.current}:document,null,2)],{type:'application/json'});const url=URL.createObjectURL(blob);const a=globalThis.document.createElement('a');a.href=url;a.download=storage.filename;a.click();setTimeout(()=>URL.revokeObjectURL(url),1000);};
return {document,recordCamera,ready,saveState,error,setError,update,undo,redo,canUndo:history.current.canUndo,canRedo:history.current.canRedo,beginGesture,endGesture,importDocument,exportDocument};
}