fix(scene): persist editor and battery profiles in Core
This commit is contained in:
@@ -11,13 +11,13 @@ export function BatteryAppearanceSettings({open,onClose,profile,sensor}:{sensor?
|
||||
const {value,update}=profile,m=value.markings;
|
||||
const range=(label:string,value:number,min:number,max:number,onChange:(v:number)=>void)=><RangeControl label={label} value={value} min={min} max={max} step={1} exactValueBounds={{min,max}} onChange={onChange}/>;
|
||||
const exportJson=()=>{const url=URL.createObjectURL(new Blob([JSON.stringify(value,null,2)],{type:'application/json'}));const a=document.createElement('a');a.href=url;a.download='battery-ui.json';a.click();setTimeout(()=>URL.revokeObjectURL(url),1000);};
|
||||
return <FeatureSettingsWindow open={open} title="Настройки батареи" identity={{title:'Батарея',subtitle:section==='markings'||section==='panels'?'Локальный профиль':'BMS',avatarLabel:'АКБ'}} sections={[{id:'markings',label:'Маркировка ячеек',icon:'layers'},{id:'panels',label:'Дизайн',icon:'settings'},...(sensor?[{id:'diagnostics' as const,label:'Диагностика BMS',icon:'activity' as const},{id:'protection' as const,label:'Параметры BMS',icon:'sliders' as const},{id:'control' as const,label:'Управление BMS',icon:'power' as const}]:[])]} activeSection={section} onSectionChange={setSection} onClose={onClose}
|
||||
return <FeatureSettingsWindow open={open} title="Настройки батареи" identity={{title:'Батарея',subtitle:section==='markings'||section==='panels'?'Профиль Mission Core':'BMS',avatarLabel:'АКБ'}} sections={[{id:'markings',label:'Маркировка ячеек',icon:'layers'},{id:'panels',label:'Дизайн',icon:'settings'},...(sensor?[{id:'diagnostics' as const,label:'Диагностика BMS',icon:'activity' as const},{id:'protection' as const,label:'Параметры BMS',icon:'sliders' as const},{id:'control' as const,label:'Управление BMS',icon:'power' as const}]:[])]} activeSection={section} onSectionChange={setSection} onClose={onClose}
|
||||
headerActions={(section==='markings'||section==='panels')&&<><IconButton label="Отменить настройку батареи" disabled={!profile.canUndo} onClick={profile.undo}><Icon name="undo"/></IconButton><IconButton label="Повторить настройку батареи" disabled={!profile.canRedo} onClick={profile.redo}><Icon name="redo"/></IconButton></>}
|
||||
footer={(section==='markings'||section==='panels')&&<><Button onClick={exportJson}>Экспорт JSON</Button><Button onClick={()=>input.current?.click()}>Импорт JSON</Button><input ref={input} type="file" accept="application/json,.json" hidden onChange={async event=>{const file=event.currentTarget.files?.[0];event.currentTarget.value='';if(!file)return;try{if(file.size>32000)throw new Error('Файл настроек слишком большой.');update(parseBatteryAppearance(JSON.parse(await file.text())));}catch(error){profile.setError(error instanceof Error?error.message:'Не удалось прочитать профиль.');}}}/></>}>
|
||||
{sensor&§ion!=='markings'&§ion!=='panels'?<BmsSettings {...sensor} section={section} open={open}/>:section==='markings'?<SettingsCard title="Маркировка ячеек" description="Номер и напряжение на заводских площадках модели. Размер меняет надпись внутри площадки.">
|
||||
<ControlRow label="Цвет маркировки"><ColorField label="Цвет маркировки" value={m.color} onChange={color=>update({...value,markings:{...m,color}})}/></ControlRow>
|
||||
{range('Размер маркировки, %',m.size,50,160,size=>update({...value,markings:{...m,size}}))}
|
||||
</SettingsCard>:<BatteryDesignSettings value={value} update={update}/>}
|
||||
{(section==='markings'||section==='panels')&&<Description>Сохраняется на этом компьютере для этой батареи. Ctrl Z / ⌘ Z — отмена, Shift Ctrl Z / ⇧ ⌘ Z — повтор.</Description>}
|
||||
{(section==='markings'||section==='panels')&&<Description>Сохраняется в Mission Core для этой батареи. Ctrl Z / ⌘ Z — отмена, Shift Ctrl Z / ⇧ ⌘ Z — повтор.</Description>}
|
||||
</FeatureSettingsWindow>;
|
||||
}
|
||||
|
||||
@@ -1,23 +1,24 @@
|
||||
import {useBatteryView} from '../../core/batteryScene/useBatteryView';
|
||||
import type {SensorDetailProps} from '../../../../../packages/sensor-ui/src/extensions';
|
||||
import {BatteryAppearanceSettings} from './BatteryAppearanceSettings';
|
||||
import {useBatteryAppearance} from '../../core/batteryScene/useBatteryAppearance';
|
||||
import type {BatteryAppearance} from '../../core/batteryScene/appearance';
|
||||
import {useEffect,useState,type ReactNode} from 'react';
|
||||
import {createPortal} from 'react-dom';
|
||||
import {EditorWorkspace,Icon,IconButton,ResizableViewport,ToastStack,useApplicationPanelFullscreen} from '@nodedc/ui-react';
|
||||
import {batteryViewHeight,batteryViewHeightKey,minBatteryViewHeight,maxBatteryViewHeight} from '../../core/batteryScene/viewHeight';
|
||||
import {EditorWorkspace,Icon,IconButton,LoadingRegion,ResizableViewport,ToastStack,useApplicationPanelFullscreen} from '@nodedc/ui-react';
|
||||
import {minBatteryViewHeight,maxBatteryViewHeight} from '../../core/batteryScene/viewHeight';
|
||||
|
||||
export function BatteryWorkspace({children,deviceId,title,headerActionsTarget,back,sensor,fullscreenControl}:{sensor?:SensorDetailProps;fullscreenControl?:{fullscreen:boolean;setFullscreen:(value:boolean)=>void};deviceId:string;title:string;headerActionsTarget?:HTMLElement|null;back:()=>void;children:(controls:{editing:boolean;appearance:BatteryAppearance;renderViewport:(children:ReactNode)=>ReactNode})=>ReactNode}){
|
||||
const inheritedFull=useApplicationPanelFullscreen(),full=fullscreenControl??inheritedFull,[editing,setEditing]=useState(false),[error,setError]=useState(''),[settings,setSettings]=useState(false);
|
||||
const profile=useBatteryAppearance(deviceId,settings);
|
||||
const [height,setHeight]=useState(()=>{try{return batteryViewHeight(localStorage.getItem(batteryViewHeightKey(deviceId)),window.innerHeight);}catch{return batteryViewHeight(null,window.innerHeight);}});
|
||||
const view=useBatteryView(deviceId);const {height,setHeight,commitHeight}=view;
|
||||
const fullscreen=full?.fullscreen??false,setFullscreen=full?.setFullscreen;
|
||||
useEffect(()=>()=>{setFullscreen?.(false);},[setFullscreen]);
|
||||
useEffect(()=>{const escape=(event:KeyboardEvent)=>{
|
||||
if(event.key!=='Escape'||event.defaultPrevented||document.querySelector('[role=dialog],[role=listbox]'))return;
|
||||
event.preventDefault();if(fullscreen)setFullscreen?.(false);else if(editing)setEditing(false);else back();
|
||||
};window.addEventListener('keydown',escape);return()=>window.removeEventListener('keydown',escape);},[editing,fullscreen,setFullscreen,back]);
|
||||
const commitHeight=(value:number)=>{try{localStorage.setItem(batteryViewHeightKey(deviceId),JSON.stringify({height:value}));setError('');}catch{setError('Не удалось сохранить высоту окна на этом компьютере.');}};
|
||||
|
||||
const actions=<>{full&&<IconButton label={fullscreen?'Восстановить окно батареи':'Развернуть окно батареи'} onClick={()=>setFullscreen?.(!fullscreen)}><Icon name={fullscreen?'minimize':'expand'}/></IconButton>}<IconButton label={editing?'Завершить редактирование сцены':'Редактировать сцену'} aria-pressed={editing} onClick={()=>{setSettings(false);setEditing(value=>!value);}}><Icon name="edit"/></IconButton><IconButton label="Настройки батареи" aria-pressed={settings} onClick={()=>{setEditing(false);setSettings(true);}}><Icon name="settings"/></IconButton></>;
|
||||
return <>{headerActionsTarget?createPortal(actions,headerActionsTarget):actions}{children({editing,appearance:profile.value,renderViewport:content=><ResizableViewport resizeIndicator={false} className="bms-stage" height={height} minHeight={minBatteryViewHeight} maxHeight={maxBatteryViewHeight} onHeightChange={setHeight} onHeightCommit={commitHeight}><EditorWorkspace editing={editing} title={title} subtitle="Редактирование сцены аккумулятора" onBack={()=>setEditing(false)}><div className="bms-stage bms-editor-content">{content}</div></EditorWorkspace></ResizableViewport>})}<BatteryAppearanceSettings open={settings} onClose={()=>setSettings(false)} profile={profile} sensor={sensor}/><ToastStack items={(error||profile.error)?[{id:'battery-view-save',title:error||profile.error,tone:'error'}]:[]} onDismiss={()=>{setError('');profile.setError('');}}/></>;
|
||||
return <>{headerActionsTarget?createPortal(actions,headerActionsTarget):actions}<LoadingRegion loading={!profile.ready||!view.ready} label="Загрузка настроек батареи">{profile.ready&&view.ready&&children({editing,appearance:profile.value,renderViewport:content=><ResizableViewport resizeIndicator={false} className="bms-stage" height={height} minHeight={minBatteryViewHeight} maxHeight={maxBatteryViewHeight} onHeightChange={setHeight} onHeightCommit={commitHeight}><EditorWorkspace editing={editing} title={title} subtitle="Редактирование сцены аккумулятора" onBack={()=>setEditing(false)}><div className="bms-stage bms-editor-content">{content}</div></EditorWorkspace></ResizableViewport>})}</LoadingRegion><BatteryAppearanceSettings open={settings} onClose={()=>setSettings(false)} profile={profile} sensor={sensor}/><ToastStack items={(error||profile.error||view.error)?[{id:'battery-view-save',title:error||profile.error||view.error,tone:'error'}]:[]} onDismiss={()=>{setError('');profile.setError('');view.setError('');}}/></>;
|
||||
}
|
||||
|
||||
@@ -23,7 +23,7 @@ export function EnvironmentProfiles({document:doc,update,onError}:{document:Scen
|
||||
<Description>{dirty?'Есть изменения относительно профиля. Настройки сцены сохраняются автоматически.':'Настройки совпадают с профилем.'}</Description>
|
||||
<div className="rover-scene-actions"><Button size="compact" disabled={!ready||!selected||selected.id===builtin.id||pending||!dirty} loading={pending&&!draft} onClick={()=>void save(false)}>Пересохранить профиль</Button><Button size="compact" disabled={!ready||pending} onClick={()=>begin()}>Сохранить как…</Button></div>
|
||||
<div className="rover-scene-actions"><Button size="compact" onClick={exportJson}>Экспорт JSON</Button><Button size="compact" disabled={!ready||pending} onClick={()=>input.current?.click()}>Импорт JSON</Button></div>
|
||||
<Description>Библиотека общая для сцен на этом компьютере. Профиль переносит окружение и поведение камеры; ракурс, материалы и компоновка сцены сохраняются.</Description>
|
||||
<Description>Библиотека общая для сцен в Mission Core. Профиль переносит окружение и поведение камеры; ракурс, материалы и компоновка сцены сохраняются.</Description>
|
||||
<input ref={input} type="file" hidden accept=".json,application/json" onChange={async e=>{const f=e.currentTarget.files?.[0];e.currentTarget.value='';if(!f)return;try{if(f.size>2_000_000)throw new Error('Профиль больше 2 МБ.');const value=parseEnvironmentProfile(JSON.parse(await f.text()));if(mounted.current)begin(value);}catch(error){onError(error instanceof Error?error.message:'Не удалось импортировать профиль.');}}}/>
|
||||
<Window open={!!draft} onClose={()=>{if(!pending)setDraft(null);}} title="Сохранить профиль окружения" size="sm" footer={<WindowFooterActions><Button disabled={pending} onClick={()=>setDraft(null)}>Отмена</Button><Button variant="primary" loading={pending} disabled={!name.trim()} onClick={()=>void save(true)}>Сохранить</Button></WindowFooterActions>}>
|
||||
<TextField label="Название профиля" value={name} maxLength={80} disabled={pending} onChange={e=>setName(e.target.value)}/>
|
||||
|
||||
@@ -44,7 +44,7 @@ export function SceneEditor({scene,editing,onModelState,modelUrl=roverModelURL,o
|
||||
const node=findSceneObject(root,selectedObject),targets=node?objectTargets(node):[];
|
||||
useObjectSelection(sceneApi,targets,editing&&modelPhase==='ready');
|
||||
const material=selected?scene.document.materials[selected]:null;
|
||||
const saved=scene.saveState==='saved',status=textureState==='loading'?'Загрузка текстур':scene.saveState==='loading'?'Загрузка настроек сцены':scene.saveState==='saving'?'Сохранение сцены':scene.saveState==='error'?'Изменения не сохранены':'Сохранено на этом компьютере';
|
||||
const saved=scene.saveState==='saved',status=textureState==='loading'?'Загрузка текстур':scene.saveState==='loading'?'Загрузка настроек сцены':scene.saveState==='saving'?'Сохранение сцены':scene.saveState==='error'?'Изменения не сохранены':'Сохранено в Mission Core';
|
||||
const tools:EditorDockTool[]=[
|
||||
{id:'objects',title:'Объекты сцены',label:'Объекты сцены',open:objectsOpen,onClose:()=>setObjectsOpen(false),className:'scene-object-window',initialRect:{left:16,top:16,width:380,height:600},content:<SceneObjectTree revealVersion={selectionVersion} root={root} selected={selectedObject} visibility={scene.document.objectVisibility} legacyVisibility={scene.document.objects} onSelect={selectObject} onVisibility={(id,value)=>scene.update(doc=>({...doc,objectVisibility:{...doc.objectVisibility,[id]:value}}))}/>},
|
||||
{id:'palette',title:'Материалы сцены',label:'Материалы сцены',open:palette,onClose:()=>setPalette(false),className:'rover-material-palette',initialRect:{left:400,top:420,width:640,height:340},minimumSize:{width:280,height:180},
|
||||
|
||||
@@ -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};
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user