Compare commits
74
Commits
ab8e977f11
..
main
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
1b67d5f7df | ||
|
|
d4ed96f3cd | ||
|
|
43d4916331 | ||
|
|
a50d638ced | ||
|
|
3ff43dd2af | ||
|
|
bed1db3508 | ||
|
|
3d04fa45d3 | ||
|
|
1635299252 | ||
|
|
22f262ca59 | ||
|
|
c45bd6b882 | ||
|
|
bd8af772d9 | ||
|
|
e26582fc75 | ||
|
|
e9527060f6 | ||
|
|
56d89197a8 | ||
|
|
29ef038a43 | ||
|
|
9cbdd4ea5c | ||
|
|
b1533ce0ea | ||
|
|
f4b506d593 | ||
|
|
a3781bcf4b | ||
|
|
a3927ce846 | ||
|
|
0a29522f2f | ||
|
|
7c0dbd4e06 | ||
|
|
9871ae500f | ||
|
|
a80e3a8ff5 | ||
|
|
a5e4fba807 | ||
|
|
996ce7efdf | ||
|
|
0f97f79216 | ||
|
|
8aeb5b3fd2 | ||
|
|
958e9c396d | ||
|
|
778a558a34 | ||
|
|
4a8fffb418 | ||
|
|
6911da71d8 | ||
|
|
87c0c7960a | ||
|
|
b96bea1599 | ||
|
|
136be019af | ||
|
|
e8e450e93a | ||
|
|
28cb2e49a4 | ||
|
|
c6280525ba | ||
|
|
4002ae4c96 | ||
|
|
71705ea862 | ||
|
|
91a18c580a | ||
|
|
8e37ef6968 | ||
|
|
1a0b5b0bd7 | ||
|
|
d88ea2de93 | ||
|
|
c785f1173f | ||
|
|
1c092ff0e3 | ||
|
|
f6e0bab559 | ||
|
|
e8920f56a2 | ||
|
|
9937eb66d8 | ||
|
|
cd27a5e483 | ||
|
|
a49fb00b8e | ||
|
|
58ac9fe3d2 | ||
|
|
800518ea80 | ||
|
|
1317f78672 | ||
|
|
a724a9796a | ||
|
|
4d0306f353 | ||
|
|
40872d3534 | ||
|
|
1472926112 | ||
|
|
e8025bc99f | ||
|
|
ad5a929e06 | ||
|
|
fe5900ff3b | ||
|
|
cd34b6ce1a | ||
|
|
7595bea07c | ||
|
|
ab5766df6a | ||
|
|
43148a8769 | ||
|
|
09c13a5c68 | ||
|
|
b0332fa377 | ||
|
|
d5f35e4a74 | ||
|
|
14e6426cd5 | ||
|
|
f228b20c2b | ||
|
|
55e1ab8d1c | ||
|
|
5f8ed0d94c | ||
|
|
c9d79456ef | ||
|
|
42213001ba |
@@ -5,6 +5,17 @@ real device plugin investigates an owner-controlled XGRIDS/LixelKity K1 as a
|
||||
black-box sensor. Preserve the device, the host, the working LAN, raw evidence,
|
||||
and the boundary between Mission Core and vendor-specific integration code.
|
||||
|
||||
- Owner clarification (2026-11-08): LAB trash means permanent deletion of that
|
||||
LAB's admitted files on Core and Worker, followed by removal from history.
|
||||
Do not replace it with catalog-only hiding or leave unreachable result bytes.
|
||||
Source recordings and files shared by retained LABs are separate owners.
|
||||
Worker acknowledgement is mandatory; on failure keep a retryable history row.
|
||||
Local-copy expiry/delete is a separate action that preserves history and Worker
|
||||
results. Pin protects against expiry, not explicit full-LAB deletion.
|
||||
A LAB module/registered component, its model, benchmark and shared inputs are
|
||||
not disposable run output. Missing UI history alone is never evidence of junk;
|
||||
establish ownership and dependencies before retiring an old experiment.
|
||||
|
||||
## Single working directory — owner requirement, 2026-10-08
|
||||
|
||||
The governing Ops record is [MISSIONCOR-50 — Фундаментальная архитектура Mission Core](https://ops.nodedc.ru/nodedc/browse/MISSIONCOR-50),
|
||||
@@ -33,6 +44,12 @@ links to that record for monorepo, storage, resource and live-only telemetry rul
|
||||
terminal, close only your own hold with `finish` (pin qualified/rollback
|
||||
outcomes), review its plan and apply it as part of build completion. Never
|
||||
expire active holds by age or declare unknown legacy inputs disposable.
|
||||
- Node/X4 owner installers close out their exact unpacked `.deb` duplicates via
|
||||
`scripts/packaging/qualified_payloads.py` after durable publication and full
|
||||
hash verification. Keep the installer and `PAYLOAD_LOCATION.json`. Register a
|
||||
persistent payload hold before a dependent consumer needs loose files; release
|
||||
it only after that consumer ends. Read retired payloads through the helper,
|
||||
not by leaving another permanent extracted copy. See `docs/STORAGE_RETENTION.md`.
|
||||
- Run local Python validation through `scripts/check_python.py pytest|ruff|mypy`
|
||||
(pass the usual file/selection arguments). It owns temporary caches, disables
|
||||
persistent pytest/Ruff cache output, and cleans its own scratch after child
|
||||
@@ -75,6 +92,55 @@ links to that record for monorepo, storage, resource and live-only telemetry rul
|
||||
retain the immutable algorithm result and human provenance separately.
|
||||
See `docs/SEMANTIC_EDITOR.md` for the delivered scope and outstanding gates.
|
||||
|
||||
## LAB placement — owner clarification, 2026-11-08
|
||||
|
||||
All supported laboratory execution, raw inputs, intermediate arrays and heavy
|
||||
working directories belong to the portable Worker runtime. The operator Core is
|
||||
a viewport: retain ready visual products, semantic maps/manual edits and bounded
|
||||
metadata, never a silent local compute fallback. See
|
||||
`docs/LAB_AND_INSTALLER_STORAGE.md` and `deploy/laboratory/README.md`.
|
||||
|
||||
Canonical Ops policy: [MISSIONCOR-97 — Storage rules](https://ops.nodedc.ru/nodedc/browse/MISSIONCOR-97).
|
||||
Read its current rules before a new LAB/AI data producer or storage migration;
|
||||
keep current implementation distinct from the dated distributed-storage research.
|
||||
|
||||
A LAB viewing result means a full playable recording with synchronized
|
||||
segmentation/camera frames, 3D cuboids and timeline where the experiment provides
|
||||
those layers. Catalog JSON, a screenshot or a textual report does not establish
|
||||
playback acceptance. Preserve the current UI; do not add neural/narrative reports
|
||||
or redesign LAB as part of storage migration. Later owner clarification on
|
||||
8 November explicitly adds global Storage settings (configurable local LAB-copy
|
||||
retention), offline pins, actual local availability and removal of local copies.
|
||||
Run history must remain discoverable independently of replay compatibility or
|
||||
local cache presence. These are requirements, not features already implemented
|
||||
by the storage audit; see `outputs/storage-fresh-audit-20261108/REPORT.md`.
|
||||
Verify real playback before retiring local working data; preserve accepted
|
||||
recordings, Gaussians, semantic edits and original captures.
|
||||
|
||||
The configurable LAB-copy TTL (default 30 days) applies exclusively to unpinned
|
||||
local viewing copies in Mission Core, never to Worker experiments or their models.
|
||||
Integrated/experimental model assets, installed executor packages/images, runtime
|
||||
environments and experimental configurations are retained until a separate owner
|
||||
decision consolidates the pipeline, even under `cache` or `derived`. Do not apply
|
||||
LAB-copy TTL or absence-from-UI cleanup to them. A disposable transport package
|
||||
means job input/output transfer bytes, not an executor/model distribution. Before retiring an intermediate
|
||||
copy, verify publication/retry readers, shared owners and restoration of its exact
|
||||
identity. See the 8 November intermediate-store rules in
|
||||
`docs/STORAGE_RETENTION.md` and `outputs/intermediate-storage-review-20261108/REPORT.md`.
|
||||
|
||||
Portable source/result transfer uses shared physical-disk reservations (2 GiB
|
||||
free reserve), not fixed 8/4 GiB directory ceilings or model-count limits.
|
||||
Source copies registered by admitted producers retire only after durable queue
|
||||
consumers finish and exact originals remain available. HTTP reader locks span the
|
||||
whole response. Preserve unknown paths, changed originals, shared filesystem
|
||||
owners and pending publication/reconciliation. Source retirement is not a TTL.
|
||||
Result closeout retains manifest/receipt for archive-backed retries; do not
|
||||
readmit retired compute definitions merely to retire historical copies.
|
||||
Use an explicit target allowlist for one-time historical cleanup and verify
|
||||
unselected files; unknown old copies are not automatically adopted by a scan.
|
||||
These rules do not change installed model/executor assets or viewing-copy TTL.
|
||||
See the 9 November transfer lifecycle section of `docs/STORAGE_RETENTION.md`.
|
||||
|
||||
## Non-negotiable safety boundaries
|
||||
|
||||
- Default to non-mutating discovery or read-only operations. CoreBluetooth BLE
|
||||
@@ -280,12 +346,21 @@ decoders before BLE/Wi-Fi/data-session evidence exists.
|
||||
- The compact summary must explain the decision question, immutable source,
|
||||
tested method/models/algorithms, experimental mode, principal result,
|
||||
limitations, and retained authority. It is not the engineering report.
|
||||
- Owner reporting rule (2026-10-09): Ops contains concise, verified delivered
|
||||
results only: what works, the implementation used, and its accepted scope.
|
||||
Keep intermediate experiments, failed attempts, architecture proposals,
|
||||
detailed logs and future plans in local engineering evidence, not Ops.
|
||||
Consolidate superseded intermediate blocks instead of appending a run diary.
|
||||
Never present a partial experiment as a completed product result.
|
||||
- Owner reporting rule (2026-10-09), clarified 2026-11-04: keep current Ops
|
||||
summaries concise and evidence-backed: what works, implementation and accepted
|
||||
scope. Replace or remove obsolete assertions about the current state.
|
||||
Preserve decision-relevant dated experiments: capability/limit findings, tested
|
||||
alternatives and consequential failures that explain a decision or prevent
|
||||
repeating a dead end. Keep the method/conditions, outcome, limitation, decision
|
||||
and evidence reference separate from current state. Age alone does not make
|
||||
useful evidence disposable. Do not retain every attempt, intermediate UI edit,
|
||||
routine check or duplicate metric merely for history; consolidate nonessential
|
||||
detail and keep traces local. A local backup alone does not preserve important
|
||||
experiment findings in Ops. Annotate disproved interpretations without erasing
|
||||
their observations; never invent why an untested option was rejected.
|
||||
Raw logs/media, credentials and secret fields remain in private evidence;
|
||||
proposals remain explicitly unverified. Never present a partial experiment as
|
||||
a completed product result. Follow the ops-context skill for card updates.
|
||||
- Spatial evidence uses 3D by default. Image-space reprojection may be offered
|
||||
as a 2D diagnostic mode inside the same reusable viewer. Primary evidence
|
||||
viewers must provide the canonical expand/restore action.
|
||||
@@ -326,3 +401,24 @@ decoders before BLE/Wi-Fi/data-session evidence exists.
|
||||
unchanged searches or model variants under a new name.
|
||||
- Worker access/power/runtime authority comes from the owner's current session
|
||||
instructions, never from the card or an old experiment's training allowance.
|
||||
|
||||
|
||||
## Scene profile persistence — owner requirement, 2026-11-09
|
||||
|
||||
- Rover/battery materials, imported textures, scene/environment profiles, camera
|
||||
pose, editor-window layout and battery UI/view settings are durable Core JSON
|
||||
configuration. Use `data_dir/scene-profiles/.../meta.json`; never make browser
|
||||
IndexedDB/localStorage their sole authority. Do not classify these files or
|
||||
their recovery copies as cache or task scratch.
|
||||
- Legacy browser records may be read once only when the Core document is absent.
|
||||
A failed read must not save defaults over user settings. Preserve source data
|
||||
during migration/recovery; use atomic replacement, previous-version backup and
|
||||
revision checks so a stale tab cannot silently replace a newer profile.
|
||||
- Recover actual settings from retained JSON/records before considering manual
|
||||
reconstruction. Distinguish a proven storage defect from an unproven deletion
|
||||
trigger, and state the timestamp/fidelity limit of any recovered source.
|
||||
|
||||
|
||||
## Enforced compact typography
|
||||
|
||||
Operational values/section headings use md (13 px), explanatory/status/error copy uses Description/sm (12 px). Only canonical window/page title roles use title (18 px). Do not add browser-default paragraphs, local larger sizes, font shorthand or inline fontSize. Typography checks are mandatory build gates; never extend the frozen compact legacy baseline or generalize scene/display exceptions to satisfy a feature. Run the typography contract tests and verify computed sizes in centered/floating and narrow windows. See Design Guideline docs/OPERATIONAL_TYPOGRAPHY.md.
|
||||
|
||||
Generated
+17
-5
@@ -10,6 +10,7 @@
|
||||
"hasInstallScript": true,
|
||||
"dependencies": {
|
||||
"@noble/hashes": "^2.2.0",
|
||||
"@nodedc/bim-viewer": "file:../../vendor/bim/nodedc-bim-viewer-0.2.86.tgz",
|
||||
"@nodedc/map-cesium-react": "file:../../../NODEDC_DESIGN_GUIDELINE/packages/map-cesium-react",
|
||||
"@nodedc/page-patterns": "file:../../../NODEDC_DESIGN_GUIDELINE/packages/page-patterns",
|
||||
"@nodedc/tokens": "file:../../../NODEDC_DESIGN_GUIDELINE/packages/tokens",
|
||||
@@ -41,9 +42,9 @@
|
||||
},
|
||||
"../../../NODEDC_DESIGN_GUIDELINE/packages/map-cesium-react": {
|
||||
"name": "@nodedc/map-cesium-react",
|
||||
"version": "0.1.0",
|
||||
"version": "0.1.4",
|
||||
"dependencies": {
|
||||
"cesium": "1.143.0"
|
||||
"cesium": "1.147.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/react": "^19.1.0",
|
||||
@@ -63,19 +64,19 @@
|
||||
},
|
||||
"../../../NODEDC_DESIGN_GUIDELINE/packages/ui-core": {
|
||||
"name": "@nodedc/ui-core",
|
||||
"version": "0.7.0",
|
||||
"version": "0.7.4",
|
||||
"dependencies": {
|
||||
"@nodedc/tokens": "0.6.0"
|
||||
}
|
||||
},
|
||||
"../../../NODEDC_DESIGN_GUIDELINE/packages/ui-react": {
|
||||
"name": "@nodedc/ui-react",
|
||||
"version": "0.7.0",
|
||||
"version": "0.7.10",
|
||||
"dependencies": {
|
||||
"@dnd-kit/core": "^6.3.1",
|
||||
"@dnd-kit/sortable": "^10.0.0",
|
||||
"@dnd-kit/utilities": "^3.2.2",
|
||||
"@nodedc/ui-core": "0.7.0",
|
||||
"@nodedc/ui-core": "0.7.4",
|
||||
"lucide-react": "^0.468.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
@@ -882,6 +883,17 @@
|
||||
"url": "https://paulmillr.com/funding/"
|
||||
}
|
||||
},
|
||||
"node_modules/@nodedc/bim-viewer": {
|
||||
"version": "0.2.86",
|
||||
"resolved": "file:../../vendor/bim/nodedc-bim-viewer-0.2.86.tgz",
|
||||
"integrity": "sha512-1yaWhAbEx3Y1V93b+T1HKfra7Z6hGpFL/Fhz/S6Bi+AzFMEJsQ4TpE32uVIARxN6EWJtAx3QuBlmaD8TP499IQ==",
|
||||
"peerDependencies": {
|
||||
"@nodedc/map-cesium-react": ">=0.1.4 <0.2",
|
||||
"@nodedc/ui-react": ">=0.7.10 <0.8",
|
||||
"react": ">=19 <20",
|
||||
"react-dom": ">=19 <20"
|
||||
}
|
||||
},
|
||||
"node_modules/@nodedc/map-cesium-react": {
|
||||
"resolved": "../../../NODEDC_DESIGN_GUIDELINE/packages/map-cesium-react",
|
||||
"link": true
|
||||
|
||||
@@ -6,14 +6,16 @@
|
||||
"scripts": {
|
||||
"dev": "vite",
|
||||
"postinstall": "node scripts/install-rerun-navigation.mjs",
|
||||
"prebuild": "node scripts/install-rerun-navigation.mjs",
|
||||
"prebuild": "npm run check:typography && node scripts/install-rerun-navigation.mjs",
|
||||
"build": "tsc -b && vite build",
|
||||
"preview": "vite preview",
|
||||
"test:unit": "node --test --test-concurrency=1 test/*.test.mjs",
|
||||
"typecheck": "tsc -b --pretty false"
|
||||
"typecheck": "tsc -b --pretty false",
|
||||
"check:typography": "node --test test/operationalTypography.test.mjs"
|
||||
},
|
||||
"dependencies": {
|
||||
"@noble/hashes": "^2.2.0",
|
||||
"@nodedc/bim-viewer": "file:../../vendor/bim/nodedc-bim-viewer-0.2.86.tgz",
|
||||
"@nodedc/map-cesium-react": "file:../../../NODEDC_DESIGN_GUIDELINE/packages/map-cesium-react",
|
||||
"@nodedc/page-patterns": "file:../../../NODEDC_DESIGN_GUIDELINE/packages/page-patterns",
|
||||
"@nodedc/tokens": "file:../../../NODEDC_DESIGN_GUIDELINE/packages/tokens",
|
||||
|
||||
Binary file not shown.
@@ -1,10 +1,10 @@
|
||||
{
|
||||
"source": "Cattle_Battery_Enclosure_R04.blend",
|
||||
"source_sha256": "ec802dfbc2866ab474ce5f809ea9289f2402ec791c0abccb22826620af78a42b",
|
||||
"source": "CATL_Battery_Enclosure_R05.blend",
|
||||
"source_sha256": "8a3da0abaeeabc3a006dec51e2ae5a1af8af56b3b1361772279d7766084faea3",
|
||||
"model": "catl-r04.glb",
|
||||
"sha256": "1f4ac32560ac1906abd92e7c3be35f852ce166ead700f5e27c3b3ce2bdcc7dd3",
|
||||
"bytes": 39541516,
|
||||
"groups": 63,
|
||||
"sha256": "7a01c35d7b8fac13e841053841e372170715c7b79b865f8719ab137b24d5cd20",
|
||||
"bytes": 39916192,
|
||||
"groups": 75,
|
||||
"cell_bodies": 13,
|
||||
"objects": [
|
||||
"bms/Cable / red silicone",
|
||||
@@ -61,6 +61,18 @@
|
||||
"bms/DISPLAY | black glass",
|
||||
"bms/CASE | recessed black",
|
||||
"bms/CASE | darker frame",
|
||||
"bms/FRAME | welded graphite steel/FRAME | bottom cross front",
|
||||
"bms/FRAME | welded graphite steel/FRAME | bottom cross rear",
|
||||
"bms/FRAME | welded graphite steel/FRAME | bottom longitudinal left",
|
||||
"bms/FRAME | welded graphite steel/FRAME | bottom longitudinal right",
|
||||
"bms/FRAME | welded graphite steel/FRAME | post front left",
|
||||
"bms/FRAME | welded graphite steel/FRAME | post front right",
|
||||
"bms/FRAME | welded graphite steel/FRAME | post rear left",
|
||||
"bms/FRAME | welded graphite steel/FRAME | post rear right",
|
||||
"bms/FRAME | welded graphite steel/FRAME | top cross front",
|
||||
"bms/FRAME | welded graphite steel/FRAME | top cross rear",
|
||||
"bms/FRAME | welded graphite steel/FRAME | top longitudinal left",
|
||||
"bms/FRAME | welded graphite steel/FRAME | top longitudinal right",
|
||||
"bms/CASE | bead-blasted graphite/HANDLE | folded aperture return",
|
||||
"bms/CASE | bead-blasted graphite/HANDLE | folded aperture return.001",
|
||||
"bms/CASE | bead-blasted graphite/HANDLE | integral web underside",
|
||||
@@ -108,6 +120,7 @@
|
||||
"bms/DISPLAY | black glass",
|
||||
"bms/CASE | recessed black",
|
||||
"bms/CASE | darker frame",
|
||||
"bms/FRAME | welded graphite steel",
|
||||
"bms/CASE | dielectric liner",
|
||||
"bms/Connector / gold plated contacts",
|
||||
"bms/XT90-S / anti spark green insert",
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import {SceneDisplayControls} from "../../../packages/spatial-ui/src/SceneDisplayControls";
|
||||
import {SceneLayerControls} from "../../../packages/spatial-ui/src/SceneLayerControls";
|
||||
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
|
||||
import {
|
||||
import { Description,
|
||||
AdminNavigationPanel,
|
||||
AppHeader,
|
||||
ApplicationPanel,
|
||||
@@ -9,7 +9,6 @@ import {
|
||||
Button,
|
||||
ControlRow,
|
||||
HeaderNavigation,
|
||||
HeaderProfile,
|
||||
Icon,
|
||||
Inspector,
|
||||
StatusBadge,
|
||||
@@ -51,6 +50,8 @@ import type {
|
||||
import { useRecordedSessionAdmission } from "./core/observation/useRecordedSessionAdmission";
|
||||
import { useWorkspaceLayoutProfile } from "./core/observation/useWorkspaceLayoutProfile";
|
||||
import { useSessionDisplayProfile } from "./core/observation/useSessionDisplayProfile";
|
||||
import { EventPanel } from './components/notifications/NotificationHost';
|
||||
import { useNotifications } from './core/notifications/useNotificationHistory';
|
||||
import { viewerSettingsTargetIdentity } from "./core/observation/viewerSettingsTarget";
|
||||
import { resolvePolygonRunRoute } from "./core/polygon/runArchive";
|
||||
import {
|
||||
@@ -59,6 +60,7 @@ import {
|
||||
type ObservationWorkspaceLayoutProfile,
|
||||
} from "./core/observation/workspaceLayout";
|
||||
import {
|
||||
capabilityStatusLabel,
|
||||
rootById,
|
||||
roots,
|
||||
workspaceById,
|
||||
@@ -233,6 +235,7 @@ export default function App() {
|
||||
);
|
||||
runtimeUpdateViewerSettingsRef.current = runtime.updateViewerSettings;
|
||||
replayActiveRef.current = replayPresented;
|
||||
const notifications = useNotifications();
|
||||
const sessionDisplayProfile = useSessionDisplayProfile(replayPresented ? recordedReplay?.sessionId ?? null : null, (settings) => {
|
||||
sceneSettingsRef.current = settings;
|
||||
displayDraftRef.current = settings;
|
||||
@@ -444,7 +447,7 @@ export default function App() {
|
||||
workspace.openNavigation();
|
||||
if (rootId === "system") {
|
||||
workspace.openView(
|
||||
activeDefinition?.root === "system" ? activeDefinition.id : "modules",
|
||||
activeDefinition?.id === "vps" ? "vps" : "workers",
|
||||
);
|
||||
} else {
|
||||
workspace.closeView();
|
||||
@@ -666,7 +669,7 @@ export default function App() {
|
||||
connectionScenarioResetting: runtime.pendingAction === "mode",
|
||||
saveWorkspaceLayout,
|
||||
workspaceLayoutSaving: workspaceLayoutProfile.state === "saving",
|
||||
systemUtilityActions: computeContourSettings.utilityActions,
|
||||
systemUtilityActions: [...computeContourSettings.utilityActions, {label: "К списку воркеров", icon: "chevron-left", onClick: () => openNavigationView("workers")}],
|
||||
sessionOverview: { ...sessionOverview, available: Boolean(recordedReplay && replayPresented && !sourceSwitchBlocked) },
|
||||
});
|
||||
|
||||
@@ -687,11 +690,11 @@ export default function App() {
|
||||
/>
|
||||
}
|
||||
right={
|
||||
<HeaderProfile>
|
||||
<UserProfileMenu
|
||||
displayName="DC"
|
||||
subtitle="Mission Core"
|
||||
triggerLabel={null}
|
||||
headerAction={{label: notifications.unread ? `Центр событий · непрочитанных: ${notifications.unread}` : 'Центр событий', pressed: notifications.open, controls: 'operator-events', onSelect: () => notifications.setOpen(open => !open)}}
|
||||
actions={[
|
||||
{
|
||||
id: "refresh",
|
||||
@@ -707,7 +710,6 @@ export default function App() {
|
||||
},
|
||||
]}
|
||||
/>
|
||||
</HeaderProfile>
|
||||
}
|
||||
/>
|
||||
);
|
||||
@@ -723,6 +725,8 @@ export default function App() {
|
||||
}
|
||||
contentOpen={workspace.contentOpen && activeDefinition !== null}
|
||||
contentExpanded
|
||||
endPanel={<EventPanel/>}
|
||||
endPanelOpen={notifications.open}
|
||||
header={header}
|
||||
stage={activeDefinition ? null :
|
||||
<LandingStage
|
||||
@@ -738,8 +742,8 @@ export default function App() {
|
||||
navigation={currentRoot && activeRoot === "system" ? (
|
||||
<SystemNavigationPanel
|
||||
title={currentRoot.title}
|
||||
onAdd={computeContourSettings.openCreate}
|
||||
onNavigateRoot={() => openNavigationView("modules")}
|
||||
activeId={activeDefinition?.id ?? "workers"}
|
||||
onNavigate={openNavigationView}
|
||||
onClose={workspace.closeNavigation}
|
||||
/>
|
||||
) : currentRoot ? (
|
||||
@@ -789,7 +793,7 @@ export default function App() {
|
||||
allowFullscreen={activeDefinition.kind === "vehicles"}
|
||||
eyebrow={activeDefinition.eyebrow}
|
||||
title={
|
||||
activeDefinition.kind === "vehicles"
|
||||
(activeDefinition.kind === "vehicles" || activeDefinition.kind === "architectural-projects")
|
||||
? <>{activeDefinition.title}<span className="fleet-header-title" ref={setWorkspaceHeaderTitleHost}/></>
|
||||
: activeDefinition.kind === "recordings"
|
||||
&& replayPresented
|
||||
@@ -836,7 +840,7 @@ export default function App() {
|
||||
/>
|
||||
) : activeDefinition.kind === "missions" ? (
|
||||
<div ref={setWorkspaceHeaderToolsHost} />
|
||||
) : activeDefinition.kind === "vehicles" ? <div className="fleet-header-tools" ref={setWorkspaceHeaderToolsHost} /> : activeDefinition.kind === "simulations" ? <div className="ai-polygon__actions" ref={setWorkspaceHeaderToolsHost} /> : activeDefinition.kind === "datasets" ? (
|
||||
) : activeDefinition.kind === "vehicles" || activeDefinition.kind === "architectural-projects" ? <div className="fleet-header-tools" ref={setWorkspaceHeaderToolsHost} /> : activeDefinition.kind === "simulations" ? <div className="ai-polygon__actions" ref={setWorkspaceHeaderToolsHost} /> : activeDefinition.kind === "datasets" ? (
|
||||
<StatusBadge tone="neutral">Offline evaluation</StatusBadge>
|
||||
) : activeDefinition.kind === "lab-archive" ? (
|
||||
laboratoryAnnotation.control
|
||||
@@ -844,13 +848,15 @@ export default function App() {
|
||||
<StatusBadge tone="neutral">Только наблюдение</StatusBadge>
|
||||
) : activeDefinition.kind === "contour-health" ? (
|
||||
<div ref={setWorkspaceHeaderToolsHost} />
|
||||
) : activeDefinition.kind === "workers" || activeDefinition.kind === "vps" ? (
|
||||
<div className="fleet-header-tools" ref={setWorkspaceHeaderToolsHost} />
|
||||
) : activeDefinition.root === "system" ? (
|
||||
<SystemWorkspaceSelector
|
||||
value={activeDefinition.id}
|
||||
onChange={openNavigationView}
|
||||
/>
|
||||
) : (
|
||||
<StatusBadge tone="warning">Интерфейс готов</StatusBadge>
|
||||
<StatusBadge tone={activeDefinition.status === "active" ? "success" : "warning"}>{capabilityStatusLabel[activeDefinition.status ?? "contract"]}</StatusBadge>
|
||||
)
|
||||
}
|
||||
utilityActions={contentActions}
|
||||
@@ -1108,7 +1114,7 @@ export default function App() {
|
||||
<i className="api-dot" data-status={effectiveSourceUrl ? "online" : "checking"} aria-hidden="true" />
|
||||
{effectiveSourceUrl ? "Источник назначен" : "Источник не назначен"}
|
||||
</span>
|
||||
<p>Структура повторяет продуктовые сущности, а не внутренние панели визуального движка.</p>
|
||||
<Description>Структура повторяет продуктовые сущности, а не внутренние панели визуального движка.</Description>
|
||||
</div>
|
||||
<SceneLayerControls sceneSettings={sceneSettings} pending={runtime.pendingAction === "viewer"} applyScenePatch={applyScenePatch}/>
|
||||
</Window>
|
||||
|
||||
@@ -1,5 +1,8 @@
|
||||
import { EnvironmentSettingsWindow as SharedEnvironmentSettingsWindow } from "@nodedc/ui-react";
|
||||
import { environmentSurfaceIds, type EnvironmentSettings, type EnvironmentSurfaceId, type UploadedEnvironmentMedia } from "../core/environment/environmentSettings";
|
||||
import { NetworkSettings } from "./network/NetworkSettings";
|
||||
import { CesiumServiceSettings } from "./map/CesiumServiceSettings";
|
||||
import { useLabStorageSettings } from "./storage/LabStorageSettings";
|
||||
import { roots, workspaces, workspacesForRoot } from "../productModel";
|
||||
|
||||
interface Props {
|
||||
@@ -16,7 +19,8 @@ const surfaces = environmentSurfaceIds.map(id => ({
|
||||
actions: id === "home" ? workspaces.filter(item => !item.internalOnly) : workspacesForRoot(id),
|
||||
}));
|
||||
export function EnvironmentSettingsWindow(props: Props) {
|
||||
return <SharedEnvironmentSettingsWindow {...props} productName="Mission Core" surfaces={surfaces} initialSurfaceId="fleet"
|
||||
const storage = useLabStorageSettings(props.open);
|
||||
return <SharedEnvironmentSettingsWindow {...props} productName="Mission Core" surfaces={surfaces} initialSurfaceId="fleet" additionalSections={[storage, {id: "network", label: "Сеть", icon: "network", content: props.open ? <NetworkSettings/> : null}, {id: "services", label: "Сервисы", icon: "key", content: props.open ? <CesiumServiceSettings/> : null}]}
|
||||
onSave={draft => props.onSave({ ...draft, pages: Object.fromEntries(environmentSurfaceIds.map(id => [id, draft.pages[id]])) as EnvironmentSettings["pages"] })}
|
||||
onUpload={(id, itemId, file) => {
|
||||
if (!environmentSurfaceIds.includes(id as EnvironmentSurfaceId)) throw new Error("Страница окружения недоступна.");
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { LandingStage as SharedLandingStage, StatusBadge } from "@nodedc/ui-react";
|
||||
import { Description, LandingStage as SharedLandingStage, StatusBadge } from "@nodedc/ui-react";
|
||||
|
||||
import type { BackendStatus, RuntimePhase } from "../core/runtime/contracts";
|
||||
import type { EnvironmentPage } from "../core/environment/environmentSettings";
|
||||
@@ -35,7 +35,7 @@ export function LandingStage({
|
||||
<span className="section-eyebrow">ИСТОЧНИК</span>
|
||||
<StatusBadge tone={phaseTone(phase)}>{phaseLabel(phase)}</StatusBadge>
|
||||
</div>
|
||||
<p>{message || "Выберите архитектурный блок в верхней навигации."}</p>
|
||||
<Description>{message || "Выберите архитектурный блок в верхней навигации."}</Description>
|
||||
</>}
|
||||
footer={<>
|
||||
<span>{root?.accent ?? "НАБЛЮДЕНИЕ · МИССИИ · ДАННЫЕ"}</span>
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { GlassSurface } from "@nodedc/ui-react";
|
||||
import { Description, GlassSurface } from "@nodedc/ui-react";
|
||||
|
||||
export interface MetricCardProps {
|
||||
eyebrow: string;
|
||||
@@ -16,7 +16,7 @@ export function MetricCard({ eyebrow, value, unit, detail, featured = false }: M
|
||||
<strong>{value}</strong>
|
||||
{unit ? <span>{unit}</span> : null}
|
||||
</div>
|
||||
<p>{detail}</p>
|
||||
<Description>{detail}</Description>
|
||||
</GlassSurface>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { useState } from "react";
|
||||
import { ConfirmationModal, Dropdown, Icon } from "@nodedc/ui-react";
|
||||
import { Description, ConfirmationModal, Dropdown, Icon } from "@nodedc/ui-react";
|
||||
|
||||
import {
|
||||
type ObservationSessionReplayLaunch,
|
||||
@@ -279,16 +279,16 @@ export function ObservationSessionSelect({
|
||||
description={deleteTarget ? <>
|
||||
<strong>{deleteTarget.label}</strong>
|
||||
{deleteTarget.lab ? (
|
||||
<p>
|
||||
<Description>
|
||||
Будут удалены только LAB-запись из каталога и её подготовленный кэш.
|
||||
Исходная запись {deleteTarget.lab.sourceSessionId} и зафиксированный
|
||||
лабораторный результат останутся неизменными.
|
||||
</p>
|
||||
</Description>
|
||||
) : (
|
||||
<p>
|
||||
<Description>
|
||||
Сессия, исходные данные наблюдения, подготовленная Rerun-запись и
|
||||
видеоматериалы будут удалены с этого сервера без возможности восстановления.
|
||||
</p>
|
||||
</Description>
|
||||
)}
|
||||
{sessions.error && sessions.deletingSessionId === null ? (
|
||||
<p className="observation-session-delete-error" role="alert">{sessions.error}</p>
|
||||
@@ -346,11 +346,11 @@ export function ObservationSessionArchive({
|
||||
{labsOnly ? "ВОСПРОИЗВОДИМЫЕ ЛАБОРАТОРНЫЕ ЗАПИСИ" : "АРХИВ НАБЛЮДЕНИЯ"}
|
||||
</span>
|
||||
<h2>{labsOnly ? "Записанные лабораторные работы" : "Сохранённые сессии"}</h2>
|
||||
<p>
|
||||
<Description>
|
||||
{labsOnly
|
||||
? "Каждая запись связана с LAB-конфигурацией и открывается как самостоятельный визуальный результат."
|
||||
: "Выберите запись: сцена и синхронные каналы откроются ниже, не меняя эфир наблюдения."}
|
||||
</p>
|
||||
</Description>
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
@@ -457,16 +457,16 @@ export function ObservationSessionArchive({
|
||||
description={deleteTarget ? <>
|
||||
<strong>{deleteTarget.label}</strong>
|
||||
{deleteTarget.lab ? (
|
||||
<p>
|
||||
<Description>
|
||||
Будут удалены только LAB-запись из каталога и её подготовленный кэш.
|
||||
Исходная запись {deleteTarget.lab.sourceSessionId} и зафиксированный
|
||||
лабораторный результат останутся неизменными.
|
||||
</p>
|
||||
</Description>
|
||||
) : (
|
||||
<p>
|
||||
<Description>
|
||||
Сессия, исходные данные наблюдения, подготовленная Rerun-запись и
|
||||
видеоматериалы будут удалены с этого сервера без возможности восстановления.
|
||||
</p>
|
||||
</Description>
|
||||
)}
|
||||
</> : null}
|
||||
confirmLabel="Удалить сессию"
|
||||
|
||||
@@ -2200,7 +2200,7 @@ function RerunViewportInstance({
|
||||
/>
|
||||
) : null}
|
||||
{presentationStatus === "loading" ? (
|
||||
<div className="rerun-viewport__notice" role="status">
|
||||
<div data-glass-context="scene" className="rerun-viewport__notice nodedc-viewport-surface" role="status">
|
||||
<span className="busy-indicator" aria-hidden="true" />
|
||||
<div>
|
||||
<strong>
|
||||
@@ -2217,7 +2217,7 @@ function RerunViewportInstance({
|
||||
</div>
|
||||
) : null}
|
||||
{presentationStatus === "error" ? (
|
||||
<div className="rerun-viewport__notice rerun-viewport__notice--error" role="alert">
|
||||
<div data-glass-context="scene" className="rerun-viewport__notice rerun-viewport__notice--error nodedc-viewport-surface" role="alert">
|
||||
<div>
|
||||
<strong>Источник не открыт</strong>
|
||||
<span>Проверьте локальный поток Rerun или повторите подключение.</span>
|
||||
|
||||
@@ -1,31 +1,23 @@
|
||||
import {BatteryDesignSettings} from './BatteryDesignSettings';
|
||||
import {useRef,useState} from 'react';
|
||||
import {Button,ColorField,ControlRow,Description,FeatureSettingsWindow,Icon,IconButton,RangeControl,SettingsCard} from '@nodedc/ui-react';
|
||||
import {parseBatteryAppearance,type BatteryAppearance} from '../../core/batteryScene/appearance';
|
||||
import {parseBatteryAppearance} from '../../core/batteryScene/appearance';
|
||||
import type {useBatteryAppearance} from '../../core/batteryScene/useBatteryAppearance';
|
||||
type Section='markings'|'panels';
|
||||
export function BatteryAppearanceSettings({open,onClose,profile}:{open:boolean;onClose:()=>void;profile:ReturnType<typeof useBatteryAppearance>}){
|
||||
import type {SensorDetailProps} from '../../../../../packages/sensor-ui/src/extensions';
|
||||
import {BmsSettings} from '../../../../../plugins/jk-bms/frontend/src/BmsSettings';
|
||||
type Section='markings'|'panels'|'diagnostics'|'protection'|'control';
|
||||
export function BatteryAppearanceSettings({open,onClose,profile,sensor}:{sensor?:SensorDetailProps;open:boolean;onClose:()=>void;profile:ReturnType<typeof useBatteryAppearance>}){
|
||||
const [section,setSection]=useState<Section>('markings'),input=useRef<HTMLInputElement>(null);
|
||||
const {value,update}=profile,p=value.panels,m=value.markings;
|
||||
const panel=(patch:Partial<BatteryAppearance['panels']>)=>update({...value,panels:{...p,...patch}});
|
||||
const glass=(patch:Partial<typeof p.glass>)=>panel({glass:{...p.glass,...patch}});
|
||||
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:'Локальный профиль',avatarLabel:'АКБ'}} sections={[{id:'markings',label:'Маркировка ячеек',icon:'layers'},{id:'panels',label:'Плашки показаний',icon:'settings'}]} activeSection={section} onSectionChange={setSection} onClose={onClose}
|
||||
headerActions={<><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={<><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:'Не удалось прочитать профиль.');}}}/></>}>
|
||||
{section==='markings'?<SettingsCard title="Маркировка ячеек" description="Номер и напряжение на заводских площадках модели. Размер меняет надпись внутри площадки.">
|
||||
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>:<SettingsCard title="Плашки показаний" description="Общий вид верхних и нижних плашек над моделью.">
|
||||
{range('Высота плашек, px',p.height,56,160,height=>panel({height}))}
|
||||
{range('Радиус углов, px',p.radius,0,48,radius=>panel({radius}))}
|
||||
{range('Размер подписей, px',p.labelSize,10,20,labelSize=>panel({labelSize}))}
|
||||
{range('Размер значений, px',p.valueSize,12,30,valueSize=>panel({valueSize}))}
|
||||
<ControlRow label="Цвет текста"><ColorField label="Цвет текста" value={p.textColor} onChange={textColor=>panel({textColor})}/></ControlRow>
|
||||
<ControlRow label="Цвет стекла"><ColorField label="Цвет стекла" value={p.glass.tintHex} onChange={tintHex=>glass({tintHex})}/></ControlRow>
|
||||
{range('Прозрачность стекла, %',100-p.glass.tintOpacity,0,100,transparency=>glass({tintOpacity:100-transparency}))}
|
||||
{range('Размытие стекла, px',p.glass.blur,0,60,blur=>glass({blur}))}
|
||||
</SettingsCard>}
|
||||
<Description>Сохраняется на этом компьютере для этой батареи. Ctrl Z / ⌘ Z — отмена, Shift Ctrl Z / ⇧ ⌘ Z — повтор.</Description>
|
||||
</SettingsCard>:<BatteryDesignSettings value={value} update={update}/>}
|
||||
{(section==='markings'||section==='panels')&&<Description>Сохраняется в Mission Core для этой батареи. Ctrl Z / ⌘ Z — отмена, Shift Ctrl Z / ⇧ ⌘ Z — повтор.</Description>}
|
||||
</FeatureSettingsWindow>;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,2 @@
|
||||
.battery-design-settings{display:grid;gap:var(--nodedc-space-4);min-width:0}
|
||||
.battery-indicator-previews{display:flex;flex-wrap:wrap;align-items:center;gap:var(--nodedc-space-3)}
|
||||
@@ -0,0 +1,40 @@
|
||||
import {BatteryIndicator} from './BatteryIndicator';
|
||||
import './BatteryDesignSettings.css';
|
||||
import {useState} from 'react';
|
||||
import {ColorField,ControlRow,Description,RangeControl,Select,SettingsCard} from '@nodedc/ui-react';
|
||||
import type {BatteryAppearance} from '../../core/batteryScene/appearance';
|
||||
export function BatteryDesignSettings({value,update}:{value:BatteryAppearance;update:(value:BatteryAppearance)=>void}){
|
||||
const [target,setTarget]=useState<'panels'|'indicator'>('panels');
|
||||
const p=value.panels,i=value.indicator;
|
||||
const panel=(patch:Partial<typeof p>)=>update({...value,panels:{...p,...patch}});
|
||||
const glass=(patch:Partial<typeof p.glass>)=>panel({glass:{...p.glass,...patch}});
|
||||
const indicator=(patch:Partial<typeof i>)=>update({...value,indicator:{...i,...patch}});
|
||||
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 color=(label:string,value:string,onChange:(v:string)=>void)=><ControlRow label={label}><ColorField label={label} value={value} onChange={onChange}/></ControlRow>;
|
||||
return <div className="battery-design-settings"><Select label="Элемент дизайна" value={target} onChange={setTarget} options={[{value:'panels',label:'Плашки показаний'},{value:'indicator',label:'Индикатор в обсерватории'}]}/>
|
||||
{target==='panels'?<SettingsCard title="Плашки показаний" description="Общий вид верхних и нижних плашек над моделью.">
|
||||
{range('Высота плашек, px',p.height,56,160,height=>panel({height}))}
|
||||
{range('Радиус углов, px',p.radius,0,48,radius=>panel({radius}))}
|
||||
{range('Размер подписей, px',p.labelSize,10,20,labelSize=>panel({labelSize}))}
|
||||
{range('Размер значений, px',p.valueSize,12,30,valueSize=>panel({valueSize}))}
|
||||
{color('Цвет текста',p.textColor,textColor=>panel({textColor}))}
|
||||
{color('Цвет стекла',p.glass.tintHex,tintHex=>glass({tintHex}))}
|
||||
{range('Прозрачность стекла, %',100-p.glass.tintOpacity,0,100,transparency=>glass({tintOpacity:100-transparency}))}
|
||||
{range('Размытие стекла, px',p.glass.blur,0,60,blur=>glass({blur}))}
|
||||
</SettingsCard>:<SettingsCard title="Индикатор в обсерватории" description="Размеры, цвет заливки и диапазоны уровня заряда для этой батареи.">
|
||||
{range('Ширина индикатора, px',i.width,32,320,width=>indicator({width}))}
|
||||
{range('Высота индикатора, px',i.height,12,96,height=>indicator({height}))}
|
||||
{range('Радиус углов индикатора, px',i.radius,0,48,radius=>indicator({radius}))}
|
||||
{range('Отступ от кнопок шапки влево, px',i.offset,0,320,offset=>indicator({offset}))}
|
||||
<Select label="Режим цвета индикатора" value={i.mode} onChange={mode=>indicator({mode})} options={[{value:'ranges',label:'По уровню заряда'},{value:'mono',label:'Один цвет'}]}/>
|
||||
{i.mode==='mono'?color('Цвет индикатора',i.color,color=>indicator({color})):<>
|
||||
{range('Низкий заряд ниже, %',i.lowUntil,0,99,lowUntil=>indicator({lowUntil,middleUntil:Math.max(i.middleUntil,lowUntil+1)}))}
|
||||
{color('Низкий заряд',i.lowColor,lowColor=>indicator({lowColor}))}
|
||||
{range('Средний заряд ниже, %',i.middleUntil,i.lowUntil+1,100,middleUntil=>indicator({middleUntil}))}
|
||||
{color('Средний заряд',i.middleColor,middleColor=>indicator({middleColor}))}
|
||||
{color('Высокий заряд',i.highColor,highColor=>indicator({highColor}))}
|
||||
</>}
|
||||
<Description>Чёрный или белый текст выбирается автоматически по цвету заливки. Предпросмотр:</Description>
|
||||
<div className="battery-indicator-previews">{[10,25,80].map(soc=><BatteryIndicator key={soc} appearance={i} soc={soc} label="Предпросмотр заряда" valueText={`${soc}%`} disabled/>)}</div>
|
||||
</SettingsCard>}</div>;
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
import {LevelButton,type LevelButtonProps} from '@nodedc/ui-react';
|
||||
import {batteryIndicatorColor,type BatteryIndicatorAppearance} from '../../core/batteryScene/appearance';
|
||||
type Props=Omit<LevelButtonProps,'value'|'fillColor'>&{appearance:BatteryIndicatorAppearance;soc:number|null};
|
||||
export function BatteryIndicator({appearance,soc,style,...props}:Props){
|
||||
return <LevelButton {...props} value={soc===null?null:soc/100} fillColor={batteryIndicatorColor(appearance,soc)} geometry={{width:appearance.width,height:appearance.height,radius:appearance.radius}} style={style}/>;
|
||||
}
|
||||
@@ -5,15 +5,15 @@ import {useMemo,useState} from 'react';
|
||||
import {Description} from '@nodedc/ui-react';
|
||||
import {SceneEditor} from '../rover/editor/RoverScene';
|
||||
import {useSceneDocument} from '../../core/roverScene/useSceneDocument';
|
||||
import {batterySceneProfile,defaultBatteryScene} from '../../core/batteryScene/profile';
|
||||
import {batterySceneProfile} from '../../core/batteryScene/profile';
|
||||
|
||||
export function BatteryScene({editing,soc,fresh,deviceId,seedKey,cellVoltages=[],markingAppearance}:{editing:boolean;soc:number|null;fresh:boolean;deviceId:string;seedKey?:string;cellVoltages?:readonly number[];markingAppearance:CellMarkingAppearance}){
|
||||
const profile=useMemo(()=>batterySceneProfile(seedKey),[seedKey]);
|
||||
const scene=useSceneDocument(deviceId,profile);
|
||||
const [api,setApi]=useState<Parameters<NonNullable<PlayCanvasViewerProps['onSceneReady']>>[0]|null>(null);
|
||||
const [phase,setPhase]=useState<'loading'|'ready'|'error'>('loading');
|
||||
return <div className="bms-scene" data-editing={editing} aria-label="3D-модель батареи R04">
|
||||
<SceneEditor scene={scene} defaults={defaultBatteryScene} editing={editing} modelUrl="/battery-scene/catl-r04.glb?objects-v5" minFitDistance={.6} chargeState={{soc,fresh}} onModelState={setPhase} onSceneReady={setApi}/>
|
||||
return <div className="bms-scene" data-editing={editing} aria-label="3D-модель батареи R05">
|
||||
<SceneEditor scene={scene} editing={editing} modelUrl="/battery-scene/catl-r04.glb?objects-v6-r05" minFitDistance={.6} chargeState={{soc,fresh}} onModelState={setPhase} onSceneReady={setApi}/>
|
||||
<BatteryCellLabels api={api} ready={phase==='ready'} values={cellVoltages} appearance={markingAppearance}/>
|
||||
{phase!=='ready'&&<div className="bms-scene-status"><Description role="status">{phase==='error'?'Модель не загрузилась. Показания BMS доступны ниже.':'Загружается модель аккумулятора…'}</Description></div>}
|
||||
</div>;
|
||||
|
||||
@@ -1,22 +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}:{deviceId:string;title:string;headerActionsTarget?:HTMLElement|null;back:()=>void;children:(controls:{editing:boolean;appearance:BatteryAppearance;renderViewport:(children:ReactNode)=>ReactNode})=>ReactNode}){
|
||||
const full=useApplicationPanelFullscreen(),[editing,setEditing]=useState(false),[error,setError]=useState(''),[settings,setSettings]=useState(false);
|
||||
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}/><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('');}}/></>;
|
||||
}
|
||||
|
||||
@@ -6,7 +6,6 @@ import {
|
||||
useState,
|
||||
} from "react";
|
||||
import {
|
||||
ActivityIndicator,
|
||||
Button,
|
||||
Checker,
|
||||
ControlRow,
|
||||
@@ -35,7 +34,9 @@ import {
|
||||
import type { CanonicalLabReplayDescriptor } from "../../core/laboratory/canonicalLabReplay";
|
||||
import type { ObservationSessionReplayLaunch } from "../../core/observation/sessionArchive";
|
||||
import { laboratoryResultRerunProfile } from "../../core/observation/viewerProfile";
|
||||
import { resolveObservationSessionReplay } from "../../core/observation/useObservationSessions";
|
||||
import { prepareLabReplay, type LabReplayProgress as Progress } from "../../core/laboratory/prepareLabReplay";
|
||||
import { LabReplayProgress } from "./LabReplayProgress";
|
||||
import { announceLabStorageChange } from "../../core/storage/localLabStorage";
|
||||
import type { AIViewerLayer } from "../../core/observatory/aiComposition";
|
||||
import {
|
||||
fetchLabViewProfile,
|
||||
@@ -216,6 +217,7 @@ export function CanonicalResultRerunReplay({
|
||||
const [viewerStatus, setViewerStatus] = useState<RerunViewportStatus>("idle");
|
||||
const [launch, setLaunch] = useState<CanonicalReplayLaunch | null>(null);
|
||||
const [launchError, setLaunchError] = useState<string | null>(null);
|
||||
const [preparationProgress, setPreparationProgress] = useState<Progress>({ phase: "checking", fraction: null });
|
||||
const sceneDraftRef = useRef(sceneDraft);
|
||||
const previousSplitViewRef = useRef(splitView);
|
||||
const trackedLaunchSha256Ref = useRef<string | null>(null);
|
||||
@@ -275,15 +277,10 @@ export function CanonicalResultRerunReplay({
|
||||
setPlayback(null);
|
||||
setPlaybackController(null);
|
||||
setViewerStatus("idle");
|
||||
void resolveObservationSessionReplay(sessionId, {
|
||||
signal: controller.signal,
|
||||
maximumWaitMs: 30 * 60 * 1000,
|
||||
onUpdate: () => undefined,
|
||||
}).then(async (value) => ({
|
||||
base: value,
|
||||
replay: await resolveReplay(resultId, value, { signal: controller.signal }),
|
||||
})).then((value) => {
|
||||
if (!controller.signal.aborted) setLaunch(value);
|
||||
void prepareLabReplay(resultId, sessionId, resolveReplay, {
|
||||
signal: controller.signal, onProgress: setPreparationProgress,
|
||||
}).then((value) => {
|
||||
if (!controller.signal.aborted) { setLaunch(value); announceLabStorageChange(); }
|
||||
}).catch((caught: unknown) => {
|
||||
if (!controller.signal.aborted) {
|
||||
setLaunchError(caught instanceof Error ? caught.message : "Сохранённая запись недоступна.");
|
||||
@@ -465,7 +462,9 @@ export function CanonicalResultRerunReplay({
|
||||
emptyMessage="Слои результата недоступны."
|
||||
deckOverlays={presentationState === "loading" ? (
|
||||
<div className="canonical-vegetation-rerun-replay__loading">
|
||||
<ActivityIndicator label="Загружаем синхронизированную запись" />
|
||||
<LabReplayProgress progress={launch
|
||||
? { phase: "opening", fraction: playback?.bufferProgress ?? null }
|
||||
: preparationProgress} />
|
||||
</div>
|
||||
) : undefined}
|
||||
transport={transport}
|
||||
|
||||
@@ -0,0 +1,10 @@
|
||||
import { Description, ProgressBar } from "@nodedc/ui-react";
|
||||
import { labReplayProgressView, type LabReplayProgress as Progress } from "../../core/laboratory/prepareLabReplay";
|
||||
|
||||
export function LabReplayProgress({ progress }: { progress: Progress }) {
|
||||
const view = labReplayProgressView(progress);
|
||||
return <div className="lab-replay-progress" aria-busy="true">
|
||||
<Description role="status" aria-live="polite">{view.text}</Description>
|
||||
<ProgressBar label={view.label} value={view.value} valueText={view.text} />
|
||||
</div>;
|
||||
}
|
||||
@@ -1,3 +1,4 @@
|
||||
import { Description } from '@nodedc/ui-react';
|
||||
import {
|
||||
forwardRef,
|
||||
type CSSProperties,
|
||||
@@ -915,7 +916,7 @@ LaboratoryMetricEvidenceSceneHandle,
|
||||
return (
|
||||
<div className="laboratory-metric-evidence-scene">
|
||||
<div ref={hostRef} className="laboratory-metric-evidence-scene__viewport">
|
||||
{renderError ? <p>{renderError}</p> : null}
|
||||
{renderError ? <Description>{renderError}</Description> : null}
|
||||
</div>
|
||||
<div className="laboratory-metric-evidence-scene__legend">
|
||||
{showRenderStats && renderStats ? (
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { useId, useState, type ReactNode } from "react";
|
||||
import { Icon, IconButton, Select, StatusBadge } from "@nodedc/ui-react";
|
||||
import { Description, Icon, IconButton, Select, StatusBadge } from "@nodedc/ui-react";
|
||||
|
||||
export interface LaboratoryOption<T extends string> {
|
||||
id: T;
|
||||
@@ -91,7 +91,7 @@ export function LaboratorySelector<T extends string>({
|
||||
<div>
|
||||
<span className="section-eyebrow">{eyebrow}</span>
|
||||
<h2>{title}</h2>
|
||||
<p>{description}</p>
|
||||
<Description>{description}</Description>
|
||||
</div>
|
||||
<div className="laboratory-selector__control">
|
||||
<span>{label}</span>
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { GlassSurface } from "@nodedc/ui-react";
|
||||
import { Description, GlassSurface } from "@nodedc/ui-react";
|
||||
import { CanonicalResultRerunReplay } from "./CanonicalResultRerunReplay";
|
||||
import { resolveCanonicalLabReplay } from "../../core/laboratory/canonicalLabReplay";
|
||||
import type { ObservatoryPortableResultReview } from "../../core/observatory/recordedRun";
|
||||
@@ -38,7 +38,7 @@ export function PortableResultReplay({
|
||||
&& (moduleId === "rf-detr" || moduleId === "object-distance");
|
||||
if (!tgs && !semantics && !objects) return (
|
||||
<GlassSurface className="observatory-replay-state" padding="lg">
|
||||
<p role="alert">Сохранённый результат этого профиля пока не поддерживает визуальный разбор.</p>
|
||||
<Description role="alert">Сохранённый результат этого профиля пока не поддерживает визуальный разбор.</Description>
|
||||
</GlassSurface>
|
||||
);
|
||||
return <CanonicalResultRerunReplay key={review.resultId} resultId={review.resultId}
|
||||
|
||||
@@ -0,0 +1,89 @@
|
||||
import {useEffect, useState} from "react";
|
||||
import {Description, Icon, IconButton, Select, SettingsCard, StatusBadge, TextField} from "@nodedc/ui-react";
|
||||
import {cesiumServiceMessage, cesiumTokenIndicator, readCesiumService, saveCesiumService, verifyCesiumService,
|
||||
type CesiumRouteMode, type CesiumServiceSettings as Settings, type CesiumVerification} from "../../core/map/cesiumService";
|
||||
import "./cesiumServiceSettings.css";
|
||||
import {serverRequest, type Server} from "../../core/system/servers";
|
||||
|
||||
export function CesiumServiceSettings() {
|
||||
const [service, setService] = useState("");
|
||||
const [pending, setPending] = useState<"verify" | "save" | "remove" | null>(null);
|
||||
const [settings, setSettings] = useState<Settings | null>(null);
|
||||
const [mode, setMode] = useState<CesiumRouteMode>("auto");
|
||||
const [egress, setEgress] = useState("");
|
||||
const [servers, setServers] = useState<Server[]>([]);
|
||||
const [routesError, setRoutesError] = useState("");
|
||||
const [token, setToken] = useState("");
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [error, setError] = useState("");
|
||||
const [checking, setChecking] = useState(false);
|
||||
const [checkError, setCheckError] = useState("");
|
||||
const [showVerification, setShowVerification] = useState(false);
|
||||
const [verification, setVerification] = useState<CesiumVerification | null>(null);
|
||||
useEffect(() => {
|
||||
let active = true;
|
||||
void readCesiumService().then(value => {if (active) {setSettings(value); setMode(value.mode); setEgress(value.egress_id || "");}})
|
||||
.catch(reason => {if (active) setError(reason.message);});
|
||||
void serverRequest<{items:Server[]}>("").then(value => {if(active) setServers(value.items);})
|
||||
.catch(reason => {if(active) setRoutesError(reason.message);});
|
||||
return () => {active = false;};
|
||||
}, []);
|
||||
useEffect(() => {
|
||||
let active = true;
|
||||
setVerification(null); setCheckError(""); setShowVerification(false);
|
||||
if (service !== "cesium" || !settings?.token_configured || token.trim() || egress !== (settings.egress_id || "")) {setChecking(false); return;}
|
||||
setChecking(true);
|
||||
void verifyCesiumService().then(value => {if (active) setVerification(value);})
|
||||
.catch(reason => {if (active) setCheckError(reason instanceof Error ? reason.message : cesiumServiceMessage());})
|
||||
.finally(() => {if (active) setChecking(false);});
|
||||
return () => {active = false;};
|
||||
}, [service, settings?.revision, settings?.token_configured, token, egress]);
|
||||
const indicator = cesiumTokenIndicator({configured: !!settings?.token_configured, draft: !!token.trim(),
|
||||
checking: checking || pending === "verify" || pending === "save", error: error || checkError, verification});
|
||||
async function action(kind: "verify" | "save" | "remove") {
|
||||
if (!settings || busy) return;
|
||||
setBusy(true); setPending(kind); setError(""); setCheckError(""); setVerification(null); setShowVerification(kind === "verify");
|
||||
try {
|
||||
if (kind === "verify") setVerification(await verifyCesiumService(token.trim() || undefined, egress));
|
||||
else {
|
||||
const result = await saveCesiumService({revision: settings.revision, mode, egress_id: egress,
|
||||
...(kind === "remove" ? {remove_token: true} : token.trim() ? {token: token.trim()} : {})});
|
||||
setSettings(result); setToken("");
|
||||
}
|
||||
} catch (reason) {setError(reason instanceof Error ? reason.message : cesiumServiceMessage());}
|
||||
finally {setBusy(false); setPending(null);}
|
||||
}
|
||||
return <SettingsCard title="Сервисы" actions={service === "cesium" && <>
|
||||
<IconButton label="Проверить доступ" disabled={busy || checking || !settings || (!token.trim() && !settings.token_configured)}
|
||||
loading={pending === "verify"} onClick={() => void action("verify")}><Icon name="activity"/></IconButton>
|
||||
<IconButton label="Сохранить" disabled={busy || !settings} loading={pending === "save"}
|
||||
onClick={() => void action("save")}><Icon name="save"/></IconButton>
|
||||
{settings?.token_configured && <IconButton label="Удалить токен" disabled={busy} loading={pending === "remove"}
|
||||
onClick={() => void action("remove")}><Icon name="trash"/></IconButton>}
|
||||
</>}>
|
||||
<Select label="Выберите сервис" value={service} disabled={busy} onChange={setService}
|
||||
options={[{value: "", label: "Выберите сервис"}, {value: "cesium", label: "Cesium ion",
|
||||
icon: <StatusBadge variant="indicator" tone={indicator.tone} pulse={indicator.pulse} title={indicator.label} aria-label={indicator.label}/>} ]}/>
|
||||
{service === "cesium" && <>
|
||||
<Description>Общий доступ к спутниковым картам, рельефу и зданиям во всех разделах Mission Core.</Description>
|
||||
{!settings && !error && <Description role="status">Получаем настройки…</Description>}
|
||||
{settings && <>
|
||||
<Select label="Подключение" value={mode} disabled={busy} onChange={value => setMode(value as CesiumRouteMode)}
|
||||
options={[{value: "auto", label: "Автоматически"}, {value: "direct", label: "Напрямую к источнику"},
|
||||
{value: "gateway", label: "Сервер хранения локальных данных"}]}/>
|
||||
<Description>{mode === "auto" ? "Карты используют сервер хранения локальных данных. Если сервер недоступен, подключение переключается на источник через интернет." :
|
||||
mode === "direct" ? "Карты загружаются через интернет без сохранения тайлов на этом компьютере." : "Карты загружаются только через сервер хранения локальных данных. Если сервер недоступен, загрузка приостанавливается."}</Description>
|
||||
<Select label="Маршрутизация" value={egress} disabled={busy} onChange={value=>{setEgress(value);setVerification(null);setError("");}}
|
||||
options={[{value:"",label:"Текущий маршрут"},...servers.flatMap(server=>server.services.filter(item=>item.kind==='egress').map(item=>({value:item.id,label:`${server.name} · ${server.address}`})))]}/>
|
||||
{routesError&&<Description role="alert">{routesError}</Description>}
|
||||
<TextField label={settings.token_configured ? "Новый токен Cesium ion" : "Токен Cesium ion"} type="password" value={token}
|
||||
disabled={busy} autoComplete="off" spellCheck={false} onChange={event => {setToken(event.target.value); setVerification(null); setError("");}}
|
||||
placeholder={settings.token_configured ? "Токен сохранён; заполните для замены" : "Токен"}/>
|
||||
<Description>Токен сохраняется только в Mission Core. Для прямого подключения нужен доступ к рельефу, спутниковой карте и зданиям Cesium ion.</Description>
|
||||
{showVerification && verification && <div className="cesium-service-results" role="status">{Object.entries(verification.assets).map(([id, result]) =>
|
||||
<Description key={id}>{({"1": "Рельеф", "2": "Спутниковая карта", "96188": "Здания"} as Record<string, string>)[id] ?? id}: {result.ok ? "доступ подтверждён" : cesiumServiceMessage(result.code)}</Description>)}</div>}
|
||||
</>}
|
||||
{error && <Description role="alert">{error}</Description>}
|
||||
</>}
|
||||
</SettingsCard>;
|
||||
}
|
||||
@@ -652,6 +652,7 @@ function CacheHealth({
|
||||
);
|
||||
}
|
||||
const { cache } = health.snapshot;
|
||||
if (!cache) return <ControlRow label="Подключение"><StatusBadge tone="neutral">Источник · без кэша</StatusBadge></ControlRow>;
|
||||
return (
|
||||
<dl className="mission-map__cache-health">
|
||||
<div>
|
||||
|
||||
@@ -0,0 +1 @@
|
||||
.cesium-service-results { display: grid; gap: var(--nodedc-space-2); }
|
||||
@@ -1,20 +1,20 @@
|
||||
import { Button, LoadingRegion, Window } from "@nodedc/ui-react";
|
||||
import { Description, Button, LoadingRegion, Window } from "@nodedc/ui-react";
|
||||
import type { RouteCheck } from "../../core/missions/planner";
|
||||
export function MissionCheckWindow({ open, onClose, busy, error, report, run }: {
|
||||
open: boolean; onClose: () => void; busy: boolean; error: string | null; report: RouteCheck | null; run: () => void;
|
||||
}) {
|
||||
return <Window open={open} title="Проверка маршрута" size="md" onClose={onClose}><div className="mission-planner__check">
|
||||
<p>Проверка сохранённой записи и выбранного участка. Новый проход со сканером для этой проверки не требуется.</p>
|
||||
<Description>Проверка сохранённой записи и выбранного участка. Новый проход со сканером для этой проверки не требуется.</Description>
|
||||
<LoadingRegion loading={busy} label="Проверка исходных данных">
|
||||
{error && <p role="alert">{error}</p>}
|
||||
{error && <Description role="alert">{error}</Description>}
|
||||
{report && <><dl>
|
||||
<div><dt>Исходная запись</dt><dd>{report.source_verified ? "Контрольные суммы совпадают" : "Недоступна"}</dd></div>
|
||||
<div><dt>Версия черновика</dt><dd>{report.revision}</dd></div>
|
||||
<div><dt>Длина маршрута</dt><dd>{report.length_m.toFixed(2)} м</dd></div>
|
||||
<div><dt>Положения сканера</dt><dd>{report.pose_count.toLocaleString("ru-RU")}</dd></div>
|
||||
<div><dt>Максимальный шаг</dt><dd>{report.max_step_m.toFixed(2)} м</dd></div></dl>
|
||||
{report.warnings.map(w => <p key={w}>{w}</p>)}
|
||||
<p>Совмещение с повторным проходом не выполнялось. Записанная траектория описывает движение сканера; проходимость для аппарата по ней не проверена.</p></>}
|
||||
{report.warnings.map(w => <Description key={w}>{w}</Description>)}
|
||||
<Description>Совмещение с повторным проходом не выполнялось. Записанная траектория описывает движение сканера; проходимость для аппарата по ней не проверена.</Description></>}
|
||||
<Button disabled={busy} onClick={run}>{report ? "Повторить проверку" : "Начать проверку"}</Button>
|
||||
</LoadingRegion>
|
||||
</div></Window>;
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { useEffect, useMemo, useState } from "react";
|
||||
import { RangeControl } from "@nodedc/ui-react";
|
||||
import { Description, RangeControl } from "@nodedc/ui-react";
|
||||
import { routeLength, type PlanningPose, type PlanningSource } from "../../core/missions/planner";
|
||||
/** Equal-axis plan projection; the moving marker is an archive pose, not localization. */
|
||||
export function MissionRoutePreview({ source, poses }: { source: PlanningSource; poses: PlanningPose[] }) {
|
||||
@@ -22,8 +22,8 @@ export function MissionRoutePreview({ source, poses }: { source: PlanningSource;
|
||||
<polyline points={projection.selected} className="mission-route-preview__selected" fill="none" />
|
||||
<circle cx={x} cy={y} r="6" className="mission-route-preview__cursor" />
|
||||
<path d="M40 450h100" className="mission-route-preview__selected" /><text x="40" y="438">{(100 / projection.scale).toFixed(1)} м</text>
|
||||
</svg><p>Путь: {routeLength(poses).toFixed(2)} м · {poses.length.toLocaleString("ru-RU")} положений · X/Y, масштаб осей одинаковый</p>
|
||||
</svg><Description>Путь: {routeLength(poses).toFixed(2)} м · {poses.length.toLocaleString("ru-RU")} положений · X/Y, масштаб осей одинаковый</Description>
|
||||
<RangeControl label="Положение на маршруте" value={Math.min(cursor, poses.length - 1) + 1} min={1} max={poses.length} step={1} formatValue={n => `${n} / ${poses.length}`} onChange={n => setCursor(n - 1)} />
|
||||
<p>Кадр {point.index + 1} · X {point.position[0].toFixed(2)} · Y {point.position[1].toFixed(2)} · Z {point.position[2].toFixed(2)} м</p>
|
||||
<Description>Кадр {point.index + 1} · X {point.position[0].toFixed(2)} · Y {point.position[1].toFixed(2)} · Z {point.position[2].toFixed(2)} м</Description>
|
||||
</div>;
|
||||
}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import type {ReactNode} from 'react';
|
||||
import {Button, StatusBadge} from '@nodedc/ui-react';
|
||||
import { Description,Button, StatusBadge} from '@nodedc/ui-react';
|
||||
import {planningAwaitsCapture, usePlanningTest} from '../../core/missions/PlanningTestContext';
|
||||
|
||||
/** Composition-level handoff; never sends a device or acquisition command. */
|
||||
@@ -12,9 +12,9 @@ export function PlanningCaptureGuard({enabled, onResume, children}: {
|
||||
if (!enabled || !planningAwaitsCapture(planning.test)) return <>{children}</>;
|
||||
return <div className="mission-planner__check">
|
||||
<StatusBadge tone="warning">Исследование ожидает новую запись</StatusBadge>
|
||||
<p>{planning.test!.draft.name}</p>
|
||||
<p>Для самостоятельной съёмки завершите подготовленное исследование. Запись и подключение сканера не будут остановлены.</p>
|
||||
{planning.error && <p role="alert">{planning.error}</p>}
|
||||
<Description>{planning.test!.draft.name}</Description>
|
||||
<Description>Для самостоятельной съёмки завершите подготовленное исследование. Запись и подключение сканера не будут остановлены.</Description>
|
||||
{planning.error && <Description role="alert">{planning.error}</Description>}
|
||||
<div className="mission-planner__actions">
|
||||
<Button loading={planning.busy} onClick={() => void planning.finish()}>Завершить исследование</Button>
|
||||
<Button disabled={planning.busy} onClick={onResume}>Вернуться к исследованию</Button>
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import {useEffect,useState,type ReactNode} from 'react';
|
||||
import {Button,LoadingRegion,StatusBadge,Window} from '@nodedc/ui-react';
|
||||
import { Description,Button,LoadingRegion,StatusBadge,Window} from '@nodedc/ui-react';
|
||||
import {useDevicePluginHost} from '../../core/device-plugins/DevicePluginHost';
|
||||
import {planningTestTerminal,usePlanningTest} from '../../core/missions/PlanningTestContext';
|
||||
|
||||
@@ -15,17 +15,17 @@ export function PlanningConnectionWindow({children}:{children:ReactNode}){
|
||||
if(!p.test)return <>{children}</>;
|
||||
const t=p.test, terminal=planningTestTerminal(t);
|
||||
const details=<><StatusBadge tone="neutral">Профиль · Планирование</StatusBadge>
|
||||
<p>{t.draft.name} · эталон {t.draft.zone.label} · {t.draft.route.length_m.toFixed(1)} м</p>
|
||||
<p>Укажите новое имя проекта сканера. Неподвижная калибровка просматривает весь выбранный маршрут; после калибровки сканера оставайтесь на месте до статуса «Сопровождение». Если совпадение не найдено или неоднозначно, сцена сообщит причину и не начнёт сопровождение.</p></>;
|
||||
<Description>{t.draft.name} · эталон {t.draft.zone.label} · {t.draft.route.length_m.toFixed(1)} м</Description>
|
||||
<Description>Укажите новое имя проекта сканера. Неподвижная калибровка просматривает весь выбранный маршрут; после калибровки сканера оставайтесь на месте до статуса «Сопровождение». Если совпадение не найдено или неоднозначно, сцена сообщит причину и не начнёт сопровождение.</Description></>;
|
||||
return <div className="mission-planner__check">
|
||||
{details}<p>{t.message}</p>{p.error&&<p role="alert">{p.error}</p>}
|
||||
{details}<Description>{t.message}</Description>{p.error&&<Description role="alert">{p.error}</Description>}
|
||||
<div className="mission-planner__actions"><Button onClick={()=>setOpen(true)}>Подключение сканера</Button>
|
||||
{t.state==='running'&&t.planning_phase==='lost'&&!t.tracking_established&&<Button loading={p.busy} onClick={()=>void p.retryInitialization()}>Переинициализировать</Button>}
|
||||
{!terminal&&<Button loading={p.busy} onClick={()=>void p.finish()}>Завершить исследование</Button>}</div>
|
||||
<Window open={open} title="Подключение сканера · Планирование" size="lg" className="planning-connection" onClose={()=>setOpen(false)}>
|
||||
<div className="mission-planner__check">{details}
|
||||
{t.state==='preparing'?<LoadingRegion loading label="Подготовка эталонного участка" />
|
||||
: terminal?<p>{t.message}</p>:children}
|
||||
: terminal?<Description>{t.message}</Description>:children}
|
||||
</div>
|
||||
</Window>
|
||||
</div>;
|
||||
|
||||
@@ -1,11 +1,11 @@
|
||||
import { Inspector, Icon, StatusBadge } from '@nodedc/ui-react';
|
||||
import { Description, Inspector, Icon, StatusBadge } from '@nodedc/ui-react';
|
||||
import { planningProjectStatus, type PlanningProjectDetail } from '../../core/missions/planningProjects';
|
||||
|
||||
export function PlanningProjectResult({project:p}:{project:PlanningProjectDetail}) {
|
||||
const r=p.result;
|
||||
return <Inspector variant="panel" defaultOpen={['sources','result']} sections={[
|
||||
{id:'sources',label:'Проект',icon:<Icon name="file"/>,content:<div className="inspector-control-stack">
|
||||
<p>{p.name}</p><small>{new Date(p.created_at_utc).toLocaleString('ru-RU')}</small>
|
||||
<Description>{p.name}</Description><small>{new Date(p.created_at_utc).toLocaleString('ru-RU')}</small>
|
||||
<dl><div><dt>Эталон</dt><dd>{p.reference_label}</dd></div><div><dt>Повторный проход</dt><dd>{p.query_label??'—'}</dd></div>
|
||||
<div><dt>Участок эталона</dt><dd>{p.draft.route.length_m.toFixed(2)} м</dd></div></dl>
|
||||
</div>},
|
||||
@@ -15,7 +15,7 @@ export function PlanningProjectResult({project:p}:{project:PlanningProjectDetail
|
||||
<div><dt>Расхождение поверхностей</dt><dd>{r.inlier_rmse_m==null?'—':`${r.inlier_rmse_m.toFixed(3)} м`}</dd></div>
|
||||
{r.correction_m!=null&&<div><dt>Уточнение привязки</dt><dd>{r.correction_m.toFixed(2)} м · {r.correction_deg.toFixed(1)}°</dd></div>}
|
||||
{r.registration_seconds!=null&&<div><dt>Расчёт</dt><dd>{r.registration_seconds.toFixed(2)} с</dd></div>}
|
||||
</dl><small>Совпадение поверхностей не является измеренной точностью положения.</small></>:<p>{p.message?`Сохранённое сообщение: ${p.message}`:'Расчёт совмещения ещё не выполнен.'}</p>}
|
||||
</dl><small>Совпадение поверхностей не является измеренной точностью положения.</small></>:<Description>{p.message?`Сохранённое сообщение: ${p.message}`:'Расчёт совмещения ещё не выполнен.'}</Description>}
|
||||
{p.evidence_relation==='same_recording'&&<small>Оба участка из одной записи: внутренняя проверка общей карты.</small>}
|
||||
{p.scene_note&&p.scene_url&&<small>{p.scene_note}</small>}
|
||||
{r?.reasons.map(reason=><small key={reason}>{reason}</small>)}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { useState } from 'react';
|
||||
import { ConfirmationModal, Icon, Select, ToastStack } from '@nodedc/ui-react';
|
||||
import { Description, ConfirmationModal, Icon, Select, ToastStack } from '@nodedc/ui-react';
|
||||
import { planningProjectDeletable, planningProjectStatus, type PlanningProject } from '../../core/missions/planningProjects';
|
||||
|
||||
export function PlanningProjectSelect({items, value, disabled, onChange, onRemove}: {
|
||||
@@ -29,8 +29,8 @@ export function PlanningProjectSelect({items, value, disabled, onChange, onRemov
|
||||
<ConfirmationModal open={target !== null} title="Удалить совмещённый маршрут?"
|
||||
description={target ? <>
|
||||
<strong>{target.name}</strong>
|
||||
<p>{new Date(target.created_at_utc).toLocaleString('ru-RU')} · {planningProjectStatus(target)}</p>
|
||||
<p>Проект будет удалён из списка совмещённых маршрутов. Эталон, запись прохода и сохранённые отчёты останутся на диске. Другие проекты не изменятся.</p>
|
||||
<Description>{new Date(target.created_at_utc).toLocaleString('ru-RU')} · {planningProjectStatus(target)}</Description>
|
||||
<Description>Проект будет удалён из списка совмещённых маршрутов. Эталон, запись прохода и сохранённые отчёты останутся на диске. Другие проекты не изменятся.</Description>
|
||||
</> : null}
|
||||
confirmLabel="Удалить маршрут" pendingLabel="Удаление…" danger
|
||||
onClose={() => { if (!busy) setTarget(null); }}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { Button, Icon, Inspector, InspectorSelectField, TextField } from '@nodedc/ui-react';
|
||||
import { Description, Button, Icon, Inspector, InspectorSelectField, TextField } from '@nodedc/ui-react';
|
||||
import { routeLength, canStartPlanningRoute } from '../../core/missions/planner';
|
||||
import type { useMissionPlanner } from '../../core/missions/useMissionPlanner';
|
||||
|
||||
@@ -24,7 +24,7 @@ export function PlanningProjectSettings({p,onStart,starting}:{
|
||||
<div className="inspector-control-stack">
|
||||
{p.source&&!routeReady&&<small>В записи недостаточно перемещения для привязки. Выберите другой эталон.</small>}
|
||||
<Button variant="primary" loading={starting} disabled={disabled||!p.ready||!routeReady} onClick={onStart}><Icon name="play"/>Начать новый проход</Button>
|
||||
{p.error&&<p role="alert">{p.error}</p>}
|
||||
{p.error&&<Description role="alert">{p.error}</Description>}
|
||||
</div>
|
||||
</>;
|
||||
}
|
||||
|
||||
@@ -2,10 +2,10 @@ import {Fragment,useEffect,useState} from 'react';
|
||||
import {Button,Icon,SettingsCard} from '@nodedc/ui-react';
|
||||
|
||||
type Installer={id:string;label:string;version:string;os:string;filename:string;download_url:string;instructions:string[]};
|
||||
export function InstallerCard({kind}:{kind:'node'|'vps-arnavi'|'vps-wireguard'|'vps-netbird'}){
|
||||
export function InstallerCard({kind,connectionInstruction}:{connectionInstruction?:string;kind:'node'|'vps-arnavi'|'vps-wireguard'|'vps-netbird'|'vps-librespeed'|'vps-egress'}){
|
||||
const [item,setItem]=useState<Installer|null>(null),[failed,setFailed]=useState(false);
|
||||
useEffect(()=>{let active=true;void fetch('/api/v1/fleet/installers',{cache:'no-store'}).then(async r=>{if(!r.ok)throw Error();return r.json() as Promise<{items:Installer[]}>;}).then(v=>{if(active){setItem(v.items.find(i=>i.id===kind)??null);setFailed(!v.items.some(i=>i.id===kind));}}).catch(()=>{if(active)setFailed(true);});return()=>{active=false;};},[kind]);
|
||||
return <SettingsCard title="Установка" description={item?<>{`${item.label} ${item.version} · Только ${item.os}`}<br/><br/>{item.instructions.map((step,index)=><Fragment key={step}>{index>0&&<br/>}{index+1}. {step}</Fragment>)}</>:failed?'Установщик пока недоступен в этом Mission Core.':'Получение установщика…'}>
|
||||
return <SettingsCard title="Установка" description={item?<>{`${item.label} ${item.version} · Только ${item.os}`}<br/><br/>{item.instructions.map((original,index)=>{const step=connectionInstruction&&index===item.instructions.length-1?connectionInstruction:original;return <Fragment key={step}>{index>0&&<br/>}{index+1}. {step}</Fragment>;})}</>:failed?'Установщик пока недоступен в этом Mission Core.':'Получение установщика…'}>
|
||||
<Button disabled={!item} icon={<Icon name="download"/>} onClick={()=>{if(item){const link=document.createElement('a');link.href=item.download_url;link.download=item.filename;link.click();}}}>Скачать установщик</Button>
|
||||
</SettingsCard>;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,50 @@
|
||||
import {useState} from 'react';
|
||||
import {Button,Description,Select,SettingsCard} from '@nodedc/ui-react';
|
||||
import {useServers,useServerHealth} from '../../core/system/servers';
|
||||
import {selectedSpeedServer,speedtestServers} from '../../core/system/speedtestServers';
|
||||
import {useCoreSpeedtest} from '../../core/system/networkSpeedtest';
|
||||
import {ServerServiceSetup} from '../system/ServerServiceSetup';
|
||||
import {RouterSpeedGauge} from './RouterSpeedGauge';
|
||||
import './networkSettings.css';
|
||||
|
||||
const format=(value:number)=>`${new Intl.NumberFormat('ru-RU',{maximumFractionDigits:1}).format(value)} мс`;
|
||||
export function NetworkSettings(){
|
||||
const servers=useServers(),health=useServerHealth(servers.items,servers.generation),test=useCoreSpeedtest();
|
||||
const [selected,setSelected]=useState(''),[setup,setSetup]=useState(false);
|
||||
const items=speedtestServers(servers.items,health);
|
||||
const chosen=selectedSpeedServer(items,selected,test.running?test.receipt?.server_id:undefined);
|
||||
const measurement=test.receipt?.measurement;
|
||||
const busy=test.sending||test.running;
|
||||
const ready=test.loaded&&test.fresh&&chosen?.online&&!servers.error;
|
||||
return <>
|
||||
<SettingsCard title="Замер скорости" description="Проверяется интернет компьютера, на котором работает Mission Core. Замер занимает около 30 секунд.">
|
||||
{!servers.items&&!test.receipt?<Description role="status">{servers.error||'Получаем список VPS…'}</Description>:items.length===0&&!test.receipt?<>
|
||||
<Description>Для замера подключите службу LibreSpeed на одном из ваших VPS.</Description>
|
||||
<Button disabled={busy||!!servers.error} onClick={()=>setSetup(true)}>Добавить службу</Button>
|
||||
</>:<>
|
||||
{items.length>0?<Select label="Сервер замера" disabled={busy} value={chosen?.service.id??''} onChange={setSelected}
|
||||
options={[{value:'',label:'Выберите VPS'},...items.map(item=>({value:item.service.id,label:`${item.server.name} · ${item.server.address}${item.online?'':` · ${item.label}`}`}))]}/>:<Description>Служба замера больше не доступна в списке VPS.</Description>}
|
||||
{chosen&&!chosen.online&&<Description role="status">Служба не подтвердила доступность. Список обновляется автоматически.</Description>}
|
||||
{servers.error&&<Description role="alert">{servers.error}</Description>}
|
||||
<RouterSpeedGauge key={test.receipt?.operation_id??'idle'} measurement={measurement} waiting={test.receipt?.state==='queued'} fresh={test.fresh} staleLabel="Обновляем данные замера"/>
|
||||
{test.receipt?.state==='cancelling'&&<Description role="status">Останавливаем замер…</Description>}
|
||||
{measurement?.phase==='complete'&&<>
|
||||
<dl className="network-speed-facts">
|
||||
<div><dt>Задержка HTTP</dt><dd>{format(measurement.latency_ms)}</dd></div>
|
||||
<div><dt>Джиттер HTTP</dt><dd>{format(measurement.jitter_ms)}</dd></div>
|
||||
</dl>
|
||||
<Description>{test.receipt?.server_name} · {new Date((measurement.finished_at??measurement.started_at)*1000).toLocaleString('ru-RU')}</Description>
|
||||
</>}
|
||||
{measurement?.phase==='error'&&<Description role="alert">Замер не завершён. Проверьте соединение и доступность VPS. Возможно, на сервере уже идёт другой замер.</Description>}
|
||||
{test.loaded&&!test.fresh&&<Description role="status">Нет свежих данных от Mission Core. Состояние замера уточняется.</Description>}
|
||||
<div className="network-speed-actions">
|
||||
{test.running?<Button disabled={test.sending||test.receipt?.state==='cancelling'} onClick={()=>void test.cancel()}>Остановить замер</Button>:<Button disabled={test.sending||!ready} loading={test.sending} onClick={()=>chosen&&void test.start(chosen.service.id)}>Начать замер</Button>}
|
||||
<Button disabled={busy} onClick={()=>setSetup(true)}>Добавить службу</Button>
|
||||
</div>
|
||||
<Description>Используется текущее соединение компьютера, включая VPN, если он включён. Результат относится к выбранному VPS и времени замера.</Description>
|
||||
</>}
|
||||
{test.error&&<Description role="alert">{test.error}</Description>}
|
||||
</SettingsCard>
|
||||
{setup&&<ServerServiceSetup fixedKind="librespeed" onClose={()=>setSetup(false)} onSaved={()=>{setSetup(false);servers.refresh();}}/>}
|
||||
</>;
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
import {Description,StatusBadge} from '@nodedc/ui-react';
|
||||
import {ObservationHeader} from '../../../../../packages/sensor-ui/src/ObservationHeader';
|
||||
import type {ObservationHeaderTargets} from '../../../../../packages/sensor-ui/src/observation';
|
||||
import {metric,type RouterDevice,type RouterSnapshot} from '../../../../../packages/router-ui/src/contracts';
|
||||
import {RouterSignal} from '../../../../../packages/router-ui/src/RouterSignal';
|
||||
import {routerObservation} from '../../core/fleet/routerObservation';
|
||||
import '../../../../../packages/router-ui/src/router.css';
|
||||
import './routerObservation.css';
|
||||
|
||||
export function RouterObservation({device,value,compact=false,header}:{device:RouterDevice;value:RouterSnapshot|null;compact?:boolean;header?:ObservationHeaderTargets}){
|
||||
const view=routerObservation(device,value);
|
||||
return <div className="router-observation" aria-label={`Связь · ${view.name}`}>
|
||||
{header&&<ObservationHeader targets={header} live={view.live} waiting={view.waiting} label={view.status}/>}
|
||||
{!compact&&<div>
|
||||
<div className="router-observation__summary"><strong>{view.mode.current}</strong><StatusBadge variant="indicator" tone={view.ready?'success':'neutral'} aria-label={view.status} title={view.status}/></div>
|
||||
<Description>{view.internet}</Description>
|
||||
{view.ready&&view.mode.message&&<Description role="status">{view.mode.message}</Description>}
|
||||
</div>}
|
||||
{view.channels.map(channel=><section key={channel.slot} className="router-observation__channel" aria-label={`${channel.label} · ${channel.detail} · ${channel.status}`}>
|
||||
<div className="router-observation__summary"><StatusBadge variant="indicator" tone={channel.indicator} aria-label={`${channel.label} · ${channel.indicatorLabel}`} title={`${channel.label} · ${channel.indicatorLabel}`}/><strong>{channel.label}</strong><span>{channel.operator}</span><strong className="router-observation__value">{channel.rsrp==null?'—':metric(channel.rsrp,'dBm')}</strong></div>
|
||||
{!compact&&<RouterSignal rsrp={channel.rsrp} compact/>}
|
||||
</section>)}
|
||||
</div>;
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
import {useEffect,useRef,useState} from 'react';
|
||||
import {Description,Icon} from '@nodedc/ui-react';
|
||||
import type {SpeedMeasurement} from '../../../../../packages/router-ui/src/contracts';
|
||||
import {speedFraction,speedPoint,speedTrack,speedValues} from './speedGauge';
|
||||
import './routerSpeedGauge.css';
|
||||
|
||||
function useMarker(target:number){
|
||||
const [position,setPosition]=useState(target),last=useRef(target);
|
||||
useEffect(()=>{
|
||||
if(window.matchMedia('(prefers-reduced-motion: reduce)').matches){last.current=target;setPosition(target);return;}
|
||||
const start=performance.now(),from=last.current;let frame=0;
|
||||
function animate(now:number){const t=Math.min(1,(now-start)/650),next=from+(target-from)*(1-Math.pow(1-t,3));last.current=next;setPosition(next);if(t<1)frame=requestAnimationFrame(animate);}
|
||||
frame=requestAnimationFrame(animate);return()=>cancelAnimationFrame(frame);
|
||||
},[target]);
|
||||
return position;
|
||||
}
|
||||
const format=(n:number|null)=>n===null?'—':new Intl.NumberFormat('ru-RU',{maximumFractionDigits:1}).format(n/1e6);
|
||||
const tickLength=12;
|
||||
function markerPoint(fraction:number){
|
||||
const p=speedPoint(fraction);
|
||||
return{x:p.x+p.nx*tickLength/2,y:p.y+p.ny*tickLength/2};
|
||||
}
|
||||
export function RouterSpeedGauge({measurement,waiting,fresh,staleLabel="Ожидаем данные борта"}:{measurement?:SpeedMeasurement;waiting:boolean;fresh:boolean;staleLabel?:string}){
|
||||
const {down,up}=speedValues(measurement),phase=measurement?.phase;
|
||||
const running=phase==='download'||phase==='upload';
|
||||
const [clock,setClock]=useState(Date.now());
|
||||
useEffect(()=>{if(!running)return;const timer=setInterval(()=>setClock(Date.now()),1000);return()=>clearInterval(timer);},[running]);
|
||||
const stale=running&&(!fresh||!!measurement?.sampled_at&&clock-measurement.sampled_at>6000);
|
||||
const ceiling=Math.max(down??0,up??0)>1e9?1e10:1e9;
|
||||
const active=phase==='upload'?up:down;
|
||||
const marker=markerPoint(useMarker(speedFraction(active??0,ceiling)));
|
||||
const secondary=markerPoint(speedFraction(up??0,ceiling));
|
||||
const state=waiting?'Подготовка замера':stale?staleLabel:phase==='latency'?'Проверяем задержку':phase==='download'?'Измеряем приём':phase==='upload'?'Измеряем передачу':phase==='complete'?'Замер завершён':phase==='cancelled'?'Замер остановлен':phase==='error'?'Замер не завершён':'Готов к замеру';
|
||||
const caption=phase==='download'||phase==='upload'?'Текущая средняя · Мбит/с':'Мбит/с';
|
||||
return <div className="router-speed-visual"><div className="router-speed-state"><Description role="status">{state}</Description></div><figure className="router-speed-gauge" aria-label={`Скорость соединения. ${state}. Приём ${format(down)}, передача ${format(up)} Мбит/с.`}>
|
||||
<svg viewBox="0 0 720 280" aria-hidden="true" className={stale?'router-speed-instrument is-stale':'router-speed-instrument'}>
|
||||
<path d={speedTrack} className="router-speed-track"/>
|
||||
{Array.from({length:121},(_,i)=>{const p=speedPoint(i/120),lit=active!==null&&i/120<=speedFraction(active,ceiling);return <line key={i} x1={p.x} y1={p.y} x2={p.x+p.nx*tickLength} y2={p.y+p.ny*tickLength} className={lit?'router-speed-tick is-lit':'router-speed-tick'}/>;})}
|
||||
{[0,10,100,1000].map(n=>{const p=speedPoint(speedFraction(n*1e6*(ceiling/1e9),ceiling));return <line key={n} x1={p.x} y1={p.y} x2={p.x+p.nx*22} y2={p.y+p.ny*22} className="router-speed-major"/>;})}
|
||||
{active!==null&&<g className="router-speed-marker"><circle cx={marker.x} cy={marker.y} r="11" className="router-speed-halo"/><circle cx={marker.x} cy={marker.y} r="4"/></g>}
|
||||
{phase==='complete'&&up!==null&&<circle cx={secondary.x} cy={secondary.y} r="5" className="router-speed-upload-marker"/>}
|
||||
</svg>
|
||||
{[0,10,100,1000].map(n=>{const p=speedPoint(speedFraction(n*1e6*(ceiling/1e9),ceiling));return <span key={n} className="router-speed-scale" style={{left:`${(p.x-p.nx*22)/720*100}%`,top:`${(p.y-p.ny*22)/280*100}%`}}>{n*(ceiling/1e9)}</span>;})}
|
||||
<figcaption className="router-speed-center">
|
||||
<div className="router-speed-readings">
|
||||
<div data-active={phase==='download'}><span><Icon name="download"/> Приём</span><strong>{format(down)}</strong></div>
|
||||
<div data-active={phase==='upload'}><span><Icon name="upload"/> Передача</span><strong>{format(up)}</strong></div>
|
||||
</div>
|
||||
<Description>{caption}</Description>
|
||||
</figcaption>
|
||||
</figure></div>;
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
.network-speed-facts{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:var(--nodedc-space-4);margin:0;}
|
||||
.network-speed-facts dt{color:var(--nodedc-text-secondary);font-size:var(--nodedc-font-size-sm);}
|
||||
.network-speed-facts dd{margin:var(--nodedc-space-1) 0 0;font-size:var(--nodedc-font-size-md);}
|
||||
.network-speed-actions{display:flex;flex-wrap:wrap;gap:var(--nodedc-space-2);}
|
||||
@@ -0,0 +1,10 @@
|
||||
.router-observation {height:100%;min-height:0;overflow:auto;display:flex;flex-direction:column;gap:var(--nodedc-space-2);padding:var(--nodedc-space-2);font-size:var(--nodedc-font-size-sm);--nodedc-description-font-size:var(--nodedc-font-size-xs);}
|
||||
.router-observation__channel {display:flex;flex-direction:column;}
|
||||
.router-observation__summary {display:flex;align-items:center;flex-wrap:wrap;gap:var(--nodedc-space-2);}
|
||||
.router-observation__summary strong {font-weight:var(--nodedc-font-weight-medium);}
|
||||
.router-observation__value {margin-inline-start:auto;white-space:nowrap;}
|
||||
|
||||
.router-observation .router-signal-scale {margin-top:0;}
|
||||
.router-observation .router-signal-zone {min-height:24px;}
|
||||
.router-observation .router-signal-track {height:4px;}
|
||||
.router-observation .router-signal-marker {width:8px;height:8px;}
|
||||
@@ -0,0 +1,20 @@
|
||||
.router-speed-visual{margin:8px 0}.router-speed-state{text-align:center}
|
||||
.router-speed-gauge{position:relative;width:100%;max-width:600px;aspect-ratio:18/7;margin:0 auto;isolation:isolate;color:var(--nodedc-text-primary)}
|
||||
.router-speed-instrument{display:block;width:100%;height:100%;overflow:visible}
|
||||
.router-speed-track{fill:none;stroke:currentColor;stroke-width:1;opacity:.06}
|
||||
.router-speed-tick{stroke:currentColor;stroke-width:1.4;stroke-linecap:round;opacity:.18;transition:opacity 450ms ease}
|
||||
.router-speed-tick.is-lit{opacity:.8}
|
||||
.router-speed-major{stroke:currentColor;stroke-width:1.5;stroke-linecap:round;opacity:.5}
|
||||
.router-speed-marker{fill:currentColor}
|
||||
.router-speed-halo{opacity:.1}
|
||||
.router-speed-upload-marker{fill:none;stroke:var(--nodedc-text-muted);stroke-width:2}
|
||||
.router-speed-instrument.is-stale{opacity:.45}
|
||||
.router-speed-scale{position:absolute;transform:translate(-50%,-50%);font-size:var(--nodedc-font-size-sm);color:var(--nodedc-text-muted);font-variant-numeric:tabular-nums}
|
||||
.router-speed-center{position:absolute;top:50%;left:50%;transform:translate(-50%,-50%);width:52%;display:grid;gap:12px;text-align:center}
|
||||
.router-speed-readings{display:grid;grid-template-columns:1fr 1fr;gap:16px}
|
||||
.router-speed-readings>div{display:grid;gap:8px}
|
||||
.router-speed-readings span{display:flex;align-items:center;justify-content:center;gap:6px;color:var(--nodedc-text-muted);font-size:var(--nodedc-font-size-sm)}
|
||||
.router-speed-readings strong{font-size:var(--nodedc-font-size-md);font-weight:600;font-variant-numeric:tabular-nums}
|
||||
.router-speed-readings [data-active=true] span{color:var(--nodedc-text-primary)}
|
||||
@media(max-width:600px){.router-speed-gauge{margin:8px auto}.router-speed-center{gap:6px;width:58%}.router-speed-readings{gap:8px}.router-speed-readings>div{gap:4px}.router-speed-scale{font-size:var(--nodedc-font-size-xs)}}
|
||||
@media(prefers-reduced-motion:reduce){.router-speed-tick{transition:none}}
|
||||
@@ -0,0 +1,21 @@
|
||||
/** Geometry of the router speed instrument. Values stay measured, only the marker interpolates. */
|
||||
export function speedFraction(bps:number,ceiling=1e9){
|
||||
return Math.log1p(Math.max(0,Math.min(ceiling,bps))/(ceiling/100))/Math.log(101);
|
||||
}
|
||||
export function speedPoint(fraction:number){
|
||||
const radius=95,left=142,right=578,top=45,bottom=235,tail=143,straight=right-left;
|
||||
let d=Math.max(0,Math.min(1,fraction))*(tail*2+Math.PI*radius*2+straight);
|
||||
if(d<=tail)return{x:285-d,y:bottom,nx:0,ny:1};d-=tail;
|
||||
if(d<=Math.PI*radius){const a=Math.PI/2+d/radius;return{x:left+radius*Math.cos(a),y:140+radius*Math.sin(a),nx:Math.cos(a),ny:Math.sin(a)};}d-=Math.PI*radius;
|
||||
if(d<=straight)return{x:left+d,y:top,nx:0,ny:-1};d-=straight;
|
||||
if(d<=Math.PI*radius){const a=-Math.PI/2+d/radius;return{x:right+radius*Math.cos(a),y:140+radius*Math.sin(a),nx:Math.cos(a),ny:Math.sin(a)};}d-=Math.PI*radius;
|
||||
return{x:right-d,y:bottom,nx:0,ny:1};
|
||||
}
|
||||
export const speedTrack='M285 235 H142 A95 95 0 0 1 142 45 H578 A95 95 0 0 1 578 235 H435';
|
||||
export function speedValues(m:{phase:string;current_bps?:number;sampled_at?:number;download_bps:number;upload_bps:number}|undefined){
|
||||
if(!m)return{down:null,up:null};
|
||||
if(m.phase==='complete')return{down:m.download_bps,up:m.upload_bps};
|
||||
if(m.phase==='download')return{down:m.sampled_at?m.current_bps??null:null,up:null};
|
||||
if(m.phase==='upload')return{down:m.download_bps,up:m.sampled_at?m.current_bps??null:null};
|
||||
return{down:null,up:null};
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
import {useEffect, useState} from 'react';
|
||||
import {Button, Checker, Description, FeatureSettingsWindow, SettingsCard} from '@nodedc/ui-react';
|
||||
import {notificationRequest} from '../../core/notifications/history';
|
||||
|
||||
interface Preference {
|
||||
key: string;
|
||||
section: string;
|
||||
group: string;
|
||||
label: string;
|
||||
enabled: boolean;
|
||||
}
|
||||
|
||||
export function EventSettings({onClose}: {onClose: () => void}) {
|
||||
const [items, setItems] = useState<Preference[]>([]);
|
||||
const [section, setSection] = useState('Сеть');
|
||||
const [error, setError] = useState('');
|
||||
const [saving, setSaving] = useState(false);
|
||||
const [attempt, setAttempt] = useState(0);
|
||||
useEffect(() => {
|
||||
let active = true;
|
||||
setError('');
|
||||
notificationRequest<Preference[]>('/preferences').then(result => {
|
||||
if (active) setItems(result);
|
||||
}).catch(() => { if (active) setError('Не удалось загрузить настройки событий.'); });
|
||||
return () => { active = false; };
|
||||
}, [attempt]);
|
||||
|
||||
async function configure(key: string, enabled: boolean) {
|
||||
setSaving(true);
|
||||
setError('');
|
||||
try {
|
||||
setItems(await notificationRequest<Preference[]>('/preferences', 'PATCH', {key, enabled}));
|
||||
} catch {
|
||||
setError('Не удалось подтвердить изменение. Обновите настройки и повторите попытку.');
|
||||
} finally {
|
||||
setSaving(false);
|
||||
}
|
||||
}
|
||||
const sections = [...new Set(items.map(item => item.section))];
|
||||
const current = items.filter(item => item.section === section);
|
||||
const groups = [...new Set(current.map(item => item.group))];
|
||||
return <FeatureSettingsWindow open title="Настройки центра событий"
|
||||
identity={{title: 'Центр событий', avatarLabel: 'ЦС'}}
|
||||
sections={sections.map(label => ({id: label, label, icon: label === 'Сеть' ? 'network' : 'activity'}))}
|
||||
activeSection={section} onSectionChange={setSection} onClose={onClose}>
|
||||
{error && <><Description role="alert">{error}</Description><Button onClick={() => setAttempt(n => n + 1)}>Обновить настройки</Button></>}
|
||||
{!error && !items.length && <Description role="status">Загружаем настройки…</Description>}
|
||||
{groups.map(group => <SettingsCard key={group} title={group}>
|
||||
{current.filter(item => item.group === group).map(item => <Checker key={item.key}
|
||||
label={item.label} checked={item.enabled} disabled={saving}
|
||||
onChange={enabled => void configure(item.key, enabled)}/>)}
|
||||
</SettingsCard>)}
|
||||
</FeatureSettingsWindow>;
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
import {useEffect, useRef, useState, type ReactNode} from 'react';
|
||||
import {ApplicationSidePanel, Button, Description, Icon, IconButton, ResourceList, ResourceRow, StatusBadge, ToastStack} from '@nodedc/ui-react';
|
||||
import {NotificationContext, useNotificationHistory, useNotifications} from '../../core/notifications/useNotificationHistory';
|
||||
import type {NotificationTone} from '../../core/notifications/history';
|
||||
import {EventSettings} from './EventSettings';
|
||||
|
||||
const tones = {success: 'success', warning: 'warning', error: 'danger', info: 'neutral'} as const;
|
||||
const labels: Record<NotificationTone, string> = {success: 'Успешно', warning: 'Внимание', error: 'Ошибка', info: 'Информация'};
|
||||
|
||||
export function NotificationHost({children}: {children: ReactNode}) {
|
||||
const state = useNotificationHistory();
|
||||
return <NotificationContext.Provider value={state}>
|
||||
{children}
|
||||
<ToastStack items={state.toasts} onDismiss={state.dismiss} observe={false}/>
|
||||
</NotificationContext.Provider>;
|
||||
}
|
||||
|
||||
export function EventPanel() {
|
||||
const state = useNotifications();
|
||||
const [settings, setSettings] = useState(false);
|
||||
const gear = useRef<HTMLButtonElement>(null);
|
||||
const close = () => {
|
||||
state.setOpen(false);
|
||||
document.querySelector<HTMLButtonElement>('[aria-controls="operator-events"]')?.focus();
|
||||
};
|
||||
useEffect(() => {
|
||||
if (!state.open) return;
|
||||
gear.current?.focus({preventScroll: true});
|
||||
}, [state.open]);
|
||||
return <ApplicationSidePanel id="operator-events" eyebrow="Mission Core" title="Центр событий"
|
||||
inert={!state.open} aria-label="Центр событий" closeLabel="Закрыть центр событий" onClose={close}
|
||||
onKeyDown={event => {
|
||||
if (event.key === 'Escape' && !settings) { event.stopPropagation(); close(); }
|
||||
}}
|
||||
headerActions={<IconButton ref={gear} label="Настройки центра событий" onClick={() => setSettings(true)}><Icon name="settings"/></IconButton>}>
|
||||
{state.error && <Description role="status">{state.error}</Description>}
|
||||
{!state.items.length && <Description>{state.loading ? 'Получаем события…' : 'Событий пока нет.'}</Description>}
|
||||
<ResourceList aria-label="История событий">{state.items.map(item => <li key={item.identity}>
|
||||
<ResourceRow title={item.title} description={item.description}
|
||||
metadata={new Date(item.at * 1000).toLocaleString('ru-RU')}
|
||||
statusPlacement="leading" status={<StatusBadge variant="indicator" tone={tones[item.tone]}
|
||||
aria-label={labels[item.tone]} title={labels[item.tone]}/>}/>
|
||||
</li>)}</ResourceList>
|
||||
{state.more && <Button loading={state.loading} onClick={() => void state.loadMore()}>Показать ещё</Button>}
|
||||
{settings && state.open && <EventSettings onClose={() => setSettings(false)}/>}
|
||||
</ApplicationSidePanel>;
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
import { useState } from "react";
|
||||
import { Description, ConfirmationModal, Icon, IconButton } from "@nodedc/ui-react";
|
||||
import type { ObservatoryRecordedJob } from "../../core/observatory/recordedJobs";
|
||||
import { deleteFailedRunProjection } from "../../core/observatory/failedRunHistory";
|
||||
|
||||
export function FailedRunActions({ job, onDeleted }: {
|
||||
job: ObservatoryRecordedJob;
|
||||
onDeleted: () => void;
|
||||
}) {
|
||||
const [open, setOpen] = useState(false);
|
||||
const [pending, setPending] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
return <>
|
||||
<IconButton label="Удалить ошибочную попытку" onClick={() => { setError(null); setOpen(true); }}>
|
||||
<Icon name="trash" size={16} />
|
||||
</IconButton>
|
||||
<ConfirmationModal open={open} title="Удалить ошибочную попытку?"
|
||||
description={<><Description>Попытка и её рабочие файлы будут удалены с этого устройства и Worker. Исходная запись сохранится.</Description>
|
||||
{error ? <Description role="alert">{error}</Description> : null}</>}
|
||||
confirmLabel="Удалить попытку" pendingLabel="Удаляем…" danger
|
||||
onClose={() => { if (!pending) setOpen(false); }}
|
||||
onConfirm={async () => {
|
||||
setPending(true); setError(null);
|
||||
try { await deleteFailedRunProjection(job); setOpen(false); onDeleted(); }
|
||||
catch (cause) { setError(cause instanceof Error ? cause.message : "Не удалось удалить попытку."); }
|
||||
finally { setPending(false); }
|
||||
}} />
|
||||
</>;
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
import { ConfirmationModal, Icon, IconButton, ToastStack, type ToastItem } from "@nodedc/ui-react";
|
||||
import { announceLabStorageChange, pinLabCopy, prepareLocalLabCopy, removeLabCopy,
|
||||
type LocalLabCopy } from "../../core/storage/localLabStorage";
|
||||
import { formatLocalLabSize } from "../../core/storage/localLabPresentation";
|
||||
import type { LabReplayProgress } from "../../core/laboratory/prepareLabReplay";
|
||||
|
||||
export type LabCopyProgress = LabReplayProgress;
|
||||
|
||||
export function LabCopyActions({ id, sourceId, composition = false, copy, available, storageError, onProgress }: {
|
||||
id: string; sourceId: string; composition?: boolean; copy?: LocalLabCopy;
|
||||
available: boolean; storageError: string | null;
|
||||
onProgress?: (value: LabReplayProgress | null) => void;
|
||||
}) {
|
||||
const [busy, setBusy] = useState<"download" | "pin" | "remove" | null>(null);
|
||||
const [toasts, setToasts] = useState<ToastItem[]>([]);
|
||||
const [confirm, setConfirm] = useState(false);
|
||||
const request = useRef<AbortController | null>(null);
|
||||
const progressCallback = useRef(onProgress);
|
||||
progressCallback.current = onProgress;
|
||||
useEffect(() => () => { request.current?.abort(); progressCallback.current?.(null); }, []);
|
||||
const status = storageError ?? (!available ? "Проверяем локальную копию"
|
||||
: copy?.local ? `На этом устройстве · ${formatLocalLabSize(copy, true)}`
|
||||
: "Загрузить запись на это устройство");
|
||||
async function perform(kind: "download" | "pin" | "remove", action: (signal: AbortSignal) => Promise<unknown>) {
|
||||
if (request.current) return;
|
||||
const controller = new AbortController(); request.current = controller;
|
||||
setBusy(kind); setToasts([]);
|
||||
try {
|
||||
await action(controller.signal);
|
||||
if (!controller.signal.aborted) setConfirm(false);
|
||||
} catch (reason) {
|
||||
if (!controller.signal.aborted) setToasts([{ id: "lab-copy-error", tone: "error",
|
||||
title: "Не удалось изменить локальную копию",
|
||||
description: reason instanceof Error ? reason.message : "Повторите действие." }]);
|
||||
} finally {
|
||||
announceLabStorageChange();
|
||||
progressCallback.current?.(null);
|
||||
request.current = null;
|
||||
if (!controller.signal.aborted) setBusy(null);
|
||||
}
|
||||
}
|
||||
const prepare = (signal: AbortSignal) => prepareLocalLabCopy(id, sourceId, composition,
|
||||
{ signal, onProgress: (value) => progressCallback.current?.(value) });
|
||||
const unavailable = !available || !!storageError;
|
||||
return <>
|
||||
<IconButton label={status} loading={busy === "download"}
|
||||
disabled={!!busy || unavailable || !!copy?.local}
|
||||
onClick={() => void perform("download", prepare)}>
|
||||
<Icon name={copy?.local ? "database" : "download"} size={16} />
|
||||
</IconButton>
|
||||
<IconButton label={copy?.pinned ? "Открепить локальную запись" : "Оставить полную запись на этом устройстве"}
|
||||
aria-pressed={copy?.pinned ?? false} loading={busy === "pin"} disabled={!!busy || unavailable}
|
||||
onClick={() => void perform("pin", async (signal) => {
|
||||
if (!copy?.local && !copy?.pinned) await prepare(signal);
|
||||
signal.throwIfAborted();
|
||||
await pinLabCopy(id, !copy?.pinned);
|
||||
})}>
|
||||
<Icon name="pin" size={16} />
|
||||
</IconButton>
|
||||
{copy?.local ? <IconButton label="Удалить только локальную копию" loading={busy === "remove"}
|
||||
disabled={!!busy || copy.pinned || unavailable} onClick={() => setConfirm(true)}>
|
||||
<Icon name="minus" size={16} />
|
||||
</IconButton> : null}
|
||||
<ToastStack items={toasts} onDismiss={(key) => setToasts((items) => items.filter((item) => item.id !== key))} />
|
||||
<ConfirmationModal open={confirm} title="Удалить локальную копию?"
|
||||
description="Результат и история запуска останутся. Копию можно вернуть кнопкой загрузки или открытием просмотра."
|
||||
confirmLabel="Удалить копию" cancelLabel="Отмена" onClose={() => { if (!busy) setConfirm(false); }}
|
||||
onConfirm={() => perform("remove", () => removeLabCopy(id))} />
|
||||
</>;
|
||||
}
|
||||
@@ -3,29 +3,40 @@ import {Button,Description,Select,SettingsCard,Switch,Window,WindowFooterActions
|
||||
import {localDevOptions,type DevOptions,type RoverDiagnostics} from '../../core/fleet/useRoverDiagnostics';
|
||||
import './roverLogs.css';
|
||||
|
||||
export function RoverDevWindow({capture,close,started}:{capture:RoverDiagnostics;close:()=>void;started:()=>void}){
|
||||
export function RoverDevWindow({capture,close}:{capture:RoverDiagnostics;close:()=>void}){
|
||||
const [options,setOptions]=useState<DevOptions>({...localDevOptions});
|
||||
const [local,setLocal]=useState({enabled:true,preview:true});
|
||||
const set=(key:keyof DevOptions,value:boolean|number)=>setOptions(current=>({...current,[key]:value}));
|
||||
const rates=[8,16,32,64].map(value=>({value:String(value),label:`${value} кбит/с`}));
|
||||
const begin=async()=>{if(await capture.toggle(options,local)){started();close();}};
|
||||
return <Window open onClose={close} title="Настройки DEV-записи" size="md" footer={<WindowFooterActions><Button onClick={close}>Отмена</Button><Button variant="primary" loading={capture.pending} disabled={!capture.state.options_supported} onClick={()=>void begin()}>Начать запись</Button></WindowFooterActions>}>
|
||||
const begin=async()=>{if(await capture.toggle({...options,router:!!capture.state.sources_supported&&options.router,system:!!capture.state.sources_supported&&options.system},local)){close();}};
|
||||
return <Window open onClose={close} title="Настройки DEV-записи" size="md" footer={<WindowFooterActions><Button onClick={close}>Отмена</Button><Button variant="primary" loading={capture.pending} disabled={!capture.state.options_supported||(options.passive&&!capture.state.passive_supported)} onClick={()=>void begin()}>Начать запись</Button></WindowFooterActions>}>
|
||||
<div className="rover-dev-options">
|
||||
<Description>Запись сохраняется на борту. После завершения её можно скачать в окне логов. Закрытие окна не останавливает запись.</Description>
|
||||
<SettingsCard title="Что записывать" description="Переходы управления, остановки и ошибки записываются всегда.">
|
||||
<Switch label="Подробные замеры моторов" checked={options.motor_samples} onChange={value=>set('motor_samples',value)}/>
|
||||
<Switch label="Сетевые события и распределение полосы" checked={options.network} onChange={value=>set('network',value)}/>
|
||||
<Switch label="Моторы и CAN" checked={options.motor_samples} onChange={value=>set('motor_samples',value)}/>
|
||||
<Switch label="Связь с Mission Core" checked={options.network} onChange={value=>set('network',value)}/>
|
||||
<Description>Доставка команд и телеметрии, задержки, распределение полосы, сетевой путь и счётчики интерфейсов.</Description>
|
||||
<Switch label="Роутер и SIM-карты" disabled={!capture.state.sources_supported} checked={!!capture.state.sources_supported&&options.router} onChange={value=>set('router',value)}/>
|
||||
<Description>Режим роутера, активный выход, состояние SIM и радиосигнал с временем исходного замера. В пассивном режиме используются обычные обновления роутера.</Description>
|
||||
<Switch label="Состояние борта и оборудования" disabled={!capture.state.sources_supported} checked={!!capture.state.sources_supported&&options.system} onChange={value=>set('system',value)}/>
|
||||
<Description>Сетевые интерфейсы, USB-устройства, нагрузка и задержки выполнения на борту.</Description>
|
||||
{!capture.state.sources_supported&&<Description>Новые источники записи станут доступны после обновления Node.</Description>}
|
||||
</SettingsCard>
|
||||
<SettingsCard title="Замеры на компьютере" description="Задержки команд и события браузера сохраняются отдельно от записи борта. Эти замеры не передаются на борт.">
|
||||
<Switch label="Записать замеры Core и браузера" checked={local.enabled} onChange={enabled=>setLocal(current=>({...current,enabled}))}/>
|
||||
{local.enabled&&<><Switch label="Добавить статистику видео" checked={local.preview} onChange={preview=>setLocal(current=>({...current,preview}))}/><Description>Без записи изображения. Замер хранится в памяти до перезапуска Core: не более 15 минут и последних 6000 событий. После остановки сохраните его отдельной кнопкой в окне логов.</Description></>}
|
||||
{local.enabled&&<><Switch label="Добавить статистику видео" checked={local.preview} onChange={preview=>setLocal(current=>({...current,preview}))}/><Description>Без записи изображения. Замер сохраняется на компьютере до одного часа, не более 32 МБ. Доступны текущий и три предыдущих файла; перезапуск Core их не удаляет.</Description></>}
|
||||
</SettingsCard>
|
||||
<SettingsCard title="Передача во время записи" description={!options.live&&!options.core_trace?'Диагностические события остаются на борту. По сети передаётся только короткое состояние записи.':'Эти потоки используют сеть. На слабом канале их можно отключить и скачать файл позже.'}>
|
||||
<SettingsCard title="Передача во время записи" description={options.passive?'Логи остаются на борту и в Core. Дополнительных сетевых запросов во время записи нет; выгрузка — по вашему запросу.':!options.live&&!options.core_trace?'Диагностические события остаются на борту. По сети передаётся только короткое состояние записи.':'Эти потоки используют сеть. На слабом канале их можно отключить и скачать файл позже.'}>
|
||||
<Switch label="Пассивная запись" checked={options.passive} onChange={passive=>setOptions(current=>({...current,passive,...(passive?{live:false,core_trace:false}:{})}))}/>
|
||||
{options.passive&&<Description>Подтверждения запуска и остановки передаются один раз. Статистика браузера добавляется при остановке или сохранении; до этого она хранится локально в браузере.</Description>}
|
||||
{!options.passive&&<>
|
||||
<Switch label="Показывать события онлайн" checked={options.live} onChange={value=>set('live',value)}/>
|
||||
{options.live&&<Select label="Лимит live-событий" value={String(options.live_kbps)} options={rates} onChange={value=>set('live_kbps',Number(value))}/>}
|
||||
<Switch label="Добавлять события Core и браузера" checked={options.core_trace} onChange={value=>set('core_trace',value)}/>
|
||||
{options.core_trace&&<><Description>Эти события передаются с компьютера оператора на борт. При нехватке полосы пропуски отмечаются в записи.</Description><Select label="Лимит событий на борт" value={String(options.core_kbps)} options={rates} onChange={value=>set('core_kbps',Number(value))}/></>}
|
||||
</>}
|
||||
</SettingsCard>
|
||||
{options.passive&&!capture.state.passive_supported&&<Description>Для пассивной записи требуется обновление Node на борту.</Description>}
|
||||
{!capture.state.options_supported&&<Description>Борт ещё не подтвердил доступность настроек записи. Запуск станет доступен после подключения совместимого борта.</Description>}
|
||||
</div>
|
||||
</Window>;
|
||||
|
||||
@@ -1,21 +1,28 @@
|
||||
import {useState} from 'react';
|
||||
import {createPortal} from 'react-dom';
|
||||
import {Button,StatusBadge} from '@nodedc/ui-react';
|
||||
import { Description,Button,Select,StatusBadge} from '@nodedc/ui-react';
|
||||
import type {RoverDiagnostics} from '../../core/fleet/useRoverDiagnostics';
|
||||
import type {ObservationHeaderTargets} from '../../../../../packages/sensor-ui/src/observation';
|
||||
import './roverLogs.css';
|
||||
export function RoverLogs({capture,header}:{capture:RoverDiagnostics;header:ObservationHeaderTargets}){
|
||||
const [selected,setSelected]=useState('');
|
||||
const localCaptures=[capture.state.local_capture,...(capture.state.local_history??[])].filter(item=>item?.id);
|
||||
const selectedCapture=localCaptures.find(item=>item?.id===selected)??localCaptures[0];
|
||||
const storage=capture.state.node?.storage,failed=storage?.error||capture.state.node?.transport_error;
|
||||
const passive=capture.state.active&&capture.state.options?.passive===true;
|
||||
const status=failed?'Ошибка записи':capture.state.closing?'Завершение записи':storage?.closed?'Запись завершена':capture.state.node?.active?'Запись на борт':'Ожидание борта';
|
||||
return <>
|
||||
{createPortal(<StatusBadge variant="indicator" tone={failed?'danger':capture.state.node?.active?'success':'warning'} aria-label={status} title={status}/>,header.statusTarget)}
|
||||
|
||||
<div className="rover-logs">
|
||||
<div className="rover-logs__actions"><Button disabled={!storage?.file} loading={capture.saving} onClick={()=>void capture.save()}>Сохранить с борта</Button>{capture.state.local_capture?.id&&<Button loading={capture.saving} onClick={()=>void capture.saveLocal()}>Сохранить с компьютера</Button>}</div>
|
||||
<p>{status} · {storage?.written??0} записей{storage?.dropped?` · Потеряно при записи: ${storage.dropped}`:''}</p>
|
||||
{storage?.file&&<p title={storage.file}>{storage.file}</p>}
|
||||
{failed&&<p role="alert">Файл может быть неполным: {failed}</p>}
|
||||
<p>{capture.state.options?.live===false?'События записываются локально; live-передача отключена.':'Последние события онлайн.'} «Сохранить с борта» выгружает полный бортовой файл. Закрытие окна не завершает запись.</p>
|
||||
{capture.state.local_capture?.id&&<p>Замер компьютера: {capture.state.local_capture.active?'идёт запись':'завершён'} · {capture.state.local_capture.sequence??0} событий{capture.state.local_capture.dropped?` · Пропущено: ${capture.state.local_capture.dropped}`:''}. Сохраните до перезапуска Core.</p>}
|
||||
<div className="rover-logs__actions"><Button disabled={!storage?.file} loading={capture.saving} onClick={()=>void capture.save()}>Сохранить с борта</Button>{selectedCapture?.id&&<Button loading={capture.saving} onClick={()=>void capture.saveLocal(selectedCapture.id!)}>Сохранить с компьютера</Button>}</div>
|
||||
{localCaptures.length>1&&<Select label="Замер компьютера" value={selectedCapture?.id??''} options={localCaptures.map(item=>({value:item!.id!,label:`${item!.started_at?new Date(item!.started_at).toLocaleString('ru-RU'):'Последний замер'} · ${item!.active?'Запись идёт':'Завершён'}`}))} onChange={setSelected}/>}
|
||||
<Description>{status}{passive?' · Пассивная запись':` · ${storage?.written??0} записей`}{storage?.dropped?` · Потеряно при записи: ${storage.dropped}`:''}</Description>
|
||||
{storage?.file&&<Description title={storage.file}>{storage.file}</Description>}
|
||||
{failed&&<Description role="alert">Файл может быть неполным: {failed}</Description>}
|
||||
<Description>{passive?(capture.state.passive_confirmed?'Запуск подтверждён. Состояние файла обновится при остановке или сохранении.':'Ожидаем подтверждение запуска записи на борту.'):capture.state.options?.live===false?'События записываются локально; live-передача отключена.':'Последние события онлайн.'} «Сохранить с борта» выгружает полный бортовой файл. Закрытие окна не завершает запись.</Description>
|
||||
{selectedCapture?.id&&<Description>Замер компьютера: {selectedCapture.active?'идёт запись':'завершён'} · {selectedCapture.storage?.written??selectedCapture.sequence??0} событий{(selectedCapture.storage?.dropped??selectedCapture.dropped)?` · Пропущено: ${selectedCapture.storage?.dropped??selectedCapture.dropped}`:''}. Доступны текущий и три предыдущих файла. Новый запуск постепенно заменяет старые замеры; нужные можно скачать.</Description>}
|
||||
{selectedCapture?.storage?.error&&<Description role="alert">Замер компьютера может быть неполным: {selectedCapture.storage.error}</Description>}
|
||||
<div className="rover-logs__entries" role="log" aria-live="off" aria-label="События DEV-сессии">
|
||||
{[...capture.rows].reverse().map(item=>{const row=item.record??item;return <pre key={item.record_sequence}>{JSON.stringify(row,null,2)}</pre>;})}
|
||||
</div>
|
||||
|
||||
@@ -1,9 +1,12 @@
|
||||
import {ComparisonTable,Description,StatusBadge} from '@nodedc/ui-react';
|
||||
import type {RoverState} from '../../core/fleet/useRoverControl';
|
||||
import type {RoverObservationStatus} from '../../core/fleet/roverObservation';
|
||||
import {ObservationHeader} from '../../../../../packages/sensor-ui/src/ObservationHeader';
|
||||
import type {ObservationHeaderTargets} from '../../../../../packages/sensor-ui/src/observation';
|
||||
import type {RoverConnection} from '../../core/fleet/roverTransport';
|
||||
import {drivePositions} from '../../../../../plugins/vesc/frontend/src/model';
|
||||
const number=(v:number|undefined,digits=1)=>typeof v==='number'&&Number.isFinite(v)?v.toLocaleString('ru-RU',{maximumFractionDigits:digits}):'—';
|
||||
export function roverTelemetryTable(state:RoverState){
|
||||
export function roverTelemetryTable(state:RoverState,compact=false){
|
||||
const devices=state.snapshot.devices??[],profile=state.snapshot.profile;
|
||||
const positions=drivePositions(profile?.layout??null);
|
||||
const assigned=Object.entries(profile?.bindings??{}).map(([slot,binding])=>({
|
||||
@@ -13,17 +16,24 @@ export function roverTelemetryTable(state:RoverState){
|
||||
const readings=[...assigned,...devices.filter(d=>!assigned.some(a=>a.id===d.id&&a.uuid===d.uuid)).map(d=>({...d,reading:d}))];
|
||||
const fresh=(d:typeof readings[number])=>state.fresh&&!!d.reading&&Number.isFinite(d.reading.age_ms)&&d.reading.age_ms>=0&&d.reading.age_ms<1000;
|
||||
const metrics=[['motor_current_a','Ток мотора','А',1],['input_current_a','Ток батареи','А',1],['input_voltage_v','Напряжение','В',1],['erpm','Обороты, ERPM','',0],['mos_temperature_c','Контроллер','°C',1]] as const;
|
||||
const available=readings.filter(fresh).length;
|
||||
const health=state.snapshot.supported&&available>0&&available===readings.length?'online':available||state.snapshot.observation?.initializing_devices?.length?'partial':'offline';
|
||||
return {
|
||||
columns:readings.map(d=>({id:d.id+':'+d.uuid,label:d.uuid.slice(0,6).toUpperCase()})),
|
||||
health,columns:readings.map(d=>({id:d.id+':'+d.uuid,label:d.uuid.slice(0,6).toUpperCase()})),
|
||||
rows:[{id:'position',label:'Расположение',cells:readings.map(d=>d.label||'Не назначено')},
|
||||
{id:'status',label:'Связь',cells:readings.map(d=>!state.fresh?'Нет данных':!d.reading?'Нет связи':fresh(d)?'В сети':'Нет данных')},
|
||||
...metrics.map(([key,label,unit,digits])=>({id:key,label,cells:readings.map(d=>{const value=fresh(d)?d.reading?.values?.[key]:undefined;return typeof value==='number'&&Number.isFinite(value)?`${number(value,digits)}${unit?' '+unit:''}`:'—';})})),
|
||||
{id:'fault',label:'Ошибка VESC',cells:readings.map(d=>{const code=fresh(d)?d.reading?.values?.fault_code:undefined;return typeof code==='number'?code===0?'Нет':String(code):'—';})}],
|
||||
...(compact?metrics.slice(0,1):metrics).map(([key,label,unit,digits])=>({id:key,label,cells:readings.map(d=>{const value=fresh(d)?d.reading?.values?.[key]:undefined;return typeof value==='number'&&Number.isFinite(value)?`${number(value,digits)}${unit?' '+unit:''}`:'—';})})),
|
||||
...(!compact?[{id:'fault',label:'Ошибка VESC',cells:readings.map(d=>{const code=fresh(d)?d.reading?.values?.fault_code:undefined;return typeof code==='number'?code===0?'Нет':String(code):'—';})}]:[])],
|
||||
};
|
||||
}
|
||||
export function RoverTelemetry({state,observation}:{state:RoverState;observation?:RoverObservationStatus}){
|
||||
const table=roverTelemetryTable(state);
|
||||
return <div className="rover-telemetry">{observation?.label&&<StatusBadge tone="warning" pulse={observation.pulse}>{observation.label}</StatusBadge>}{table.columns.length?<ComparisonTable density="compact" label="Телеметрия VESC" heading="VESC" {...table}/>:!observation?.label&&<Description>{state.fresh?'Получение показаний VESC…':'Нет свежих показаний VESC.'}</Description>}</div>;
|
||||
export function RoverTelemetry({state,observation,compact=false,header,connection='connected'}:{
|
||||
state:RoverState;observation?:RoverObservationStatus;compact?:boolean;header?:ObservationHeaderTargets;connection?:RoverConnection
|
||||
}){
|
||||
const table=roverTelemetryTable(state,compact);
|
||||
const live=connection==='connected' && state.fresh && table.health==='online';
|
||||
const waiting=connection==='connecting'||connection==='reconnecting'||(connection==='connected'&&state.fresh&&table.health==='partial');
|
||||
const label=live?'Телеметрия VESC поступает':waiting?'Ожидание свежей телеметрии VESC':'Телеметрия VESC недоступна';
|
||||
return <div className="rover-telemetry">{header&&<ObservationHeader targets={header} live={live} waiting={waiting} label={label}/>}{observation?.label&&<StatusBadge tone="warning" pulse={observation.pulse}>{observation.label}</StatusBadge>}{table.columns.length?<ComparisonTable density="compact" label="Телеметрия VESC" heading="VESC" {...table}/>:!observation?.label&&<Description>{state.fresh?'Получение показаний VESC…':'Нет свежих показаний VESC.'}</Description>}</div>;
|
||||
}
|
||||
|
||||
export function roverTelemetryMinimum(state:RoverState){return {width:Math.max(288,144+88*roverTelemetryTable(state).columns.length),height:280};}
|
||||
export function roverTelemetryMinimum(state:RoverState,compact=false){return {width:Math.max(288,144+88*roverTelemetryTable(state).columns.length),height:compact?172:280};}
|
||||
|
||||
@@ -1,10 +1,12 @@
|
||||
import {useObservationView} from '../../core/observation/useObservationView';
|
||||
import {roverModelID} from '../../core/roverScene/model';
|
||||
import {lazy,Suspense,useCallback,useEffect,useRef,useState} from 'react';
|
||||
import {createPortal} from 'react-dom';
|
||||
import {Button,EditorWorkspace,Icon,IconButton,KeyButton,LoadingRegion,Select,StatusBadge,TextField,ToastStack,Window} from '@nodedc/ui-react';
|
||||
import { Description,Button,EditorWorkspace,Icon,IconButton,KeyButton,LoadingRegion,Select,StatusBadge,TextField,ToastStack,Window} from '@nodedc/ui-react';
|
||||
import {keysFor,roverSettings,roverNumberInput,persistableRoverSettings,type RoverMode} from '../../core/fleet/roverInput';
|
||||
import {roverDevEvent} from '../../core/fleet/roverDevEvents';
|
||||
import {bindRoverHoldInput} from '../../core/fleet/roverHoldInput';
|
||||
import {useRoverTelemetryPolicy} from '../../core/fleet/useRoverTelemetryPolicy';
|
||||
import {bindRoverHoldInput,hasBlockingRoverOverlay} from '../../core/fleet/roverHoldInput';
|
||||
import type {RoverController} from '../../core/fleet/useRoverControl';
|
||||
import {roverObservationStatus,type RoverObservationStatus} from '../../core/fleet/roverObservation';
|
||||
import type {ObservationHeaderTargets} from '../../../../../packages/sensor-ui/src/observation';
|
||||
@@ -15,7 +17,11 @@ const labels:Record<string,string>={observing:'Наблюдение',preparing:'
|
||||
export function RoverView({vehicleID,name,controller:c,header,active,observation}:{vehicleID:string;name:string;controller:RoverController;header:ObservationHeaderTargets;active:boolean;observation?:RoverObservationStatus}){
|
||||
const storage=`missioncore.rover-view.v1:${vehicleID}`;
|
||||
const [settings,setSettings]=useState(()=>{try{return roverSettings(JSON.parse(localStorage.getItem(storage)??'null'));}catch{return roverSettings(null);}});
|
||||
const presentation=useObservationView('rover-view',vehicleID,()=>({schema:'missioncore.rover-view/v1' as const,model:''}),async()=>{
|
||||
try{const raw=localStorage.getItem(storage);return raw?{schema:'missioncore.rover-view/v1' as const,model:roverSettings(JSON.parse(raw)).model}:null;}catch{return null;}
|
||||
});
|
||||
const [open,setOpen]=useState(false),[held,setHeld]=useState<Set<string>>(new Set());
|
||||
const telemetryPolicy=useRoverTelemetryPolicy(vehicleID,open);
|
||||
const [editing,setEditing]=useState(false);
|
||||
const [modelState,setModelState]=useState<'loading'|'ready'|'error'>('loading');
|
||||
const stage=useRef<HTMLDivElement>(null),input=useRef<ReturnType<typeof bindRoverHoldInput>|null>(null);
|
||||
@@ -25,7 +31,7 @@ export function RoverView({vehicleID,name,controller:c,header,active,observation
|
||||
focusAfterArm.current=false;
|
||||
// Window restores its opener on close. Transfer input after that cleanup,
|
||||
// once only, without taking focus back from another window or dialog.
|
||||
const frame=requestAnimationFrame(()=>{if(active&&!document.hidden&&document.hasFocus()&&!document.querySelector('[role=dialog],[role=listbox]'))stage.current?.focus({preventScroll:true});});
|
||||
const frame=requestAnimationFrame(()=>{if(active&&!document.hidden&&document.hasFocus()&&!hasBlockingRoverOverlay(document))stage.current?.focus({preventScroll:true});});
|
||||
return()=>cancelAnimationFrame(frame);
|
||||
},[open,active]);
|
||||
const stop=useCallback(()=>{input.current?.dispose();input.current=null;c.setInputGuard(null);setHeld(new Set());c.stop();},[c.stop,c.setInputGuard]);
|
||||
@@ -57,10 +63,10 @@ export function RoverView({vehicleID,name,controller:c,header,active,observation
|
||||
onKeyDown={e=>{if(!c.ready&&(c.armed||c.pending||c.recovering)&&e.isTrusted&&['Space','Escape'].includes(e.code)){e.preventDefault();stop();}}}
|
||||
onBlur={e=>{if(c.armed&&!e.currentTarget.contains(e.relatedTarget as Node|null))c.pauseInput();}}>
|
||||
<EditorWorkspace editing={editing&&active} title={`Ровер / ${name}`} subtitle="Редактирование сцены" onBack={()=>setEditing(false)}>
|
||||
{settings.model===roverModelID?<LoadingRegion className="rover-view__scene" loading={modelState==='loading'||c.recovering} label={c.recovering?'Восстанавливаем связь':'Загрузка модели ровера'}>
|
||||
{!presentation.ready?<LoadingRegion loading label="Загрузка настроек вида"/>:presentation.document.model===roverModelID?<LoadingRegion className="rover-view__scene" loading={modelState==='loading'||c.recovering} label={c.recovering?'Восстанавливаем связь':'Загрузка модели ровера'}>
|
||||
<Suspense fallback={null}><Scene key={vehicleID} vehicleID={vehicleID} editing={editing&&active} onModelState={setModelState}/></Suspense>
|
||||
{modelState==='error'&&<p className="rover-view__empty">Не удалось загрузить модель ровера.</p>}
|
||||
</LoadingRegion>:<div className="rover-view__empty"><p>Выберите модель аппарата.</p><Button onClick={showSettings}>Настройки вида</Button></div>}
|
||||
</LoadingRegion>:<div className="rover-view__empty"><Description>Выберите модель аппарата.</Description><Button onClick={showSettings}>Настройки вида</Button></div>}
|
||||
{c.ready&&!editing&&<div className="rover-view__controls">
|
||||
<div className={`rover-keys rover-keys--${settings.mode}`} aria-label={settings.mode==='arcade'?'Аркадное управление':'Танковое управление'}>
|
||||
{keysFor(settings.mode).map(code=><KeyButton key={code} className={`rover-key-${code}`} label={settings.mode==='arcade'?({KeyW:'Вперёд · W',KeyS:'Назад · S',KeyA:'Налево · A',KeyD:'Направо · D'}[code]??code):({KeyQ:'Левая сторона вперёд · Q',KeyA:'Левая сторона назад · A',KeyE:'Правая сторона вперёд · E',KeyD:'Правая сторона назад · D'}[code]??code)}
|
||||
@@ -75,15 +81,18 @@ export function RoverView({vehicleID,name,controller:c,header,active,observation
|
||||
</EditorWorkspace>
|
||||
</div>
|
||||
<Window open={open} onClose={()=>setOpen(false)} title="Управление ровером" size="md"><div className="rover-settings">
|
||||
{presentation.error&&<><Description>{presentation.error}</Description><Button onClick={presentation.retry}>Повторить сохранение вида</Button></>}
|
||||
<Select label="Тип управления" value={settings.mode} options={[{value:'arcade',label:'Аркадный · W A S D'},{value:'tank',label:'Танковый · Q A / E D'}]} onChange={mode=>setSettings(v=>({...v,mode:mode as RoverMode}))}/>
|
||||
<Select label="3D-модель" value={settings.model} options={[{value:'',label:'Не выбрана'},{value:roverModelID,label:'DCD-006 · сборка v022'}]} onChange={model=>setSettings(v=>({...v,model}))}/>
|
||||
<Select label="3D-модель" disabled={!presentation.ready} value={presentation.document.model} options={[{value:'',label:'Не выбрана'},{value:roverModelID,label:'DCD-006 · сборка v022'}]} onChange={model=>presentation.update(v=>({...v,model}))}/>
|
||||
{duty?<TextField label="Газ, %" hint="1–100" description="Доля полного газа пульта. Фактическая скорость зависит от нагрузки." type="number" min={1} max={100} step={1} value={Number.isFinite(settings.throttlePercent)?settings.throttlePercent:''} onChange={e=>setSettings(v=>({...v,throttlePercent:roverNumberInput(e.target.value)}))}/>:
|
||||
<TextField label="Скорость, ERPM" hint="300–3000" description="Электрические обороты двигателя. Скорость по земле требует параметров трансмиссии." type="number" min={300} max={3000} step={100} value={Number.isFinite(settings.maxErpm)?settings.maxErpm:''} onChange={e=>setSettings(v=>({...v,maxErpm:roverNumberInput(e.target.value)}))}/>}
|
||||
<TextField label="Предел тока каждого мотора, А" description={currentDescription} type="number" min={.5} step={.5} value={Number.isFinite(settings.currentA)?settings.currentA:''} onChange={e=>setSettings(v=>({...v,currentA:roverNumberInput(e.target.value)}))}/>
|
||||
<TextField label="Максимальный возраст телеметрии, мс" hint="250–5000 · по умолчанию 1000" description="Управление останавливается, если возраст последних данных достигает этого порога. Применяется при следующем включении управления; срок действия команд не меняется." type="number" min={250} max={5000} step={50} disabled={!telemetryPolicy.ready} value={Number.isFinite(telemetryPolicy.value)?telemetryPolicy.value:''} onChange={e=>telemetryPolicy.setValue(roverNumberInput(e.target.value))} onBlur={()=>{if(telemetryPolicy.valid)void telemetryPolicy.save().catch(()=>{});}}/>
|
||||
{telemetryPolicy.error&&<Description>{telemetryPolicy.error}</Description>}
|
||||
{(availability||c.error)&&<StatusBadge tone="warning">{availability||c.error}</StatusBadge>}
|
||||
<p>Включайте управление на остановленном аппарате. Движение — только при удержании клавиш или кнопок. При уходе из окна команда снимается. После восстановления связи для движения нажмите клавишу заново. Команда с пульта прекращает удалённое управление.</p>
|
||||
<Button variant="primary" tone="neutral" disabled={!c.canArm||!!observing.label||!(Number.isFinite(settings.currentA)&&settings.currentA>=.5&&speedValid)} loading={c.pending}
|
||||
onClick={async()=>{roverDevEvent(`/api/v1/fleet/${encodeURIComponent(vehicleID)}/rover`,'settings',{mode:settings.mode,current_a:settings.currentA,speed:duty?settings.throttlePercent:settings.maxErpm,control_mode:duty?'duty':'rpm'});const acquired=await c.arm(settings.currentA,duty?settings.throttlePercent:settings.maxErpm,duty?'duty':'rpm');if(acquired){focusAfterArm.current=true;setOpen(false);}}}>Включить управление</Button>
|
||||
<Description>Включайте управление на остановленном аппарате. Движение — только при удержании клавиш или кнопок. При уходе из окна команда снимается. После восстановления связи для движения нажмите клавишу заново. Команда с пульта прекращает удалённое управление.</Description>
|
||||
<Button variant="primary" tone="neutral" disabled={!c.canArm||!!observing.label||!telemetryPolicy.ready||!telemetryPolicy.valid||!(Number.isFinite(settings.currentA)&&settings.currentA>=.5&&speedValid)} loading={c.pending}
|
||||
onClick={async()=>{try{const threshold=await telemetryPolicy.save();roverDevEvent(`/api/v1/fleet/${encodeURIComponent(vehicleID)}/rover`,'settings',{mode:settings.mode,current_a:settings.currentA,speed:duty?settings.throttlePercent:settings.maxErpm,control_mode:duty?'duty':'rpm',telemetry_stop_ms:threshold});const acquired=await c.arm(settings.currentA,duty?settings.throttlePercent:settings.maxErpm,duty?'duty':'rpm',threshold);if(acquired){focusAfterArm.current=true;setOpen(false);}}catch{/* Field retains the save error; no arm is sent. */}}}>Включить управление</Button>
|
||||
</div></Window>
|
||||
<ToastStack onDismiss={c.clearError} items={c.error?[{id:'rover-control-error',tone:'error',title:'Управление остановлено',description:c.error}]:[]}/>
|
||||
</>;
|
||||
|
||||
@@ -9,6 +9,8 @@ export function ChargeGradientInspector({value,onChange}:{value:ChargeGradient;o
|
||||
<RangeControl label="Сила свечения градиента" value={value.intensity} min={0} max={10} step={.05} exactValueBounds={{min:0,max:10}} onChange={intensity=>patch({intensity})}/>
|
||||
<RangeControl label="Скорость переливания" value={value.speed} min={0} max={3} step={.01} exactValueBounds={{min:0,max:3}} onChange={speed=>patch({speed})}/>
|
||||
<RangeControl label="Масштаб рисунка" value={value.scale} min={1} max={50} step={.1} exactValueBounds={{min:1,max:50}} onChange={scale=>patch({scale})}/>
|
||||
<RangeControl label="Контраст градиента" value={value.contrast} min={.1} max={4} step={.01} exactValueBounds={{min:.1,max:4}} onChange={contrast=>patch({contrast})}/>
|
||||
<RangeControl label="Насыщенность градиента" value={value.saturation} min={0} max={2} step={.01} exactValueBounds={{min:0,max:2}} onChange={saturation=>patch({saturation})}/>
|
||||
<Description>Ореол свечения настраивается в окружении → Bloom. При временном обрыве связи сохраняются последние цвет и яркость; движение возобновится с новыми показаниями.</Description>
|
||||
</div>;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,10 @@
|
||||
import {useState} from 'react';
|
||||
import {Button,Description,TextField,Window,WindowFooterActions} from '@nodedc/ui-react';
|
||||
export function DuplicateMaterialDialog({initialName,onDuplicate,onClose}:{initialName:string;onDuplicate:(name:string)=>void;onClose:()=>void}){
|
||||
const [name,setName]=useState(initialName),[error,setError]=useState('');
|
||||
const save=()=>{try{onDuplicate(name);onClose();}catch(e){setError(e instanceof Error?e.message:'Не удалось создать копию материала.');}};
|
||||
return <Window open title="Дублировать материал" size="sm" onClose={onClose} footer={<WindowFooterActions><Button onClick={onClose}>Отмена</Button><Button variant="primary" tone="neutral" disabled={!name.trim()} onClick={save}>Создать дубликат</Button></WindowFooterActions>}>
|
||||
<TextField label="Название дубликата" autoFocus maxLength={120} value={name} onChange={e=>{setName(e.target.value);setError('');}} onKeyDown={e=>{if(e.key==='Enter'&&!e.nativeEvent.isComposing&&name.trim()){e.preventDefault();save();}}}/>
|
||||
{error&&<Description role="alert">{error}</Description>}
|
||||
</Window>;
|
||||
}
|
||||
@@ -1,11 +1,13 @@
|
||||
import {EnvironmentProfiles} from './EnvironmentProfiles';
|
||||
import type {ReactNode} from 'react';
|
||||
import {LutField} from './LutField';
|
||||
import {useRef} from 'react';
|
||||
import {Button,ColorField,ControlRow,Inspector,InspectorSelectField,RangeControl,Switch,TextField} from '@nodedc/ui-react';
|
||||
import {environmentFields,fieldValue,fieldDisabled,type SceneDocument,type SceneField} from '../../../core/roverScene/sceneDocument';
|
||||
const labels:Record<string,string>={'Камера':'Камера',Lighting:'Освещение',Rendering:'Рендеринг',Grid:'Сетка',SSAO:'Контактное затенение · SSAO',Bloom:'Свечение · Bloom','Chromatic Aberration':'Хроматическая аберрация',TAA:'Временное сглаживание · TAA',Grading:'Цветокоррекция',LUT:'Цветовая таблица · LUT',Vignette:'Виньетка','Environment Atlas':'Карта окружения','Skybox':'Небо','Directional Light':'Направленный свет','Shadow Catcher':'Тень на поверхности'};
|
||||
export function EnvironmentInspector({document,onChange,onResetCamera,onError}:{document:SceneDocument;onChange:(key:string,value:unknown)=>void;onResetCamera:()=>void;onError:(error:string)=>void}){
|
||||
export function EnvironmentInspector({document,onChange,onResetCamera,onError,update,sceneFiles}:{document:SceneDocument;update:(fn:(doc:SceneDocument)=>SceneDocument)=>void;sceneFiles:ReactNode;onChange:(key:string,value:unknown)=>void;onResetCamera:()=>void;onError:(error:string)=>void}){
|
||||
const groups=[...new Set(environmentFields.map(f=>f.group))];
|
||||
return <Inspector defaultOpen={['Камера','PostProcess/Lighting']} sections={groups.map(group=>({id:group,label:labels[group.split('/').at(-1)!]??group,content:<div className="rover-scene-fields">{environmentFields.filter(f=>f.group===group).map(f=><EnvironmentField key={f.key} field={f} value={fieldValue(document,f.key)} disabled={fieldDisabled(document,f)} onChange={v=>onChange(f.key,v)} onResetCamera={onResetCamera} onError={onError}/>)}</div>}))}/>;
|
||||
return <Inspector defaultOpen={['profiles']} sections={[{id:'profiles',label:'Профили',content:<><EnvironmentProfiles document={document} update={update} onError={onError}/><Inspector sections={[{id:'scene-json',label:'Вся сцена · JSON',content:sceneFiles}]}/></>},...groups.map(group=>({id:group,label:labels[group.split('/').at(-1)!]??group,content:<div className="rover-scene-fields">{environmentFields.filter(f=>f.group===group).map(f=><EnvironmentField key={f.key} field={f} value={fieldValue(document,f.key)} disabled={fieldDisabled(document,f)} onChange={v=>onChange(f.key,v)} onResetCamera={onResetCamera} onError={onError}/>)}</div>}))]}/>;
|
||||
}
|
||||
function EnvironmentField({field:f,value,disabled,onChange,onResetCamera,onError}:{field:SceneField;value:unknown;disabled:boolean;onChange:(v:unknown)=>void;onResetCamera:()=>void;onError:(error:string)=>void}){
|
||||
if(f.type==='texture')return <LutField value={value as string|null} onChange={onChange} onError={onError}/>;
|
||||
@@ -17,7 +19,7 @@ function EnvironmentField({field:f,value,disabled,onChange,onResetCamera,onError
|
||||
if(f.type==='number')return <TextField type="number" label={f.label} min={f.min} max={f.max} step={f.step??.01} value={Number(value)} disabled={disabled} onChange={e=>onChange(Number(e.target.value))}/>;
|
||||
return <RangeControl label={f.label} value={Number(value)} min={f.min??0} max={f.max??100} step={f.step??.01} exactValueBounds={{min:f.min,max:f.max}} disabled={disabled} onChange={onChange}/>;
|
||||
}
|
||||
export function SceneFileActions({onImport,onExport,onReset}:{onImport:(file:File)=>void;onExport:()=>void;onReset:()=>void}){
|
||||
export function SceneFileActions({onImport,onExport}:{onImport:(file:File)=>void;onExport:()=>void}){
|
||||
const input=useRef<HTMLInputElement>(null);
|
||||
return <div className="rover-scene-actions"><Button size="compact" onClick={onExport}>Экспорт JSON</Button><Button size="compact" onClick={()=>input.current?.click()}>Импорт JSON</Button><Button size="compact" onClick={onReset}>Окружение NodeDC</Button><input ref={input} hidden type="file" accept=".json,application/json" onChange={e=>{const f=e.currentTarget.files?.[0];if(f)onImport(f);e.currentTarget.value='';}}/></div>;
|
||||
return <div className="rover-scene-actions"><Button size="compact" onClick={onExport}>Экспорт всей сцены</Button><Button size="compact" onClick={()=>input.current?.click()}>Импорт всей сцены</Button><input ref={input} hidden type="file" accept=".json,application/json" onChange={e=>{const f=e.currentTarget.files?.[0];if(f)onImport(f);e.currentTarget.value='';}}/></div>;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,33 @@
|
||||
import {useEffect,useRef,useState} from 'react';
|
||||
import {Button,Description,InspectorSelectField,TextField,Window,WindowFooterActions} from '@nodedc/ui-react';
|
||||
import {applyEnvironment,builtinEnvironment,environmentMatches,parseEnvironmentProfile,sceneEnvironment,type EnvironmentProfile,type StoredEnvironmentProfile} from '../../../core/roverScene/environmentProfiles';
|
||||
import {readEnvironmentProfiles,saveEnvironmentProfile,watchEnvironmentProfiles} from '../../../core/roverScene/environmentProfileStorage';
|
||||
import type {SceneDocument} from '../../../core/roverScene/sceneDocument';
|
||||
export function EnvironmentProfiles({document:doc,update,onError}:{document:SceneDocument;update:(fn:(doc:SceneDocument)=>SceneDocument)=>void;onError:(message:string)=>void}){
|
||||
const [profiles,setProfiles]=useState<StoredEnvironmentProfile[]>([]),[ready,setReady]=useState(false),[pending,setPending]=useState(false),[draft,setDraft]=useState<EnvironmentProfile|null>(null),[name,setName]=useState('');
|
||||
const input=useRef<HTMLInputElement>(null),mounted=useRef(true);
|
||||
useEffect(()=>{mounted.current=true;let generation=0;const refresh=()=>{const current=++generation;readEnvironmentProfiles().then(value=>{if(mounted.current&¤t===generation){setProfiles(value);setReady(true);}}).catch(e=>{if(mounted.current&¤t===generation)onError(e instanceof Error?e.message:'Не удалось прочитать профили.');});};refresh();const stop=watchEnvironmentProfiles(refresh);return()=>{mounted.current=false;stop();};},[onError]);
|
||||
const builtin=builtinEnvironment(),all=[builtin,...profiles],id=doc.environmentProfileId??(environmentMatches(doc,builtin.environment)?builtin.id:'current'),selected=all.find(p=>p.id===id);
|
||||
const dirty=!selected||!environmentMatches(doc,selected.environment);
|
||||
const current=():EnvironmentProfile=>({schema:'missioncore.environment-profile/v1',name:selected?.name??'Мой профиль',environment:sceneEnvironment(doc)});
|
||||
const begin=(value=current())=>{setDraft(value);setName(value.name==='NodeDC'?'Мой профиль':value.name);};
|
||||
const save=async(copy:boolean)=>{
|
||||
const source=copy?draft:current();if(!source||(!copy&&!selected))return;setPending(true);
|
||||
try{const saved=await saveEnvironmentProfile({...source,name:copy?name:source.name,id:copy?`env/${crypto.randomUUID()}`:selected!.id,revision:0},copy?null:selected!.revision);
|
||||
if(mounted.current){setProfiles(previous=>[...previous.filter(p=>p.id!==saved.id),saved]);if(copy){update(d=>applyEnvironment(d,saved));setDraft(null);}else update(d=>d.environmentProfileId===saved.id?d:{...d,environmentProfileId:saved.id});}
|
||||
}catch(e){onError(e instanceof Error?e.message:'Не удалось сохранить профиль.');}finally{if(mounted.current)setPending(false);}
|
||||
};
|
||||
const exportJson=()=>{const value=current(),url=URL.createObjectURL(new Blob([JSON.stringify(value,null,2)],{type:'application/json'}));const a=globalThis.document.createElement('a');a.href=url;a.download='environment-profile.json';a.click();setTimeout(()=>URL.revokeObjectURL(url),1000);};
|
||||
return <div className="rover-scene-fields">
|
||||
<InspectorSelectField label="Профиль окружения" value={id} disabled={!ready||pending} options={[...(!selected?[{value:id,label:'Текущие настройки · без сохранённого профиля'}]:[]),...all.map(p=>({value:p.id,label:p.name}))]} onChange={value=>{const profile=all.find(p=>p.id===value);if(profile)update(d=>applyEnvironment(d,profile));}}/>
|
||||
<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>Библиотека общая для сцен в 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)}/>
|
||||
<Description>Профиль будет доступен для батареи, ровера и других сцен.</Description>
|
||||
</Window>
|
||||
</div>;
|
||||
}
|
||||
@@ -1,19 +1,20 @@
|
||||
import {useState} from 'react';
|
||||
import {DuplicateMaterialDialog} from './DuplicateMaterialDialog';
|
||||
import {Description,Inspector,InspectorSelectField,TextField,Button} from '@nodedc/ui-react';
|
||||
import type {MaterialSpec} from '../../../core/roverScene/sceneDocument';
|
||||
import {ChargeGradientInspector} from './ChargeGradientInspector';
|
||||
import {useRef,useState} from 'react';
|
||||
import {Button,ColorField,ControlRow,Icon,IconButton,Inspector,RangeControl,Switch,TextField} from '@nodedc/ui-react';
|
||||
import {textureSlots,type TextureSlot,type MaterialSpec} from '../../../core/roverScene/sceneDocument';
|
||||
import {textureFromFile} from '../../../core/roverScene/sceneStorage';
|
||||
const slotLabels:Record<TextureSlot,string>={diffuse:'Базовый цвет',normal:'Нормали',roughness:'Шероховатость',metalness:'Металличность',opacity:'Прозрачность',emissive:'Свечение',ao:'Окклюзия · AO'};
|
||||
export function MaterialInspector({material,onChange,onReset,onError}:{material:MaterialSpec;onChange:(patch:Partial<MaterialSpec>)=>void;onReset:()=>void;onError:(message:string)=>void}){
|
||||
const range=(key:keyof MaterialSpec,label:string,max=1)=><RangeControl label={label} value={Number(material[key])} min={0} max={max} step={.01} exactValueBounds={{min:0,max}} onChange={v=>onChange({[key]:v})}/>;
|
||||
return <><TextField label="Название материала" value={material.name} maxLength={120} onChange={e=>onChange({name:e.target.value})}/><p className="rover-scene-note">Изменения применяются ко всем деталям с этим материалом.</p><Inspector defaultOpen={material.chargeGradient?['charge']:['surface']} sections={[
|
||||
...(material.chargeGradient?[{id:'charge',label:'Градиент заряда',content:<ChargeGradientInspector value={material.chargeGradient} onChange={chargeGradient=>onChange({chargeGradient})}/>}]:[]),
|
||||
{id:'surface',label:'Поверхность',content:<div className="rover-scene-fields">{!material.chargeGradient?.enabled&&<ControlRow label="Базовый цвет"><ColorField label="Базовый цвет" value={material.color} onChange={color=>onChange({color})}/></ControlRow>}{range('metalness','Металличность')}{range('roughness','Шероховатость')}{range('reflectivity','Отражение')}{range('opacity','Непрозрачность')}<Switch label="Двусторонняя поверхность" checked={material.doubleSided} onChange={doubleSided=>onChange({doubleSided})}/></div>},
|
||||
{id:'coat',label:'Лак и свечение',content:<div className="rover-scene-fields">{range('clearCoat','Слой лака')}{range('clearCoatRoughness','Шероховатость лака')}<ControlRow label="Цвет свечения"><ColorField label="Цвет свечения" value={material.emissive} onChange={emissive=>onChange({emissive})}/></ControlRow>{range('emissiveIntensity','Сила свечения',10)}</div>},
|
||||
{id:'textures',label:'Текстуры',description:'PNG / JPEG / WebP · до 4096 px',content:<div className="rover-scene-fields">{textureSlots.map(slot=><TextureField key={slot} slot={slot} value={material.textures[slot]} onChange={texture=>onChange({textures:{...material.textures,[slot]:texture}})} onError={onError}/>)}{range('normalStrength','Сила нормалей',2)}<RangeControl label="Повторение текстуры" min={.01} max={20} step={.01} exactValueBounds={{min:.01,max:20}} value={material.tiling} onChange={tiling=>onChange({tiling})}/></div>},
|
||||
]}/><Button onClick={onReset}>Исходный материал</Button></>;
|
||||
}
|
||||
function TextureField({slot,value,onChange,onError}:{slot:TextureSlot;value:MaterialSpec['textures'][TextureSlot];onChange:(value:MaterialSpec['textures'][TextureSlot])=>void;onError:(message:string)=>void}){
|
||||
const input=useRef<HTMLInputElement>(null),[pending,setPending]=useState(false);
|
||||
return <div className="rover-scene-texture"><ControlRow label={slotLabels[slot]} layout="stack"><div className="rover-scene-texture__row">{value&&<img src={value.data} alt=""/>}<Button size="compact" loading={pending} onClick={()=>input.current?.click()}>{value?.name??'Загрузить текстуру'}</Button>{value&&<IconButton label={`Удалить текстуру: ${slotLabels[slot]}`} onClick={()=>onChange(undefined)}><Icon name="trash"/></IconButton>}</div></ControlRow><input hidden ref={input} type="file" accept="image/png,image/jpeg,image/webp" onChange={async e=>{const file=e.currentTarget.files?.[0];e.currentTarget.value='';if(!file)return;setPending(true);try{onChange(await textureFromFile(file));}catch(error){onError(error instanceof Error?error.message:'Не удалось загрузить текстуру.');}finally{setPending(false);}}}/></div>;
|
||||
import {MaterialSurfaceInspector} from './MaterialSurfaceInspector';
|
||||
export type MaterialPreview='auto'|'active'|'inactive';
|
||||
export function MaterialInspector({material,onChange,onDuplicate,copyName,selectionDescription,onError,preview='auto',onPreview}:{material:MaterialSpec;onChange:(patch:Partial<MaterialSpec>)=>void;onDuplicate:(name:string)=>void;copyName:string;selectionDescription:string;onError:(message:string)=>void;preview?:MaterialPreview;onPreview?:(value:MaterialPreview)=>void}){
|
||||
const gradient=material.chargeGradient,[duplicate,setDuplicate]=useState(false);
|
||||
const header=<><Description>{selectionDescription}</Description><TextField label="Название материала" value={material.name} maxLength={120} onChange={e=>onChange({name:e.target.value})}/><Description>Изменения применяются ко всем деталям с этим материалом.</Description>
|
||||
{gradient&&<InspectorSelectField label="Предпросмотр материала" value={preview} options={[{value:'auto',label:'По данным BMS'},{value:'active',label:'Активный · градиент'},{value:'inactive',label:'Неактивный · без данных'}]} onChange={v=>onPreview?.(v as MaterialPreview)}/>}
|
||||
{gradient&&preview==='active'&&<Description>Предпросмотр градиента: текущий заряд, а при отсутствии показаний — 50%.</Description>}</>;
|
||||
const footer=<Button variant="primary" tone="neutral" onClick={()=>setDuplicate(true)}>Дублировать материал</Button>;
|
||||
return <>{gradient?
|
||||
<Inspector header={header} footer={footer} defaultOpen={['active']} sections={[
|
||||
{id:'active',label:'Активный материал · градиент',content:<><ChargeGradientInspector value={gradient} onChange={chargeGradient=>onChange({chargeGradient})}/><MaterialSurfaceInspector material={material} onChange={onChange} onError={onError}/></>},
|
||||
{id:'inactive',label:'Неактивный материал · без данных',content:<><Description>Самостоятельный материал, когда сохранённого заряда нет. Свои поверхность, текстуры и свечение.</Description><MaterialSurfaceInspector material={gradient.inactive} onChange={patch=>onChange({chargeGradient:{...gradient,inactive:{...gradient.inactive,...patch}}})} onError={onError}/></>}
|
||||
]}/>:<MaterialSurfaceInspector header={header} footer={footer} material={material} onChange={onChange} onError={onError}/>}
|
||||
{duplicate&&<DuplicateMaterialDialog initialName={copyName} onDuplicate={onDuplicate} onClose={()=>setDuplicate(false)}/>}</>;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,18 @@
|
||||
import {useRef,useState,type ReactNode} from 'react';
|
||||
import {Button,ColorField,ControlRow,Icon,IconButton,Inspector,RangeControl,Switch} from '@nodedc/ui-react';
|
||||
import {textureSlots,type TextureSlot,type MaterialSurface} from '../../../core/roverScene/materialSurface';
|
||||
import {textureFromFile} from '../../../core/roverScene/sceneStorage';
|
||||
const slotLabels:Record<TextureSlot,string>={diffuse:'Базовый цвет',normal:'Нормали',roughness:'Шероховатость',metalness:'Металличность',opacity:'Прозрачность',emissive:'Свечение',ao:'Окклюзия · AO'};
|
||||
export function MaterialSurfaceInspector({material,onChange,onError,header,footer}:{header?:ReactNode;footer?:ReactNode;material:MaterialSurface;onChange:(patch:Partial<MaterialSurface>)=>void;onError:(message:string)=>void}){
|
||||
const range=(key:keyof MaterialSurface,label:string,max=1)=><RangeControl label={label} value={Number(material[key])} min={0} max={max} step={.01} exactValueBounds={{min:0,max}} onChange={v=>onChange({[key]:v})}/>;
|
||||
return <Inspector header={header} footer={footer} defaultOpen={['surface']} sections={[
|
||||
{id:'surface',label:'Поверхность',content:<div className="rover-scene-fields"><ControlRow label="Базовый цвет"><ColorField label="Базовый цвет" value={material.color} onChange={color=>onChange({color})}/></ControlRow>{range('metalness','Металличность')}{range('roughness','Шероховатость')}{range('reflectivity','Отражение')}{range('opacity','Непрозрачность')}<Switch label="Двусторонняя поверхность" checked={material.doubleSided} onChange={doubleSided=>onChange({doubleSided})}/></div>},
|
||||
{id:'coat',label:'Лак и свечение',content:<div className="rover-scene-fields">{range('clearCoat','Слой лака')}{range('clearCoatRoughness','Шероховатость лака')}<ControlRow label="Цвет свечения"><ColorField label="Цвет свечения" value={material.emissive} onChange={emissive=>onChange({emissive})}/></ControlRow>{range('emissiveIntensity','Сила свечения',10)}</div>},
|
||||
{id:'textures',label:'Текстуры',description:'PNG / JPEG / WebP · до 4096 px',content:<div className="rover-scene-fields">{textureSlots.map(slot=><TextureField key={slot} slot={slot} value={material.textures[slot]} onChange={texture=>onChange({textures:{...material.textures,[slot]:texture}})} onError={onError}/>)}{range('normalStrength','Сила нормалей',2)}<RangeControl label="Повторение текстуры" min={.01} max={20} step={.01} exactValueBounds={{min:.01,max:20}} value={material.tiling} onChange={tiling=>onChange({tiling})}/></div>},
|
||||
|
||||
]}/>;
|
||||
}
|
||||
function TextureField({slot,value,onChange,onError}:{slot:TextureSlot;value:MaterialSurface['textures'][TextureSlot];onChange:(value:MaterialSurface['textures'][TextureSlot])=>void;onError:(message:string)=>void}){
|
||||
const input=useRef<HTMLInputElement>(null),[pending,setPending]=useState(false);
|
||||
return <div className="rover-scene-texture"><ControlRow label={slotLabels[slot]} layout="stack"><div className="rover-scene-texture__row">{value&&<img src={value.data} alt=""/>}<Button size="compact" loading={pending} onClick={()=>input.current?.click()}>{value?.name??'Загрузить текстуру'}</Button>{value&&<IconButton label={`Удалить текстуру: ${slotLabels[slot]}`} onClick={()=>onChange(undefined)}><Icon name="trash"/></IconButton>}</div></ControlRow><input hidden ref={input} type="file" accept="image/png,image/jpeg,image/webp" onChange={async e=>{const file=e.currentTarget.files?.[0];e.currentTarget.value='';if(!file)return;setPending(true);try{onChange(await textureFromFile(file));}catch(error){onError(error instanceof Error?error.message:'Не удалось загрузить текстуру.');}finally{setPending(false);}}}/></div>;
|
||||
}
|
||||
@@ -1,14 +1,15 @@
|
||||
import {duplicateMaterial,materialCopyName} from '../../../core/roverScene/materialActions';
|
||||
import {editorDockLayout,materialTileSizes} from '../../../core/roverScene/editorLayout';
|
||||
import {roverModelURL} from '../../../core/roverScene/model';
|
||||
import {useCallback,useEffect,useRef,useState} from 'react';
|
||||
import {Description,DragDropRoot,DropZone,EditorDockLayout,GlassSurface,Icon,IconButton,LoadingRegion,StatusBadge,ToastStack,type EditorDockTool} from '@nodedc/ui-react';
|
||||
import {createMaterial,changeField,defaultScene,maxSceneMaterials,textureBytes,type MaterialSpec} from '../../../core/roverScene/sceneDocument';
|
||||
import {DragDropRoot,DropZone,EditorDockLayout,GlassSurface,Icon,IconButton,LoadingRegion,StatusBadge,ToastStack,type EditorDockTool} from '@nodedc/ui-react';
|
||||
import {createMaterial,changeField,maxSceneMaterials,textureBytes,type MaterialSpec} from '../../../core/roverScene/sceneDocument';
|
||||
import {assignObjectMaterial,findSceneObject,objectTargets,type SceneObject} from '../../../core/roverScene/sceneObjects';
|
||||
import {useSceneDocument} from '../../../core/roverScene/useSceneDocument';
|
||||
import PlayCanvasViewer,{type PlayCanvasViewerProps} from '../playcanvas/PlayCanvasViewer';
|
||||
import type {ScenePicker,ScenePick} from '../playcanvas/useSceneMaterials';
|
||||
import {EnvironmentInspector,SceneFileActions} from './EnvironmentInspector';
|
||||
import {MaterialInspector} from './MaterialInspector';
|
||||
import {MaterialInspector,type MaterialPreview} from './MaterialInspector';
|
||||
import {MaterialPalette,MaterialPaletteActions,MaterialTile} from './MaterialPalette';
|
||||
import {SceneObjectTree} from './SceneObjectTree';
|
||||
import {useSceneUndo} from './useSceneUndo';
|
||||
@@ -18,10 +19,11 @@ import './sceneEditor.css';
|
||||
export default function RoverScene({vehicleID,...props}:{vehicleID:string;editing:boolean;onModelState:(state:'loading'|'ready'|'error')=>void}){
|
||||
const scene=useSceneDocument(vehicleID);return <SceneEditor {...props} scene={scene}/>;
|
||||
}
|
||||
export function SceneEditor({scene,editing,onModelState,modelUrl=roverModelURL,defaults=defaultScene,onSceneReady,minFitDistance,chargeState}:{scene:ReturnType<typeof useSceneDocument>;editing:boolean;onModelState:NonNullable<PlayCanvasViewerProps['onModelState']>;modelUrl?:string;defaults?:typeof defaultScene;onSceneReady?:PlayCanvasViewerProps['onSceneReady'];minFitDistance?:number;chargeState?:ChargeState}){
|
||||
export function SceneEditor({scene,editing,onModelState,modelUrl=roverModelURL,onSceneReady,minFitDistance,chargeState}:{scene:ReturnType<typeof useSceneDocument>;editing:boolean;onModelState:NonNullable<PlayCanvasViewerProps['onModelState']>;modelUrl?:string;onSceneReady?:PlayCanvasViewerProps['onSceneReady'];minFitDistance?:number;chargeState?:ChargeState}){
|
||||
useSceneUndo(scene,editing);
|
||||
const layout=scene.document.editorLayout;
|
||||
const docking=editorDockLayout(layout),tileSize=layout?.materialTileSize??materialTileSizes.default;
|
||||
const [materialPreview,setMaterialPreview]=useState<MaterialPreview>('auto');
|
||||
const [palette,setPalette]=useState(true),[environment,setEnvironment]=useState(false),[selected,setSelected]=useState<string|null>(null),[materialOpen,setMaterialOpen]=useState(false),[cameraReset,setCameraReset]=useState(0),[textureState,setTextureState]=useState<'loading'|'ready'|'error'>('ready');
|
||||
const [objectsOpen,setObjectsOpen]=useState(true),[root,setRoot]=useState<SceneObject|null>(null),[selectedObject,setSelectedObject]=useState<string|null>(null);
|
||||
const [selectionVersion,setSelectionVersion]=useState(0);
|
||||
@@ -33,7 +35,7 @@ export function SceneEditor({scene,editing,onModelState,modelUrl=roverModelURL,d
|
||||
const sceneReady=useCallback((api:Parameters<NonNullable<PlayCanvasViewerProps['onSceneReady']>>[0])=>{setSceneApi(api);onSceneReady?.(api);},[onSceneReady]);
|
||||
const modelState=useCallback((value:'loading'|'ready'|'error')=>{setModelPhase(value);onModelState(value);},[onModelState]);
|
||||
|
||||
const pick=useCallback((id:string)=>{setSelected(id);setMaterialOpen(true);setObjectsOpen(true);},[]);
|
||||
const pick=useCallback((id:string)=>{setMaterialPreview('auto');setSelected(id);setMaterialOpen(true);setObjectsOpen(true);},[]);
|
||||
const objectPick=useCallback((hit:ScenePick|null)=>{setSelectionVersion(v=>v+1);if(!hit){setSelectedObject(null);setSelected(null);setMaterialOpen(false);return;}setSelectedObject(hit.objectId);setPalette(true);pick(hit.materialId);},[pick]);
|
||||
const selectObject=(id:string)=>{setSelectionVersion(v=>v+1);setSelectedObject(id);const item=findSceneObject(root,id),source=item?.materialIds?.[0];const material=scene.document.objectAssignments?.[id]??(source?(scene.document.assignments[source]??source):null);if(material){setPalette(true);pick(material);}};
|
||||
const addMaterial=()=>{if(Object.keys(scene.document.materials).length>=maxSceneMaterials){scene.setError(`В сцене может быть не больше ${maxSceneMaterials} материалов.`);return;}const id=`custom/${crypto.randomUUID()}`;scene.update(doc=>createMaterial(doc,id));pick(id);};
|
||||
@@ -42,15 +44,15 @@ export function SceneEditor({scene,editing,onModelState,modelUrl=roverModelURL,d
|
||||
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},
|
||||
actions:<MaterialPaletteActions tileSize={tileSize} onTileSize={size=>scene.update(doc=>({...doc,editorLayout:{windows:{},...doc.editorLayout,materialTileSize:size}}))}/>,content:<MaterialPalette tileSize={tileSize} revealVersion={selectionVersion} materials={scene.document.materials} selected={selected} pick={pick} add={addMaterial}/>},
|
||||
{id:'environment',title:'Окружение сцены',label:'Окружение сцены',open:environment,onClose:()=>setEnvironment(false),footer:<SceneFileActions onImport={scene.importDocument} onExport={scene.exportDocument} onReset={()=>scene.update(doc=>({...doc,postFx:defaults().postFx}))}/>,content:<EnvironmentInspector onError={scene.setError} document={scene.document} onChange={(key,value)=>scene.update(doc=>changeField(doc,key,value))} onResetCamera={()=>setCameraReset(v=>v+1)}/>},
|
||||
{id:'environment',title:'Окружение сцены',label:'Окружение сцены',open:environment,onClose:()=>setEnvironment(false),content:<EnvironmentInspector update={scene.update} sceneFiles={<SceneFileActions onImport={scene.importDocument} onExport={scene.exportDocument}/>} onError={scene.setError} document={scene.document} onChange={(key,value)=>scene.update(doc=>changeField(doc,key,value))} onResetCamera={()=>setCameraReset(v=>v+1)}/>},
|
||||
{id:'material',title:material?.name||'Материал',label:'Материал',activationKey:`${selectionVersion}:${selected}`,subtitle:node?`Назначить: ${node.name}`:'Выберите объект в дереве',open:materialOpen&&!!material,onClose:()=>setMaterialOpen(false),
|
||||
actions:<IconButton label="Назначить материал выбранному объекту" disabled={!selected||!targets.length} onClick={()=>selected&&scene.update(doc=>assignObjectMaterial(doc,targets,selected))}><Icon name="chevron-right"/></IconButton>,
|
||||
content:material&&selected?<><Description>{node?`Выбран объект: ${node.name}${targets.length>1?` · деталей: ${targets.length}`:''}`:'Выберите деталь в дереве объектов. Назначение доступно стрелкой рядом с крестиком.'}</Description><MaterialInspector key={selected} material={material} onChange={patch=>patchMaterial(selected,patch)} onReset={()=>{const base=defaults().materials[selected]??createMaterial(defaults(),selected).materials[selected];if(base)patchMaterial(selected,{...base,name:material.name});}} onError={scene.setError}/></>:null}
|
||||
content:material&&selected?<MaterialInspector key={selected} selectionDescription={node?`Выбран объект: ${node.name}${targets.length>1?` · деталей: ${targets.length}`:''}`:'Выберите деталь в дереве объектов. Назначение доступно стрелкой рядом с крестиком.'} copyName={materialCopyName(scene.document,selected)} onDuplicate={name=>{const id=`custom/${crypto.randomUUID()}`,next=duplicateMaterial(scene.document,selected,id,name);scene.update(()=>next);setPalette(true);setSelectionVersion(v=>v+1);pick(id);}} preview={materialPreview} onPreview={setMaterialPreview} material={material} onChange={patch=>patchMaterial(selected,patch)} onError={scene.setError}/>:null}
|
||||
];
|
||||
return <DragDropRoot renderOverlay={({data})=>{const m=scene.document.materials[String(data?.materialId)];return m?<GlassSurface padding="sm"><MaterialTile material={m}/></GlassSurface>:null;}} onDragEnd={({activeData,pointer})=>{
|
||||
const id=String(activeData?.materialId??'');if(!editing||!pointer||!Object.hasOwn(scene.document.materials,id))return;
|
||||
@@ -61,10 +63,10 @@ export function SceneEditor({scene,editing,onModelState,modelUrl=roverModelURL,d
|
||||
}}>
|
||||
<EditorDockLayout value={docking} enabled={editing} tools={tools} onChange={next=>scene.update(doc=>({...doc,editorLayout:{windows:{},materialTileSize:materialTileSizes.default,...doc.editorLayout,docking:next}}))} primary={<>
|
||||
<DropZone id="scene-model" className="rover-scene-drop"><LoadingRegion className="rover-view__scene" loading={!scene.ready} label="Загрузка настроек сцены">
|
||||
{scene.ready&&<PlayCanvasViewer modelUrl={modelUrl} onSceneReady={sceneReady} onSceneGraph={sceneGraph} minFitDistance={minFitDistance} postFx={scene.document.postFx} cameraAutoRotate={scene.document.cameraAutoRotate} cameraZoomStrength={scene.document.cameraZoomStrength} cameraResetToken={cameraReset} cameraState={scene.document.camera} onCameraChange={scene.recordCamera} materials={scene.document.materials} assignments={scene.document.assignments} objectAssignments={scene.document.objectAssignments} objectVisibility={scene.document.objectVisibility} legacyObjectVisibility={scene.document.objects} editing={editing} chargeState={chargeState} onObjectPick={objectPick} onPickerReady={pickerReady} onModelState={modelState} onTextureState={setTextureState}/>}
|
||||
{scene.ready&&<PlayCanvasViewer modelUrl={modelUrl} onSceneReady={sceneReady} onSceneGraph={sceneGraph} minFitDistance={minFitDistance} postFx={scene.document.postFx} cameraAutoRotate={scene.document.cameraAutoRotate} cameraZoomStrength={scene.document.cameraZoomStrength} cameraResetToken={cameraReset} cameraState={scene.document.camera} onCameraChange={scene.recordCamera} materials={scene.document.materials} assignments={scene.document.assignments} objectAssignments={scene.document.objectAssignments} objectVisibility={scene.document.objectVisibility} legacyObjectVisibility={scene.document.objects} editing={editing} chargeState={chargeState} materialPreview={editing&&materialOpen&&selected&&materialPreview!=='auto'?{id:selected,mode:materialPreview}:undefined} onObjectPick={objectPick} onPickerReady={pickerReady} onModelState={modelState} onTextureState={setTextureState}/>}
|
||||
</LoadingRegion></DropZone>
|
||||
{editing&&<>
|
||||
<div className="rover-scene-tools"><GlassSurface className="rover-scene-tools__surface nodedc-viewport-controls"><IconButton label="Отменить изменение · Ctrl/Cmd+Z" disabled={!scene.canUndo} onClick={scene.undo}><Icon name="undo"/></IconButton><IconButton label="Повторить изменение · Ctrl/Cmd+Shift+Z" disabled={!scene.canRedo} onClick={scene.redo}><Icon name="redo"/></IconButton><IconButton label="Материалы сцены" aria-pressed={palette} onClick={()=>{setPalette(v=>!v);setObjectsOpen(true);}}><Icon name="layers"/></IconButton><IconButton label="Окружение сцены" aria-pressed={environment} onClick={()=>setEnvironment(v=>!v)}><Icon name="globe"/></IconButton><IconButton label="Объекты сцены" aria-pressed={objectsOpen} onClick={()=>setObjectsOpen(v=>!v)}><Icon name="list"/></IconButton></GlassSurface></div>
|
||||
<div className="rover-scene-tools"><div className="rover-scene-tools__surface nodedc-viewport-controls"><IconButton label="Отменить изменение · Ctrl/Cmd+Z" disabled={!scene.canUndo} onClick={scene.undo}><Icon name="undo"/></IconButton><IconButton label="Повторить изменение · Ctrl/Cmd+Shift+Z" disabled={!scene.canRedo} onClick={scene.redo}><Icon name="redo"/></IconButton><IconButton label="Материалы сцены" aria-pressed={palette} onClick={()=>{setPalette(v=>!v);setObjectsOpen(true);}}><Icon name="layers"/></IconButton><IconButton label="Окружение сцены" aria-pressed={environment} onClick={()=>setEnvironment(v=>!v)}><Icon name="globe"/></IconButton><IconButton label="Объекты сцены" aria-pressed={objectsOpen} onClick={()=>setObjectsOpen(v=>!v)}><Icon name="list"/></IconButton></div></div>
|
||||
<div className="rover-scene-save"><StatusBadge tone={saved&&textureState!=='loading'?'neutral':'warning'}>{status}</StatusBadge></div>
|
||||
</>}
|
||||
</>}/>
|
||||
|
||||
@@ -882,7 +882,7 @@ function applyPostFx(
|
||||
export default function PlayCanvasViewer({
|
||||
minFitDistance = 1.8,
|
||||
modelUrl,
|
||||
materials, assignments, objectAssignments, objectVisibility, legacyObjectVisibility, editing, onObjectPick, onPickerReady, onTextureState, chargeState,
|
||||
materials, assignments, objectAssignments, objectVisibility, legacyObjectVisibility, editing, onObjectPick, onPickerReady, onTextureState, chargeState, materialPreview,
|
||||
postFx,
|
||||
viewportSize,
|
||||
onSceneReady,
|
||||
@@ -930,7 +930,7 @@ export default function PlayCanvasViewer({
|
||||
const [skyboxVersion, setSkyboxVersion] = useState(0)
|
||||
const [modelVersion, setModelVersion] = useState(0)
|
||||
|
||||
useSceneMaterials(appRef,cameraEntityRef,canvasRef,modelVersion,{materials,assignments,objectAssignments,objectVisibility,legacyObjectVisibility,editing,onObjectPick,onPickerReady,onTextureState,chargeState})
|
||||
useSceneMaterials(appRef,cameraEntityRef,canvasRef,modelVersion,{materials,assignments,objectAssignments,objectVisibility,legacyObjectVisibility,editing,onObjectPick,onPickerReady,onTextureState,chargeState,materialPreview})
|
||||
|
||||
const fx = useMemo(() => mergePostFxDefaults(postFx), [postFx])
|
||||
const lutError = useCallback(()=>onTextureState?.('error'),[onTextureState])
|
||||
|
||||
@@ -1,6 +1,15 @@
|
||||
import * as pc from 'playcanvas';
|
||||
import {chargePair,type ChargeGradient} from '../../../core/roverScene/chargeGradient';
|
||||
import type {MaterialSpec} from '../../../core/roverScene/sceneDocument';
|
||||
import type {MaterialSurface} from '../../../core/roverScene/materialSurface';
|
||||
import {applyMaterialSurface} from './materialSurface';
|
||||
const surfaces=new WeakMap<pc.StandardMaterial,{surface:MaterialSurface;gradient:ChargeGradient}>();
|
||||
export type ChargeState={soc:number|null;fresh:boolean};
|
||||
export type ChargePreview={id:string;mode:'active'|'inactive'};
|
||||
export function previewChargeState(state:ChargeState|undefined,preview?:ChargePreview):ChargeState|undefined{
|
||||
return preview?.mode==='inactive'?{soc:null,fresh:false}:preview?.mode==='active'?{soc:Number.isFinite(state?.soc)?state!.soc:50,fresh:true}:state;
|
||||
}
|
||||
export function chargeSurface(spec:MaterialSpec,state:ChargeState|undefined):MaterialSurface{return spec.chargeGradient&&!Number.isFinite(state?.soc)?spec.chargeGradient.inactive:spec;}
|
||||
const emission=`
|
||||
uniform vec3 chargeColorA;
|
||||
uniform vec3 chargeColorB;
|
||||
@@ -8,27 +17,42 @@ uniform float chargeTime;
|
||||
uniform float chargeScale;
|
||||
uniform float chargeIntensity;
|
||||
uniform float chargeSaturation;
|
||||
uniform float chargeContrast;
|
||||
uniform vec3 material_emissive;
|
||||
uniform float material_emissiveIntensity;
|
||||
void getEmission() {
|
||||
vec3 p=vPositionW*chargeScale;
|
||||
float wave=sin(p.x*0.77+sin(p.y*0.91+chargeTime)*1.2+chargeTime*0.43);
|
||||
wave+=sin(p.z*0.71-p.y*0.48+sin(p.x*0.57-chargeTime*0.61));
|
||||
float blend=smoothstep(-1.6,1.6,wave);
|
||||
float blend=clamp((smoothstep(-1.6,1.6,wave)-0.5)*chargeContrast+0.5,0.0,1.0);
|
||||
vec3 color=mix(chargeColorA,chargeColorB,blend);
|
||||
color=mix(vec3(dot(color,vec3(0.2126,0.7152,0.0722))),color,chargeSaturation);
|
||||
dEmission=color*chargeIntensity;
|
||||
vec3 baseEmission=material_emissive*material_emissiveIntensity;
|
||||
#ifdef STD_EMISSIVE_TEXTURE
|
||||
baseEmission *= {STD_EMISSIVE_TEXTURE_DECODE}(texture2DBias({STD_EMISSIVE_TEXTURE_NAME}, {STD_EMISSIVE_TEXTURE_UV}, textureBias)).{STD_EMISSIVE_TEXTURE_CHANNEL};
|
||||
#endif
|
||||
#ifdef STD_EMISSIVE_VERTEX
|
||||
baseEmission *= saturate(vVertexColor.{STD_EMISSIVE_VERTEX_CHANNEL});
|
||||
#endif
|
||||
dEmission=baseEmission+max(color,vec3(0.0))*chargeIntensity;
|
||||
}`;
|
||||
export function configureChargeMaterial(material:pc.StandardMaterial,gradient?:ChargeGradient){
|
||||
const chunks=material.getShaderChunks(pc.SHADERLANGUAGE_GLSL);
|
||||
if(gradient?.enabled){chunks.set('emissivePS',emission);material.emissive.set(1,1,1);material.emissiveIntensity=1;material.diffuse.set(.02,.02,.02);}
|
||||
else chunks.delete('emissivePS');
|
||||
if(gradient)chunks.set('emissivePS',emission);else chunks.delete('emissivePS');
|
||||
surfaces.delete(material);
|
||||
}
|
||||
export function updateChargeMaterial(material:pc.StandardMaterial,gradient:ChargeGradient,state:ChargeState|undefined,time:number){
|
||||
const known=state?.soc!==null&&state?.soc!==undefined;
|
||||
const colors=known?chargePair(gradient,state!.soc):[[.12,.14,.16],[.18,.20,.22]];
|
||||
export function updateChargeMaterial(material:pc.StandardMaterial,gradient:ChargeGradient,state:ChargeState|undefined,time:number,spec:MaterialSpec,bindTextures?:(surface:MaterialSurface)=>void){
|
||||
const known=typeof state?.soc==='number'&&Number.isFinite(state.soc),surface=known?spec:gradient.inactive;
|
||||
const applied=surfaces.get(material);
|
||||
if(!applied||applied.surface!==surface||applied.gradient!==gradient){
|
||||
applyMaterialSurface(material,surface);bindTextures?.(surface);material.update();surfaces.set(material,{surface,gradient});
|
||||
}
|
||||
const colors=known?chargePair(gradient,state!.soc):[[0,0,0],[0,0,0]];
|
||||
material.setParameter('chargeColorA',colors[0].map(value=>value**2.2));
|
||||
material.setParameter('chargeColorB',colors[1].map(value=>value**2.2));
|
||||
material.setParameter('chargeTime',time*gradient.speed);
|
||||
material.setParameter('chargeScale',gradient.scale);
|
||||
material.setParameter('chargeIntensity',gradient.intensity*(known?1:.2));
|
||||
material.setParameter('chargeSaturation',known?1:0);
|
||||
material.setParameter('chargeIntensity',known&&gradient.enabled?gradient.intensity:0);
|
||||
material.setParameter('chargeSaturation',gradient.saturation);
|
||||
material.setParameter('chargeContrast',gradient.contrast);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,13 @@
|
||||
import * as pc from 'playcanvas';
|
||||
import type {MaterialSurface,TextureSlot} from '../../../core/roverScene/materialSurface';
|
||||
export const surfaceMaps:Record<TextureSlot,string>={diffuse:'diffuseMap',normal:'normalMap',metalness:'metalnessMap',roughness:'glossMap',opacity:'opacityMap',emissive:'emissiveMap',ao:'aoMap'};
|
||||
export function applyMaterialSurface(m:pc.StandardMaterial,spec:MaterialSurface){
|
||||
m.diffuse.fromString(spec.color);m.useMetalness=true;m.metalness=spec.metalness;
|
||||
m.glossInvert=true;m.gloss=spec.roughness;m.opacity=spec.opacity;
|
||||
m.specularityFactor=spec.reflectivity;m.clearCoat=spec.clearCoat;
|
||||
m.clearCoatGlossInvert=true;m.clearCoatGloss=spec.clearCoatRoughness;
|
||||
m.emissive.fromString(spec.emissive);m.emissiveIntensity=spec.emissiveIntensity;
|
||||
m.bumpiness=spec.normalStrength;m.cull=spec.doubleSided?pc.CULLFACE_NONE:pc.CULLFACE_BACK;
|
||||
m.blendType=spec.opacity<1||spec.textures.opacity?pc.BLEND_NORMAL:pc.BLEND_NONE;
|
||||
m.depthWrite=m.blendType===pc.BLEND_NONE;
|
||||
}
|
||||
@@ -1,14 +1,16 @@
|
||||
import {useEffect,useRef,type RefObject} from 'react';
|
||||
import * as pc from 'playcanvas';
|
||||
import {configureChargeMaterial,updateChargeMaterial,type ChargeState} from './chargeMaterial';
|
||||
import {configureChargeMaterial,updateChargeMaterial,chargeSurface,previewChargeState,type ChargePreview,type ChargeState} from './chargeMaterial';
|
||||
import {sceneObjectId} from './sceneTree';
|
||||
export type ScenePick={objectId:string;materialId:string};
|
||||
export type ScenePicker={pick:(x:number,y:number)=>ScenePick|null};
|
||||
import type {MaterialSpec,TextureSlot} from '../../../core/roverScene/sceneDocument';
|
||||
export type SceneMaterialsProps={materials?:Record<string,MaterialSpec>;assignments?:Record<string,string>;objectAssignments?:Record<string,string>;objectVisibility?:Record<string,boolean>;legacyObjectVisibility?:Record<string,boolean>;editing?:boolean;onObjectPick?:(hit:ScenePick|null)=>void;chargeState?:ChargeState;onPickerReady?:(picker:ScenePicker|null)=>void;onTextureState?:(state:'loading'|'ready'|'error')=>void};
|
||||
const maps:Record<TextureSlot,string>={diffuse:'diffuseMap',normal:'normalMap',metalness:'metalnessMap',roughness:'glossMap',opacity:'opacityMap',emissive:'emissiveMap',ao:'aoMap'};
|
||||
export function useSceneMaterials(appRef:RefObject<pc.Application|null>,cameraRef:RefObject<pc.Entity|null>,canvasRef:RefObject<HTMLCanvasElement|null>,modelVersion:number,{materials,assignments,objectAssignments,objectVisibility,legacyObjectVisibility,editing,onObjectPick,onPickerReady,onTextureState,chargeState}:SceneMaterialsProps){
|
||||
const latest=useRef({materials,onObjectPick,onTextureState,chargeState});latest.current={materials,onObjectPick,onTextureState,chargeState};
|
||||
import type {MaterialSpec} from '../../../core/roverScene/sceneDocument';
|
||||
import type {MaterialSurface,TextureSlot} from '../../../core/roverScene/materialSurface';
|
||||
import {applyMaterialSurface,surfaceMaps as maps} from './materialSurface';
|
||||
export type SceneMaterialsProps={materials?:Record<string,MaterialSpec>;assignments?:Record<string,string>;objectAssignments?:Record<string,string>;objectVisibility?:Record<string,boolean>;legacyObjectVisibility?:Record<string,boolean>;editing?:boolean;onObjectPick?:(hit:ScenePick|null)=>void;chargeState?:ChargeState;materialPreview?:ChargePreview;onPickerReady?:(picker:ScenePicker|null)=>void;onTextureState?:(state:'loading'|'ready'|'error')=>void};
|
||||
export function useSceneMaterials(appRef:RefObject<pc.Application|null>,cameraRef:RefObject<pc.Entity|null>,canvasRef:RefObject<HTMLCanvasElement|null>,modelVersion:number,{materials,assignments,objectAssignments,objectVisibility,legacyObjectVisibility,editing,onObjectPick,onPickerReady,onTextureState,chargeState,materialPreview}:SceneMaterialsProps){
|
||||
const latest=useRef({materials,onObjectPick,onTextureState,chargeState,materialPreview});latest.current={materials,onObjectPick,onTextureState,chargeState,materialPreview};
|
||||
const bindings=useRef(new Map<string,(surface:MaterialSurface)=>void>());
|
||||
const animated=useRef(new Map<string,pc.StandardMaterial>());
|
||||
const textures=useRef(new Map<string,{texture?:pc.Texture;promise:Promise<pc.Texture>}>());
|
||||
const generation=useRef(0);
|
||||
@@ -32,40 +34,36 @@ export function useSceneMaterials(appRef:RefObject<pc.Application|null>,cameraRe
|
||||
const source=originalGroups.current.get(mi);if(source)mi.material=map.get(objectAssignments?.[sceneObjectId(mi.node)]??assignments?.[source.id]??source.id)??source.material;
|
||||
}
|
||||
for(const [id,m] of customMaterials.current)if(!Object.hasOwn(materials,id)){m.destroy();customMaterials.current.delete(id);}
|
||||
const applyTexture=(m:pc.StandardMaterial,slot:TextureSlot,texture:pc.Texture|null,spec:MaterialSpec)=>{
|
||||
const applyTexture=(m:pc.StandardMaterial,slot:TextureSlot,texture:pc.Texture|null,spec:MaterialSurface)=>{
|
||||
(m as any)[maps[slot]]=texture;
|
||||
const prefix=maps[slot];(m as any)[prefix+'Tiling']=new pc.Vec2(spec.tiling,spec.tiling);
|
||||
if(['metalness','roughness','opacity','ao'].includes(slot))(m as any)[prefix+'Channel']='r';
|
||||
m.update();
|
||||
};
|
||||
const used=new Set<string>();animated.current.clear();
|
||||
const used=new Set<string>();animated.current.clear();bindings.current.clear();
|
||||
for(const [id,spec] of Object.entries(materials)){
|
||||
const m=map.get(id);if(!m)continue;
|
||||
m.diffuse.fromString(spec.color);m.useMetalness=true;m.metalness=spec.metalness;
|
||||
m.glossInvert=true;m.gloss=spec.roughness;m.opacity=spec.opacity;
|
||||
// Specular factor is independent from the donor's global IBL multiplier.
|
||||
m.specularityFactor=spec.reflectivity;m.clearCoat=spec.clearCoat;
|
||||
m.clearCoatGlossInvert=true;m.clearCoatGloss=spec.clearCoatRoughness;
|
||||
m.emissive.fromString(spec.emissive);m.emissiveIntensity=spec.emissiveIntensity;
|
||||
m.bumpiness=spec.normalStrength;m.cull=spec.doubleSided?pc.CULLFACE_NONE:pc.CULLFACE_BACK;
|
||||
m.blendType=spec.opacity<1||spec.textures.opacity?pc.BLEND_NORMAL:pc.BLEND_NONE;
|
||||
m.depthWrite=m.blendType===pc.BLEND_NONE;
|
||||
const state=()=>previewChargeState(latest.current.chargeState,latest.current.materialPreview?.id===id?latest.current.materialPreview:undefined);
|
||||
const selectedSurface=()=>chargeSurface(spec,state());
|
||||
const bind=(surface:MaterialSurface)=>{for(const slot of Object.keys(maps) as TextureSlot[]){const data=surface.textures[slot]?.data;applyTexture(m,slot,data?textures.current.get(`${slot==='diffuse'||slot==='emissive'}:${data}`)?.texture??null:null,surface);}};
|
||||
bindings.current.set(id,bind);
|
||||
for(const surface of [spec,...(spec.chargeGradient?[spec.chargeGradient.inactive]:[])]){
|
||||
for(const slot of Object.keys(maps) as TextureSlot[]){
|
||||
const data=spec.textures[slot]?.data;if(!data){applyTexture(m,slot,null,spec);continue;}
|
||||
const data=surface.textures[slot]?.data;if(!data)continue;
|
||||
const srgb=slot==='diffuse'||slot==='emissive';const key=`${srgb}:${data}`;used.add(key);
|
||||
let item=textures.current.get(key);
|
||||
if(!item){
|
||||
const promise=new Promise<pc.Texture>((resolve,reject)=>{const img=new Image();img.onload=()=>{if(generation.current<0){reject(new Error('Scene disposed'));return;}const tex=new pc.Texture(app.graphicsDevice,{name:spec.textures[slot]?.name,format:srgb?pc.PIXELFORMAT_SRGBA8:pc.PIXELFORMAT_RGBA8,mipmaps:true,addressU:pc.ADDRESS_REPEAT,addressV:pc.ADDRESS_REPEAT});tex.setSource(img);resolve(tex);};img.onerror=()=>reject(new Error('Texture decode failed'));img.src=data;});
|
||||
const promise=new Promise<pc.Texture>((resolve,reject)=>{const img=new Image();img.onload=()=>{if(generation.current<0){reject(new Error('Scene disposed'));return;}const tex=new pc.Texture(app.graphicsDevice,{name:surface.textures[slot]?.name,format:srgb?pc.PIXELFORMAT_SRGBA8:pc.PIXELFORMAT_RGBA8,mipmaps:true,addressU:pc.ADDRESS_REPEAT,addressV:pc.ADDRESS_REPEAT});tex.setSource(img);resolve(tex);};img.onerror=()=>reject(new Error('Texture decode failed'));img.src=data;});
|
||||
item={promise};textures.current.set(key,item);const cached=item;
|
||||
promise.then(tex=>{cached.texture=tex;if(textures.current.get(key)!==cached){tex.destroy();}}).catch(()=>{if(textures.current.get(key)===cached)textures.current.delete(key);});
|
||||
}
|
||||
if(item.texture)applyTexture(m,slot,item.texture,spec);
|
||||
else{
|
||||
pending++;item.promise.then(tex=>{if(generation.current===current)applyTexture(m,slot,tex,spec);}).catch(()=>{failed=true;}).finally(()=>{pending--;if(generation.current===current&&!pending)latest.current.onTextureState?.(failed?'error':'ready');});
|
||||
if(!item.texture){
|
||||
pending++;item.promise.then(tex=>{if(generation.current===current&&selectedSurface()===surface)applyTexture(m,slot,tex,surface);}).catch(()=>{failed=true;}).finally(()=>{pending--;if(generation.current===current&&!pending)latest.current.onTextureState?.(failed?'error':'ready');});
|
||||
}
|
||||
}
|
||||
}
|
||||
configureChargeMaterial(m,spec.chargeGradient);
|
||||
if(spec.chargeGradient?.enabled){animated.current.set(id,m);updateChargeMaterial(m,spec.chargeGradient,latest.current.chargeState,0);}
|
||||
if(spec.chargeGradient){animated.current.set(id,m);updateChargeMaterial(m,spec.chargeGradient,state(),0,spec,bind);}else{applyMaterialSurface(m,spec);bind(spec);}
|
||||
m.update();
|
||||
}
|
||||
for(const [key,item] of textures.current)if(!used.has(key)){item.texture?.destroy();textures.current.delete(key);}
|
||||
@@ -75,7 +73,7 @@ export function useSceneMaterials(appRef:RefObject<pc.Application|null>,cameraRe
|
||||
useEffect(()=>{
|
||||
const app=appRef.current;if(!app||!modelVersion)return;
|
||||
let time=0;const motion=window.matchMedia('(prefers-reduced-motion: reduce)');
|
||||
const update=(dt:number)=>{const live=latest.current;if(live.chargeState?.fresh&&!motion.matches)time+=Math.min(dt,.1);for(const [id,material] of animated.current){const gradient=live.materials?.[id]?.chargeGradient;if(gradient?.enabled)updateChargeMaterial(material,gradient,live.chargeState,time);}};
|
||||
const update=(dt:number)=>{const live=latest.current;if(live.chargeState?.fresh&&!motion.matches)time+=Math.min(dt,.1);for(const [id,material] of animated.current){const gradient=live.materials?.[id]?.chargeGradient;if(gradient)updateChargeMaterial(material,gradient,previewChargeState(live.chargeState,live.materialPreview?.id===id?live.materialPreview:undefined),time,live.materials![id],bindings.current.get(id));}};
|
||||
app.on('update',update);return()=>{app.off('update',update);};
|
||||
},[appRef,modelVersion]);
|
||||
useEffect(()=>()=>{generation.current=-1;for(const item of textures.current.values())item.texture?.destroy();textures.current.clear();for(const m of customMaterials.current.values())m.destroy();customMaterials.current.clear();},[]);
|
||||
|
||||
@@ -11,3 +11,5 @@
|
||||
.rover-settings { display:flex; flex-direction:column; gap:var(--nodedc-space-3); }
|
||||
.rover-settings p { font-size:var(--nodedc-font-size-sm); color:var(--nodedc-text-secondary); }
|
||||
.rover-telemetry {height:100%; min-height:0; min-width:0; overflow:hidden; padding:var(--nodedc-space-3);}.rover-telemetry > .nodedc-comparison-table {max-height:100%;}
|
||||
|
||||
.rover-telemetry .nodedc-comparison-table table {font-size:var(--nodedc-font-size-xs);}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
.nodedc-icon-button > .rover-dev-label {color:inherit;font-size:var(--nodedc-font-size-xs);font-weight:var(--nodedc-font-weight-medium);}
|
||||
.rover-logs {height:100%;min-height:0;overflow:auto;display:flex;flex-direction:column;gap:var(--nodedc-space-2);padding:calc(var(--observation-overlay-header-space, 0px) + var(--nodedc-space-3)) var(--nodedc-space-3) var(--nodedc-space-3);}
|
||||
.rover-logs > p {margin:0;font-size:var(--nodedc-font-size-xs);color:var(--nodedc-text-secondary);overflow-wrap:anywhere;}
|
||||
.rover-logs > p {margin:0;font-size:var(--nodedc-font-size-sm);color:var(--nodedc-text-secondary);overflow-wrap:anywhere;}
|
||||
.rover-logs__entries {flex:1;min-height:0;overflow:auto;}
|
||||
.rover-logs__entries pre {white-space:pre-wrap;overflow-wrap:anywhere;font-size:var(--nodedc-font-size-xs);color:var(--nodedc-text-primary);}
|
||||
|
||||
|
||||
@@ -1,12 +1,13 @@
|
||||
import type {SceneView} from "../../core/simulation/simulationLayout";
|
||||
import {isOrthographic,screenSpan,type EditorProjection} from "../../core/simulation/editorProjection";
|
||||
import { sceneClipBounds } from "../../core/simulation/sceneClip";
|
||||
import { heightSlice } from "../../core/heightSlice";
|
||||
import { sceneClipBounds, sceneClipRange } from "../../core/simulation/sceneClip";
|
||||
import { EditorUrbanMapLayer } from "./EditorUrbanMapLayer";
|
||||
import { urbanExtent, type UrbanMap, type UrbanClassId } from "../../core/simulation/urbanMap";
|
||||
import { EditorCollisionLayer } from "./EditorCollisionLayer";
|
||||
import { waypointHit } from "../../core/simulation/waypointHit";
|
||||
import { PlannerMarkers } from "./PlannerMarkers";
|
||||
import { QUALITY_PROFILES } from "../../core/simulation/gaussianQuality";
|
||||
import { QUALITY_PROFILES, orthographicLodFov } from "../../core/simulation/gaussianQuality";
|
||||
import { DEFAULT_PLANNER_PREFERENCES, type PlannerPreferences } from "../../core/simulation/plannerPreferences";
|
||||
import { Application, Asset, BoundingBox, Color, Entity, FILLMODE_NONE, Mat4, Quat, PROJECTION_ORTHOGRAPHIC, PROJECTION_PERSPECTIVE, RESOLUTION_AUTO, Vec3, WORKBUFFER_UPDATE_ONCE } from "playcanvas";
|
||||
import { toEditor, toMission, type EditorCache } from "../../core/simulation/aiEditor";
|
||||
@@ -37,6 +38,7 @@ export class AiEditorRuntime {
|
||||
private semanticProject: (()=>void)|null = null;
|
||||
private visualBounds:number[][]=[];
|
||||
private urbanVisible=false;
|
||||
private semanticMode=false;
|
||||
private experienceLayer: EditorUrbanMapLayer | null = null;
|
||||
private experiencePoints: number[][] = [];
|
||||
private onExperienceProject: (p: ScreenPoint[])=>void = ()=>undefined;
|
||||
@@ -130,11 +132,14 @@ export class AiEditorRuntime {
|
||||
this.scan.gsplat!.setWorkBufferModifier({ glsl: `
|
||||
uniform float editorClip;
|
||||
uniform float editorFloor;
|
||||
uniform float editorClipEnabled;
|
||||
uniform float editorFloorEnabled;
|
||||
void modifySplatCenter(inout vec3 center) {}
|
||||
void modifySplatRotationScale(vec3 a, vec3 b, inout vec4 rotation, inout vec3 scale) {}
|
||||
void modifySplatColor(vec3 center, inout vec4 color) {
|
||||
// Unified work-buffer modifiers receive the calibrated world center.
|
||||
if (center.y > editorClip || center.y < editorFloor) color.a = 0.0;
|
||||
if ((editorClipEnabled > 0.5 && center.y > editorClip) ||
|
||||
(editorFloorEnabled > 0.5 && center.y < editorFloor)) color.a = 0.0;
|
||||
}` });
|
||||
this.setPreferences(this.preferences);
|
||||
if (terrain.isEmpty()) this.controls.sceneCenter.set(bounds.center.x,bounds.center.y,bounds.center.z);
|
||||
@@ -151,10 +156,10 @@ export class AiEditorRuntime {
|
||||
setUrbanMap(document: UrbanMap) {
|
||||
this.urbanBounds=urbanExtent(document);
|
||||
this.urbanLayer?.dispose();
|
||||
this.urbanLayer=new EditorUrbanMapLayer(this.app,this.camera,document);this.urbanLayer.setClip(this.clip,this.clipFloor);this.urbanLayer.setVisible(this.urbanVisible);this.dirty=true;
|
||||
this.urbanLayer=new EditorUrbanMapLayer(this.app,this.camera,document);this.urbanLayer.setClip(this.clip,this.clipFloor);this.urbanLayer.setVisible(this.semanticMode&&this.urbanVisible);this.dirty=true;
|
||||
}
|
||||
snapshotView():SceneView{return {...this.controls.snapshot(),clip:[Number.isFinite(this.clipFloor)?this.clipFloor:null,Number.isFinite(this.clip)?this.clip:null]};}
|
||||
restoreView(view:SceneView){this.setClip(view.clip[1]??Infinity,view.clip[0]??-Infinity);this.controls.restore(view);this.syncCamera();this.dirty=true;}
|
||||
restoreView(view:SceneView){const [floor,ceiling]=sceneClipRange(view.clip,this.height);this.setClip(ceiling,floor);this.controls.restore(view);this.syncCamera();this.dirty=true;}
|
||||
watchCamera(callback:((q:[number,number,number,number])=>void)|null) {this.cameraProject=callback;this.dirty=true;}
|
||||
setProjection(mode:EditorProjection){this.surfacePicker.invalidate();this.controls.setProjection(mode);this.syncCamera();this.dirty=true;}
|
||||
view(direction:number[]){this.surfacePicker.invalidate();this.controls.view(direction);this.syncCamera();this.dirty=true;}
|
||||
@@ -202,7 +207,8 @@ export class AiEditorRuntime {
|
||||
return q[2]>=this.clipFloor&&q[2]<=this.clip?q:null;
|
||||
}
|
||||
setUrbanClasses(selected:readonly UrbanClassId[]) {this.urbanLayer?.setClasses(selected);this.dirty=true;}
|
||||
showUrbanMap(visible: boolean) { this.urbanVisible=visible;this.urbanLayer?.setVisible(visible);this.dirty=true; }
|
||||
setSemanticMode(active: boolean) { this.semanticMode=active;this.urbanLayer?.setVisible(active&&this.urbanVisible);this.dirty=true; }
|
||||
showUrbanMap(visible: boolean) { this.urbanVisible=visible;this.urbanLayer?.setVisible(this.semanticMode&&visible);this.dirty=true; }
|
||||
setSceneLayers({gaussian,collision}:{gaussian:boolean;collision:boolean}) {
|
||||
this.surfacePicker.invalidate();this.controls.invalidateSurface();this.collisionVisible=collision;
|
||||
if (collision && !this.collisionLayer && !this.terrain.bounds.isEmpty()) {
|
||||
@@ -229,13 +235,17 @@ export class AiEditorRuntime {
|
||||
this.app.resizeCanvas(this.canvas.clientWidth,this.canvas.clientHeight);this.dirty=true;
|
||||
}
|
||||
setClip(height: number, floor = -Infinity) {
|
||||
const slice=heightSlice(sceneClipRange([floor,height],this.height),this.height);
|
||||
height=slice.ceiling??Infinity;floor=slice.floor??-Infinity;
|
||||
this.surfacePicker.invalidate();this.controls.invalidateSurface();
|
||||
this.clip = height; this.clipFloor = floor;
|
||||
this.collisionLayer?.setClip(height,floor);
|
||||
this.urbanLayer?.setClip(height,floor);this.experienceLayer?.setClip(height,floor);
|
||||
if (this.scan.gsplat) {
|
||||
this.scan.gsplat.setParameter("editorClip", Number.isFinite(height) ? height : 1e9);
|
||||
this.scan.gsplat.setParameter("editorFloor", Number.isFinite(floor) ? floor : -1e9);
|
||||
this.scan.gsplat.setParameter("editorClip", Number.isFinite(height) ? height : 0);
|
||||
this.scan.gsplat.setParameter("editorFloor", Number.isFinite(floor) ? floor : 0);
|
||||
this.scan.gsplat.setParameter("editorClipEnabled", Number.isFinite(height) ? 1 : 0);
|
||||
this.scan.gsplat.setParameter("editorFloorEnabled", Number.isFinite(floor) ? 1 : 0);
|
||||
this.scan.gsplat.workBufferUpdate = WORKBUFFER_UPDATE_ONCE;
|
||||
}
|
||||
this.dirty = true;
|
||||
@@ -248,7 +258,10 @@ export class AiEditorRuntime {
|
||||
private syncCamera() {
|
||||
const c=this.controls.camera;
|
||||
this.camera.camera!.projection=isOrthographic(c)?PROJECTION_ORTHOGRAPHIC:PROJECTION_PERSPECTIVE;
|
||||
if(isOrthographic(c))this.camera.camera!.orthoHeight=c.top;
|
||||
if(isOrthographic(c)){
|
||||
this.camera.camera!.orthoHeight=screenSpan(c,1)/2;
|
||||
this.camera.camera!.fov=orthographicLodFov(screenSpan(c,1)/2,this.controls.focusDepth);
|
||||
}else this.camera.camera!.fov=c.fov;
|
||||
const { position:p, quaternion:q } = c;
|
||||
this.camera.setPosition(p.x,p.y,p.z); this.camera.setRotation(q.x,q.y,q.z,q.w);
|
||||
}
|
||||
|
||||
@@ -23,7 +23,7 @@ export function AiInferencePreview({preview,layer}:{preview:InferencePreview;lay
|
||||
{selected.kind==="points3d"?<Suspense fallback={<LoadingRegion loading label="Открываем 3D"/>}>
|
||||
<SpatialPreview points={selected.points} label={selected.label}/>
|
||||
</Suspense>:<img src={`data:image/jpeg;base64,${selected.jpeg}`} alt={`${selected.label}, кадр ${preview.frame_id}`}/>}
|
||||
<div className="ai-inference-preview__caption">
|
||||
<div data-glass-context="scene" className="ai-inference-preview__caption nodedc-viewport-surface">
|
||||
Кадр {preview.frame_id} · Время мира {(preview.simulation_time_ns/1e9).toFixed(1)} с
|
||||
{selected.legend?.length?<span className="ai-inference-preview__legend">{selected.legend.map(c=><span key={c.class_id}><i style={{background:c.color}}/>{c.label}</span>)}</span>:null}
|
||||
{selected.kind==="points3d"?<span>{selected.points.length} из {selected.source_count} точек · Система координат ровера · метры</span>:null}
|
||||
|
||||
@@ -1,11 +1,11 @@
|
||||
import {getSimulationLayout,readSceneView,writeSceneView,useSimulationLayout} from "./useSimulationLayout";
|
||||
import {PlannerCameraTools} from "./PlannerCameraTools";
|
||||
import { heightSlice } from "../../core/heightSlice";
|
||||
import { sceneClipRange, sceneClipLabel } from "../../core/simulation/sceneClip";
|
||||
import { InfrastructureAnalysis } from "./InfrastructureAnalysis";
|
||||
import { PlannerLegend } from "./PlannerLegend";
|
||||
import { SemanticEditor } from "./SemanticEditor";
|
||||
import { PlannerExperience } from "./PlannerExperience";
|
||||
import { loadUrbanMap, type UrbanClassId, type UrbanMap } from "../../core/simulation/urbanMap";
|
||||
import { loadUrbanMap, type UrbanMap } from "../../core/simulation/urbanMap";
|
||||
import type { PreparedRoute } from "../../core/simulation/routePreparation";
|
||||
import type { ScreenPoint } from "../../core/simulation/aiPolygon";
|
||||
import { editWaypoints, waypointEditing, waypointShortcut } from "../../core/simulation/waypointEditing";
|
||||
@@ -13,7 +13,7 @@ import { SimulationViewTools } from "./SimulationViewTools";
|
||||
import { usePlannerPreferences } from "./usePlannerPreferences";
|
||||
import { useEffect, useReducer, useRef, useState } from "react";
|
||||
import { createPortal } from "react-dom";
|
||||
import { Button, FieldFrame, Icon, IconButton, LoadingRegion, RangeControl, Select, SegmentedControl, SegmentedGroup, SegmentedButton, StatusBadge } from "@nodedc/ui-react";
|
||||
import { Description, Button, FieldFrame, Icon, IconButton, LoadingRegion, RangeControl, Select, SegmentedControl, SegmentedGroup, SegmentedButton, StatusBadge } from "@nodedc/ui-react";
|
||||
import { type EditorCache } from "../../core/simulation/aiEditor";
|
||||
import type { AiWaypoint, AiWorld } from "../../core/simulation/aiPolygon";
|
||||
import { AiEditorRuntime, type EditorMarker } from "./AiEditorRuntime";
|
||||
@@ -23,11 +23,11 @@ import { useSimulationFullscreen } from "./useSimulationFullscreen";
|
||||
|
||||
export interface LocalDraft { cache: EditorCache; points: AiWaypoint[]; id: string; sequence: number }
|
||||
export type LocationMode = "view" | "semantic" | "planning";
|
||||
export function AiLocalPlanner({ world, initialPoints, onDraft, actionsHost, headerActions, routeActions, sceneMode, onSceneMode, busy=false, preparedRoute=null }: {
|
||||
export function AiLocalPlanner({ world, initialPoints, onDraft, actionsHost, headerActions, routeActions, sceneMode, onSceneMode, onBack, busy=false, preparedRoute=null }: {
|
||||
world: AiWorld; initialPoints: AiWaypoint[]; onDraft: (draft: LocalDraft | null) => void;
|
||||
actionsHost: HTMLElement | null; headerActions: React.ReactNode;
|
||||
routeActionsHost: HTMLElement | null; routeActions: React.ReactNode; busy?: boolean; preparedRoute?:PreparedRoute|null;
|
||||
sceneMode:LocationMode; onSceneMode:(mode:LocationMode)=>void;
|
||||
sceneMode:LocationMode; onSceneMode:(mode:LocationMode)=>void; onBack:()=>void;
|
||||
}) {
|
||||
const [semanticHeader,setSemanticHeader]=useState<HTMLSpanElement|null>(null);
|
||||
const markerSvg=useRef<SVGSVGElement>(null);
|
||||
@@ -46,10 +46,7 @@ export function AiLocalPlanner({ world, initialPoints, onDraft, actionsHost, hea
|
||||
const sceneLayers=layout.sceneLayers,setSceneLayers=(sceneLayers:typeof layout.sceneLayers)=>updateLayout({sceneLayers});
|
||||
const [urbanMap,setUrbanMap]=useState<UrbanMap|null>(null);
|
||||
const semantic=sceneMode==="semantic", planning=sceneMode==="planning";
|
||||
const urbanVisible=layout.infrastructure,setUrbanVisible=(infrastructure:boolean)=>updateLayout({infrastructure});
|
||||
const urbanClasses=layout.urbanLayers,setUrbanClasses=(urbanLayers:UrbanClassId[])=>updateLayout({urbanLayers});
|
||||
const [memoryVisible,setMemoryVisible]=useState(false);
|
||||
const [urbanError,setUrbanError]=useState<string|null>(null);
|
||||
const [markers, setMarkers] = useState<EditorMarker[]>([]);
|
||||
const [mode,setMode] = useState<"view" | "add">("view");
|
||||
const [clip,setClip] = useState<[number,number]|null>(null);
|
||||
@@ -62,7 +59,7 @@ export function AiLocalPlanner({ world, initialPoints, onDraft, actionsHost, hea
|
||||
const sceneKey=cache.world.sha256!,remember=()=>{if(loaded&&runtime.current)writeSceneView(sceneKey,runtime.current.snapshotView());};
|
||||
const timer=window.setInterval(remember,1500);window.addEventListener("pagehide",remember);
|
||||
const abort=new AbortController();
|
||||
setUrbanMap(null);setUrbanError(null);
|
||||
setUrbanMap(null);
|
||||
setReady(false); setError(null); setClip(null);
|
||||
let view: AiEditorRuntime;
|
||||
try { view = new AiEditorRuntime(canvas.current,cache,setMarkers,setRouteProjection); }
|
||||
@@ -71,12 +68,12 @@ export function AiLocalPlanner({ world, initialPoints, onDraft, actionsHost, hea
|
||||
view.setPreferences(preferences);view.setPoints(initialPoints); view.home();
|
||||
void view.load().then(() => { if (active) {
|
||||
const remembered=readSceneView(sceneKey),settings=getSimulationLayout();
|
||||
if(remembered){view.restoreView(remembered);setClip([remembered.clip[0]??view.height[0],remembered.clip[1]??view.height[1]]);}
|
||||
if(remembered){view.restoreView(remembered);setClip(sceneClipRange(view.snapshotView().clip,view.height));}
|
||||
view.setProjection(settings.projection);view.setSceneLayers(settings.sceneLayers);
|
||||
loaded=true;setReady(true);
|
||||
void loadUrbanMap(cache.world.world_id,cache.world.sha256!,abort.signal).then(map=>{
|
||||
if(active && map){view.setUrbanMap(map);setUrbanMap(map);}
|
||||
}).catch((e:Error)=>{if(active)setUrbanError(e.message);});
|
||||
}).catch((e:Error)=>{if(active)setError(e.message);});
|
||||
} }).catch((e: Error) => { if (active) setError(e.message); });
|
||||
return () => { remember();clearInterval(timer);window.removeEventListener("pagehide",remember);active=false; abort.abort(); runtime.current=null; view.dispose(); callback.current(null); };
|
||||
}, [cache?.key,cache?.status,retry]);
|
||||
@@ -85,8 +82,8 @@ export function AiLocalPlanner({ world, initialPoints, onDraft, actionsHost, hea
|
||||
if (cache?.status === "ready" && ready) callback.current({ cache,points,id:draftId.current,sequence });
|
||||
}, [points,cache,ready,sequence,planning]);
|
||||
useEffect(()=>{
|
||||
if(!semantic&&urbanMap){runtime.current?.setUrbanMap(urbanMap);runtime.current?.setUrbanClasses(urbanClasses);runtime.current?.showUrbanMap(urbanVisible);}
|
||||
},[semantic,urbanMap,urbanVisible,urbanClasses]);
|
||||
runtime.current?.setSemanticMode(semantic);
|
||||
},[semantic,ready]);
|
||||
useEffect(()=>{
|
||||
runtime.current?.setRoute(planning?preparedRoute?.preview_xyz??[]:[]);
|
||||
|
||||
@@ -95,8 +92,6 @@ export function AiLocalPlanner({ world, initialPoints, onDraft, actionsHost, hea
|
||||
setMode("view");press.current=null;runtime.current?.setAddMode(false);
|
||||
if(drag.current){edit({type:"cancel"});drag.current=null;runtime.current?.setNavigation(!busy);}
|
||||
},[sceneMode,ready]);
|
||||
// SemanticEditor owns both the edited map and its layer mask in semantic mode.
|
||||
useEffect(()=>{if(!semantic)runtime.current?.setUrbanClasses(urbanClasses);},[semantic,urbanClasses,urbanMap,ready]);
|
||||
useEffect(()=>{if(ready)try{runtime.current?.setSceneLayers(sceneLayers);}catch(e){setError((e as Error).message);}},[sceneLayers,ready]);
|
||||
useEffect(()=>{runtime.current?.setPreferences(preferences);},[preferences,ready]);
|
||||
useEffect(()=>{runtime.current?.setSelected(selected);},[selected,ready]);
|
||||
@@ -123,12 +118,20 @@ export function AiLocalPlanner({ world, initialPoints, onDraft, actionsHost, hea
|
||||
: cache?.status === "ready" ? "Открываем локальную сцену" : "Готовим локальную копию сцены";
|
||||
const modeLabels={view:"Просмотр",semantic:"Семантика",planning:"Планирование миссии"};
|
||||
const infrastructure=semantic?<InfrastructureAnalysis worldId={world.world_id} worldSha={world.sha256!} busy={busy} hasMap={!!urbanMap}
|
||||
onMap={map=>{setUrbanMap(map);runtime.current?.setUrbanMap(map);runtime.current?.showUrbanMap(true);setUrbanError(null);}}/>:null;
|
||||
const header=<>{planning?<FieldFrame label="Выбор задания" labelPlacement="below" className="ai-polygon__task-field">{headerActions}</FieldFrame>:null}
|
||||
<FieldFrame label="Режим" labelPlacement="below" className="ai-polygon__mode-field">
|
||||
<Select label="Режим" value={sceneMode} onChange={onSceneMode} disabled={busy}
|
||||
options={([{value:"view",label:modeLabels.view},{value:"semantic",label:modeLabels.semantic},{value:"planning",label:modeLabels.planning}] as const).map(o=>({...o}))}/>
|
||||
</FieldFrame>{infrastructure}{semantic?<span className="ai-polygon__semantic-actions" ref={setSemanticHeader}/>:null}{planning?routeActions:null}</>;
|
||||
onMap={map=>{setUrbanMap(map);runtime.current?.setUrbanMap(map);runtime.current?.showUrbanMap(true);setError(null);}}/>:null;
|
||||
const header=<div className="ai-polygon__scene-actions">
|
||||
<div className="ai-polygon__context-actions">
|
||||
{planning?<FieldFrame label="Выбор задания" labelPlacement="below" className="ai-polygon__task-field">{headerActions}</FieldFrame>:null}
|
||||
{infrastructure}{semantic?<span className="ai-polygon__semantic-actions" ref={setSemanticHeader}/>:null}{planning?routeActions:null}
|
||||
</div>
|
||||
<div className="ai-polygon__mode-actions">
|
||||
<FieldFrame label="Режим" labelPlacement="below" className="ai-polygon__mode-field">
|
||||
<Select label="Режим" value={sceneMode} onChange={onSceneMode} disabled={busy}
|
||||
options={([{value:"view",label:modeLabels.view},{value:"semantic",label:modeLabels.semantic},{value:"planning",label:modeLabels.planning}] as const).map(o=>({...o}))}/>
|
||||
</FieldFrame>
|
||||
<IconButton label="Назад к локациям" disabled={busy} onClick={onBack}><Icon name="chevron-left"/></IconButton>
|
||||
</div>
|
||||
</div>;
|
||||
return <div className="ai-polygon__stage" ref={host}>
|
||||
{expanded ? <>
|
||||
<div className="ai-polygon__actions ai-polygon__planner-actions">{header}</div>
|
||||
@@ -137,8 +140,7 @@ export function AiLocalPlanner({ world, initialPoints, onDraft, actionsHost, hea
|
||||
</>}
|
||||
<div className="ai-polygon__telemetry-row ai-polygon__telemetry-row--local">
|
||||
<StatusBadge tone={ready ? "success" : "neutral"}>{ready ? modeLabels[sceneMode] : message}</StatusBadge>
|
||||
{planning?<p>{preparedRoute?`${preparedRoute.length_m.toFixed(1)} м · маршрут — ориентир, препятствия оцениваются при движении`:`${points.length} точек · первая — старт, последняя — финиш`}</p>:null}
|
||||
{!semantic && urbanVisible && urbanMap ? <p>Инфраструктура · {urbanMap.coverage.kind === "objects-only" ? `${urbanMap.schema_version === "missioncore.urban-map/v3" ? "по скану" : urbanMap.analysis?.scope === "whole-scene" ? `обследовано ${urbanMap.analysis.tiles_total} участков · данные в ${urbanMap.analysis.tiles_mapped}` : "участок"} · ${urbanMap.features.length} объектов · распознано автоматически` : `${(urbanMap.coverage.accepted_cells * urbanMap.coverage.cell_m ** 2).toFixed(0)} м² · неполное покрытие`}</p> : null}
|
||||
{planning?<Description>{preparedRoute?`${preparedRoute.length_m.toFixed(1)} м · маршрут — ориентир, препятствия оцениваются при движении`:`${points.length} точек · первая — старт, последняя — финиш`}</Description>:null}
|
||||
</div>
|
||||
<div className="ai-polygon__viewer">
|
||||
<div ref={viewport} className="ai-polygon__viewport ai-local-editor" onContextMenu={(e)=>e.preventDefault()}
|
||||
@@ -158,13 +160,10 @@ export function AiLocalPlanner({ world, initialPoints, onDraft, actionsHost, hea
|
||||
}}><Icon name="trash"/></IconButton>:null}
|
||||
</div>
|
||||
<SegmentedGroup label="Слои сцены" className="ai-local-editor__layers">
|
||||
{!semantic&&urbanMap?<SegmentedButton title={urbanError??"Карта дорожной инфраструктуры"}
|
||||
active={urbanVisible} aria-pressed={urbanVisible}
|
||||
onClick={()=>{const visible=!urbanVisible;setUrbanVisible(visible);runtime.current?.showUrbanMap(visible);}}>Инфраструктура</SegmentedButton>:null}
|
||||
{(["gaussian","collision"] as const).map(key=><SegmentedButton key={key} active={sceneLayers[key]} aria-pressed={sceneLayers[key]}
|
||||
onClick={()=>{try {const next={...sceneLayers,[key]:!sceneLayers[key]};runtime.current?.setSceneLayers(next);setSceneLayers(next);setError(null);}
|
||||
catch(e){setError(e instanceof Error?e.message:"Не удалось показать слой коллизий.");}}}>{key==="gaussian"?"Gaussian":"Коллизии"}</SegmentedButton>)}
|
||||
{runtime.current && viewport.current ? <PlannerExperience worldId={world.world_id} worldSha={world.sha256!}
|
||||
{sceneMode!=="view" && runtime.current && viewport.current ? <PlannerExperience worldId={world.world_id} worldSha={world.sha256!}
|
||||
runtime={runtime.current} viewport={viewport.current} onVisibilityChange={setMemoryVisible}/> : null}
|
||||
</SegmentedGroup>
|
||||
{urbanMap&&urbanMap.schema_version!=="missioncore.urban-map/v1"&&runtime.current&&viewport.current?<SemanticEditor key={world.sha256} worldId={world.world_id} worldSha={world.sha256!}
|
||||
@@ -223,15 +222,15 @@ export function AiLocalPlanner({ world, initialPoints, onDraft, actionsHost, hea
|
||||
<text x={m[axis]![0]*1280+16} y={m[axis]![1]*720-12}>{axis.toUpperCase()}</text></g>:null):null}
|
||||
</g>:null)}
|
||||
</svg></div>
|
||||
{!semantic?<PlannerLegend map={urbanVisible?urbanMap:null} memory={memoryVisible}
|
||||
selected={urbanClasses} onChange={setUrbanClasses} disabled={busy}/>:null}
|
||||
{planning?<PlannerLegend map={null} memory={memoryVisible}
|
||||
selected={[]} onChange={()=>undefined} disabled={busy}/>:null}
|
||||
{!ready && !error ? <LoadingRegion className="ai-local-editor__loading" loading label={message} />:null}
|
||||
{ready ? <><div className="ai-route__height"><RangeControl orientation="vertical" limitSide="right" label="Срез"
|
||||
min={runtime.current!.height[0]} max={runtime.current!.height[1]} step="any" value={clip??runtime.current!.height}
|
||||
formatValue={(v)=>`${v.toFixed(1)} м`} formatLimit={(v)=>v.toFixed(1)}
|
||||
onChange={(v)=>{const next=heightSlice(v,runtime.current!.height);setClip(v);runtime.current!.setClip(next.ceiling??Infinity,next.floor??-Infinity);}}/></div>
|
||||
{error?<div className="ai-route__tools"><p role="alert">{error}</p></div>:null}</>:null}
|
||||
{error && !ready ? <div className="ai-polygon__preview-error"><p role="alert">{error}</p><Button onClick={()=>setRetry(retry+1)}>Повторить загрузку</Button></div>:null}
|
||||
formatValue={(v)=>sceneClipLabel(v,runtime.current!.height)} formatLimit={(v)=>sceneClipLabel(v,runtime.current!.height)}
|
||||
onChange={(v)=>{const view=runtime.current!;view.setClip(v[1],v[0]);setClip(sceneClipRange(view.snapshotView().clip,view.height));}}/></div>
|
||||
{error?<div className="ai-route__tools"><Description role="alert">{error}</Description></div>:null}</>:null}
|
||||
{error && !ready ? <div className="ai-polygon__preview-error"><Description role="alert">{error}</Description><Button onClick={()=>setRetry(retry+1)}>Повторить загрузку</Button></div>:null}
|
||||
</div>
|
||||
</div>
|
||||
</div>;
|
||||
|
||||
@@ -1,14 +1,21 @@
|
||||
import { useState } from "react";
|
||||
import { useInfrastructureQueue } from "../../core/simulation/infrastructureAnalysis";
|
||||
import { Button, ConfirmationModal, Icon, IconButton, ResourceList, ResourceRow,
|
||||
StatusBadge, TextField, ToastStack, Window, WindowFooterActions } from "@nodedc/ui-react";
|
||||
import { Description, Button, ConfirmationModal, Icon, IconButton, ResourceList, ResourceRow,
|
||||
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,19 +63,25 @@ 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>}>
|
||||
<TextField label="Название локации" value={name} maxLength={120} disabled={!!busy}
|
||||
onChange={event => setName(event.target.value)}/>
|
||||
{editing?.world_id === activeWorldId ? <p>Удаление станет доступно после завершения симуляции.</p> : null}
|
||||
{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}
|
||||
</>;
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { Button, TextField, Window, WindowFooterActions } from "@nodedc/ui-react";
|
||||
import { Description, Button, TextField, Window, WindowFooterActions } from "@nodedc/ui-react";
|
||||
|
||||
export function AiPlanSaveWindow({name,onName,busy,launch,onClose,onSave,error}: {
|
||||
error:string|null;name:string;onName:(name:string)=>void;busy:boolean;launch:boolean;
|
||||
@@ -9,9 +9,9 @@ export function AiPlanSaveWindow({name,onName,busy,launch,onClose,onSave,error}:
|
||||
footer={<WindowFooterActions><Button variant="primary" loading={busy} disabled={!name.trim()}
|
||||
onClick={onSave}>{launch?"Сохранить и запустить":"Сохранить"}</Button></WindowFooterActions>}>
|
||||
<div className="ai-polygon__form">
|
||||
{error?<p role="alert">{error}</p>:null}
|
||||
{error?<Description role="alert">{error}</Description>:null}
|
||||
<TextField label="Название задания" value={name} maxLength={120} disabled={busy} onChange={(e)=>onName(e.target.value)}/>
|
||||
<p>Сохраняются текущие точки маршрута и выбранный ровер. Задание появится в списке над сценой.</p>
|
||||
<Description>Сохраняются текущие точки маршрута и выбранный ровер. Задание появится в списке над сценой.</Description>
|
||||
</div>
|
||||
</Window>;
|
||||
}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { useEffect, useRef, useState, type PointerEvent } from "react";
|
||||
import { Button, RangeControl, SegmentedControl } from "@nodedc/ui-react";
|
||||
import { Description, Button, RangeControl, SegmentedControl } from "@nodedc/ui-react";
|
||||
import { type AiRun, type ScreenPoint } from "../../core/simulation/aiPolygon";
|
||||
import { useAiPlanningControls } from "./useAiPlanningControls";
|
||||
|
||||
@@ -133,8 +133,8 @@ export function AiRouteOverlay({ run, onChange, videoReady, visible = true }: {
|
||||
<Button disabled={!ready || !data?.markers.some((m) => m.id === selected)} onClick={() => send({ action: "delete", point_id: selected! })}>Удалить точку</Button>
|
||||
<Button disabled={!ready || !draft?.can_undo} onClick={() => send({ action: "undo" })}>Отменить</Button>
|
||||
<Button disabled={!cameraReady} onClick={() => send({ action: "home" })}>К началу маршрута</Button>
|
||||
<p>Мышь — взгляд · Shift + мышь — сдвиг · Колесо — приближение · WASD / стрелки — полёт · Q / E — вниз / вверх · Shift — быстрее</p>
|
||||
{error || draft?.error ? <p role="alert">{error ?? draft?.error}</p> : null}
|
||||
<Description>Мышь — взгляд · Shift + мышь — сдвиг · Колесо — приближение · WASD / стрелки — полёт · Q / E — вниз / вверх · Shift — быстрее</Description>
|
||||
{error || draft?.error ? <Description role="alert">{error ?? draft?.error}</Description> : null}
|
||||
</div> : null}
|
||||
</div>;
|
||||
}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { Inspector, Icon, GlassSurface, StatusBadge } from "@nodedc/ui-react";
|
||||
import { Description, Inspector, Icon, GlassSurface, StatusBadge } from "@nodedc/ui-react";
|
||||
import type { AiModules, AiRun } from "../../core/simulation/aiPolygon";
|
||||
|
||||
import { AiSessionSection, useSessionLayout } from "./AiSessionSection";
|
||||
@@ -32,11 +32,11 @@ export function AiRunReport({ runs, modules, onRemove, removing, worldId }: { wo
|
||||
action:{label:`Удалить прогон ${new Date(run.created_at ?? "").toLocaleString("ru-RU")}`,
|
||||
icon:<Icon name="trash"/>,disabled:removing!==null || !["completed","stopped","failed"].includes(run.state),
|
||||
onAction:()=>onRemove(run)},
|
||||
}))}/> : <p>В этой локации ещё нет прогонов.</p>}
|
||||
}))}/> : <Description>В этой локации ещё нет прогонов.</Description>}
|
||||
</AiSessionSection>;
|
||||
}
|
||||
function RunDetails({run}:{run:AiRun}) {
|
||||
if(!run.report)return <p>{run.message ?? "Отчёт появится после завершения прогона."}</p>;
|
||||
if(!run.report)return <Description>{run.message ?? "Отчёт появится после завершения прогона."}</Description>;
|
||||
const report=run.report;
|
||||
return <div className="ai-polygon__form ai-polygon__report">
|
||||
<StatusBadge tone={report.mission_outcome === "goal-reached" ? "success" : "neutral"}>
|
||||
@@ -60,8 +60,8 @@ function RunDetails({run}:{run:AiRun}) {
|
||||
<h3>Остановки после начала движения</h3>
|
||||
{report.stops.length ? <dl>{report.stops.map((stop) => <div key={stop.reason}>
|
||||
<dt>{reasons[stop.reason] ?? stop.reason}</dt><dd>{stop.events} · {stop.seconds.toFixed(1)} с</dd>
|
||||
</div>)}</dl> : <p>Переходов от движения к нулевой команде не записано.</p>}
|
||||
<p>Исходные кадры и телеметрия хранятся на Worker. Архив: {report.evidence_files} файлов, {(report.evidence_bytes / 1024 ** 2).toFixed(1)} МБ.</p>
|
||||
</div>)}</dl> : <Description>Переходов от движения к нулевой команде не записано.</Description>}
|
||||
<Description>Исходные кадры и телеметрия хранятся на Worker. Архив: {report.evidence_files} файлов, {(report.evidence_bytes / 1024 ** 2).toFixed(1)} МБ.</Description>
|
||||
<dl className="ai-polygon__report-identities">
|
||||
<div><dt>Прогон</dt><dd>{report.run_id}</dd></div>
|
||||
<div><dt>Профиль ровера</dt><dd>{report.robot_sha256 ?? "Не записан"}</dd></div>
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { StatusBadge } from "@nodedc/ui-react";
|
||||
import { Description, StatusBadge } from "@nodedc/ui-react";
|
||||
import { type AiRun } from "../../core/simulation/aiPolygon";
|
||||
|
||||
const STATES: Record<AiRun["state"], string> = {
|
||||
@@ -51,6 +51,6 @@ export function AiRunView({ run }: { run: AiRun }) {
|
||||
<dt>{label}</dt><dd>{value}</dd>
|
||||
</div>)}
|
||||
</dl>
|
||||
{run.state === "failed" && run.message ? <p>{run.message}</p> : null}
|
||||
{run.state === "failed" && run.message ? <Description>{run.message}</Description> : null}
|
||||
</section>;
|
||||
}
|
||||
|
||||
@@ -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)); }
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { useCallback, useRef, useState, type ReactNode } from "react";
|
||||
import { createPortal } from "react-dom";
|
||||
import { Button, Checker, Dropdown, Icon, IconButton, LoadingRegion, Select, StatusBadge } from "@nodedc/ui-react";
|
||||
import { Description, Button, Checker, Dropdown, Icon, IconButton, LoadingRegion, Select, StatusBadge } from "@nodedc/ui-react";
|
||||
import { setAiCamera, type AiCamera, type AiRun, type AiWorld } from "../../core/simulation/aiPolygon";
|
||||
import { WorkerVideo, type WorkerVideoState } from "./WorkerVideo";
|
||||
import { AiRouteOverlay } from "./AiRouteOverlay";
|
||||
@@ -60,7 +60,7 @@ export function AiWorldStream({ world, run, onBack, onChange, controls, headerAc
|
||||
video={<div className="ai-polygon__viewport ai-polygon__stream-bounds" ref={surface} tabIndex={0} aria-label="Управление камерой симуляции">
|
||||
<div className="ai-polygon__stream-picture">
|
||||
{connectable ? <span className="ai-polygon__stream-fps">{state === "live" ? `Видео · ${fps?.toFixed(0) ?? "—"} FPS` : state === "failed" ? "Видео недоступно" : "Подключаем видео"}</span> : null}
|
||||
{cameraError ? <p role="alert">Не удалось переключить камеру.</p> : null}
|
||||
{cameraError ? <Description role="alert">Не удалось переключить камеру.</Description> : null}
|
||||
<LoadingRegion loading={!terminal && (!connectable || state === "connecting")}
|
||||
label={run?.state === "disconnected" ? "Восстанавливаем связь с Worker" : !connectable ? "Подготавливаем сцену на Worker" : "Подключаем видео"}>
|
||||
<div className="ai-polygon__video" inert>
|
||||
@@ -69,9 +69,9 @@ export function AiWorldStream({ world, run, onBack, onChange, controls, headerAc
|
||||
</div>
|
||||
</LoadingRegion>
|
||||
{!terminal && run && run.telemetry?.route_overlay ? <AiRouteOverlay key={run.run_id} run={run} onChange={onChange} videoReady={state === "live"} visible={routeVisible} /> : null}
|
||||
{terminal ? <div className="ai-polygon__preview-error"><p>{run?.state === "failed" ? run.message ?? "Симуляция прервана." : "Симуляция завершена."}</p></div>
|
||||
{terminal ? <div className="ai-polygon__preview-error"><Description>{run?.state === "failed" ? run.message ?? "Симуляция прервана." : "Симуляция завершена."}</Description></div>
|
||||
: connectable && state === "failed" ? <div className="ai-polygon__preview-error" role="status">
|
||||
<p>Не удалось получить видео после повторных подключений. Если сцена открыта в другой вкладке, закройте её и подключитесь снова.</p>
|
||||
<Description>Не удалось получить видео после повторных подключений. Если сцена открыта в другой вкладке, закройте её и подключитесь снова.</Description>
|
||||
<Button onClick={() => {setState("connecting");setRevision((value) => value + 1);}}>Подключить видео</Button>
|
||||
</div> : null}
|
||||
</div>
|
||||
|
||||
@@ -27,6 +27,7 @@ export class EditorCamera {
|
||||
private right = new Vector3();
|
||||
private delta = new Vector3();
|
||||
sceneCenter = new Vector3();
|
||||
get focusDepth(){return navigationDepth(this.camera,this.lastAnchor??this.sceneCenter);}
|
||||
pick: ((x:number,y:number)=>number[]|null)|null = null;
|
||||
pickSurface: ((x:number,y:number)=>Promise<number[]|null>)|null = null;
|
||||
constructor(private surface: HTMLElement, private canvas: HTMLCanvasElement) {
|
||||
|
||||
@@ -2,7 +2,7 @@ import { SimulationViewTools } from "./SimulationViewTools";
|
||||
import { usePlannerPreferences } from "./usePlannerPreferences";
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
import { createPortal } from "react-dom";
|
||||
import { Button, GlassSurface, LoadingRegion, StatusBadge } from "@nodedc/ui-react";
|
||||
import { Description, Button, GlassSurface, LoadingRegion, StatusBadge } from "@nodedc/ui-react";
|
||||
import type { AiRobot, AiWorld } from "../../core/simulation/aiPolygon";
|
||||
import type { RoverSettings } from "../../core/simulation/roverSettings";
|
||||
import { toEditor } from "../../core/simulation/aiEditor";
|
||||
@@ -48,7 +48,7 @@ export function LocalManualScene({world,robot,settings,actionsHost,headerActions
|
||||
<canvas ref={canvas} aria-label={`Ручное управление ${robot.name}`} />
|
||||
{ready?<div className="ai-simulation__speed"><GlassSurface tone="strong" radius="pill" padding="sm">Скорость: {Math.abs(speed).toFixed(2)} м/с</GlassSurface></div>:null}
|
||||
{!ready&&!error?<div className="ai-polygon__preview-error"><LoadingRegion loading label="Открываем локальную сцену"/></div>:null}
|
||||
{error?<div className="ai-polygon__preview-error"><p role="alert">{error}</p><Button onClick={()=>{setError(null);setRetry(retry+1);}}>Повторить</Button></div>:null}
|
||||
{error?<div className="ai-polygon__preview-error"><Description role="alert">{error}</Description><Button onClick={()=>{setError(null);setRetry(retry+1);}}>Повторить</Button></div>:null}
|
||||
</div>
|
||||
</div>
|
||||
</div>;
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import {useSimulationLayout} from "./useSimulationLayout";
|
||||
import { useEffect, useState } from "react";
|
||||
import { Checker, Dropdown, SegmentedButton } from "@nodedc/ui-react";
|
||||
import { Description, Checker, Dropdown, SegmentedButton } from "@nodedc/ui-react";
|
||||
import { createPortal } from "react-dom";
|
||||
import { loadExperience, attemptLabel, experienceMap, type SpatialExperience } from "../../core/simulation/spatialExperience";
|
||||
import type { ScreenPoint } from "../../core/simulation/aiPolygon";
|
||||
@@ -33,20 +33,20 @@ export function PlannerExperience({worldId,worldSha,runtime,viewport,onVisibilit
|
||||
aria-haspopup="dialog" aria-expanded={open} aria-controls={surfaceId} onClick={toggle}>Память</SegmentedButton>}>
|
||||
<div className="ai-polygon__layer-options">
|
||||
<strong>Память локации</strong>
|
||||
<p>Сохраняет посещённые места и попытки проезда между заездами. Новый заезд с той же конфигурацией ровера продолжает эту историю.</p>
|
||||
{error?<p role="alert">{error}</p>:memory?<>
|
||||
<p>Посещено участков: {memory.visits.length}. Попыток проезда: {memory.attempts.length}, из них позже пройдено: {memory.attempts.filter(a=>a.status==="revisited-successfully").length}.</p>
|
||||
<Description>Сохраняет посещённые места и попытки проезда между заездами. Новый заезд с той же конфигурацией ровера продолжает эту историю.</Description>
|
||||
{error?<Description role="alert">{error}</Description>:memory?<>
|
||||
<Description>Посещено участков: {memory.visits.length}. Попыток проезда: {memory.attempts.length}, из них позже пройдено: {memory.attempts.filter(a=>a.status==="revisited-successfully").length}.</Description>
|
||||
<Checker label="Показывать на карте" checked={visible} onChange={setVisible}/>
|
||||
</>:<p>Сохранённых проездов пока нет. Память появится после движения ровера.</p>}
|
||||
<p>Прежние попытки помогают выбрать другой подход. Возможность проезда всегда проверяется заново по текущим данным.</p>
|
||||
<p>Показана накопленная память конфигурации ровера из последнего заезда. Для другой версии локации или конфигурации сохраняется отдельная память.</p>
|
||||
</>:<Description>Сохранённых проездов пока нет. Память появится после движения ровера.</Description>}
|
||||
<Description>Прежние попытки помогают выбрать другой подход. Возможность проезда всегда проверяется заново по текущим данным.</Description>
|
||||
<Description>Показана накопленная память конфигурации ровера из последнего заезда. Для другой версии локации или конфигурации сохраняется отдельная память.</Description>
|
||||
</div>
|
||||
</Dropdown>
|
||||
{visible&&memory?createPortal(<svg className="ai-local-editor__markers" viewBox="0 0 1280 720" preserveAspectRatio="none" aria-label="Память проездов">
|
||||
{memory.attempts.map((attempt,i)=>{const p=projected[i];if(!p)return null;
|
||||
const label=attemptLabel(attempt),color=URBAN_COLORS[attempt.status==="unresolved"?"attempt":"revisited"];
|
||||
return <g key={attempt.id} role="img" aria-label={label} tabIndex={0} style={{pointerEvents:"auto"}}>
|
||||
<title>{label}</title><circle cx={p[0]*1280} cy={p[1]*720} r="7" fill={`rgb(${color.join(",")})`}/>
|
||||
return <g key={attempt.id} role="img" data-nodedc-tooltip={label} aria-label={label} tabIndex={0} style={{pointerEvents:"auto"}}>
|
||||
<circle cx={p[0]*1280} cy={p[1]*720} r="7" fill={`rgb(${color.join(",")})`}/>
|
||||
</g>;
|
||||
})}
|
||||
</svg>,viewport):null}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { useEffect, useRef, useState, type RefObject } from "react";
|
||||
import { ColorField, ControlRow, RangeControl, Select, ToastStack, WorkspaceWindow } from "@nodedc/ui-react";
|
||||
import { Description, ColorField, ControlRow, RangeControl, Select, ToastStack, WorkspaceWindow } from "@nodedc/ui-react";
|
||||
import type { PlannerPreferences } from "../../core/simulation/plannerPreferences";
|
||||
import {PlannerCubeSettings} from "./PlannerCubeSettings";
|
||||
import {PlannerToolbarSettings} from "./PlannerToolbarSettings";
|
||||
@@ -79,7 +79,7 @@ export function PlannerSettings({ boundsRef, onClose }: { boundsRef: RefObject<H
|
||||
<ControlRow label="Цвет свечения"><ColorField label="Цвет свечения" value={value.waypoint.emissionColor} onChange={(v)=>set("waypoint","emissionColor",v)}/></ControlRow>
|
||||
</> : <>
|
||||
<strong>Сдвиг камеры</strong>
|
||||
<p>Расстояние до поверхности под курсором. Чувствительность плавно меняется между двумя границами.</p>
|
||||
<Description>Расстояние до поверхности под курсором. Чувствительность плавно меняется между двумя границами.</Description>
|
||||
{range("navigation","nearDistance","Ближнее расстояние",.5,50,.5,"м")}
|
||||
{range("navigation","nearPan","Чувствительность вблизи",.1,5,.1,"×")}
|
||||
{range("navigation","farDistance","Дальнее расстояние",Math.max(2,value.navigation.nearDistance+1),500,1,"м")}
|
||||
@@ -87,7 +87,7 @@ export function PlannerSettings({ boundsRef, onClose }: { boundsRef: RefObject<H
|
||||
<strong>Зум</strong>
|
||||
{range("navigation","zoom","Скорость зума",.1,3,.1,"×")}
|
||||
<strong>Центр вращения</strong>
|
||||
<p>Шарик появляется в точке нажатия на время вращения.</p>
|
||||
<Description>Шарик появляется в точке нажатия на время вращения.</Description>
|
||||
{range("navigation","centroidPixels","Размер центра на экране",6,64,1,"px")}
|
||||
<ControlRow label="Цвет центра"><ColorField label="Цвет центра" value={value.navigation.centroidColor} onChange={(v)=>set("navigation","centroidColor",v)}/></ControlRow>
|
||||
{range("navigation","centroidOpacity","Непрозрачность центра",.1,1,.05,"")}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { useState } from "react";
|
||||
import { Button, TextField, Window, WindowFooterActions } from "@nodedc/ui-react";
|
||||
import { Description, Button, TextField, Window, WindowFooterActions } from "@nodedc/ui-react";
|
||||
import type { AiRobot } from "../../core/simulation/aiPolygon";
|
||||
import { defaultRoverSettings, validRoverSettings, type RoverSettings } from "../../core/simulation/roverSettings";
|
||||
|
||||
@@ -23,11 +23,11 @@ export function RoverSettingsWindow({robot,value,manual,onApply,onClose}:{
|
||||
{field("base_mass_kg","Масса ровера без груза, кг",10,1000,1)}
|
||||
{field("payload_mass_kg","Дополнительный груз, кг",0,500,1)}
|
||||
{field("payload_height_m","Высота центра груза над грунтом, м",.1,3,.01)}
|
||||
<p>Общая масса: {Number.isFinite(draft.base_mass_kg+draft.payload_mass_kg)?draft.base_mass_kg+draft.payload_mass_kg:"—"} кг.</p>
|
||||
<p>Груз расположен по центру ровера. Масса и высота влияют на центр тяжести и инерцию; мощность моторов остаётся прежней.</p>
|
||||
{manual?<p>В ручном режиме учитываются скорость и общая масса. Высота груза применяется в заезде на Worker.</p>:null}
|
||||
<p>Изменения применяются к следующему заезду. Его результат сохраняет использованные настройки.</p>
|
||||
{!valid?<p role="status">Допустимо: конечная скорость от 0.05 м/с, масса 10–1000 кг, груз 0–500 кг, высота 0.1–3 м.</p>:null}
|
||||
<Description>Общая масса: {Number.isFinite(draft.base_mass_kg+draft.payload_mass_kg)?draft.base_mass_kg+draft.payload_mass_kg:"—"} кг.</Description>
|
||||
<Description>Груз расположен по центру ровера. Масса и высота влияют на центр тяжести и инерцию; мощность моторов остаётся прежней.</Description>
|
||||
{manual?<Description>В ручном режиме учитываются скорость и общая масса. Высота груза применяется в заезде на Worker.</Description>:null}
|
||||
<Description>Изменения применяются к следующему заезду. Его результат сохраняет использованные настройки.</Description>
|
||||
{!valid?<Description role="status">Допустимо: конечная скорость от 0.05 м/с, масса 10–1000 кг, груз 0–500 кг, высота 0.1–3 м.</Description>:null}
|
||||
</div>
|
||||
</Window>;
|
||||
}
|
||||
|
||||
@@ -38,21 +38,20 @@ export function SemanticEditOverlay(props:SemanticOverlayProps) {
|
||||
{props.editing&&!props.blocked&&base&&g?<g aria-label="Пивот перемещения">
|
||||
{(["x","y","z"] as const).map(axis=>{const end=g[axis];if(!end)return null;const p=[end[0]*rect.width,end[1]*rect.height],d=Math.hypot(p[0]-base[0],p[1]-base[1]);if(d<12)return null;
|
||||
const ux=(p[0]-base[0])/d,uy=(p[1]-base[1])/d;
|
||||
return <g key={axis} data-semantic-axis={axis} style={{pointerEvents:"stroke",cursor:"move"}}>
|
||||
<title>{`Переместить по ${axis.toUpperCase()}`}</title>
|
||||
return <g key={axis} data-nodedc-tooltip={`Переместить по ${axis.toUpperCase()}`} aria-label={`Переместить по ${axis.toUpperCase()}`} data-semantic-axis={axis} style={{pointerEvents:"stroke",cursor:"move"}}>
|
||||
<line x1={base[0]} y1={base[1]} x2={p[0]} y2={p[1]} stroke="transparent" strokeWidth={18}/>
|
||||
<line x1={base[0]} y1={base[1]} x2={p[0]} y2={p[1]} stroke={g.colors[axis]} strokeWidth={3}/>
|
||||
<path d={`M${p[0]},${p[1]} L${p[0]-ux*12-uy*5},${p[1]-uy*12+ux*5} L${p[0]-ux*12+uy*5},${p[1]-uy*12-ux*5} Z`} fill={g.colors[axis]}/>
|
||||
<text x={p[0]+7} y={p[1]-7} fill={g.colors[axis]} fontSize={12}>{axis.toUpperCase()}</text>
|
||||
</g>;
|
||||
})}
|
||||
<rect data-semantic-axis={props.axis} x={base[0]-7} y={base[1]-7} width={14} height={14} fill={color} stroke="var(--nodedc-glass-panel-bg)" strokeWidth={2} style={{pointerEvents:"all",cursor:"move"}}><title>{`Переместить: ${props.axis.toUpperCase()}`}</title></rect>
|
||||
{chosen[0]&&(isRigidMarking(chosen[0])||selected?.object)?<circle data-semantic-axis="rotate" cx={base[0]} cy={base[1]} r={48} fill="none" stroke={color} strokeWidth={3} style={{pointerEvents:"stroke",cursor:"grab"}}><title>Повернуть элемент в плоскости</title></circle>:null}
|
||||
<rect data-nodedc-tooltip={`Переместить: ${props.axis.toUpperCase()}`} aria-label={`Переместить: ${props.axis.toUpperCase()}`} data-semantic-axis={props.axis} x={base[0]-7} y={base[1]-7} width={14} height={14} fill={color} stroke="var(--nodedc-glass-panel-bg)" strokeWidth={2} style={{pointerEvents:"all",cursor:"move"}}/>
|
||||
{chosen[0]&&(isRigidMarking(chosen[0])||selected?.object)?<circle data-nodedc-tooltip="Повернуть элемент в плоскости" aria-label="Повернуть элемент в плоскости" data-semantic-axis="rotate" cx={base[0]} cy={base[1]} r={48} fill="none" stroke={color} strokeWidth={3} style={{pointerEvents:"stroke",cursor:"grab"}}/>:null}
|
||||
</g>:null}
|
||||
{props.editing&&node&&props.selection.length===1?(["incoming","outgoing"] as const).map(key=>{
|
||||
const a=project(node.point),b=project(curveControlPoint(node,key,handleScale));
|
||||
if(!a||!b||!node[key].some(Boolean))return null;
|
||||
return <g key={key} data-semantic-handle-scale={handleScale}><line x1={a[0]} y1={a[1]} x2={b[0]} y2={b[1]} stroke="var(--nodedc-glass-panel-bg)" strokeWidth={4}/><line x1={a[0]} y1={a[1]} x2={b[0]} y2={b[1]} stroke={color} strokeWidth={1.5}/><circle data-semantic-handle={key} cx={b[0]} cy={b[1]} r={6} fill="var(--nodedc-text-primary)" stroke={color} strokeWidth={2} style={{pointerEvents:"all",cursor:"move"}}><title>Ручка кривой</title></circle></g>;
|
||||
return <g key={key} data-semantic-handle-scale={handleScale}><line x1={a[0]} y1={a[1]} x2={b[0]} y2={b[1]} stroke="var(--nodedc-glass-panel-bg)" strokeWidth={4}/><line x1={a[0]} y1={a[1]} x2={b[0]} y2={b[1]} stroke={color} strokeWidth={1.5}/><circle data-nodedc-tooltip="Ручка кривой" aria-label="Ручка кривой" data-semantic-handle={key} cx={b[0]} cy={b[1]} r={6} fill="var(--nodedc-text-primary)" stroke={color} strokeWidth={2} style={{pointerEvents:"all",cursor:"move"}}/></g>;
|
||||
}):null}
|
||||
</svg>,viewport);
|
||||
}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import {
|
||||
import { Description,
|
||||
ActivityIndicator,
|
||||
Button,
|
||||
Icon,
|
||||
@@ -85,7 +85,7 @@ export function SimulationCatalog({
|
||||
<div className="simulation-catalog__empty">
|
||||
<span><Icon name="globe" size={20} /></span>
|
||||
<strong>Перетащите архивы в это окно</strong>
|
||||
<p>Каждый ZIP, RAR или 7z сразу станет отдельным проектом и встанет в очередь.</p>
|
||||
<Description>Каждый ZIP, RAR или 7z сразу станет отдельным проектом и встанет в очередь.</Description>
|
||||
<Button variant="primary" icon={<Icon name="plus" size={16} />} onClick={onCreate}>
|
||||
Новый проект
|
||||
</Button>
|
||||
|
||||
@@ -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};
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
import {useEffect,useRef,useState,type ReactNode} from 'react';
|
||||
import {createPortal} from 'react-dom';
|
||||
import {Button,Checker,DockHandle,Dropdown,GlassSurface,Icon,IconButton,Select,ToastStack} from '@nodedc/ui-react';
|
||||
import { Description,Button,Checker,DockHandle,Dropdown,GlassSurface,Icon,IconButton,Select,ToastStack} from '@nodedc/ui-react';
|
||||
import {withObservationTree,orderedObservationIDs,observationTree} from '../../core/fleet/observationLayout';
|
||||
import {useObservationPresets} from '../../core/fleet/useObservationPresets';
|
||||
import {observationArrangements,retainDormantObservationTree} from '../../core/fleet/observationPresets';
|
||||
@@ -48,7 +48,7 @@ export function SimulationObservationDeck({video,videoActions,toolbar,preview}:{
|
||||
</div></ObservationPanelHeader>
|
||||
<div className="observation-mount">{source.id==='video'?video:preview&&<AiInferencePreview preview={preview} layer={source.id}/>}</div>
|
||||
</GlassSurface></div>,mounts.current.get(source.id)!,source.id))}
|
||||
</ObservationDeck>:<div className="observation-empty"><p>Все окна скрыты.</p><Button onClick={()=>show('video',true)}>Показать симуляцию</Button></div>}</div>
|
||||
</ObservationDeck>:<div className="observation-empty"><Description>Все окна скрыты.</Description><Button onClick={()=>show('video',true)}>Показать симуляцию</Button></div>}</div>
|
||||
{saving&&<ObservationLayoutSaveWindow onClose={()=>setSaving(false)} onSave={presets.save}/>}
|
||||
{edited&&<ObservationLayoutSaveWindow key={edited.id} initialName={edited.name} onClose={()=>setEditing(null)} onSave={name=>presets.rename(edited.id,name)} onRemove={()=>presets.remove(edited.id)}/>}
|
||||
<ToastStack items={presets.error?[{id:"layout-save",tone:"error",title:"Раскладка не сохранена",description:presets.error}]:[]} onDismiss={presets.clearError}/>
|
||||
|
||||
@@ -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 { 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"><p>{p.name}</p>
|
||||
<Button onClick={()=>{onClose();setError(null);setProject(p);}}>Подготовка локации</Button></div>)}
|
||||
{error?<p role="alert">{error}</p>:null}
|
||||
{pending.map(p=><div key={p.projectId} className="ai-polygon__row"><Description>{p.name}</Description>
|
||||
<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="Подготовка локации">
|
||||
<p>{error??project.error??'Локация появится в общей библиотеке после подготовки.'}</p>
|
||||
<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>;
|
||||
}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import {
|
||||
import { Description,
|
||||
Button,
|
||||
Icon,
|
||||
RangeControl,
|
||||
@@ -44,12 +44,12 @@ export function SimulationUgvSettingsPanel({
|
||||
<strong>Физика UGV</strong>
|
||||
<span>Дифференциальный привод</span>
|
||||
</div>
|
||||
<p>
|
||||
<Description>
|
||||
A/D без W/S разворачивают UGV вокруг собственного центра. Скорость и
|
||||
динамика применяются сразу. Мышь вращает камеру вокруг машины, колесо
|
||||
меняет дистанцию; после паузы камера плавно возвращается назад. Ползунок
|
||||
работает в штатном диапазоне, точное значение можно ввести вручную.
|
||||
</p>
|
||||
</Description>
|
||||
<TextField
|
||||
label="Название пресета"
|
||||
value={value.presetName}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { useState, type ReactNode, type RefObject } from "react";
|
||||
import { Icon, IconButton, Select, ToastStack, Window } from "@nodedc/ui-react";
|
||||
import { Description, Icon, IconButton, Select, ToastStack, Window } from "@nodedc/ui-react";
|
||||
import { PlannerSettings } from "./PlannerSettings";
|
||||
import { usePlannerPreferences } from "./usePlannerPreferences";
|
||||
|
||||
@@ -22,12 +22,12 @@ export function SimulationViewTools({expanded,toggle,semantic=false,planning=fal
|
||||
{settings?<PlannerSettings boundsRef={boundsRef} onClose={()=>setSettings(false)}/>:null}
|
||||
<Window open={help} onClose={()=>setHelp(false)} title="Управление сценой">
|
||||
<div className="ai-polygon__form">{planning?<>
|
||||
<p>{semantic?"При редактировании Ctrl + перетаскивание ЛКМ — вращение камеры; без Ctrl — выбранный инструмент. Вне редактирования ЛКМ вращает камеру без Ctrl.":"ЛКМ — вращение вокруг точки нажатия."} ПКМ или клик двумя пальцами с движением — сдвиг.</p>
|
||||
<p>{semantic?"При редактировании прокрутка двумя пальцами сдвигает вид; щипок или Ctrl + прокрутка — зум к курсору.":"Прокрутка — зум к курсору, в том числе в режиме добавления точек."}</p>
|
||||
<p>WASD / стрелки — перемещение. Q / E — вниз / вверх. Shift — быстрее.</p>
|
||||
{semantic?<p>Клик по полосе выбирает элемент целиком, по её вершине — точку; рамка или Shift + клик выбирают несколько точек. Shift + перетаскивание пивота копирует целый элемент или продолжает выбранную точку. Escape отменяет действие, Ctrl/Cmd+Z — отменяет правку. Hold закрепляет тулбар.</p>:null}
|
||||
{routeEditing?<p>Waypoint по клику — установка точки на поверхности. Выберите точку и перемещайте её за стрелки X, Y, Z. Delete — удалить, Ctrl/Cmd+Z — отменить. Клик по пустому месту в обзоре снимает выделение.</p>:null}
|
||||
</>:<><p>WASD / стрелки — движение. Пробел — тормоз. R — к старту.</p><p>Мышь — обзор.</p></>}</div>
|
||||
<Description>{semantic?"При редактировании Ctrl + перетаскивание ЛКМ — вращение камеры; без Ctrl — выбранный инструмент. Вне редактирования ЛКМ вращает камеру без Ctrl.":"ЛКМ — вращение вокруг точки нажатия."} ПКМ или клик двумя пальцами с движением — сдвиг.</Description>
|
||||
<Description>{semantic?"При редактировании прокрутка двумя пальцами сдвигает вид; щипок или Ctrl + прокрутка — зум к курсору.":"Прокрутка — зум к курсору, в том числе в режиме добавления точек."}</Description>
|
||||
<Description>WASD / стрелки — перемещение. Q / E — вниз / вверх. Shift — быстрее.</Description>
|
||||
{semantic?<Description>Клик по полосе выбирает элемент целиком, по её вершине — точку; рамка или Shift + клик выбирают несколько точек. Shift + перетаскивание пивота копирует целый элемент или продолжает выбранную точку. Escape отменяет действие, Ctrl/Cmd+Z — отменяет правку. Hold закрепляет тулбар.</Description>:null}
|
||||
{routeEditing?<Description>Waypoint по клику — установка точки на поверхности. Выберите точку и перемещайте её за стрелки X, Y, Z. Delete — удалить, Ctrl/Cmd+Z — отменить. Клик по пустому месту в обзоре снимает выделение.</Description>:null}
|
||||
</>:<><Description>WASD / стрелки — движение. Пробел — тормоз. R — к старту.</Description><Description>Мышь — обзор.</Description></>}</div>
|
||||
</Window>
|
||||
{error?<ToastStack items={[{id:"quality",tone:"error",title:error}]} onDismiss={()=>setError(null)}/>:null}
|
||||
</>;
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { useEffect, useId, useRef, useState } from "react";
|
||||
import {
|
||||
import { Description,
|
||||
ActivityIndicator,
|
||||
Button,
|
||||
GlassMaterialSurface,
|
||||
@@ -237,7 +237,7 @@ export function SimulationViewport({
|
||||
data-control-mode={controlMode}
|
||||
aria-label={`Сцена ${project.name}`}
|
||||
>
|
||||
<header className="simulation-viewport__toolbar">
|
||||
<header data-glass-context="scene" className="simulation-viewport__toolbar nodedc-viewport-surface">
|
||||
<div>
|
||||
<StatusBadge tone={state === "failed" || collisionState === "failed" ? "warning" : state === "ready" && collisionState !== "loading" ? "success" : "accent"}>
|
||||
{controlState === "loading"
|
||||
@@ -341,7 +341,7 @@ export function SimulationViewport({
|
||||
role="dialog"
|
||||
aria-label="Настройки сцены"
|
||||
>
|
||||
<div className="simulation-viewport__settings-head">
|
||||
<div data-glass-context="scene" className="simulation-viewport__settings-head nodedc-viewport-surface">
|
||||
<div>
|
||||
<strong>Настройки сцены</strong>
|
||||
<span>Локация, камера и UGV</span>
|
||||
@@ -356,9 +356,9 @@ export function SimulationViewport({
|
||||
<strong>Система координат</strong>
|
||||
<span>Мир сцены · Y вверх</span>
|
||||
</div>
|
||||
<p>
|
||||
<Description>
|
||||
Коррекция слоёв не меняет координаты камеры, навигации и будущей физики.
|
||||
</p>
|
||||
</Description>
|
||||
<div className="simulation-viewport__settings-rotations">
|
||||
<LayerRotationFields
|
||||
label="Гауссовый слой"
|
||||
@@ -450,10 +450,10 @@ export function SimulationViewport({
|
||||
<div className="simulation-viewport__stage">
|
||||
<canvas ref={canvasRef} aria-label={`Сцена ${project.name}`} />
|
||||
{state !== "ready" ? (
|
||||
<div className="simulation-viewport__state" role={state === "failed" ? "alert" : "status"}>
|
||||
<div data-glass-context="scene" className="simulation-viewport__state nodedc-viewport-surface" role={state === "failed" ? "alert" : "status"}>
|
||||
{state === "failed" ? null : <ActivityIndicator label="Загрузка локации" />}
|
||||
<strong>{state === "failed" ? "Локация не открылась" : "Загружаем локацию"}</strong>
|
||||
<p>{error ?? "LOD-уровни загружаются по мере готовности runtime."}</p>
|
||||
<Description>{error ?? "LOD-уровни загружаются по мере готовности runtime."}</Description>
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
|
||||
@@ -0,0 +1,32 @@
|
||||
import { useEffect, useState } from "react";
|
||||
import { Description, Button, SettingsCard, TextField, WindowFooterActions } from "@nodedc/ui-react";
|
||||
import { announceLabStorageChange, saveLabRetention, useLocalLabStorage } from "../../core/storage/localLabStorage";
|
||||
|
||||
export function useLabStorageSettings(open: boolean) {
|
||||
const { data, error: loadError, refresh } = useLocalLabStorage(open);
|
||||
const [days, setDays] = useState("30");
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [saved, setSaved] = useState(false);
|
||||
useEffect(() => { if (data) setDays(String(data.retention_days)); }, [data?.retention_days]);
|
||||
const number = Number(days);
|
||||
const valid = Number.isInteger(number) && number >= 1 && number <= 365;
|
||||
const content = <SettingsCard eyebrow="ХРАНИЛИЩЕ" title="Локальные записи лабораторий"
|
||||
description="Срок хранения готовых записей просмотра после последнего открытия. Закреплённые записи остаются на этом устройстве до снятия булавки.">
|
||||
<TextField label="Срок временного хранения, дней" type="number" min={1} max={365}
|
||||
value={days} disabled={busy || !data} onChange={event => { setDays(event.target.value); setSaved(false); }} />
|
||||
<Description>После снятия булавки срок начинается заново. История запусков и результаты на Worker сохраняются.</Description>
|
||||
<Description>Правило применяется к учтённым записям просмотра AI Inference. Исходные записи, Gaussian-сцены и разметка сохраняются отдельно.</Description>
|
||||
{loadError || error ? <Description role="alert">{error ?? loadError}</Description> : saved ? <Description role="status">Настройки сохранены.</Description> : null}
|
||||
</SettingsCard>;
|
||||
const footer = <WindowFooterActions>
|
||||
<Button variant="secondary" disabled={busy || !data || days === String(data.retention_days)}
|
||||
onClick={() => { setDays(String(data!.retention_days)); setError(null); }}>Сбросить изменения</Button>
|
||||
<Button variant="primary" tone="neutral" disabled={busy || !data || !valid || days === String(data.retention_days)}
|
||||
onClick={() => { setBusy(true); setError(null); void saveLabRetention(number).then(async () => {
|
||||
await refresh(); setSaved(true); announceLabStorageChange();
|
||||
}).catch(reason => setError(reason instanceof Error ? reason.message : "Не удалось сохранить срок хранения."))
|
||||
.finally(() => setBusy(false)); }}>{busy ? "Сохраняем…" : "Сохранить"}</Button>
|
||||
</WindowFooterActions>;
|
||||
return { id: "storage", label: "Хранилище", icon: "database" as const, content, footer };
|
||||
}
|
||||
@@ -1,579 +0,0 @@
|
||||
import { useEffect, useMemo, useState } from "react";
|
||||
import {
|
||||
Button,
|
||||
FeatureSettingsWindow,
|
||||
FieldFrame,
|
||||
Icon,
|
||||
Select,
|
||||
SettingsCard,
|
||||
StatusBadge,
|
||||
TextField,
|
||||
WindowFooterActions,
|
||||
} from "@nodedc/ui-react";
|
||||
|
||||
import {
|
||||
applyComputeContourNetwork,
|
||||
fetchComputeContourAgentInstall,
|
||||
fetchComputeContourNetwork,
|
||||
type ComputeContour,
|
||||
type ComputeContourAgentInstall,
|
||||
type ComputeContourDraft,
|
||||
type ComputeContourNetworkStatus,
|
||||
type ComputeContourPlatform,
|
||||
} from "../../core/system/computeContours";
|
||||
import {
|
||||
DEFAULT_TELEMETRY_POLL_INTERVAL_SECONDS,
|
||||
parseTelemetryPollIntervalDraft,
|
||||
resolveTelemetryPollIntervalDraft,
|
||||
} from "../../core/system/telemetryPollInterval";
|
||||
|
||||
interface ComputeContourSettingsWindowProps {
|
||||
open: boolean;
|
||||
contour: ComputeContour | null;
|
||||
mode: "create" | "edit";
|
||||
onClose: () => void;
|
||||
onCreate: (draft: ComputeContourDraft) => Promise<ComputeContour>;
|
||||
onUpdate: (
|
||||
contour: ComputeContour,
|
||||
draft: ComputeContourDraft,
|
||||
) => Promise<ComputeContour>;
|
||||
}
|
||||
|
||||
const platformOptions = [
|
||||
{ value: "windows", label: "Windows", description: "Worker с Windows service" },
|
||||
{ value: "linux", label: "Linux", description: "Worker с systemd service" },
|
||||
{ value: "unknown", label: "Не определено", description: "Платформа будет уточнена" },
|
||||
] satisfies Array<{
|
||||
value: ComputeContourPlatform;
|
||||
label: string;
|
||||
description: string;
|
||||
}>;
|
||||
|
||||
function emptyDraft(): ComputeContourDraft {
|
||||
return {
|
||||
display_name: "",
|
||||
expected_node_id: "",
|
||||
platform: "unknown",
|
||||
telemetry_mode: "agent-mqtt",
|
||||
address: "",
|
||||
ssh_port: 22,
|
||||
mqtt_host: "127.0.0.1",
|
||||
mqtt_port: 1883,
|
||||
mqtt_bind_address: "127.0.0.1",
|
||||
telemetry_poll_interval_seconds: DEFAULT_TELEMETRY_POLL_INTERVAL_SECONDS,
|
||||
mqtt_publish_interval_seconds: 2,
|
||||
};
|
||||
}
|
||||
|
||||
function draftFromContour(contour: ComputeContour | null): ComputeContourDraft {
|
||||
if (!contour) return emptyDraft();
|
||||
return {
|
||||
display_name: contour.display_name,
|
||||
expected_node_id: contour.expected_node_id,
|
||||
platform: contour.platform,
|
||||
telemetry_mode: contour.telemetry_mode,
|
||||
address: contour.address,
|
||||
ssh_port: contour.ssh_port,
|
||||
mqtt_host: contour.mqtt_host,
|
||||
mqtt_port: contour.mqtt_port,
|
||||
mqtt_bind_address: contour.mqtt_bind_address,
|
||||
telemetry_poll_interval_seconds: contour.telemetry_poll_interval_seconds,
|
||||
mqtt_publish_interval_seconds: contour.mqtt_publish_interval_seconds,
|
||||
};
|
||||
}
|
||||
|
||||
export function ComputeContourSettingsWindow({
|
||||
open,
|
||||
contour,
|
||||
mode,
|
||||
onClose,
|
||||
onCreate,
|
||||
onUpdate,
|
||||
}: ComputeContourSettingsWindowProps) {
|
||||
const [draft, setDraft] = useState<ComputeContourDraft>(() => draftFromContour(contour));
|
||||
const [telemetryPollIntervalDraft, setTelemetryPollIntervalDraft] = useState(
|
||||
() => String(draftFromContour(contour).telemetry_poll_interval_seconds),
|
||||
);
|
||||
const [mqttPublishIntervalDraft, setMqttPublishIntervalDraft] = useState(
|
||||
() => String(draftFromContour(contour).mqtt_publish_interval_seconds),
|
||||
);
|
||||
const [activeSection, setActiveSection] = useState<"connection" | "agent">("connection");
|
||||
const [install, setInstall] = useState<ComputeContourAgentInstall | null>(null);
|
||||
const [network, setNetwork] = useState<ComputeContourNetworkStatus | null>(null);
|
||||
const [networkAction, setNetworkAction] = useState<
|
||||
"refresh" | "broker" | "worker" | null
|
||||
>(null);
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
if (!open) return;
|
||||
const nextDraft = draftFromContour(mode === "edit" ? contour : null);
|
||||
setDraft(nextDraft);
|
||||
setTelemetryPollIntervalDraft(String(nextDraft.telemetry_poll_interval_seconds));
|
||||
setMqttPublishIntervalDraft(String(nextDraft.mqtt_publish_interval_seconds));
|
||||
setActiveSection("connection");
|
||||
setInstall(null);
|
||||
setNetwork(null);
|
||||
setNetworkAction(null);
|
||||
setError(null);
|
||||
}, [contour, mode, open]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!open || mode !== "edit" || !contour) return;
|
||||
const controller = new AbortController();
|
||||
setNetworkAction("refresh");
|
||||
void fetchComputeContourNetwork(contour.contour_id, controller.signal)
|
||||
.then((document) => {
|
||||
if (!controller.signal.aborted) setNetwork(document);
|
||||
})
|
||||
.catch((reason: unknown) => {
|
||||
if (!controller.signal.aborted) {
|
||||
setError(reason instanceof Error ? reason.message : "Сетевая проверка недоступна.");
|
||||
}
|
||||
})
|
||||
.finally(() => {
|
||||
if (!controller.signal.aborted) setNetworkAction(null);
|
||||
});
|
||||
return () => controller.abort();
|
||||
}, [contour, mode, open]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!open || mode !== "edit" || !contour) return;
|
||||
const controller = new AbortController();
|
||||
void fetchComputeContourAgentInstall(contour.contour_id, controller.signal)
|
||||
.then((document) => {
|
||||
if (!controller.signal.aborted) setInstall(document);
|
||||
})
|
||||
.catch((reason: unknown) => {
|
||||
if (!controller.signal.aborted) {
|
||||
setError(reason instanceof Error ? reason.message : "Инструкция агента недоступна.");
|
||||
}
|
||||
});
|
||||
return () => controller.abort();
|
||||
}, [contour, mode, open]);
|
||||
|
||||
const telemetryPollIntervalSeconds = useMemo(
|
||||
() => parseTelemetryPollIntervalDraft(telemetryPollIntervalDraft),
|
||||
[telemetryPollIntervalDraft],
|
||||
);
|
||||
const mqttPublishIntervalSeconds = useMemo(
|
||||
() => parseTelemetryPollIntervalDraft(mqttPublishIntervalDraft),
|
||||
[mqttPublishIntervalDraft],
|
||||
);
|
||||
|
||||
const valid = useMemo(() => (
|
||||
Boolean(draft.display_name.trim())
|
||||
&& Boolean(draft.expected_node_id.trim())
|
||||
&& Boolean(draft.mqtt_host.trim())
|
||||
&& Boolean(draft.mqtt_bind_address.trim())
|
||||
&& Number.isInteger(draft.ssh_port)
|
||||
&& draft.ssh_port > 0
|
||||
&& Number.isInteger(draft.mqtt_port)
|
||||
&& draft.mqtt_port > 0
|
||||
&& telemetryPollIntervalSeconds !== null
|
||||
&& mqttPublishIntervalSeconds !== null
|
||||
), [draft, mqttPublishIntervalSeconds, telemetryPollIntervalSeconds]);
|
||||
|
||||
const networkProfileDirty = Boolean(
|
||||
contour
|
||||
&& (
|
||||
draft.mqtt_host !== contour.mqtt_host
|
||||
|| draft.mqtt_port !== contour.mqtt_port
|
||||
|| draft.mqtt_bind_address !== contour.mqtt_bind_address
|
||||
|| draft.mqtt_publish_interval_seconds !== contour.mqtt_publish_interval_seconds
|
||||
),
|
||||
);
|
||||
|
||||
const commitTelemetryPollInterval = () => {
|
||||
const resolution = resolveTelemetryPollIntervalDraft(
|
||||
telemetryPollIntervalDraft,
|
||||
draft.telemetry_poll_interval_seconds,
|
||||
);
|
||||
setTelemetryPollIntervalDraft(resolution.draft);
|
||||
if (!resolution.accepted) return;
|
||||
setDraft((current) => (
|
||||
current.telemetry_poll_interval_seconds === resolution.seconds
|
||||
? current
|
||||
: {
|
||||
...current,
|
||||
telemetry_poll_interval_seconds: resolution.seconds,
|
||||
}
|
||||
));
|
||||
};
|
||||
|
||||
const commitMqttPublishInterval = () => {
|
||||
const resolution = resolveTelemetryPollIntervalDraft(
|
||||
mqttPublishIntervalDraft,
|
||||
draft.mqtt_publish_interval_seconds,
|
||||
);
|
||||
setMqttPublishIntervalDraft(resolution.draft);
|
||||
if (!resolution.accepted) return;
|
||||
setDraft((current) => (
|
||||
current.mqtt_publish_interval_seconds === resolution.seconds
|
||||
? current
|
||||
: {
|
||||
...current,
|
||||
mqtt_publish_interval_seconds: resolution.seconds,
|
||||
}
|
||||
));
|
||||
};
|
||||
|
||||
const save = async () => {
|
||||
if (
|
||||
!valid
|
||||
|| busy
|
||||
|| telemetryPollIntervalSeconds === null
|
||||
|| mqttPublishIntervalSeconds === null
|
||||
) return;
|
||||
const committedDraft = {
|
||||
...draft,
|
||||
telemetry_poll_interval_seconds: telemetryPollIntervalSeconds,
|
||||
mqtt_publish_interval_seconds: mqttPublishIntervalSeconds,
|
||||
};
|
||||
setBusy(true);
|
||||
setError(null);
|
||||
try {
|
||||
if (mode === "edit" && contour) {
|
||||
await onUpdate(contour, committedDraft);
|
||||
} else {
|
||||
await onCreate(committedDraft);
|
||||
}
|
||||
onClose();
|
||||
} catch (reason) {
|
||||
setError(reason instanceof Error ? reason.message : "Контур не сохранён.");
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
};
|
||||
|
||||
const refreshNetwork = async () => {
|
||||
if (!contour || networkAction) return;
|
||||
setNetworkAction("refresh");
|
||||
setError(null);
|
||||
try {
|
||||
setNetwork(await fetchComputeContourNetwork(contour.contour_id));
|
||||
} catch (reason) {
|
||||
setError(reason instanceof Error ? reason.message : "Сетевая проверка недоступна.");
|
||||
} finally {
|
||||
setNetworkAction(null);
|
||||
}
|
||||
};
|
||||
|
||||
const applyNetwork = async (target: "broker" | "worker") => {
|
||||
if (!contour || networkAction || networkProfileDirty) return;
|
||||
setNetworkAction(target);
|
||||
setError(null);
|
||||
try {
|
||||
await applyComputeContourNetwork(contour.contour_id, target);
|
||||
setNetwork(await fetchComputeContourNetwork(contour.contour_id));
|
||||
} catch (reason) {
|
||||
setError(
|
||||
reason instanceof Error ? reason.message : "Сетевой профиль не применён.",
|
||||
);
|
||||
} finally {
|
||||
setNetworkAction(null);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<FeatureSettingsWindow
|
||||
open={open}
|
||||
title={mode === "create" ? "Добавить вычислительный контур" : "Настройки контура"}
|
||||
subtitle="Локальная переносимая конфигурация"
|
||||
identity={{
|
||||
title: contour?.display_name ?? "Новый контур",
|
||||
subtitle: contour?.expected_node_id ?? "Node ID не назначен",
|
||||
avatarLabel: contour?.display_name.slice(0, 2).toUpperCase() ?? "WC",
|
||||
}}
|
||||
sections={[
|
||||
{
|
||||
id: "connection",
|
||||
label: "Подключение",
|
||||
group: "ВЫЧИСЛИТЕЛЬНЫЙ КОНТУР",
|
||||
icon: "network",
|
||||
},
|
||||
{
|
||||
id: "agent",
|
||||
label: "Агент",
|
||||
group: "ТЕЛЕМЕТРИЯ",
|
||||
icon: "activity",
|
||||
disabled: mode === "create",
|
||||
},
|
||||
]}
|
||||
activeSection={activeSection}
|
||||
onSectionChange={setActiveSection}
|
||||
onClose={onClose}
|
||||
footer={(
|
||||
<WindowFooterActions>
|
||||
<Button variant="secondary" onClick={onClose}>Отмена</Button>
|
||||
<Button variant="primary" disabled={!valid || busy} onClick={() => void save()}>
|
||||
{busy ? "Сохраняем…" : mode === "create" ? "Добавить контур" : "Сохранить"}
|
||||
</Button>
|
||||
</WindowFooterActions>
|
||||
)}
|
||||
>
|
||||
<div className="compute-contour-settings">
|
||||
{activeSection === "connection" ? (
|
||||
<>
|
||||
<SettingsCard
|
||||
eyebrow="КОНТУР"
|
||||
title="Идентичность и локальная сеть"
|
||||
description="Node ID проверяется независимо от IP-адреса. Адрес можно менять при переносе комплекта в другую локальную сеть."
|
||||
>
|
||||
<div className="compute-contour-settings__form">
|
||||
<TextField
|
||||
label="Название"
|
||||
value={draft.display_name}
|
||||
placeholder="Worker 006"
|
||||
onChange={(event) => setDraft((current) => ({
|
||||
...current,
|
||||
display_name: event.currentTarget.value,
|
||||
}))}
|
||||
/>
|
||||
<TextField
|
||||
label="Ожидаемый Node ID"
|
||||
value={draft.expected_node_id}
|
||||
placeholder="DESKTOP-OPJ8J04"
|
||||
onChange={(event) => setDraft((current) => ({
|
||||
...current,
|
||||
expected_node_id: event.currentTarget.value,
|
||||
}))}
|
||||
/>
|
||||
<FieldFrame label="Операционная система">
|
||||
<Select
|
||||
label="Операционная система"
|
||||
value={draft.platform}
|
||||
options={platformOptions}
|
||||
variant="split"
|
||||
menuWidth="anchor"
|
||||
onChange={(platform) => setDraft((current) => ({ ...current, platform }))}
|
||||
/>
|
||||
</FieldFrame>
|
||||
<TextField
|
||||
label="Адрес узла"
|
||||
hint="IP или hostname в текущей LAN"
|
||||
value={draft.address}
|
||||
onChange={(event) => setDraft((current) => ({
|
||||
...current,
|
||||
address: event.currentTarget.value,
|
||||
}))}
|
||||
/>
|
||||
<TextField
|
||||
label="MQTT broker"
|
||||
hint="Стабильный hostname рекомендуется вместо выдаваемого DHCP IP"
|
||||
value={draft.mqtt_host}
|
||||
onChange={(event) => setDraft((current) => ({
|
||||
...current,
|
||||
mqtt_host: event.currentTarget.value,
|
||||
}))}
|
||||
/>
|
||||
<TextField
|
||||
label="MQTT port"
|
||||
type="number"
|
||||
min={1}
|
||||
max={65535}
|
||||
value={String(draft.mqtt_port)}
|
||||
onChange={(event) => setDraft((current) => ({
|
||||
...current,
|
||||
mqtt_port: Number(event.currentTarget.value),
|
||||
}))}
|
||||
/>
|
||||
<TextField
|
||||
label="Публикация broker"
|
||||
hint="IP текущего Mac в разрешённой LAN · 0.0.0.0 запрещён"
|
||||
value={draft.mqtt_bind_address}
|
||||
onChange={(event) => setDraft((current) => ({
|
||||
...current,
|
||||
mqtt_bind_address: event.currentTarget.value,
|
||||
}))}
|
||||
/>
|
||||
<TextField
|
||||
label="Обновление интерфейса"
|
||||
hint="1–60 с"
|
||||
type="text"
|
||||
inputMode="numeric"
|
||||
autoComplete="off"
|
||||
aria-invalid={telemetryPollIntervalSeconds === null}
|
||||
value={telemetryPollIntervalDraft}
|
||||
onChange={(event) => setTelemetryPollIntervalDraft(event.currentTarget.value)}
|
||||
onBlur={commitTelemetryPollInterval}
|
||||
onKeyDown={(event) => {
|
||||
if (event.key === "Enter") {
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
commitTelemetryPollInterval();
|
||||
} else if (event.key === "Escape") {
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
setTelemetryPollIntervalDraft(
|
||||
String(draft.telemetry_poll_interval_seconds),
|
||||
);
|
||||
}
|
||||
}}
|
||||
/>
|
||||
<TextField
|
||||
label="Интервал MQTT агента"
|
||||
hint="1–60 с · применяется конфигурацией агента"
|
||||
type="text"
|
||||
inputMode="numeric"
|
||||
autoComplete="off"
|
||||
aria-invalid={mqttPublishIntervalSeconds === null}
|
||||
value={mqttPublishIntervalDraft}
|
||||
onChange={(event) => setMqttPublishIntervalDraft(event.currentTarget.value)}
|
||||
onBlur={commitMqttPublishInterval}
|
||||
onKeyDown={(event) => {
|
||||
if (event.key === "Enter") {
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
commitMqttPublishInterval();
|
||||
} else if (event.key === "Escape") {
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
setMqttPublishIntervalDraft(
|
||||
String(draft.mqtt_publish_interval_seconds),
|
||||
);
|
||||
}
|
||||
}}
|
||||
/>
|
||||
{draft.telemetry_mode === "legacy-ssh" ? (
|
||||
<TextField
|
||||
label="SSH port"
|
||||
type="number"
|
||||
min={1}
|
||||
max={65535}
|
||||
value={String(draft.ssh_port)}
|
||||
onChange={(event) => setDraft((current) => ({
|
||||
...current,
|
||||
ssh_port: Number(event.currentTarget.value),
|
||||
}))}
|
||||
/>
|
||||
) : null}
|
||||
</div>
|
||||
</SettingsCard>
|
||||
<SettingsCard
|
||||
eyebrow="СЕТЕВОЙ ПРОФИЛЬ"
|
||||
title="MQTT · Mac ↔ Worker"
|
||||
description="Mesh-точки одной LAN не закрепляются по отдельности. Профиль хранит стабильное имя Mac и адрес публикации broker в текущей сети."
|
||||
actions={(
|
||||
<StatusBadge tone={network?.broker.ready ? "success" : "warning"}>
|
||||
{network?.broker.ready ? "Broker доступен" : "Нужна проверка"}
|
||||
</StatusBadge>
|
||||
)}
|
||||
>
|
||||
<div className="compute-contour-settings__network">
|
||||
<dl>
|
||||
<div>
|
||||
<dt>Endpoint Worker</dt>
|
||||
<dd>{network
|
||||
? `${network.broker.configured_host}:${network.broker.configured_port}`
|
||||
: "—"}</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt>Текущий IP</dt>
|
||||
<dd>{network?.broker.resolved_addresses.join(", ") || "—"}</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt>Публикация Mac</dt>
|
||||
<dd>{network?.broker.bind_address ?? "—"}</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt>{contour?.display_name ?? "Worker"}</dt>
|
||||
<dd>{network?.worker.reachable
|
||||
? `${network.worker.mqtt_host ?? "—"}:${network.worker.mqtt_port ?? "—"}`
|
||||
: "Недоступен"}</dd>
|
||||
</div>
|
||||
</dl>
|
||||
<div className="compute-contour-settings__network-statuses">
|
||||
<StatusBadge tone={network?.broker.bind_reachable ? "success" : "danger"}>
|
||||
{network?.broker.bind_reachable
|
||||
? "Listener Mac доступен"
|
||||
: "Listener Mac недоступен"}
|
||||
</StatusBadge>
|
||||
<StatusBadge tone={network?.worker.broker_reachable ? "success" : "danger"}>
|
||||
{network?.worker.broker_reachable
|
||||
? "Worker видит broker"
|
||||
: "Worker не видит broker"}
|
||||
</StatusBadge>
|
||||
<StatusBadge tone={network?.worker.matches_profile ? "success" : "warning"}>
|
||||
{network?.worker.matches_profile
|
||||
? "Профиль синхронизирован"
|
||||
: "Профиль отличается"}
|
||||
</StatusBadge>
|
||||
</div>
|
||||
<div className="compute-contour-settings__network-actions">
|
||||
<Button
|
||||
size="compact"
|
||||
variant="secondary"
|
||||
disabled={Boolean(networkAction)}
|
||||
icon={<Icon name="refresh" size={14} />}
|
||||
onClick={() => void refreshNetwork()}
|
||||
>
|
||||
{networkAction === "refresh" ? "Проверяем…" : "Проверить"}
|
||||
</Button>
|
||||
<Button
|
||||
size="compact"
|
||||
variant="secondary"
|
||||
disabled={Boolean(networkAction) || networkProfileDirty}
|
||||
onClick={() => void applyNetwork("broker")}
|
||||
>
|
||||
{networkAction === "broker" ? "Применяем…" : "Применить на Mac"}
|
||||
</Button>
|
||||
<Button
|
||||
size="compact"
|
||||
variant="secondary"
|
||||
disabled={Boolean(networkAction) || networkProfileDirty}
|
||||
onClick={() => void applyNetwork("worker")}
|
||||
>
|
||||
{networkAction === "worker" ? "Применяем…" : "Применить на Worker"}
|
||||
</Button>
|
||||
</div>
|
||||
{networkProfileDirty ? (
|
||||
<p>Сначала сохраните изменённый сетевой профиль, затем примените его.</p>
|
||||
) : null}
|
||||
{error ? <StatusBadge tone="danger">{error}</StatusBadge> : null}
|
||||
</div>
|
||||
</SettingsCard>
|
||||
</>
|
||||
) : null}
|
||||
|
||||
{activeSection === "agent" ? (
|
||||
<SettingsCard
|
||||
eyebrow="АГЕНТ"
|
||||
title="Telegraf · универсальный сборщик"
|
||||
description="Hardware и runtime собирает готовый агент. Mission Core нормализует только контур, LAB/run и стадии обработки."
|
||||
actions={(
|
||||
<StatusBadge tone={install?.ready ? "success" : "warning"}>
|
||||
{install?.ready ? "Готов к установке" : "Нужен scoped MQTT credential"}
|
||||
</StatusBadge>
|
||||
)}
|
||||
>
|
||||
{install ? (
|
||||
<div className="compute-contour-settings__install">
|
||||
<dl>
|
||||
<div><dt>Шаблон</dt><dd>{install.agent.configuration_template}</dd></div>
|
||||
<div><dt>Секрет</dt><dd>интерактивный ввод · не хранится в UI</dd></div>
|
||||
</dl>
|
||||
<code>{install.command}</code>
|
||||
<Button
|
||||
size="compact"
|
||||
variant="secondary"
|
||||
icon={<Icon name="copy" size={14} />}
|
||||
onClick={() => void navigator.clipboard.writeText(install.command)}
|
||||
>
|
||||
Копировать команду
|
||||
</Button>
|
||||
{install.blocked_reason ? <p>{install.blocked_reason}</p> : null}
|
||||
</div>
|
||||
) : (
|
||||
<p className="compute-contour-settings__empty">
|
||||
Сохраните контур, чтобы получить платформенную инструкцию установки.
|
||||
</p>
|
||||
)}
|
||||
{error ? <StatusBadge tone="danger">{error}</StatusBadge> : null}
|
||||
</SettingsCard>
|
||||
) : null}
|
||||
</div>
|
||||
</FeatureSettingsWindow>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
import {useEffect,useRef,useState} from 'react';
|
||||
import {Button,Description,Icon,Select,SettingsCard,TextAreaField,ToastStack,Window,WindowFooterActions} from '@nodedc/ui-react';
|
||||
import {InstallerCard} from '../network/InstallerCard';
|
||||
import {serverRequest,useServers,type Server} from '../../core/system/servers';
|
||||
import {vpsRequest} from '../../core/fleet/vps';
|
||||
|
||||
export function ServerServiceSetup({server:initialServer,fixedKind,onClose,onSaved}:{server?:Server;fixedKind?:'librespeed';onClose:()=>void;onSaved:()=>void}) {
|
||||
const [kind,setKind]=useState<'wireguard'|'arnavi'|'librespeed'|'egress'>(fixedKind??'wireguard'),[document,setDocument]=useState(''),[filename,setFilename]=useState('');
|
||||
const catalog=useServers();const [serverId,setServerId]=useState(initialServer?.id??'');
|
||||
const server=initialServer??catalog.items?.find(s=>s.id===serverId);
|
||||
const serviceName=kind==='egress'?'Маршрутизация трафика':kind==='librespeed'?'LibreSpeed':'WireGuard';
|
||||
const [network,setNetwork]=useState(''),[interfaces,setInterfaces]=useState<{id:string;label:string}[]>([]);
|
||||
const [busy,setBusy]=useState(false),[error,setError]=useState('');const file=useRef<HTMLInputElement>(null);
|
||||
useEffect(()=>{let active=true;void vpsRequest<{items:{id:string;label:string}[]}>('/interfaces').then(r=>{if(active)setInterfaces(r.items);}).catch(()=>{});return()=>{active=false;};},[]);
|
||||
async function connect(){if(!server)return;setBusy(true);setError('');try{
|
||||
await serverRequest(`/${server.id}/services`,'POST',{kind,document:document.trim(),expected_revision:server.revision,network_interface:network||null});
|
||||
setDocument('');onSaved();
|
||||
}catch(e){setError(e instanceof Error?e.message:'Не удалось подключить службу.');}finally{setBusy(false);}}
|
||||
return <><Window open title="Добавить службу" subtitle={server?`${server.name} · ${server.address}`:'Выберите зарегистрированный VPS'} size="lg" closeOnEscape={!busy} closeOnBackdrop={false} onClose={()=>{if(!busy)onClose();}}
|
||||
footer={<WindowFooterActions><Button disabled={busy} onClick={onClose}>Отмена</Button><Button loading={busy} disabled={busy||!server||!document.trim()} onClick={()=>void connect()}>Подключить службу</Button></WindowFooterActions>}>
|
||||
<div className="system-catalog-form">
|
||||
{!initialServer&&<Select label="VPS" value={serverId} disabled={busy} options={[{value:'',label:'Выберите VPS'},...(catalog.items??[]).map(s=>({value:s.id,label:`${s.name} · ${s.address}`}))]} onChange={id=>{setServerId(id);setDocument('');setFilename('');}}/>}
|
||||
{!initialServer&&catalog.items?.length===0&&<Description>Сначала добавьте VPS в разделе «Система → VPS».</Description>}
|
||||
{catalog.error&&!initialServer&&<Description>{catalog.error}</Description>}
|
||||
<Select label="Служба" value={kind} disabled={busy||!!fixedKind} options={[{value:'wireguard',label:'WireGuard'},{value:'arnavi',label:'ARNavi'},{value:'librespeed',label:'LibreSpeed'},{value:'egress',label:'Маршрутизация трафика'}]} onChange={value=>{setKind(value as typeof kind);setDocument('');setFilename('');setError('');}}/>
|
||||
<InstallerCard key={kind} connectionInstruction={kind==='librespeed'?undefined:"Вернитесь в это окно и подключите установленную службу с выданным приглашением."} kind={kind==='egress'?'vps-egress':kind==='librespeed'?'vps-librespeed':kind==='wireguard'?'vps-wireguard':'vps-arnavi'}/>
|
||||
<SettingsCard title="Подключение установленной службы" description="Запустите установщик на выбранном VPS. Затем передайте выданное им приглашение — Mission Core проверит сервер и сохранит подключение.">
|
||||
{kind!=='arnavi'?<>
|
||||
<input ref={file} type="file" accept=".json,application/json" hidden onChange={event=>{const chosen=event.target.files?.[0];event.target.value='';if(!chosen)return;setDocument('');setFilename('');void (async()=>{if(chosen.size>16384)throw Error(`Выберите файл приглашения ${serviceName} (до 16 КБ).`);setDocument(await chosen.text());setFilename(chosen.name);})().catch(e=>setError(e.message));}}/>
|
||||
<Button icon={<Icon name="upload"/>} disabled={busy} onClick={()=>file.current?.click()}>Выбрать приглашение {serviceName}</Button>
|
||||
{filename&&<Description>{filename}</Description>}
|
||||
<Description>Файл на VPS: {kind==='egress'?'/var/lib/ndc-egress-vps/mission-core-egress.json':kind==='librespeed'?'/var/lib/ndc-librespeed-vps/mission-core-librespeed.json':'/var/lib/ndc-wireguard-vps/mission-core-wireguard.json'}. Скопируйте его по защищённому соединению (например, SFTP). Приглашение действует 24 часа; новое выпускается командой connection того же установщика. {kind==='wireguard'?'Экспорт .conf из клиента WireGuard не подходит.':''}</Description>
|
||||
</>:<TextAreaField label="Ключ подключения ARNavi" value={document} disabled={busy} rows={4} onChange={e=>setDocument(e.target.value)} hint="Ключ находится на VPS в /opt/nodedc-mission-vps/connect.key. Действует 24 часа и используется один раз."/>}
|
||||
</SettingsCard>
|
||||
{interfaces.length>0&&<Select label="Подключение к VPS" disabled={busy} value={network} options={[{value:'',label:'Через текущую сеть'},...interfaces.map(i=>({value:i.id,label:`Напрямую · ${i.label}`}))]} onChange={setNetwork}/>}
|
||||
</div>
|
||||
</Window><ToastStack items={error?[{id:'server-connect',title:error,tone:'error',durationMs:null}]:[]} onDismiss={()=>setError('')}/></>;
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
import {useState} from 'react';
|
||||
import {Button, Description, Icon, IconButton, LoadingRegion, SettingsCard, TextField, ToastStack, Window, WindowFooterActions} from '@nodedc/ui-react';
|
||||
import {serverRequest,type Server,type ServerRemovalPlan} from '../../core/system/servers';
|
||||
|
||||
export function ServerSettings({server,onClose,onSaved,onRemoved}:{server?:Server;onClose:()=>void;onSaved:(server:Server)=>void;onRemoved?:()=>void}) {
|
||||
const [name,setName]=useState(server?.name??''),[address,setAddress]=useState(server?.address??'');
|
||||
const [busy,setBusy]=useState(false),[error,setError]=useState('');
|
||||
const [removing,setRemoving]=useState(false),[plan,setPlan]=useState<ServerRemovalPlan|null>(null);
|
||||
async function prepareRemoval(){if(!server)return;setRemoving(true);setPlan(null);setBusy(true);setError('');try{
|
||||
setPlan(await serverRequest<ServerRemovalPlan>(`/${server.id}/removal`,'POST',{expected_revision:server.revision}));
|
||||
}catch(e){setError(e instanceof Error?e.message:'Не удалось проверить подключения VPS.');}finally{setBusy(false);}}
|
||||
async function remove(){if(!server||!plan||plan.blocked.length)return;setBusy(true);setError('');try{
|
||||
await serverRequest(`/${server.id}`,'DELETE',{expected_revision:server.revision,confirmation:plan.confirmation});
|
||||
onRemoved?.();
|
||||
}catch(e){setPlan(null);setError(e instanceof Error?e.message:'Удаление не завершено. Повторите проверку.');}finally{setBusy(false);}}
|
||||
async function save(){setBusy(true);setError('');try{
|
||||
const item=await serverRequest<Server>(server?`/${server.id}`:'',server?'PUT':'POST',{name:name.trim(),address:address.trim(),...(server?{expected_revision:server.revision}:{})});
|
||||
onSaved(item);
|
||||
}catch(e){setError(e instanceof Error?e.message:'Не удалось сохранить VPS.');}finally{setBusy(false);}}
|
||||
return <><Window open title={removing?'Удалить VPS?':server?'Настройки VPS':'Добавить VPS'} subtitle={server?.name}
|
||||
size="md" closeOnEscape={!busy} closeOnBackdrop={false} onClose={()=>{if(!busy)onClose();}}
|
||||
headerActionsPlacement="before-close" headerActions={server&&!removing&&<IconButton label="Удалить VPS" disabled={busy} onClick={()=>void prepareRemoval()}><Icon name="trash"/></IconButton>}
|
||||
footer={<WindowFooterActions>{removing?<><Button disabled={busy} onClick={()=>{setRemoving(false);setPlan(null);setError('');}}>Отменить</Button>{plan?<Button loading={busy} disabled={busy||!!plan.blocked.length} onClick={()=>void remove()}>Удалить</Button>:<Button loading={busy} disabled={busy} onClick={()=>void prepareRemoval()}>Повторить проверку</Button>}</>:<><Button disabled={busy} onClick={onClose}>Отмена</Button><Button loading={busy} disabled={busy||!name.trim()||!address.trim()} onClick={()=>void save()}>{server?'Сохранить':'Добавить VPS'}</Button></>}</WindowFooterActions>}>
|
||||
{removing?<LoadingRegion loading={busy&&!plan} label="Проверка подключений"><SettingsCard title={`Удалить «${server?.name}» из Mission Core?`} description="Это действие нельзя отменить.">
|
||||
<Description>Будут удалены карточка VPS, сохранённые подключения его служб и локальные туннели WireGuard. Для повторного подключения понадобятся новые приглашения.</Description>
|
||||
<Description>Сам VPS, установленные на нём службы и данные останутся на сервере.</Description>
|
||||
{plan&&<><Description>Подключения служб: {plan.services.join(', ')||'нет'}. Связанные подключения аппаратов: {plan.vehicle_connections}; воркеров: {plan.worker_connections}.</Description>{plan.blocked.map(message=><Description key={message}>{message}</Description>)}</>}
|
||||
</SettingsCard></LoadingRegion>:<div className="system-catalog-form">
|
||||
<TextField label="Название" placeholder="Например, Макхост · сеть парка" value={name} maxLength={80} disabled={busy} onChange={e=>setName(e.target.value)}/>
|
||||
<TextField label="Адрес сервера" hint={server?.services.length?'Адрес используется подключёнными службами.':'Публичный IP-адрес или DNS-имя, без протокола и порта.'} value={address} maxLength={253} disabled={busy||!!server?.services.length} onChange={e=>setAddress(e.target.value)}/>
|
||||
</div>}
|
||||
</Window><ToastStack items={error?[{id:'server-save',title:error,tone:'error',durationMs:null}]:[]} onDismiss={()=>setError('')}/></>;
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
import {useRef, useState} from "react";
|
||||
import {Button, Description, Icon, StatusBadge} from "@nodedc/ui-react";
|
||||
import {fleetRequest} from "../../core/fleet/useFleet";
|
||||
|
||||
export function ImportNetworkProfile({onImported, disabled = false}: {onImported: () => Promise<unknown>; disabled?: boolean}) {
|
||||
const input = useRef<HTMLInputElement>(null);
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
return <>
|
||||
<input ref={input} type="file" accept=".json,application/json" hidden onChange={event => {
|
||||
const file = event.currentTarget.files?.[0]; event.currentTarget.value = "";
|
||||
if (!file || busy) return;
|
||||
setBusy(true); setError(null);
|
||||
void (async () => {
|
||||
if (file.size > 16384) throw Error("Выберите файл подключения, выданный установщиком VPS.");
|
||||
await fleetRequest("/network-profiles/import", "POST", {document: await file.text()}, 240000);
|
||||
await onImported();
|
||||
})().catch(e => setError(e instanceof Error ? e.message : "Не удалось добавить профиль."))
|
||||
.finally(() => setBusy(false));
|
||||
}}/>
|
||||
<Button icon={<Icon name="upload"/>} disabled={disabled || busy} loading={busy} onClick={() => input.current?.click()}>
|
||||
Импортировать подключение к серверу
|
||||
</Button>
|
||||
<Description>Файл mission-core-wireguard.json выдаёт установщик NODE.DC на вашем VPS. Получите его у администратора этого сервера и выберите здесь. Приглашение действует 24 часа; затем администратор выпускает новое. Экспорт туннеля из приложения WireGuard (.conf) не подходит.</Description>
|
||||
{error && <Description role="alert"><StatusBadge tone="warning">{error}</StatusBadge></Description>}
|
||||
</>;
|
||||
}
|
||||
@@ -1,59 +1,13 @@
|
||||
import {
|
||||
AdminNavigationPanel,
|
||||
Icon,
|
||||
IconButton,
|
||||
} from "@nodedc/ui-react";
|
||||
import {AdminNavigationPanel, Icon} from "@nodedc/ui-react";
|
||||
import {workspacesForRoot} from "../../productModel";
|
||||
|
||||
import { useComputeContours } from "../../core/system/ComputeContourContext";
|
||||
|
||||
interface SystemNavigationPanelProps {
|
||||
title: string;
|
||||
onAdd: () => void;
|
||||
onNavigateRoot: () => void;
|
||||
onClose: () => void;
|
||||
}
|
||||
|
||||
export function SystemNavigationPanel({
|
||||
title,
|
||||
onAdd,
|
||||
onNavigateRoot,
|
||||
onClose,
|
||||
}: SystemNavigationPanelProps) {
|
||||
const { contours, selectedContour, selectContour } = useComputeContours();
|
||||
const contourCountLabel = contours.length === 1
|
||||
? "1 конфигурация"
|
||||
: `${contours.length} конфигураций`;
|
||||
|
||||
return (
|
||||
<AdminNavigationPanel
|
||||
eyebrow="MISSION CORE"
|
||||
title={title}
|
||||
closeLabel={`Закрыть раздел «${title}»`}
|
||||
navigationLabel="Вычислительные контуры"
|
||||
onClose={onClose}
|
||||
headerActions={(
|
||||
<IconButton label="Добавить вычислительный контур" onClick={onAdd}>
|
||||
<Icon name="plus" size={16} strokeWidth={1.6} />
|
||||
</IconButton>
|
||||
)}
|
||||
contexts={contours.map((contour) => ({
|
||||
id: contour.contour_id,
|
||||
label: contour.display_name,
|
||||
description: contour.expected_node_id,
|
||||
icon: <Icon name="apps" />,
|
||||
active: selectedContour?.contour_id === contour.contour_id,
|
||||
onSelect: () => { selectContour(contour.contour_id); onNavigateRoot(); },
|
||||
}))}
|
||||
items={[]}
|
||||
onItemChange={() => undefined}
|
||||
footer={(
|
||||
<>
|
||||
<span className="nodedc-admin-panel__nav-icon" aria-hidden="true">
|
||||
<Icon name="activity" />
|
||||
</span>
|
||||
<span>{contourCountLabel}</span>
|
||||
</>
|
||||
)}
|
||||
/>
|
||||
);
|
||||
export function SystemNavigationPanel({title, activeId, onNavigate, onClose}: {
|
||||
title: string; activeId: string; onNavigate: (id: string) => void; onClose: () => void;
|
||||
}) {
|
||||
const categories = workspacesForRoot("system").filter(item => item.kind === "workers" || item.kind === "vps");
|
||||
return <AdminNavigationPanel eyebrow="MISSION CORE" title={title}
|
||||
closeLabel={`Закрыть раздел «${title}»`} navigationLabel="Система" onClose={onClose}
|
||||
contexts={categories.map(item => ({id: item.id, label: item.label, icon: <Icon name={item.icon}/>,
|
||||
active: item.id === (activeId === "vps" ? "vps" : "workers"),
|
||||
onSelect: () => onNavigate(item.id)}))} items={[]} onItemChange={() => undefined}/>;
|
||||
}
|
||||
|
||||
@@ -2,7 +2,7 @@ import { SegmentedControl } from "@nodedc/ui-react";
|
||||
|
||||
import { workspacesForRoot } from "../../productModel";
|
||||
|
||||
const systemWorkspaces = workspacesForRoot("system");
|
||||
const systemWorkspaces = workspacesForRoot("system").filter(item => item.kind === "compute-modules" || item.kind === "network-monitor");
|
||||
const compactLabels: Record<string, string> = {
|
||||
modules: "Модули",
|
||||
integrations: "Интеграции",
|
||||
|
||||
@@ -0,0 +1,26 @@
|
||||
import {useState} from "react";
|
||||
import {Button, Description, Icon} from "@nodedc/ui-react";
|
||||
import {connectionRequest, type TailscaleClient} from "../../core/system/workerConnections";
|
||||
|
||||
export function TailscaleClientStatus({client, disabled, onOpened}: {
|
||||
client: TailscaleClient; disabled: boolean; onOpened: () => Promise<unknown>;
|
||||
}) {
|
||||
const [opening, setOpening] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
if (client.state === "connected") return null;
|
||||
return <>
|
||||
<Description>{client.message}</Description>
|
||||
{client.state === "not_installed" ? <Button icon={<Icon name="download"/>}
|
||||
onClick={() => window.open("https://tailscale.com/download", "_blank", "noopener,noreferrer")}>
|
||||
Скачать Tailscale
|
||||
</Button> : client.can_open ? <Button disabled={disabled || opening} loading={opening}
|
||||
onClick={() => {
|
||||
setOpening(true); setError(null);
|
||||
void connectionRequest("/tailscale/open", {}).then(onOpened)
|
||||
.catch(reason => setError(reason instanceof Error ? reason.message : "Не удалось открыть Tailscale."))
|
||||
.finally(() => setOpening(false));
|
||||
}}>{client.state === "needs_login" ? "Авторизироваться" : "Открыть Tailscale"}</Button>
|
||||
: <Description>Откройте установленный клиент Tailscale на этом компьютере и проверьте подключение.</Description>}
|
||||
{error && <Description role="alert">{error}</Description>}
|
||||
</>;
|
||||
}
|
||||
@@ -0,0 +1,146 @@
|
||||
import {useEffect, useState} from "react";
|
||||
import {Button, Description, FeatureSettingsWindow, FieldFrame, Icon, IconButton,
|
||||
Select, SettingsCard, StatusBadge, TextField, WindowFooterActions} from "@nodedc/ui-react";
|
||||
import {connectionRequest, keepAvailableSelection, workerCandidate, type ConnectionCheck} from "../../core/system/workerConnections";
|
||||
import {useConnectionCatalog} from "../../core/system/useConnectionCatalog";
|
||||
import type {ComputeContour, ComputeContourDraft} from "../../core/system/computeContours";
|
||||
import {ImportNetworkProfile} from "./SharedNetworkProfiles";
|
||||
import {TailscaleClientStatus} from "./TailscaleClientStatus";
|
||||
|
||||
interface Props {open: boolean; mode: "create" | "edit"; contour: ComputeContour | null;
|
||||
onClose: () => void; onChanged: () => void;
|
||||
onUpdate: (contour: ComputeContour, draft: ComputeContourDraft) => Promise<ComputeContour>}
|
||||
|
||||
export function WorkerConnectionSettings({open, mode, contour, onClose, onChanged, onUpdate}: Props) {
|
||||
const [section, setSection] = useState("connections");
|
||||
const [name, setName] = useState("");
|
||||
const [poll, setPoll] = useState("3");
|
||||
const [provider, setProvider] = useState("tailscale");
|
||||
const [profileId, setProfileId] = useState("");
|
||||
const [peerId, setPeerId] = useState("");
|
||||
const [selectedPath, setSelectedPath] = useState("");
|
||||
const [adding, setAdding] = useState(false);
|
||||
const [acting, setBusy] = useState(false);
|
||||
const {catalog, refresh, discoveryError, initializing} = useConnectionCatalog(open, acting);
|
||||
const busy = acting || initializing;
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [check, setCheck] = useState<ConnectionCheck | null>(null);
|
||||
const worker = mode === "edit" ? catalog?.workers.find(x => x.contour_id === contour?.contour_id) : null;
|
||||
const enroll = !worker;
|
||||
const profiles = catalog?.profiles.filter(x => x.provider === provider
|
||||
&& catalog.available_profile_ids.includes(x.id)
|
||||
&& !worker?.connections.some(c => c.profile_id === x.id)) ?? [];
|
||||
const profile = profiles.find(x => x.id === profileId);
|
||||
const peers = catalog?.peers.filter(x => x.profile_id === profileId) ?? [];
|
||||
const candidate = workerCandidate(catalog, profileId, peerId);
|
||||
|
||||
useEffect(() => {
|
||||
if (!open) return;
|
||||
setError(null); setCheck(null); setAdding(false); setSelectedPath("");
|
||||
setSection("connections"); setName(contour?.display_name ?? "");
|
||||
setPoll(String(contour?.telemetry_poll_interval_seconds ?? 3));
|
||||
}, [open, contour?.contour_id, mode]);
|
||||
useEffect(() => {setSelectedPath(worker?.active_connection_id ?? "");}, [worker?.active_connection_id]);
|
||||
useEffect(() => {setProfileId(current => keepAvailableSelection(current, profiles.map(x => x.id), profiles[0]?.id));}, [provider, catalog, worker?.revision]);
|
||||
useEffect(() => {setPeerId(current => keepAvailableSelection(current, peers.map(x => x.id)));}, [profileId, catalog]);
|
||||
const availableNetworks = catalog?.available_profile_ids.join(",");
|
||||
useEffect(() => {setCheck(null);}, [availableNetworks, catalog?.tailscale_client?.state]);
|
||||
async function action(fn: () => Promise<void>) {
|
||||
setBusy(true); setError(null);
|
||||
try {await fn();} catch (e) {setError(e instanceof Error ? e.message : "Операция не выполнена.");}
|
||||
finally {setBusy(false);}
|
||||
}
|
||||
async function add() {
|
||||
if (!catalog || !profile || !peerId) return;
|
||||
await connectionRequest(enroll ? "/enroll" : `/${worker!.contour_id}/attach`, {
|
||||
profile_id: profile.id, peer_id: peerId, revision: enroll ? catalog.revision : worker!.revision,
|
||||
...(enroll ? {binding_id: candidate.binding?.id} : {}),
|
||||
});
|
||||
await refresh(); onChanged(); setAdding(false); setCheck(null);
|
||||
if (mode === "create") onClose();
|
||||
}
|
||||
|
||||
return <FeatureSettingsWindow open={open} title={mode === "create" ? "Подключить воркер" : "Настройки воркера"}
|
||||
subtitle="Сетевые подключения" identity={{title: contour?.display_name ?? "Новый воркер",
|
||||
subtitle: contour?.expected_node_id ?? "Подключение к Mission Core", avatarLabel: "WC"}}
|
||||
sections={[{id: "connections", label: "Подключения", icon: "network", group: "ВОРКЕР"},
|
||||
...(mode === "edit" ? [{id: "agent", label: "Агент", icon: "activity" as const, group: "ВОРКЕР"}] : [])]}
|
||||
activeSection={section} onSectionChange={setSection} onClose={busy ? () => {} : onClose}
|
||||
headerActions={<IconButton label="Обновить подключения" disabled={busy} onClick={() => void action(async () => {await refresh(); setCheck(null);})}><Icon name="refresh"/></IconButton>}
|
||||
footer={<WindowFooterActions><Button onClick={onClose} disabled={busy}>Готово</Button></WindowFooterActions>}>
|
||||
<div className="compute-contour-settings">
|
||||
{section === "agent" && contour && <SettingsCard title="Устройство и телеметрия"
|
||||
description={`Идентичность: ${contour.expected_node_id}. Платформа: ${contour.platform}.`}>
|
||||
<div className="compute-contour-settings__form">
|
||||
<TextField label="Название" value={name} onChange={event => setName(event.currentTarget.value)}/>
|
||||
<TextField label="Обновление интерфейса, с" type="number" min={1} max={60} value={poll} onChange={event => setPoll(event.currentTarget.value)}/>
|
||||
</div>
|
||||
<Button disabled={busy || !name.trim() || !Number.isInteger(Number(poll)) || Number(poll) < 1 || Number(poll) > 60}
|
||||
onClick={() => void action(async () => {await onUpdate(contour, {
|
||||
display_name: name, expected_node_id: contour.expected_node_id, platform: contour.platform,
|
||||
telemetry_mode: contour.telemetry_mode, address: contour.address, ssh_port: contour.ssh_port,
|
||||
mqtt_host: contour.mqtt_host, mqtt_port: contour.mqtt_port, mqtt_bind_address: contour.mqtt_bind_address,
|
||||
mqtt_publish_interval_seconds: contour.mqtt_publish_interval_seconds,
|
||||
telemetry_poll_interval_seconds: Number(poll),
|
||||
});})}>Сохранить</Button>
|
||||
</SettingsCard>}
|
||||
{section === "connections" && worker && <SettingsCard eyebrow="ПОДКЛЮЧЕНИЯ" title="Активное подключение"
|
||||
description="Выбор сети относится только к этому воркеру. Другие устройства сохраняют свои подключения.">
|
||||
<div className="compute-contour-settings__form compute-contour-settings__connection-row">
|
||||
<FieldFrame label="Подключение"><Select label="Подключение" value={selectedPath} disabled={busy}
|
||||
options={worker.connections.map(x => ({value: x.id, label: catalog?.profiles.find(p => p.id === x.profile_id)?.name ?? x.profile_id,
|
||||
description: x.id === worker.active_connection_id ? "Активное" : "Подготовлено"}))}
|
||||
onChange={value => {setSelectedPath(value); setCheck(null);}}/></FieldFrame>
|
||||
<div className="system-workspace__actions">
|
||||
<Button disabled={busy || !selectedPath} onClick={() => void action(async () => {
|
||||
setCheck(await connectionRequest<ConnectionCheck>(`/${worker.contour_id}/check`, {connection_id: selectedPath, revision: worker.revision}));
|
||||
})}>Проверить</Button>
|
||||
<Button disabled={busy || !selectedPath || selectedPath === worker.active_connection_id} onClick={() => void action(async () => {
|
||||
await connectionRequest(`/${worker.contour_id}/activate`, {connection_id: selectedPath, revision: worker.revision});
|
||||
await refresh(); onChanged(); setCheck(null);
|
||||
})}>Использовать</Button>
|
||||
<IconButton label="Добавить подключение" disabled={busy} onClick={() => setAdding(!adding)}><Icon name="plus"/></IconButton>
|
||||
</div>
|
||||
</div>
|
||||
{catalog?.tailscale_client && worker.connections.some(path => path.id === selectedPath
|
||||
&& catalog.profiles.some(p => p.id === path.profile_id && p.provider === "tailscale"))
|
||||
&& <TailscaleClientStatus client={catalog.tailscale_client} disabled={busy} onOpened={refresh}/>}
|
||||
{catalog?.tailscale_client?.state === "connected" && worker.connections.some(path => path.id === selectedPath
|
||||
&& !catalog.available_profile_ids.includes(path.profile_id))
|
||||
&& <Description>Выбранная сеть сейчас недоступна. Подключите её в VPN-клиенте.</Description>}
|
||||
{check && <><StatusBadge tone="success">Устройство подтверждено · {check.identity.hostname}</StatusBadge>
|
||||
{check.active && check.channels.map(x => <Description key={x.id}><StatusBadge tone={x.connected ? "success" : "warning"}>{x.label} · {x.connected ? "соединение установлено" : "ожидает подключения"}</StatusBadge></Description>)}
|
||||
{check.active && <Description>Проверка подтверждает соединения. Свежие показатели и состояние сервисов отображаются в «Модулях».</Description>}
|
||||
{check.active && check.channels.length === 0 && <Description>Рабочие каналы ещё не установлены.</Description>}</>}
|
||||
</SettingsCard>}
|
||||
{section === "connections" && catalog && (enroll || adding) && <SettingsCard eyebrow="НОВОЕ ПОДКЛЮЧЕНИЕ" title={enroll ? "Выберите устройство" : "Добавить резервную сеть"}
|
||||
description="Выберите VPN, общую сеть и компьютер. Устройства в сети могут быть воркерами, бортами или другими компьютерами.">
|
||||
<div className="compute-contour-settings__form">
|
||||
<FieldFrame label="Тип VPN"><Select label="Тип VPN" value={provider} disabled={busy}
|
||||
options={[{value: "tailscale", label: "Tailscale"}, {value: "wireguard", label: "WireGuard"}]} onChange={setProvider}/></FieldFrame>
|
||||
<FieldFrame label="Сеть"><Select label="Сеть" value={profileId} disabled={busy || !profiles.length}
|
||||
options={profiles.map(x => ({value: x.id, label: x.name}))} onChange={setProfileId}/></FieldFrame>
|
||||
<FieldFrame label="Устройство в сети"><Select label="Устройство в сети" value={peerId} disabled={busy || !peers.length}
|
||||
options={[{value: "", label: "Выберите устройство"}, ...peers.map(x => ({value: x.id, label: x.name,
|
||||
description: workerCandidate(catalog, profileId, x.id).enrolled ? "Уже подключён к Mission Core" : x.online === false ? "Не в сети" : "Доступен в VPN"}))]} onChange={setPeerId}/></FieldFrame>
|
||||
</div>
|
||||
{provider === "tailscale" && catalog.tailscale_client
|
||||
&& <TailscaleClientStatus client={catalog.tailscale_client} disabled={busy} onOpened={refresh}/>}
|
||||
{enroll && candidate.enrolled && <Description>Этот воркер уже подключён. Его сети можно изменить через настройки в разделе «Система».</Description>}
|
||||
{enroll && candidate.peer && !candidate.enrolled && !candidate.binding && <Description>Устройство найдено в VPN, но доступ Mission Core к нему ещё не настроен. Сначала требуется подготовка агента и доступа на самом компьютере. Одного подключения к VPN недостаточно.</Description>}
|
||||
{enroll && candidate.binding && <Description>Доступ к {candidate.binding.name} подготовлен. При добавлении проверим устройство и его ключ.</Description>}
|
||||
{provider === "tailscale" && <Description>Сеть берётся из приложения Tailscale на этом Mac. Чтобы увидеть новый компьютер, подключите его к той же сети Tailscale.</Description>}
|
||||
{provider === "wireguard" && <Description>Здесь перечислены серверы WireGuard, добавленные в Mission Core. Адрес в названии относится к серверу VPN, а не к воркеру.</Description>}
|
||||
{provider === "wireguard" && !peers.length && <Description>Сервер не сообщает о зарегистрированных воркерах. Здесь показан его реестр устройств; поиск остальных компьютеров в туннеле не выполняется.</Description>}
|
||||
{provider === "wireguard" && <ImportNetworkProfile disabled={busy} onImported={refresh}/>}
|
||||
{!profiles.length && <Description>Доступных новых профилей этого типа нет.</Description>}
|
||||
<Button variant="primary" disabled={busy || !profile || !peerId || candidate.peer?.online === false || (enroll && (!candidate.binding || Boolean(candidate.enrolled)))} onClick={() => void action(add)}>
|
||||
{busy ? "Проверяем…" : "Проверить и добавить"}</Button>
|
||||
</SettingsCard>}
|
||||
{busy && <Description>Проверяем подключение…</Description>}
|
||||
{error && <Description role="alert"><StatusBadge tone="warning">{error}</StatusBadge></Description>}
|
||||
{discoveryError && <Description role="alert">{discoveryError}</Description>}
|
||||
{catalog?.notice && catalog.notice !== catalog.tailscale_client?.message && <Description>{catalog.notice}</Description>}
|
||||
</div>
|
||||
</FeatureSettingsWindow>;
|
||||
}
|
||||
@@ -2,7 +2,8 @@ import { useCallback, useMemo, useState, type ReactNode } from "react";
|
||||
import type { ApplicationPanelUtilityAction } from "@nodedc/ui-react";
|
||||
|
||||
import { useComputeContours } from "../../core/system/ComputeContourContext";
|
||||
import { ComputeContourSettingsWindow } from "./ComputeContourSettingsWindow";
|
||||
import { WorkerConnectionSettings } from "./WorkerConnectionSettings";
|
||||
import { useWorkerPower } from "./useWorkerPower";
|
||||
|
||||
interface ComputeContourSettingsController {
|
||||
canEdit: boolean;
|
||||
@@ -14,6 +15,7 @@ interface ComputeContourSettingsController {
|
||||
|
||||
export function useComputeContourSettings(): ComputeContourSettingsController {
|
||||
const contours = useComputeContours();
|
||||
const power = useWorkerPower(contours.selectedContour);
|
||||
const [open, setOpen] = useState(false);
|
||||
const [mode, setMode] = useState<"create" | "edit">("edit");
|
||||
const openCreate = useCallback(() => {
|
||||
@@ -47,16 +49,16 @@ export function useComputeContourSettings(): ComputeContourSettingsController {
|
||||
canEdit: contours.selectedContour !== null,
|
||||
openCreate,
|
||||
openEdit,
|
||||
utilityActions,
|
||||
utilityActions: [...utilityActions, power.action],
|
||||
window: (
|
||||
<ComputeContourSettingsWindow
|
||||
<><WorkerConnectionSettings
|
||||
open={open}
|
||||
mode={mode}
|
||||
contour={contours.selectedContour}
|
||||
contour={mode === "create" ? null : contours.selectedContour}
|
||||
onClose={() => setOpen(false)}
|
||||
onCreate={contours.createContour}
|
||||
onChanged={() => {contours.refresh(); contours.refreshTelemetry();}}
|
||||
onUpdate={contours.updateContour}
|
||||
/>
|
||||
/>{power.window}</>
|
||||
),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -0,0 +1,42 @@
|
||||
import {useState} from "react";
|
||||
import { Description,Button, ConfirmationModal, Window, WindowFooterActions, type ApplicationPanelUtilityAction} from "@nodedc/ui-react";
|
||||
import {connectionRequest} from "../../core/system/workerConnections";
|
||||
import type {ComputeContour} from "../../core/system/computeContours";
|
||||
|
||||
export function useWorkerPower(contour: ComputeContour | null) {
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [pending, setPending] = useState<{id: string; name: string; confirmation: string} | null>(null);
|
||||
const [message, setMessage] = useState<string | null>(null);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const action: ApplicationPanelUtilityAction = {
|
||||
label: "Выключить воркер", icon: "power", disabled: !contour || busy,
|
||||
onClick: () => {if (!contour) return; setBusy(true); setError(null);
|
||||
const selected = contour;
|
||||
void connectionRequest<{confirmation: string}>(`/${selected.contour_id}/power/prepare`, {})
|
||||
.then(value => setPending({id: selected.contour_id, name: selected.display_name, confirmation: value.confirmation}))
|
||||
.catch(e => setMessage(e instanceof Error ? e.message : "Воркер недоступен."))
|
||||
.finally(() => setBusy(false));
|
||||
},
|
||||
};
|
||||
const window = <>
|
||||
<ConfirmationModal open={pending !== null} title="Выключить воркер?" danger
|
||||
confirmLabel="Да, выключить" pendingLabel="Передаём команду…" onClose={() => {if (!busy) setPending(null);}}
|
||||
description={<><Description>Воркер «{pending?.name}» завершит работу. Выполняемые на нём задачи будут прерваны. Для включения потребуется доступ к компьютеру.</Description>
|
||||
{error && <Description role="alert">{error}</Description>}</>}
|
||||
onConfirm={async () => {
|
||||
if (!pending || busy) return;
|
||||
setBusy(true); setError(null);
|
||||
try {
|
||||
const result = await connectionRequest<{message: string}>(`/${pending.id}/power/shutdown`, {confirmation: pending.confirmation});
|
||||
setPending(null); setMessage(result.message);
|
||||
} catch (e) {
|
||||
setPending(null); setMessage(e instanceof Error ? e.message : "Ответ не получен. Автоматического повтора нет.");
|
||||
} finally {setBusy(false);}
|
||||
}}/>
|
||||
<Window open={message !== null} title="Питание воркера" size="sm" onClose={() => setMessage(null)}
|
||||
footer={<WindowFooterActions><Button onClick={() => setMessage(null)}>Понятно</Button></WindowFooterActions>}>
|
||||
<Description role="status">{message}</Description>
|
||||
</Window>
|
||||
</>;
|
||||
return {action, window};
|
||||
}
|
||||
@@ -69,7 +69,7 @@ export function useApplicationPanelActions({
|
||||
onClick: () => void saveWorkspaceLayout(),
|
||||
});
|
||||
}
|
||||
if (definition?.root === "system") actions.push(...systemUtilityActions);
|
||||
if (definition && ["compute-modules", "network-monitor"].includes(definition.kind)) actions.push(...systemUtilityActions);
|
||||
if (definition?.kind === "recordings" && sessionOverview) actions.push({
|
||||
label: sessionOverview.open ? "Закрыть информацию о записи" : "Информация о записи",
|
||||
icon: "info", pressed: sessionOverview.open, disabled: !sessionOverview.available,
|
||||
|
||||
@@ -20,5 +20,5 @@ export const installedDevicePlugins: readonly DeviceUiPlugin[] = Object.freeze([
|
||||
// Node-executed camera controls use the existing sensor contribution contract;
|
||||
// they do not register a desktop capture/AI runtime or a new product workspace.
|
||||
|
||||
const CoreBmsDetail=(props:SensorDetailProps)=>createElement(BatteryWorkspace,{key:props.device.id,deviceId:props.device.id,title:`Аккумулятор / ${props.device.name}`,headerActionsTarget:props.headerActionsTarget,back:props.back,children:controls=>createElement(BmsDetail,{...props,presentation:'page',editing:controls.editing,panelAppearance:controls.appearance.panels,renderViewport:controls.renderViewport,renderScene:(state:BatteryState)=>createElement(BatteryScene,{editing:controls.editing,markingAppearance:controls.appearance.markings,deviceId:props.device.id,seedKey:props.sceneSeedKey,soc:state.sample?.soc_percent??null,fresh:state.fresh,cellVoltages:state.sample?.cell_voltages_v})})});
|
||||
const CoreBmsDetail=(props:SensorDetailProps)=>createElement(BatteryWorkspace,{key:props.device.id,deviceId:props.device.id,title:`Аккумулятор / ${props.device.name}`,headerActionsTarget:props.headerActionsTarget,back:props.back,sensor:props,fullscreenControl:props.fullscreenControl,children:controls=>createElement(BmsDetail,{...props,presentation:'page',editing:controls.editing,panelAppearance:controls.appearance.panels,renderViewport:controls.renderViewport,renderScene:(state:BatteryState)=>createElement(BatteryScene,{editing:controls.editing,markingAppearance:controls.appearance.markings,deviceId:props.device.id,seedKey:props.sceneSeedKey,soc:state.sample?.soc_percent??null,fresh:state.fresh,cellVoltages:state.sample?.cell_voltages_v})})});
|
||||
export const installedNodeSensorContributions = Object.freeze([insta360X4SensorUi,vescSensorUi,usbCanSensorUi,{...jkBmsSensorUi,detailPresentation:'workspace' as const,Detail:CoreBmsDetail}]);
|
||||
|
||||
@@ -1,14 +1,21 @@
|
||||
import {defaultGlassMaterial,type GlassMaterialSettings} from '@nodedc/ui-core';
|
||||
export type CellMarkingAppearance={color:string;size:number};
|
||||
export type BatteryPanelAppearance={height:number;radius:number;labelSize:number;valueSize:number;textColor:string;glass:GlassMaterialSettings};
|
||||
export type BatteryAppearance={schema:'missioncore.battery-ui/v1';markings:CellMarkingAppearance;panels:BatteryPanelAppearance};
|
||||
export type BatteryIndicatorAppearance={offset:number;width:number;height:number;radius:number;mode:'ranges'|'mono';color:string;lowColor:string;middleColor:string;highColor:string;lowUntil:number;middleUntil:number};
|
||||
export type BatteryAppearance={schema:'missioncore.battery-ui/v1';markings:CellMarkingAppearance;panels:BatteryPanelAppearance;indicator:BatteryIndicatorAppearance};
|
||||
export const batteryAppearanceKey=(id:string)=>`missioncore.battery-ui/v1:${id}`;
|
||||
export function defaultBatteryAppearance():BatteryAppearance{return {schema:'missioncore.battery-ui/v1',markings:{color:'#ffffff',size:100},panels:{height:76,radius:24,labelSize:12,valueSize:18,textColor:'#f1f1ef',glass:{...defaultGlassMaterial,tintOpacity:52,blur:18}}};}
|
||||
export function defaultBatteryAppearance():BatteryAppearance{return {schema:'missioncore.battery-ui/v1',markings:{color:'#ffffff',size:100},indicator:{offset:0,width:115,height:46,radius:23,mode:'ranges',color:'#f1f1ef',lowColor:'#ff7474',middleColor:'#ffd166',highColor:'#b5ff5a',lowUntil:15,middleUntil:30},panels:{height:76,radius:24,labelSize:12,valueSize:13,textColor:'#f1f1ef',glass:{...defaultGlassMaterial,tintOpacity:52,blur:18}}};}
|
||||
const object=(v:unknown):Record<string,unknown>=>v!==null&&typeof v==='object'?v as Record<string,unknown>:{};
|
||||
const number=(v:unknown,fallback:number,min:number,max:number)=>typeof v==='number'&&Number.isFinite(v)?Math.min(max,Math.max(min,v)):fallback;
|
||||
const color=(v:unknown,fallback:string)=>typeof v==='string'&&/^#[0-9a-f]{6}$/i.test(v)?v.toLowerCase():fallback;
|
||||
export function parseBatteryAppearance(raw:unknown):BatteryAppearance{
|
||||
const source=object(raw);if(source.schema!=='missioncore.battery-ui/v1')throw new Error('Это не профиль интерфейса батареи.');
|
||||
const d=defaultBatteryAppearance(),m=object(source.markings),p=object(source.panels),g=object(p.glass);
|
||||
return {schema:d.schema,markings:{color:color(m.color,d.markings.color),size:number(m.size,100,50,160)},panels:{height:number(p.height,76,56,160),radius:number(p.radius,24,0,48),labelSize:number(p.labelSize,12,10,20),valueSize:number(p.valueSize,18,12,30),textColor:color(p.textColor,d.panels.textColor),glass:{...d.panels.glass,tintHex:color(g.tintHex,d.panels.glass.tintHex),tintOpacity:number(g.tintOpacity,52,0,100),blur:number(g.blur,18,0,60)}}};
|
||||
const d=defaultBatteryAppearance(),m=object(source.markings),p=object(source.panels),g=object(p.glass),i=object(source.indicator);
|
||||
const lowUntil=number(i.lowUntil,15,0,99),middleUntil=number(i.middleUntil,30,lowUntil+1,100);
|
||||
return {schema:d.schema,indicator:{offset:number(i.offset,0,0,320),width:number(i.width,115,32,320),height:number(i.height,46,12,96),radius:number(i.radius,23,0,48),mode:i.mode==='mono'?'mono':'ranges',color:color(i.color,d.indicator.color),lowColor:color(i.lowColor,d.indicator.lowColor),middleColor:color(i.middleColor,d.indicator.middleColor),highColor:color(i.highColor,d.indicator.highColor),lowUntil,middleUntil},markings:{color:color(m.color,d.markings.color),size:number(m.size,100,50,160)},panels:{height:number(p.height,76,56,160),radius:number(p.radius,24,0,48),labelSize:number(p.labelSize,12,10,20),valueSize:number(p.valueSize,13,12,30),textColor:color(p.textColor,d.panels.textColor),glass:{...d.panels.glass,tintHex:color(g.tintHex,d.panels.glass.tintHex),tintOpacity:number(g.tintOpacity,52,0,100),blur:number(g.blur,18,0,60)}}};
|
||||
}
|
||||
|
||||
export function batteryIndicatorColor(value:BatteryIndicatorAppearance,soc:number|null):string|undefined{
|
||||
if(soc===null||!Number.isFinite(soc))return undefined;
|
||||
return value.mode==='mono'?value.color:soc<value.lowUntil?value.lowColor:soc<value.middleUntil?value.middleColor:value.highColor;
|
||||
}
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user