Make simulation imports background tasks with Worker-owned sources and durable deletion
This commit is contained in:
@@ -1,14 +1,21 @@
|
||||
import { useState } from "react";
|
||||
import { useInfrastructureQueue } from "../../core/simulation/infrastructureAnalysis";
|
||||
import { Description, Button, ConfirmationModal, Icon, IconButton, ResourceList, ResourceRow,
|
||||
StatusBadge, TextField, ToastStack, Window, WindowFooterActions } from "@nodedc/ui-react";
|
||||
StatusBadge, ProgressBar, TextField, ToastStack, Window, WindowFooterActions } from "@nodedc/ui-react";
|
||||
import { updateAiWorld, type AiWorld } from "../../core/simulation/aiPolygon";
|
||||
import {useLocationImports} from "../../core/simulation/locationImports";
|
||||
|
||||
import {deleteLocation,useLocationDeletions} from "../../core/simulation/locationDeletions";
|
||||
import {SimulationOriginalDownload} from "./SimulationOriginalDownload";
|
||||
|
||||
export function AiLocationCatalog({worlds, removedWorlds, activeWorldId, paused, onOpen, onPlan, canPlan, onChanged}: {
|
||||
worlds: AiWorld[]; removedWorlds: AiWorld[]; activeWorldId?: string; paused: boolean;
|
||||
onOpen: (world: AiWorld) => void; onPlan: (world: AiWorld) => void; canPlan: boolean; onChanged: () => Promise<void>;
|
||||
}) {
|
||||
const queue=useInfrastructureQueue();
|
||||
const deletions=useLocationDeletions(onChanged);
|
||||
const imports=useLocationImports();
|
||||
const uploadingWorlds=new Set(imports.map(task=>task.project?.projectId.replace("sim-","aiworld-")));
|
||||
const [editing, setEditing] = useState<AiWorld | null>(null);
|
||||
const [name, setName] = useState("");
|
||||
const [confirming, setConfirming] = useState(false);
|
||||
@@ -27,16 +34,17 @@ export function AiLocationCatalog({worlds, removedWorlds, activeWorldId, paused,
|
||||
} finally { setBusy(null); }
|
||||
};
|
||||
return <>
|
||||
<ResourceList>{worlds.map(world => {const queued=queue.jobs.find(j=>j.world_id===world.world_id);return <li key={world.world_id}>
|
||||
<ResourceList>{worlds.filter(world=>!uploadingWorlds.has(world.world_id)).map(world => {const queued=queue.jobs.find(j=>j.world_id===world.world_id);const deletion=deletions.find(d=>d.project_id===world.local_scene?.project_id);return <li key={world.world_id}>
|
||||
<ResourceRow title={world.name} icon={<Icon name="globe"/>}
|
||||
status={activeWorldId === world.world_id ? <StatusBadge tone="neutral">
|
||||
{paused ? "На паузе" : "Сцена открыта"}</StatusBadge> : queued ? <StatusBadge tone={queue.unavailable?"neutral":"warning"}>
|
||||
{queue.unavailable?"Нет обновлений очереди":queued.cancel_requested?"Отмена расчёта":queued.status==="queued"?`В очереди · №${queued.queue?.position??"—"}`:queued.status==="running"?"Расчёт инфраструктуры":"Освобождение Worker"}</StatusBadge> : undefined}
|
||||
actions={<>
|
||||
actions={deletion?<div className="simulation-imports__progress" role="status"><ProgressBar label="Удаление локации"/><Description>{deletion.error??"Удаление локации"}</Description></div>:<>
|
||||
<IconButton label={world.status === "uploading" ? `Продолжить импорт ${world.name}` : `Открыть ${world.name}`}
|
||||
onClick={() => onOpen(world)}><Icon name={world.status === "uploading" ? "upload" : "eye"}/></IconButton>
|
||||
{canPlan&&world.status!=="uploading"&&world.settings.prepared?<IconButton label={`Подготовить маршрут · ${world.name}`}
|
||||
onClick={() => onPlan(world)}><Icon name="plan"/></IconButton>:null}
|
||||
{world.status!=="uploading"?<SimulationOriginalDownload worldId={world.world_id} name={world.name}/>:null}
|
||||
<IconButton label={`Настройки ${world.name}`} onClick={() => {
|
||||
setEditing(world); setName(world.name); setConfirming(false); setError(null);
|
||||
}}><Icon name="settings"/></IconButton>
|
||||
@@ -44,7 +52,7 @@ export function AiLocationCatalog({worlds, removedWorlds, activeWorldId, paused,
|
||||
</li>;})}</ResourceList>
|
||||
{removedWorlds.length ? <>
|
||||
<Button aria-expanded={showRemoved} onClick={() => setShowRemoved(!showRemoved)}>
|
||||
Удалённые локации · {removedWorlds.length}</Button>
|
||||
Скрытые локации · {removedWorlds.length}</Button>
|
||||
{showRemoved ? <ResourceList>{removedWorlds.map(world => <li key={world.world_id}>
|
||||
<ResourceRow title={world.name} icon={<Icon name="globe"/>} actions={
|
||||
<Button disabled={busy !== null} loading={busy === world.world_id}
|
||||
@@ -55,7 +63,7 @@ export function AiLocationCatalog({worlds, removedWorlds, activeWorldId, paused,
|
||||
onClose={() => {if (!busy) setEditing(null);}}
|
||||
footer={<WindowFooterActions>
|
||||
<Button icon={<Icon name="trash"/>} disabled={!!busy || editing?.world_id === activeWorldId}
|
||||
onClick={() => setConfirming(true)}>Удалить локацию</Button>
|
||||
onClick={() => setConfirming(true)}>{editing?.local_scene?"Удалить локацию":"Скрыть локацию"}</Button>
|
||||
<Button variant="primary" loading={!!busy} disabled={!name.trim() || name.trim() === editing?.name}
|
||||
onClick={() => {if (editing) void update(editing, {display_name:name.trim()});}}>Сохранить</Button>
|
||||
</WindowFooterActions>}>
|
||||
@@ -63,11 +71,17 @@ export function AiLocationCatalog({worlds, removedWorlds, activeWorldId, paused,
|
||||
onChange={event => setName(event.target.value)}/>
|
||||
{editing?.world_id === activeWorldId ? <Description>Удаление станет доступно после завершения симуляции.</Description> : null}
|
||||
</Window>
|
||||
<ConfirmationModal open={!!editing && confirming} title="Удалить локацию?" danger
|
||||
description={<>«{editing?.name}» исчезнет из доступных локаций. Исходный скан, разметка и задания сохранятся.
|
||||
Восстановить её можно в списке удалённых локаций.</>}
|
||||
confirmLabel="Удалить" pendingLabel="Удаляем" onClose={() => {if (!busy) setConfirming(false);}}
|
||||
onConfirm={async () => {if (editing) await update(editing, {removed:true});}}/>
|
||||
<ConfirmationModal open={!!editing && confirming} title={editing?.local_scene?"Удалить локацию полностью?":"Скрыть локацию?"} danger
|
||||
description={editing?.local_scene?<>«{editing.name}»: обработка будет остановлена, исходные файлы и результаты удалены на Worker и на этом компьютере. Общие файлы других локаций сохранятся. Отменить удаление нельзя.</>:<>«{editing?.name}» будет скрыта из каталога. Эта старая локация хранит данные в отдельном контуре симулятора; скрытие не удаляет файлы. Восстановление доступно в списке скрытых локаций.</>}
|
||||
confirmLabel={editing?.local_scene?"Удалить полностью":"Скрыть"} pendingLabel="Удаляем" onClose={() => {if (!busy) setConfirming(false);}}
|
||||
onConfirm={async () => {
|
||||
if(!editing)return;
|
||||
if(!editing.local_scene){await update(editing,{removed:true});return;}
|
||||
setBusy(editing.world_id);setError(null);
|
||||
try{await deleteLocation(editing.local_scene.project_id);setConfirming(false);setEditing(null);await onChanged();}
|
||||
catch(caught){setError(caught instanceof Error?caught.message:"Не удалось начать удаление.");}
|
||||
finally{setBusy(null);}
|
||||
}}/>
|
||||
{error ? <ToastStack items={[{id:"location-settings",tone:"error",title:"Не удалось изменить локацию",description:error}]}
|
||||
onDismiss={() => setError(null)}/> : null}
|
||||
</>;
|
||||
|
||||
@@ -2,13 +2,16 @@ import { useEffect, useRef, useState } from "react";
|
||||
import { Button, Icon, ProgressBar, TextField, ToastStack, Window } from "@nodedc/ui-react";
|
||||
import { importAiWorld, type AiSource, type AiWorld } from "../../core/simulation/aiPolygon";
|
||||
|
||||
export function AiWorldImport({ source, resume, onClose, onImported }: {
|
||||
source: AiSource | null; resume?: AiWorld; onClose: () => void; onImported: (world: AiWorld) => void;
|
||||
import {locationImports} from "../../core/simulation/locationImports";
|
||||
import {classifySimulationSource} from "../../core/simulation/sourceFiles";
|
||||
|
||||
export function AiWorldImport({ source, resume, initialFile, onClose, onImported }: {
|
||||
source: AiSource | null; resume?: AiWorld; initialFile?: File; onClose: () => void; onImported: (world: AiWorld) => void;
|
||||
}) {
|
||||
const [draft, setDraft] = useState<AiSource>(source ?? {
|
||||
name: "", author: "", license: "", source_url: "",
|
||||
name: initialFile?.name.replace(/\.ply$/i, "") ?? "", author: "", license: "", source_url: "",
|
||||
});
|
||||
const [file, setFile] = useState<File | null>(null);
|
||||
const [file, setFile] = useState<File | null>(initialFile ?? null);
|
||||
const [pending, setPending] = useState<AiWorld | undefined>(resume);
|
||||
const [progress, setProgress] = useState(0);
|
||||
const [busy, setBusy] = useState(false);
|
||||
@@ -18,6 +21,10 @@ export function AiWorldImport({ source, resume, onClose, onImported }: {
|
||||
useEffect(() => () => controller.current?.abort(), []);
|
||||
const submit = async () => {
|
||||
if (!file || busy) return;
|
||||
if (!resume) {
|
||||
locationImports.enqueue(draft.name.trim(), Promise.resolve().then(()=>({...classifySimulationSource([{file,logicalPath:file.name}]), attribution:{author:draft.author,license:draft.license,source_url:draft.source_url}})));
|
||||
onClose(); return;
|
||||
}
|
||||
setBusy(true); setError(null);
|
||||
const abort = new AbortController(); controller.current = abort;
|
||||
try { onImported(await importAiWorld(file, draft, setProgress, abort.signal, pending, setPending)); }
|
||||
|
||||
@@ -0,0 +1,97 @@
|
||||
import {useCallback, useEffect, useState} from "react";
|
||||
import {ConfirmationModal, Description, Icon, IconButton, ProgressBar, ResourceList, ResourceRow, StatusBadge} from "@nodedc/ui-react";
|
||||
import {locationImports, useLocationImports} from "../../core/simulation/locationImports";
|
||||
import {deleteLocation, useLocationDeletions} from "../../core/simulation/locationDeletions";
|
||||
import {estimateSimulationProcessing, fetchSimulationProjects, retrySimulationProject, type SimulationProject} from "../../core/simulation/projects";
|
||||
|
||||
type DeletionTarget={name:string;taskId?:string;projectId?:string};
|
||||
|
||||
/** Pending source rows stay visible before the world is admitted to the location catalog. */
|
||||
export function SimulationImports({worldIds}:{worldIds:string[]}) {
|
||||
const tasks=useLocationImports();
|
||||
const [projects,setProjects]=useState<SimulationProject[]>([]), [error,setError]=useState<string|null>(null);
|
||||
const [target,setTarget]=useState<DeletionTarget|null>(null);
|
||||
const refresh=useCallback(async()=>{
|
||||
const started=performance.now(),rows=await fetchSimulationProjects();
|
||||
setProjects(rows);locationImports.reconcile(rows.map(row=>row.projectId),started);
|
||||
},[]);
|
||||
const deletions=useLocationDeletions(refresh);
|
||||
useEffect(()=>{
|
||||
const abort=new AbortController();let timer:ReturnType<typeof setTimeout>;
|
||||
const poll=async()=>{
|
||||
try {const started=performance.now(),rows=await fetchSimulationProjects(abort.signal);
|
||||
if(!abort.signal.aborted){setProjects(rows);locationImports.reconcile(rows.map(row=>row.projectId),started);setError(null);}}
|
||||
catch(caught){if(!abort.signal.aborted)setError(caught instanceof Error?caught.message:"Нет обновлений импорта.");}
|
||||
if(!abort.signal.aborted)timer=setTimeout(()=>void poll(),2000);
|
||||
};
|
||||
void poll();return()=>{abort.abort();clearTimeout(timer);};
|
||||
},[]);
|
||||
useEffect(()=>{
|
||||
for(const task of tasks)if(task.phase==="submitted" && worldIds.includes(task.project?.projectId.replace("sim-","aiworld-")??""))locationImports.forget(task.id);
|
||||
},[tasks,worldIds]);
|
||||
const taskProjects=new Set(tasks.map(task=>task.project?.projectId));
|
||||
const deletingIds=new Set(deletions.map(row=>row.project_id));
|
||||
const pending=projects.filter(project=>project.status!=="ready"&&!taskProjects.has(project.projectId)&&!deletingIds.has(project.projectId));
|
||||
const pendingDeletions=deletions.filter(row=>!taskProjects.has(row.project_id)&&!worldIds.includes(row.project_id.replace("sim-","aiworld-")));
|
||||
if(!tasks.length&&!pending.length&&!pendingDeletions.length&&!error)return null;
|
||||
const retry=async(project:SimulationProject)=>{
|
||||
try {await retrySimulationProject(project.projectId);setProjects(await fetchSimulationProjects());}
|
||||
catch(caught){setError(caught instanceof Error?caught.message:"Не удалось продолжить обработку.");}
|
||||
};
|
||||
const trash=(item:DeletionTarget)=><IconButton label={"Удалить импорт "+item.name} onClick={()=>setTarget(item)}><Icon name="trash"/></IconButton>;
|
||||
return <section className="simulation-imports" aria-label="Импорт локаций">
|
||||
<ResourceList>
|
||||
{tasks.map(task=>{
|
||||
const project=projects.find(row=>row.projectId===task.project?.projectId)??task.project;
|
||||
const serverPhase=task.phase==="submitted"&&project?projectProgress(project):null;
|
||||
const failure=task.error??serverPhase?.error;
|
||||
const label=failure??(task.phase==="deleting"?(deletions.find(row=>row.project_id===task.project?.projectId)?.error??"Удаление импорта"):task.phase==="checking"?"Проверка файла":task.phase==="waiting"?"В очереди загрузки":task.phase==="uploading"?
|
||||
(task.progress===1?"Проверка и сохранение исходного файла":"Загрузка"):serverPhase?.label??"Обновление каталога");
|
||||
return <li key={task.id}><ImportRow name={task.name} label={label} value={task.deleteRequested?undefined:serverPhase?.value??task.progress} failed={!!failure}
|
||||
actions={task.phase==="deleting"?undefined:<>
|
||||
{failure&&!task.deleteRequested?(locationImports.canRetry(task.id)?
|
||||
<IconButton label={"Повторить импорт "+task.name} onClick={()=>locationImports.retry(task.id)}><Icon name="refresh"/></IconButton>:
|
||||
project?<IconButton label={"Повторить обработку "+task.name} onClick={()=>void retry(project)}><Icon name="refresh"/></IconButton>:null):null}
|
||||
{failure&&!project&&!task.deleteRequested?<IconButton label={"Убрать ошибку "+task.name} onClick={()=>locationImports.forget(task.id)}><Icon name="close"/></IconButton>:
|
||||
trash({name:task.name,taskId:task.id})}
|
||||
</>}/></li>;
|
||||
})}
|
||||
{pending.map(project=>{const progress=projectProgress(project);return <li key={project.projectId}>
|
||||
<ImportRow name={project.name} {...progress} failed={!!progress.error} label={progress.error??progress.label}
|
||||
actions={<>{project.status==="failed"?<IconButton label={`Повторить обработку ${project.name}`} onClick={()=>void retry(project)}><Icon name="refresh"/></IconButton>:null}{trash({name:project.name,projectId:project.projectId})}</>}/>
|
||||
</li>;})}
|
||||
{pendingDeletions.map(row=><li key={row.project_id}><ImportRow name={row.name} label={row.error??"Удаление локации"} failed={false}/></li>)}
|
||||
</ResourceList>
|
||||
{error?<Description role="alert">{error}</Description>:null}
|
||||
<ConfirmationModal open={!!target} title="Удалить импорт полностью?" danger confirmLabel="Удалить полностью" pendingLabel="Останавливаем импорт"
|
||||
description={<>«{target?.name}»: загрузка и обработка будут остановлены. Исходные файлы и результаты этой локации будут удалены на Worker и на этом компьютере. Общие файлы других локаций сохранятся.</>}
|
||||
onClose={()=>setTarget(null)} onConfirm={async()=>{
|
||||
if(!target)return;
|
||||
try {
|
||||
if(target.taskId)await locationImports.remove(target.taskId);
|
||||
else if(target.projectId)await deleteLocation(target.projectId);
|
||||
setTarget(null);await refresh();
|
||||
} catch(caught){setError(caught instanceof Error?caught.message:"Не удалось начать удаление.");}
|
||||
}}/>
|
||||
</section>;
|
||||
}
|
||||
|
||||
function ImportRow({name,label,value,failed,actions}:{name:string;label:string;value?:number;failed:boolean;actions?:React.ReactNode}){
|
||||
return <ResourceRow title={name} icon={<Icon name="globe"/>}
|
||||
status={<StatusBadge tone={failed?"danger":"warning"} pulse={!failed}>{failed?"Ошибка импорта":"Импорт"}</StatusBadge>}
|
||||
actions={<><div className="simulation-imports__progress" role={failed?"alert":"status"}>
|
||||
{!failed?<ProgressBar label={label} value={value}/>:null}<Description>{label}{!failed&&value!==undefined?` · ${Math.floor(value*100)}%`:""}</Description>
|
||||
</div>{actions}</>}/>;
|
||||
}
|
||||
|
||||
function projectProgress(project:SimulationProject):{label:string;value?:number;error?:string}{
|
||||
if(project.status==="failed")return {label:"Ошибка обработки",error:project.error??"Обработка не завершена."};
|
||||
if(project.status==="uploading")return {label:"Загрузка исходника не завершена",value:project.source.uploadedByteLength/project.source.totalByteLength};
|
||||
if(project.status==="queued")return {label:"Ожидание обработки"};
|
||||
if(project.status==="ready")return {label:"Готово",value:1};
|
||||
if(project.status==="importing")return {label:"Получение готовой локации"};
|
||||
const label:Record<string,string>={verifying_source:"Проверка исходника",inspecting:"Анализ локации",building_preview:"Конвертация превью",building_streamed_sog:"Конвертация уровней детализации",building_collision:"Подготовка коллизий"};
|
||||
const estimate=estimateSimulationProcessing(project);
|
||||
const eta=estimate?.estimatedSecondsRemaining;
|
||||
return {label:(label[project.provider.state??""]??"Обработка локации")+(eta?` · осталось ≈ ${Math.max(1,Math.ceil(eta/60))} мин`:""),value:estimate?estimate.percent/100:undefined};
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
import {useState} from "react";
|
||||
import {Button, Description, Icon, IconButton, ToastStack, Window} from "@nodedc/ui-react";
|
||||
import {polygonRequest} from "../../core/simulation/aiPolygon";
|
||||
|
||||
type OriginalFile={name:string;byte_length:number;url:string};
|
||||
export function SimulationOriginalDownload({worldId,name}:{worldId:string;name:string}){
|
||||
const [files,setFiles]=useState<OriginalFile[]|null>(null),[error,setError]=useState<string|null>(null),[busy,setBusy]=useState(false);
|
||||
const download=(file:OriginalFile)=>{window.location.assign(file.url);setFiles(null);};
|
||||
const open=async()=>{
|
||||
setBusy(true);setError(null);
|
||||
try {const result=await polygonRequest<{files:OriginalFile[]}>(`/worlds/${worldId}/originals`);
|
||||
if(result.files.length===1)download(result.files[0]);else setFiles(result.files);
|
||||
}catch(caught){setError(caught instanceof Error?caught.message:"Исходник недоступен.");}
|
||||
finally{setBusy(false);}
|
||||
};
|
||||
return <><IconButton label={`Скачать исходник ${name}`} disabled={busy} onClick={()=>void open()}><Icon name="download"/></IconButton>
|
||||
<Window open={!!files} title={`Исходные файлы · ${name}`} onClose={()=>setFiles(null)}>
|
||||
<Description>Выберите файл для скачивания.</Description>
|
||||
{files?.map(file=><Button key={file.url} onClick={()=>download(file)}>{file.name}</Button>)}
|
||||
</Window>
|
||||
{error?<ToastStack items={[{id:"original-download",tone:"error",title:"Исходник недоступен",description:error}]} onDismiss={()=>setError(null)}/>:null}
|
||||
</>;
|
||||
}
|
||||
@@ -11,26 +11,29 @@ import {
|
||||
} from "@nodedc/ui-react";
|
||||
|
||||
import {
|
||||
createAndUploadSimulationProject,
|
||||
updateSimulationProject,
|
||||
type SimulationProject,
|
||||
type SimulationSceneType,
|
||||
type SimulationUploadCandidate,
|
||||
type SimulationUploadProgress,
|
||||
} from "../../core/simulation/projects";
|
||||
import {
|
||||
candidatesFromDrop,
|
||||
validateSimulationCandidates,
|
||||
classifySimulationSource,
|
||||
} from "../../core/simulation/sourceFiles";
|
||||
|
||||
import { locationImports } from "../../core/simulation/locationImports";
|
||||
|
||||
export function SimulationProjectWindow({
|
||||
open,
|
||||
project,
|
||||
initialCandidates,
|
||||
onClose,
|
||||
onSaved,
|
||||
}: {
|
||||
open: boolean;
|
||||
project: SimulationProject | null;
|
||||
initialCandidates?: SimulationUploadCandidate[];
|
||||
onClose: () => void;
|
||||
onSaved: (project: SimulationProject) => void;
|
||||
}) {
|
||||
@@ -41,7 +44,6 @@ export function SimulationProjectWindow({
|
||||
const [candidates, setCandidates] = useState<SimulationUploadCandidate[]>([]);
|
||||
const [dragging, setDragging] = useState(false);
|
||||
const [pending, setPending] = useState(false);
|
||||
const [progress, setProgress] = useState<SimulationUploadProgress | null>(null);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
@@ -49,10 +51,16 @@ export function SimulationProjectWindow({
|
||||
setName(project?.name ?? "");
|
||||
setSceneType(project?.sceneType ?? "outdoor");
|
||||
setCandidates([]);
|
||||
setProgress(null);
|
||||
setPending(false);
|
||||
setError(null);
|
||||
}, [open, project]);
|
||||
if (!project && initialCandidates?.length) {
|
||||
try {
|
||||
validateSimulationCandidates(initialCandidates);
|
||||
setCandidates(initialCandidates);
|
||||
setName(candidateName(initialCandidates));
|
||||
} catch (caught) {setError(caught instanceof Error ? caught.message : "Источник не принят.");}
|
||||
}
|
||||
}, [open, project, initialCandidates]);
|
||||
|
||||
const sourceSummary = useMemo(() => summarizeCandidates(candidates), [candidates]);
|
||||
const canSubmit = name.trim().length > 0 && (project !== null || candidates.length > 0) && !pending;
|
||||
@@ -63,9 +71,7 @@ export function SimulationProjectWindow({
|
||||
setCandidates(next);
|
||||
setError(null);
|
||||
if (!name.trim() && next.length) {
|
||||
const named = next.find((candidate) => /\.lcc2?$/i.test(candidate.logicalPath)) ?? next[0];
|
||||
const first = named?.logicalPath.split("/").filter(Boolean).at(-1) ?? "Новая сцена";
|
||||
setName(first.replace(/\.(lcc2?|zip|rar|7z)$/i, ""));
|
||||
setName(candidateName(next));
|
||||
}
|
||||
} catch (caught) {
|
||||
setCandidates([]);
|
||||
@@ -75,17 +81,15 @@ export function SimulationProjectWindow({
|
||||
|
||||
const submit = async () => {
|
||||
if (!canSubmit) return;
|
||||
if (!project) {
|
||||
locationImports.enqueue(name, Promise.resolve({...classifySimulationSource(candidates), sceneType}));
|
||||
onClose();
|
||||
return;
|
||||
}
|
||||
setPending(true);
|
||||
setError(null);
|
||||
try {
|
||||
const saved = project
|
||||
? await updateSimulationProject(project.projectId, name, sceneType)
|
||||
: await createAndUploadSimulationProject(
|
||||
name,
|
||||
sceneType,
|
||||
candidates,
|
||||
setProgress,
|
||||
);
|
||||
const saved = await updateSimulationProject(project.projectId, name, sceneType);
|
||||
onSaved(saved);
|
||||
} catch (caught) {
|
||||
setError(caught instanceof Error ? caught.message : "Не удалось сохранить проект.");
|
||||
@@ -213,33 +217,15 @@ export function SimulationProjectWindow({
|
||||
</div>
|
||||
</FieldFrame>
|
||||
) : null}
|
||||
{progress ? (
|
||||
<div className="simulation-upload-progress" role="status">
|
||||
<span><i style={{ width: `${Math.min(100, progress.totalBytes ? progress.uploadedBytes / progress.totalBytes * 100 : 0)}%` }} /></span>
|
||||
<div>
|
||||
<strong>
|
||||
{formatBytes(progress.uploadedBytes)} / {formatBytes(progress.totalBytes)}
|
||||
{" · "}{formatUploadEta(progress.estimatedSecondsRemaining)}
|
||||
</strong>
|
||||
<small>{progress.currentPath}</small>
|
||||
</div>
|
||||
</div>
|
||||
) : null}
|
||||
{error ? <p className="simulation-project-window__error" role="alert">{error}</p> : null}
|
||||
</div>
|
||||
</Window>
|
||||
);
|
||||
}
|
||||
|
||||
function formatUploadEta(seconds: number | null): string {
|
||||
if (seconds === 0) return "загружено";
|
||||
if (seconds === null) return "считаем время";
|
||||
if (seconds < 60) return `осталось ≈ ${Math.max(1, seconds)} сек`;
|
||||
const minutes = Math.ceil(seconds / 60);
|
||||
if (minutes < 60) return `осталось ≈ ${minutes} мин`;
|
||||
const hours = Math.floor(minutes / 60);
|
||||
const remainder = minutes % 60;
|
||||
return `осталось ≈ ${hours} ч${remainder ? ` ${remainder} мин` : ""}`;
|
||||
function candidateName(candidates: SimulationUploadCandidate[]): string {
|
||||
const named = candidates.find(candidate => /\.lcc2?$/i.test(candidate.logicalPath)) ?? candidates[0];
|
||||
return (named?.logicalPath.split("/").filter(Boolean).at(-1) ?? "Новая сцена").replace(/\.(lcc2?|zip|rar|7z)$/i, "");
|
||||
}
|
||||
|
||||
function summarizeCandidates(candidates: SimulationUploadCandidate[]): { title: string; detail: string } {
|
||||
|
||||
@@ -1,15 +1,24 @@
|
||||
import { useEffect, useState } from "react";
|
||||
import { Description, Button, LoadingRegion, Window } from "@nodedc/ui-react";
|
||||
import { fetchSimulationProjects, retrySimulationProject, type SimulationProject } from "../../core/simulation/projects";
|
||||
import { useEffect, useState, type ReactNode } from "react";
|
||||
import { createPortal } from "react-dom";
|
||||
import { Description, Button, GlassMaterialSurface, Icon, IconButton, LoadingRegion, Window } from "@nodedc/ui-react";
|
||||
import { fetchSimulationProjects, retrySimulationProject, type SimulationProject, type SimulationUploadCandidate } from "../../core/simulation/projects";
|
||||
import { SIMULATION_IMPORT_FORMATS } from "../../core/simulation/sourceFiles";
|
||||
import { useSimulationFileDrop } from "../../core/simulation/useSimulationFileDrop";
|
||||
import { importDroppedLocation } from "../../core/simulation/locationImports";
|
||||
import { SimulationProjectWindow } from "./SimulationProjectWindow";
|
||||
|
||||
/** Reuses the existing resumable Gaussian Pipeline admission workflow. */
|
||||
export function SimulationSourceImport({open,onClose,onPly,onReady}: {
|
||||
open:boolean; onClose:()=>void; onPly:()=>void; onReady:(worldId:string)=>void;
|
||||
export function SimulationSourceImport({children,headerToolsHost,disabled=false,onPly,onReady}: {
|
||||
children:ReactNode; headerToolsHost?:HTMLElement|null; disabled?:boolean;
|
||||
onPly:(file?:File)=>void; onReady:(worldId:string)=>void;
|
||||
}) {
|
||||
const [archive,setArchive]=useState(false), [project,setProject]=useState<SimulationProject|null>(null);
|
||||
const [open,setOpen]=useState(false);
|
||||
const [archive,setArchive]=useState<{candidates?:SimulationUploadCandidate[]}|null>(null), [project,setProject]=useState<SimulationProject|null>(null);
|
||||
const [error,setError]=useState<string|null>(null);
|
||||
const [pending,setPending]=useState<SimulationProject[]>([]);
|
||||
const drop=useSimulationFileDrop(importDroppedLocation,!disabled&&!open&&!archive&&!project);
|
||||
const importAction=<IconButton label="Импорт локации" disabled={disabled||!!archive||open}
|
||||
onClick={()=>setOpen(true)}><Icon name="plus"/></IconButton>;
|
||||
useEffect(()=>{
|
||||
if(!open)return;
|
||||
const abort=new AbortController();setError(null);
|
||||
@@ -33,21 +42,28 @@ export function SimulationSourceImport({open,onClose,onPly,onReady}: {
|
||||
};
|
||||
void poll();return()=>{abort.abort();clearTimeout(timer);};
|
||||
},[project?.projectId,project?.status]);
|
||||
return <>
|
||||
<Window open={open} title="Импорт локации" onClose={onClose}><div className="ai-polygon__actions">
|
||||
<Button onClick={()=>{onClose();onPly();}}>Gaussian PLY</Button>
|
||||
<Button onClick={()=>{onClose();setArchive(true);}}>Архив или папка LCC</Button>
|
||||
return <div className="ai-polygon" {...drop.handlers}>
|
||||
{headerToolsHost?createPortal(importAction,headerToolsHost):<div className="ai-polygon__import-action">{importAction}</div>}
|
||||
{children}
|
||||
{drop.active?<GlassMaterialSurface context="floating" radius="panel" className="simulation-import-overlay" role="status">
|
||||
<Icon name="upload"/><strong>Отпустите файл или папку, чтобы добавить локацию</strong>
|
||||
<Description>{SIMULATION_IMPORT_FORMATS}</Description>
|
||||
<Description>Одна локация за раз. Проверка и импорт начнутся автоматически.</Description>
|
||||
</GlassMaterialSurface>:null}
|
||||
<Window open={open} title="Импорт локации" onClose={()=>setOpen(false)}><div className="ai-polygon__actions">
|
||||
<Button onClick={()=>{setOpen(false);onPly();}}>Gaussian PLY</Button>
|
||||
<Button onClick={()=>{setOpen(false);setArchive({});}}>Архив или папка LCC</Button>
|
||||
</div>
|
||||
{pending.map(p=><div key={p.projectId} className="ai-polygon__row"><Description>{p.name}</Description>
|
||||
<Button onClick={()=>{onClose();setError(null);setProject(p);}}>Подготовка локации</Button></div>)}
|
||||
<Button onClick={()=>{setOpen(false);setError(null);setProject(p);}}>Подготовка локации</Button></div>)}
|
||||
{error?<Description role="alert">{error}</Description>:null}
|
||||
</Window>
|
||||
<SimulationProjectWindow open={archive} project={null} onClose={()=>setArchive(false)} onSaved={p=>{setArchive(false);setProject(p);}} />
|
||||
<SimulationProjectWindow open={!!archive} initialCandidates={archive?.candidates} project={null} onClose={()=>setArchive(null)} onSaved={p=>{setArchive(null);setProject(p);}} />
|
||||
{project?<Window open title={`Подготовка ${project.name}`} onClose={()=>setProject(null)}>
|
||||
<LoadingRegion loading={project.status!=='failed'&&!error} label="Подготовка локации">
|
||||
<Description>{error??project.error??'Локация появится в общей библиотеке после подготовки.'}</Description>
|
||||
{project.status==='failed'?<Button onClick={()=>void retrySimulationProject(project.projectId).then(setProject).catch(e=>setError(e.message))}>Повторить подготовку</Button>:null}
|
||||
</LoadingRegion>
|
||||
</Window>:null}
|
||||
</>;
|
||||
</div>;
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user