feat(observatory): persist scene profiles and stable device view bindings
This commit is contained in:
@@ -1,5 +1,7 @@
|
||||
.observation-center { display:flex; flex-direction:column; gap:var(--nodedc-space-3); padding:var(--nodedc-space-4); min-width:0; height:max(600px, calc(100dvh - 260px)); }
|
||||
.observation-center--expanded { position:fixed; inset:0; z-index:var(--nodedc-layer-overlay); background:var(--nodedc-canvas); height:100dvh; box-sizing:border-box; }
|
||||
.observation-center--expanded { position:fixed; inset:0; z-index:calc(var(--nodedc-layer-overlay) - 1); background:var(--nodedc-canvas); height:100dvh; box-sizing:border-box; }
|
||||
/* Inline fallback for browsers without state-preserving DOM moves. */
|
||||
.nodedc-application-panel:has(.observation-center--expanded) { transform:none; overflow:visible; }
|
||||
.observation-toolbar, .observation-summary, .observation-actions { display:flex; align-items:center; gap:var(--nodedc-space-2); }
|
||||
.observation-toolbar { justify-content:space-between; flex-wrap:wrap; }
|
||||
.observation-toolbar h2, .observation-panel h3 { margin:0; }
|
||||
@@ -13,6 +15,7 @@
|
||||
.observation-mount, .observation-panel-mount, .observation-media-mount, .observation-panel, .observation-split { height:100%; min-height:0; min-width:0; }
|
||||
.observation-panel__surface { display:flex; flex-direction:column; height:100%; overflow:hidden; container-type:inline-size; }
|
||||
.observation-panel__surface > .observation-mount { flex:1; }
|
||||
.observation-panel__surface--flow > .observation-mount { height:0; flex:1 1 0; }
|
||||
.observation-panel__surface--overlay { position:relative; --observation-overlay-header-space:62px; }
|
||||
.observation-panel__surface--overlay > .observation-panel__header { position:absolute; inset:0 0 auto; z-index:1; background:transparent; pointer-events:none; }
|
||||
.observation-panel__surface--overlay > .observation-panel__header > * { pointer-events:auto; }
|
||||
@@ -29,8 +32,10 @@
|
||||
.observation-source__media { position:relative; flex:1; min-height:0; overflow:hidden; display:flex; align-items:center; justify-content:center; }
|
||||
.observation-source__media video, .observation-source__media canvas { width:100%; height:100%; object-fit:contain; }
|
||||
.observation-source__media[data-live="false"] > *, .observation-source__media [data-live="false"] { visibility:hidden; }
|
||||
.observation-source__notice { position:absolute; inset:max(30%, calc(var(--observation-overlay-header-space, 0px) + var(--nodedc-space-3))) var(--nodedc-space-4) auto; text-align:center; color:var(--nodedc-text-secondary); font-size:calc(var(--nodedc-font-size-lg) * .7); }
|
||||
.observation-source__notice--centered { inset:var(--observation-overlay-header-space, 0px) 0 0; margin:0; padding:var(--nodedc-space-4); display:grid; place-content:center; font-size:var(--nodedc-font-size-sm); pointer-events:none; }
|
||||
/* Notices use the full viewport, independent of its overlaid header. */
|
||||
.observation-source__notice { position:absolute; inset:0; box-sizing:border-box; margin:0; padding:var(--nodedc-space-4); display:flex; flex-direction:column; align-items:center; justify-content:center; gap:var(--nodedc-space-3); text-align:center; font-family:inherit; font-size:var(--nodedc-font-size-sm); font-weight:400; line-height:1.4; color:var(--nodedc-text-muted); pointer-events:none; }
|
||||
.observation-source__notice > p { margin:0; }
|
||||
.observation-source__notice > button, .observation-source__notice > a { pointer-events:auto; }
|
||||
.observation-rerun, .observation-rerun > div, .observation-map > div { width:100%; height:100%; }
|
||||
.observation-settings { display:flex; flex-direction:column; gap:var(--nodedc-space-4); }
|
||||
.observation-layer { display:grid; grid-template-columns:minmax(0, 1fr) 50%; align-items:center; gap:var(--nodedc-space-3); }
|
||||
|
||||
@@ -0,0 +1,18 @@
|
||||
import {type DockTree,dockIds} from '@nodedc/ui-core';
|
||||
import type {ObservationLayout} from './observationLayout';
|
||||
|
||||
/** Transfer chosen catalog slots once; never overwrite an existing device layout. */
|
||||
export function bindObservationLayout(layout:ObservationLayout,bindings:readonly {from:string;to:string}[]):ObservationLayout{
|
||||
const known=new Set([...layout.order,...layout.hidden,...Object.keys(layout.layers),...(layout.tree?dockIds(layout.tree):[])]);
|
||||
const map=new Map(bindings.filter(({from,to})=>(known.has(from)||layout.catalogVisible?.includes(from))&&!known.has(to)).map(({from,to})=>[from,to]));
|
||||
if(!map.size)return layout;
|
||||
const key=(id:string)=>map.get(id)??id;
|
||||
const tree=(value:DockTree):DockTree=>'id'in value?{id:key(value.id)}:{...value,first:tree(value.first),second:tree(value.second)};
|
||||
const splits=Object.fromEntries(Object.entries(layout.splits).map(([name,ratio])=>{
|
||||
try{const ids:unknown=JSON.parse(name);if(Array.isArray(ids)&&ids.every(id=>typeof id==='string'))return [JSON.stringify(ids.map(key)),ratio];}catch{/* Preserve unrelated legacy split keys. */}
|
||||
return [name,ratio];
|
||||
}));
|
||||
return {...layout,tree:layout.tree?tree(layout.tree):undefined,order:layout.order.map(key),hidden:layout.hidden.map(key),
|
||||
layers:Object.fromEntries(Object.entries(layout.layers).map(([id,value])=>[key(id),value])),splits,
|
||||
catalogVisible:layout.catalogVisible?.filter(id=>!map.has(id))};
|
||||
}
|
||||
@@ -1,3 +1,4 @@
|
||||
import {readSceneSettings,type SceneSettings} from '../../sceneSettings';
|
||||
import {dockIds, type DockTree} from '@nodedc/ui-core';
|
||||
import {decodeObservationLayout, type ObservationLayout} from './observationLayout';
|
||||
|
||||
@@ -6,7 +7,7 @@ export const observationArrangements = [
|
||||
{value:'rows',label:'Друг под другом'},
|
||||
] as const;
|
||||
export interface ObservationPreset {id:string;name:string;layout:ObservationLayout}
|
||||
export interface ObservationPresets {version:1;selected:string;layout:ObservationLayout;presets:ObservationPreset[]}
|
||||
export interface ObservationPresets {version:1;selected:string;layout:ObservationLayout;presets:ObservationPreset[];scenes?:Record<string,SceneSettings>}
|
||||
const clone = (layout:unknown):ObservationLayout => JSON.parse(JSON.stringify(decodeObservationLayout(layout)));
|
||||
export function decodeObservationPresets(value:unknown, legacy?:unknown):ObservationPresets {
|
||||
const source = value && typeof value === 'object' ? value as Partial<ObservationPresets> : {};
|
||||
@@ -19,7 +20,10 @@ export function decodeObservationPresets(value:unknown, legacy?:unknown):Observa
|
||||
}
|
||||
const layout=decodeObservationLayout(source.version===1 ? source.layout : legacy);
|
||||
const selected=source.selected;
|
||||
return {version:1,presets,layout,selected:typeof selected==='string' &&
|
||||
const scenes:Record<string,SceneSettings>={};
|
||||
if(source.version===1 && source.scenes && typeof source.scenes==='object')
|
||||
for(const [key,value] of Object.entries(source.scenes).slice(0,128)){const profile=readSceneSettings(value);if(key.length<=512&&profile)scenes[key]=profile;}
|
||||
return {version:1,presets,layout,...(Object.keys(scenes).length?{scenes}:{}),selected:typeof selected==='string' &&
|
||||
(presets.some(p=>p.id===selected) || observationArrangements.some(p=>p.value===selected))
|
||||
? selected : layout.arrangement};
|
||||
}
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import type {SceneSettings} from '../../sceneSettings';
|
||||
import {useEffect,useRef,useState,type SetStateAction} from 'react';
|
||||
import type {CameraPresentation} from '../../../../../packages/sensor-ui/src/observation';
|
||||
import type {ObservationLayout} from './observationLayout';
|
||||
@@ -132,6 +133,7 @@ export function useVehicleObservation(vehicleID:string) {
|
||||
try{localStorage.removeItem(draftKey+':recovery');}catch{}
|
||||
};
|
||||
return {...document.layouts,recovery:!!recovery,restore,ready,pending,cameras:document.cameras,setLayout,
|
||||
setScene:(id:string,value:SceneSettings)=>changeLayouts(current=>({...current,scenes:{...current.scenes,[id]:value}})),
|
||||
setCamera:(id:string,value:CameraPresentation)=>update(current=>({...current,cameras:{...current.cameras,[id]:value}})),
|
||||
select:(id:string)=>changeLayouts(current=>selectObservationPreset(current,id)),
|
||||
save:(name:string)=>changeLayouts(current=>saveObservationPreset(current,name,`saved:${crypto.randomUUID()}`)),
|
||||
|
||||
@@ -1,6 +1 @@
|
||||
/** View-only bounds. Each full-range endpoint disables its own clipping plane. */
|
||||
export function heightSlice([lower, upper]: readonly [number, number], [min, max]: readonly [number, number]) {
|
||||
const tolerance = Math.max(1, max - min) * 1e-9;
|
||||
return { floor: lower <= min + tolerance ? null : lower,
|
||||
ceiling: upper >= max - tolerance ? null : upper };
|
||||
}
|
||||
export {heightSlice} from "../../../../packages/spatial-ui/src/heightSlice";
|
||||
|
||||
@@ -0,0 +1,16 @@
|
||||
/** Reparenting with append/remove destroys iframe browsing contexts. */
|
||||
export function observationPortal(portal: HTMLElement, inline: HTMLElement, overlay: HTMLElement) {
|
||||
inline.append(portal);
|
||||
return {
|
||||
setExpanded(expanded: boolean) {
|
||||
const target = (expanded ? overlay : inline) as HTMLElement & {
|
||||
moveBefore?: (node: Node, before: Node | null) => void;
|
||||
};
|
||||
if (portal.parentElement === target) return;
|
||||
// Atomic moves preserve the running renderer, its canvas and history.
|
||||
// Older hosts stay inline; the expanded CSS escapes its containing panel.
|
||||
if (typeof target.moveBefore === 'function') target.moveBefore(portal, null);
|
||||
},
|
||||
dispose() { portal.remove(); },
|
||||
};
|
||||
}
|
||||
@@ -35,7 +35,9 @@ export function decodeSessionDisplay(value: unknown, sessionId: string): SceneSe
|
||||
|| ['showPoints','showTrajectory','showGrid','showLabels','showCameraFrustums'].some(key => typeof s[key as keyof SceneSettings] !== 'boolean')) {
|
||||
throw new Error('Некорректные настройки отображения');
|
||||
}
|
||||
return {...s, accumulationMaxSeconds: Math.max(s.accumulationSeconds, s.accumulationMaxSeconds!)};
|
||||
// Older recording profiles do not own the optional live-view navigation
|
||||
// fields. Restore their neutral defaults when reading that wire format.
|
||||
return {...defaultSceneSettings, ...s, accumulationMaxSeconds: Math.max(s.accumulationSeconds, s.accumulationMaxSeconds!)};
|
||||
}
|
||||
|
||||
export async function loadSessionDisplay(sessionId: string, signal?: AbortSignal): Promise<SceneSettings> {
|
||||
|
||||
@@ -0,0 +1,12 @@
|
||||
import {useEffect,useState} from 'react';
|
||||
import {defaultSceneSettings,type SceneSettings} from '../../sceneSettings';
|
||||
import {fetchObservationWorkspaceLayoutProfile} from './workspaceLayout';
|
||||
/** Initial profile only; a board's persisted pane settings always take precedence. */
|
||||
export function useSpatialDefaults(){
|
||||
const [settings,setSettings]=useState<SceneSettings|null>(null);
|
||||
useEffect(()=>{let active=true;
|
||||
void fetchObservationWorkspaceLayoutProfile().then(profile=>{if(active)setSettings({...defaultSceneSettings,...profile?.sceneSettings});}).catch(()=>{if(active)setSettings({...defaultSceneSettings});});
|
||||
return()=>{active=false;};
|
||||
},[]);
|
||||
return settings;
|
||||
}
|
||||
@@ -4,6 +4,8 @@ import {Button,DockHandle,GlassSurface,Icon,IconButton,LoadingRegion,Select,Stat
|
||||
import {useDevicePluginHost} from '../../../core/device-plugins/DevicePluginHost';
|
||||
import {createFleetSensorTransport} from '../../../core/fleet/sensorTransport';
|
||||
import {moveObservation,withObservationTree,orderedObservationIDs,observationTree} from '../../../core/fleet/observationLayout';
|
||||
import {bindObservationLayout} from '../../../core/fleet/observationBinding';
|
||||
import {useSpatialDefaults} from '../../../core/observation/useSpatialDefaults';
|
||||
import {useVehicleObservation} from '../../../core/fleet/useVehicleObservation';
|
||||
import {observationArrangements,retainDormantObservationTree} from '../../../core/fleet/observationPresets';
|
||||
import {ObservationLayoutSaveWindow} from '../../../components/observation/ObservationLayoutSaveWindow';
|
||||
@@ -11,8 +13,9 @@ import {createIsolatedRerunHost} from '../../../components/rerun/isolatedRerunHo
|
||||
import {CameraObservation} from '../../../../../../packages/sensor-ui/src/CameraObservation';
|
||||
import {cameraObservationViews,observationKey,type SensorObservationView,type ObservationHeaderTargets} from '../../../../../../packages/sensor-ui/src/observation';
|
||||
import {unboundObservationViews} from '../../../../../../packages/sensor-ui/src/observationCatalog';
|
||||
import {sensorContribution} from '../../../../../../packages/sensor-ui/src/extensions';
|
||||
import {sensorContribution,wirelessContributions} from '../../../../../../packages/sensor-ui/src/extensions';
|
||||
import {ObservationDeviceSettings} from './ObservationDeviceSettings';
|
||||
import {ObservationConnectionWindow} from './ObservationConnectionWindow';
|
||||
import {ObservationPanelHeader} from './ObservationPanelHeader';
|
||||
import {ObservationDeck,ObservationMount} from './ObservationDeck';
|
||||
import {ObservationMap} from './ObservationMap';
|
||||
@@ -25,28 +28,42 @@ import {RoverLogs} from '../../../components/rover/RoverLogs';
|
||||
import {useRoverDiagnostics} from '../../../core/fleet/useRoverDiagnostics';
|
||||
import {useRoverControl} from '../../../core/fleet/useRoverControl';
|
||||
import {roverObservationStatus} from '../../../core/fleet/roverObservation';
|
||||
import {observationPortal} from '../../../core/observation/observationPortal';
|
||||
|
||||
export function BoardObservationCenter({vehicleID,name,enabled,paired,back,configure,headerToolsHost}:{vehicleID:string;name:string;enabled:boolean;paired:boolean;back:()=>void;configure:()=>void;headerToolsHost?:HTMLElement|null}){
|
||||
const diagnostics=useRoverDiagnostics(vehicleID);
|
||||
const [devOpen,setDevOpen]=useState(false);
|
||||
const [primaryCamera,setPrimaryCamera]=useState<string|null>(null),primaryRef=useRef<string|null>(null);
|
||||
const {registry}=useDevicePluginHost(),transport=useMemo(()=>createFleetSensorTransport(vehicleID),[vehicleID]);
|
||||
const inventory=useObservationInventory(transport),presets=useVehicleObservation(vehicleID);
|
||||
const {inventory,refresh}=useObservationInventory(transport),presets=useVehicleObservation(vehicleID);
|
||||
const {layout,setLayout}=presets;
|
||||
const spatialDefaults=useSpatialDefaults();
|
||||
const [saving,setSaving]=useState(false),[editing,setEditing]=useState<string|null>(null);
|
||||
const edited=presets.presets.find(p=>p.id===editing);
|
||||
const [settingsView,setSettingsView]=useState('points');
|
||||
const [settingsDevice,setSettingsDevice]=useState<string|null>(null);
|
||||
const [connectingKind,setConnectingKind]=useState<string|null>(null);
|
||||
const wireless=wirelessContributions(registry.sensorContributions);
|
||||
const connect=(kind:string)=>{setSettingsDevice(null);setConnectingKind(kind);};
|
||||
const reconnect=(kind:string|undefined)=>kind&&transport.enrollment&&wireless.some(item=>item.kind===kind)?()=>connect(kind):undefined;
|
||||
const [layersOpen,setLayersOpen]=useState(false);
|
||||
const [full,setFull]=useState<string|null>(null),[expanded,setExpanded]=useState(false);
|
||||
const frame=useRef<HTMLDivElement>(null),[portal]=useState(()=>document.createElement('div'));
|
||||
useLayoutEffect(()=>{(expanded?document.body:frame.current!).append(portal);return()=>portal.remove();},[expanded,portal]);
|
||||
const portalOwner=useRef<ReturnType<typeof observationPortal>|null>(null);
|
||||
useLayoutEffect(()=>{const owner=observationPortal(portal,frame.current!,document.body);portalOwner.current=owner;return()=>{portalOwner.current=null;owner.dispose();};},[portal]);
|
||||
useLayoutEffect(()=>{portalOwner.current?.setExpanded(expanded);},[expanded]);
|
||||
const mounts=useRef(new Map<string,HTMLElement>()),media=useRef(new Map<string,HTMLElement>()),headers=useRef(new Map<string,ObservationHeaderTargets>());
|
||||
const groups=(inventory?.items??[]).flatMap(device=>{
|
||||
const contribution=sensorContribution(registry.sensorContributions,device)?.observation;
|
||||
const views=contribution?.views(device)??cameraObservationViews(device);
|
||||
return views.length?[{device,views,independentMediaLiveness:contribution?contribution.independentMediaLiveness===true:true,Session:contribution?.Session??CameraObservation}]:[];
|
||||
});
|
||||
const sources:{key:string;deviceID?:string;catalog?:string;view:SensorObservationView}[]=groups.flatMap(group=>group.views.map(view=>({key:observationKey(group.device.id,view.id),deviceID:group.device.id,view})));
|
||||
const sceneKeys=groups.flatMap(group=>group.views.filter(view=>view.scene).map(view=>observationKey(group.device.id,view.id)));
|
||||
useEffect(()=>{if(presets.ready&&spatialDefaults)for(const key of sceneKeys)if(!presets.scenes?.[key])presets.setScene(key,spatialDefaults);},[presets.ready,spatialDefaults,JSON.stringify(sceneKeys)]);
|
||||
const bindings=groups.filter(group=>groups.filter(other=>other.device.kind===group.device.kind).length===1).flatMap(group=>group.views.map(view=>({from:JSON.stringify(['catalog',group.device.kind,view.id]),to:observationKey(group.device.id,view.id)})));
|
||||
const bindingKey=JSON.stringify(bindings);
|
||||
useEffect(()=>{if(!presets.ready)return;setLayout(value=>bindObservationLayout(value,bindings));setFull(value=>bindings.find(item=>item.from===value)?.to??value);},[bindingKey,presets.ready,layout]);
|
||||
const sources:{key:string;deviceID?:string;kind?:string;catalog?:string;view:SensorObservationView}[]=groups.flatMap(group=>group.views.map(view=>({key:observationKey(group.device.id,view.id),deviceID:group.device.id,kind:group.device.kind,view})));
|
||||
sources.push(...unboundObservationViews(inventory?.items??[],registry.sensorContributions));
|
||||
sources.push({key:'map',view:{id:'map',label:'Карта'}},{key:'rover',view:{id:'rover',label:'3D View аппарата'}},{key:'telemetry',view:{id:'telemetry',label:'Телеметрия'}});
|
||||
if(diagnostics.state.id)sources.push({key:'rover-logs',view:{id:'rover-logs',label:'Логи управления'}});
|
||||
@@ -60,7 +77,7 @@ export function BoardObservationCenter({vehicleID,name,enabled,paired,back,confi
|
||||
// own this subscription; the rover transport enforces its own freshness.
|
||||
const rover=useRoverControl(vehicleID,paired&&(visible.includes('rover')||visible.includes('telemetry')));
|
||||
const roverObservation=roverObservationStatus(rover.state,rover.connection);
|
||||
const drivingVisible=visible.includes('rover')&&(!effectiveFull||effectiveFull==='rover')&&!layersOpen&&!settingsDevice&&!devOpen;
|
||||
const drivingVisible=visible.includes('rover')&&(!effectiveFull||effectiveFull==='rover')&&!layersOpen&&!settingsDevice&&!connectingKind&&!devOpen;
|
||||
useEffect(()=>{if(!drivingVisible)rover.stop();},[drivingVisible,rover.stop]);
|
||||
const configuredDevice=inventory?.items.find(device=>device.id===settingsDevice);
|
||||
useEffect(()=>{const escape=(event:KeyboardEvent)=>{if(document.querySelector('[data-docking="true"]'))return;if(event.key!=='Escape'||layersOpen||document.querySelector('[role=dialog], [role=listbox]'))return;if(effectiveFull){setFull(null);event.stopImmediatePropagation();}else if(expanded){setExpanded(false);event.stopImmediatePropagation();}};window.addEventListener('keydown',escape,true);return()=>window.removeEventListener('keydown',escape,true);},[effectiveFull,expanded,layersOpen]);
|
||||
@@ -73,7 +90,7 @@ export function BoardObservationCenter({vehicleID,name,enabled,paired,back,confi
|
||||
<div className="observation-deck">{!inventory||!presets.ready?<LoadingRegion loading={!presets.error} label="Получение визуальных источников"/>:visible.length?<ObservationDeck minimumSizes={{telemetry:roverTelemetryMinimum(rover.state)}} ids={visible} focusedId={effectiveFull} mounts={mounts.current} layout={layout} labels={Object.fromEntries(sources.map(source=>[source.key,source.view.label]))} onTreeChange={tree=>setLayout(current=>withObservationTree(current,retainDormantObservationTree(current.tree,tree)))}>
|
||||
{sources.filter(source=>visible.includes(source.key)).map(source=>createPortal(
|
||||
<div className="observation-panel">
|
||||
<GlassSurface tone="soft" radius="panel" padding="none" materialRim={false} className="observation-panel__surface observation-panel__surface--overlay">
|
||||
<GlassSurface tone="soft" radius="panel" padding="none" materialRim={false} className={`observation-panel__surface observation-panel__surface--${source.view.header==='flow'?'flow':'overlay'}`}>
|
||||
<ObservationPanelHeader>
|
||||
<DockHandle id={source.key} label={source.view.label}/>
|
||||
<div className="observation-panel__title">{source.key!=='rover'&&<h3 title={source.view.label}>{source.view.label}</h3>}<ObservationMount className="observation-header-slot" element={headers.current.get(source.key)!.statusTarget}/></div>
|
||||
@@ -81,7 +98,7 @@ export function BoardObservationCenter({vehicleID,name,enabled,paired,back,confi
|
||||
{source.view.layers&&<Select className="observation-layer-select" label={`Слой · ${source.view.label}`} value={layerFor(source.key,source.view)} options={source.view.layers} onChange={value=>setLayout(current=>({...current,layers:{...current.layers,[source.key]:value}}))} variant="inline"/>}
|
||||
<ObservationMount className="observation-header-slot" element={headers.current.get(source.key)!.actionsTarget}/>
|
||||
{source.deviceID&&cameras.some(group=>group.device.id===source.deviceID)&&<IconButton label={`${primaryRef.current===source.deviceID?'Основной видеопоток':'Сделать основным видеопотоком'} · ${source.view.label}`} aria-pressed={primaryRef.current===source.deviceID} onClick={()=>setPrimaryCamera(source.deviceID!)}><Icon name="eye"/></IconButton>}
|
||||
{source.deviceID&&<IconButton label={`Настройки · ${source.view.label}`} onClick={()=>setSettingsDevice(source.deviceID!)}><Icon name="settings"/></IconButton>}
|
||||
{source.deviceID&&<IconButton label={`Настройки · ${source.view.label}`} onClick={()=>{setSettingsView(source.view.id==='plan'?'plan':'points');setSettingsDevice(source.deviceID!);}}><Icon name="settings"/></IconButton>}
|
||||
<IconButton label={`${effectiveFull===source.key?'Восстановить':'Развернуть'} · ${source.view.label}`} onClick={()=>setFull(value=>value===source.key?null:source.key)}><Icon name={effectiveFull===source.key?'minimize':'expand'}/></IconButton>
|
||||
<IconButton label={`Скрыть · ${source.view.label}`} onClick={()=>setVisible(source.key,false)}><Icon name="close"/></IconButton>
|
||||
</div>
|
||||
@@ -90,11 +107,12 @@ export function BoardObservationCenter({vehicleID,name,enabled,paired,back,confi
|
||||
</GlassSurface>
|
||||
</div>,mounts.current.get(source.key)!,source.key))}
|
||||
</ObservationDeck>:<div className="observation-empty"><p>Все окна скрыты.</p><Button onClick={()=>setLayersOpen(true)}>Доступные слои</Button></div>}</div>
|
||||
{groups.map(({device,views,Session,independentMediaLiveness})=>visible.some(key=>views.some(view=>key===observationKey(device.id,view.id)))&&<Session key={device.id} device={device} transport={transport} presentation={presets.cameras[device.id]} onPresentationChange={presets.ready?value=>presets.setCamera(device.id,value):undefined} enabled={(independentMediaLiveness?paired:enabled&&inventory?.fresh!==false)&&device.online} fresh={enabled&&inventory?.fresh!==false} createRerunHost={createIsolatedRerunHost} views={views.map(view=>({id:view.id,layer:layerFor(observationKey(device.id,view.id),view),target:media.current.get(observationKey(device.id,view.id))!,...headers.current.get(observationKey(device.id,view.id))!}))}/>)}
|
||||
{sources.filter(source=>source.catalog&&visible.includes(source.key)).map(source=>createPortal(<div className="observation-source"><div className="observation-source__notice"><p>{source.catalog} не подключён к аппарату.</p><Button onClick={configure}>Подключить оборудование</Button></div></div>,media.current.get(source.key)!,source.key))}
|
||||
{configuredDevice&&<ObservationDeviceSettings key={configuredDevice.id} device={configuredDevice} transport={transport} contributions={registry.sensorContributions} enabled={enabled&&inventory?.fresh!==false&&configuredDevice.online} close={()=>setSettingsDevice(null)} configure={configure}/>}
|
||||
{presets.ready&&groups.map(({device,views,Session,independentMediaLiveness})=>visible.some(key=>views.some(view=>key===observationKey(device.id,view.id)))&&<Session key={device.id} device={device} transport={transport} configure={view=>{setSettingsView(view==='plan'?'plan':'points');setSettingsDevice(device.id);}} sceneProfiles={Object.fromEntries(views.map(view=>[view.id,presets.scenes?.[observationKey(device.id,view.id)]]).filter(([,value])=>value))} onSceneChange={presets.ready?(view,value)=>presets.setScene(observationKey(device.id,view),value):undefined} reconnect={reconnect(device.kind)} presentation={presets.cameras[device.id]} onPresentationChange={presets.ready?value=>presets.setCamera(device.id,value):undefined} enabled={(independentMediaLiveness?paired:enabled&&inventory?.fresh!==false)&&device.online} fresh={enabled&&inventory?.fresh!==false} createRerunHost={createIsolatedRerunHost} views={views.filter(view=>visible.includes(observationKey(device.id,view.id))).map(view=>({id:view.id,layer:layerFor(observationKey(device.id,view.id),view),target:media.current.get(observationKey(device.id,view.id))!,...headers.current.get(observationKey(device.id,view.id))!}))}/>)}
|
||||
{sources.filter(source=>source.catalog&&visible.includes(source.key)).map(source=>createPortal(<div className="observation-source"><div className="observation-source__notice"><p>{source.catalog} не подключён к аппарату.</p><Button onClick={reconnect(source.kind)??configure}>Подключить оборудование</Button></div></div>,media.current.get(source.key)!,source.key))}
|
||||
{connectingKind&&<ObservationConnectionWindow key={`${vehicleID}:${connectingKind}`} kind={connectingKind} transport={transport} contributions={registry.sensorContributions} enabled={enabled} refresh={refresh} close={()=>setConnectingKind(null)} configure={setSettingsDevice}/>}
|
||||
{configuredDevice&&<ObservationDeviceSettings key={configuredDevice.id+settingsView} sceneProfile={{view:settingsView,settings:presets.scenes?.[observationKey(configuredDevice.id,settingsView)],save:value=>presets.setScene(observationKey(configuredDevice.id,settingsView),value)}} device={configuredDevice} transport={transport} contributions={registry.sensorContributions} enabled={enabled&&inventory?.fresh!==false} close={()=>setSettingsDevice(null)} configure={configure} refresh={async()=>{await refresh();}} reconnect={reconnect(configuredDevice.kind)}/>}
|
||||
{visible.includes('map')&&createPortal(<ObservationMap vehicleID={vehicleID} header={headers.current.get('map')!}/>,media.current.get('map')!,'map-session')}
|
||||
{visible.includes('rover')&&createPortal(<RoverView vehicleID={vehicleID} controller={rover} header={headers.current.get('rover')!} active={drivingVisible} observation={roverObservation}/>,media.current.get('rover')!,'rover-session')}
|
||||
{visible.includes('rover')&&createPortal(<RoverView vehicleID={vehicleID} name={name} controller={rover} header={headers.current.get('rover')!} active={drivingVisible} observation={roverObservation}/>,media.current.get('rover')!,'rover-session')}
|
||||
{visible.includes('rover-logs')&&createPortal(<RoverLogs capture={diagnostics} header={headers.current.get('rover-logs')!}/>,media.current.get('rover-logs')!,'rover-logs-session')}
|
||||
{visible.includes('telemetry')&&createPortal(<RoverTelemetry state={rover.state} observation={roverObservation}/>,media.current.get('telemetry')!,'telemetry-session')}
|
||||
<Window open={layersOpen} onClose={()=>setLayersOpen(false)} title="Доступные слои" size="md"><div className="observation-settings">
|
||||
|
||||
@@ -0,0 +1,25 @@
|
||||
import {useEffect,useRef} from 'react';
|
||||
import {WirelessEnrollmentWindow} from '../../../../../../packages/sensor-ui/src/WirelessEnrollmentWindow';
|
||||
import {enrolledDevice,type SensorInventory,type SensorTransport} from '../../../../../../packages/sensor-ui/src/contracts';
|
||||
import type {SensorUiContribution} from '../../../../../../packages/sensor-ui/src/extensions';
|
||||
|
||||
/** One enrollment owner for every view of the selected device kind. */
|
||||
export function ObservationConnectionWindow({kind,transport,contributions,enabled,refresh,close,configure}:{
|
||||
kind:string;transport:SensorTransport;contributions:readonly SensorUiContribution[];enabled:boolean;
|
||||
refresh:()=>Promise<SensorInventory|null>;close:()=>void;configure:(deviceID:string)=>void;
|
||||
}){
|
||||
const current=useRef({active:true,enabled});
|
||||
current.current.enabled=enabled;
|
||||
useEffect(()=>{current.current.active=true;return()=>{current.current.active=false;};},[]);
|
||||
async function complete(sessionID:string,signal?:AbortSignal){
|
||||
if(!current.current.enabled)throw new Error('БК недоступен. Обновите состояние устройства.');
|
||||
const inventory=await refresh();
|
||||
if(signal?.aborted||!current.current.active)return;
|
||||
const device=inventory&&enrolledDevice(inventory,sessionID);
|
||||
if(!current.current.enabled||!device||device.kind!==kind)throw new Error('Связь с устройством пока не подтверждена. Проверьте его состояние.');
|
||||
close();configure(device.id);
|
||||
}
|
||||
if(!transport.enrollment)return null;
|
||||
return <WirelessEnrollmentWindow initialKind={kind} contributions={contributions.filter(item=>item.kind===kind)} transport={transport.enrollment}
|
||||
enabled={enabled} onClose={close} onChange={()=>{void refresh();}} onComplete={complete}/>;
|
||||
}
|
||||
@@ -1,17 +1,18 @@
|
||||
import {useState} from 'react';
|
||||
import {Button,ToastStack,Window} from '@nodedc/ui-react';
|
||||
import type {SensorDetailProps} from '../../../../../../packages/sensor-ui/src/extensions';
|
||||
import {SensorDetail} from '../../../../../../packages/sensor-ui/src/SensorDetail';
|
||||
import {sensorContribution,type SensorUiContribution} from '../../../../../../packages/sensor-ui/src/extensions';
|
||||
import type {Sensor,SensorTransport} from '../../../../../../packages/sensor-ui/src/contracts';
|
||||
import {createIsolatedRerunHost} from '../../../components/rerun/isolatedRerunHost';
|
||||
|
||||
export function ObservationDeviceSettings({device,transport,contributions,enabled,close,configure}:{device:Sensor;transport:SensorTransport;contributions:readonly SensorUiContribution[];enabled:boolean;close:()=>void;configure:()=>void}) {
|
||||
export function ObservationDeviceSettings({device,transport,contributions,enabled,close,configure,refresh,reconnect,sceneProfile}:{sceneProfile?:SensorDetailProps['sceneProfile'];device:Sensor;transport:SensorTransport;contributions:readonly SensorUiContribution[];enabled:boolean;close:()=>void;configure:()=>void;refresh:()=>Promise<void>;reconnect?:()=>void}) {
|
||||
const [error,setError]=useState('');
|
||||
const contribution=sensorContribution(contributions,device);
|
||||
const Detail=contribution?.Detail??SensorDetail;
|
||||
const content=<Detail key={device.snapshot.context.session_id} device={device} transport={transport} enabled={enabled} back={close} refresh={async()=>{await transport.inventory();}} failure={reason=>setError(reason instanceof Error?reason.message:reason?String(reason):'')} createRerunHost={createIsolatedRerunHost}/>;
|
||||
const content=<Detail key={device.snapshot.context.session_id} device={device} transport={transport} enabled={enabled} previewEnabled={false} sceneProfile={sceneProfile} back={close} backLabel="Вернуться к наблюдению" refresh={refresh} reconnect={reconnect} failure={reason=>setError(reason instanceof Error?reason.message:reason?String(reason):'')} createRerunHost={createIsolatedRerunHost}/>;
|
||||
if(contribution?.detailPresentation==='modal')return <>{content}<ToastStack items={error?[{id:'device-settings-error',tone:'error',title:error,durationMs:null}]:[]} onDismiss={()=>setError('')}/></>;
|
||||
return <Window open title={`Настройки · ${device.name}`} size="lg" placement="end" draggable closeOnBackdrop={false} lockBodyScroll={false} trapFocus={false} onClose={close}>
|
||||
return <Window open title={`Настройки · ${device.name}`} size="lg" placement="center" closeOnBackdrop={false} onClose={close}>
|
||||
{!enabled&&<p>Нет связи с устройством. Настройки оборудования будут доступны после подключения.</p>}
|
||||
{!device.prepared&&<Button onClick={configure}>Открыть оборудование аппарата</Button>}
|
||||
{error&&<p role="alert">{error}</p>}
|
||||
|
||||
@@ -1,17 +1,23 @@
|
||||
import {useEffect,useState} from 'react';
|
||||
import {useCallback,useEffect,useRef,useState} from 'react';
|
||||
import type {SensorInventory,SensorTransport} from '../../../../../../packages/sensor-ui/src/contracts';
|
||||
|
||||
export function useObservationInventory(transport:SensorTransport){
|
||||
const [inventory,setInventory]=useState<SensorInventory|null>(null);
|
||||
const reader=useRef<(()=>Promise<SensorInventory|null>)|null>(null);
|
||||
const refresh=useCallback(async()=>await reader.current?.()??null,[]);
|
||||
useEffect(()=>{
|
||||
let active=true,running=false,revision=0,last=0;
|
||||
const receive=(value:SensorInventory)=>{if(active){revision++;last=Date.now();setInventory(value);}};
|
||||
let active=true,running=false,revision=0,last=0,latest:SensorInventory|null=null;
|
||||
const lifetime=new AbortController();
|
||||
setInventory(null);
|
||||
const receive=(value:SensorInventory)=>{if(active){revision++;last=Date.now();latest=value;setInventory(value);}};
|
||||
// A lost SSE connection is not evidence that a working camera stopped.
|
||||
// Retain the last inventory for one bounded heartbeat window and verify via HTTP.
|
||||
const unavailable=()=>{if(active&&Date.now()-last>15000)setInventory(value=>value?{...value,fresh:false}:value);};
|
||||
const poll=async()=>{if(running||Date.now()-last<4000)return;running=true;const before=revision;try{const value=await transport.inventory();if(before===revision)receive(value);}catch{if(before===revision)unavailable();}finally{running=false;}};
|
||||
const read=async()=>{const before=revision;try{const value=await transport.inventory(lifetime.signal);if(!active)return null;if(before===revision)receive(value);return latest;}catch{if(before===revision)unavailable();return null;}};
|
||||
reader.current=read;
|
||||
const poll=async()=>{if(running||Date.now()-last<4000)return;running=true;try{await read();}finally{running=false;}};
|
||||
void poll();const unsubscribe=transport.subscribe?.(receive,()=>{unavailable();void poll();});const timer=setInterval(()=>{unavailable();void poll();},5000);
|
||||
return()=>{active=false;clearInterval(timer);unsubscribe?.();};
|
||||
return()=>{active=false;lifetime.abort();if(reader.current===read)reader.current=null;clearInterval(timer);unsubscribe?.();};
|
||||
},[transport]);
|
||||
return inventory;
|
||||
return {inventory,refresh};
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user