Files
road-compiler/workbench/client/src/hooks/useDirectEditSession.ts
T

77 lines
2.6 KiB
TypeScript

import { useEffect, useRef, useState } from 'react';
import { api } from '../lib/api';
import { EditSession } from '../edit/session';
import type { EditDiagnostic, HandleManifest, PreviewLayerName } from '../edit/types';
import type { GeoJson, JunctionRef, WorkbenchState } from '../types/state';
import { junctionEditSelection } from '../junction/structure';
/**
* Owns the stable v2 session and the server state that surrounds it. Gesture
* construction and map interaction stay with the composition root for now.
*/
export function useDirectEditSession({
editMode,
state,
selectedSegmentId,
selectedJunction,
setStatus,
}: {
editMode: boolean;
state?: WorkbenchState;
selectedSegmentId?: string;
selectedJunction?: JunctionRef | null;
setStatus: (status: string) => void;
}) {
const [manifest, setManifest] = useState<HandleManifest | null>(null);
const [preview, setPreview] = useState<Partial<Record<PreviewLayerName, GeoJson | null>> | null>(null);
const [diagnostics, setDiagnostics] = useState<EditDiagnostic[]>([]);
const [revision, setRevision] = useState(0);
const sessionRef = useRef<EditSession | null>(null);
const loadedDocument = useRef<string | null>(null);
if (editMode && !sessionRef.current) sessionRef.current = new EditSession();
const touch = () => setRevision((value) => value + 1);
useEffect(() => {
// Complex junction capability is published by the server as scoped handles,
// so its workspace needs that manifest to expose the edit entry point.
if (!editMode && selectedJunction?.type !== 'cluster') return;
let current = true;
setManifest(null);
api
.editState(
selectedJunction
? junctionEditSelection(selectedJunction)
: selectedSegmentId
? { segment: selectedSegmentId }
: undefined,
)
.then((value) => {
if (!current || !('handles' in value)) return;
setManifest(value.handles);
const key = `${value.areaId}:${value.documentVersion}`;
if (loadedDocument.current === key) return;
loadedDocument.current = key;
sessionRef.current?.load(value.document.constraints, value.document.operations, value.documentVersion);
touch();
})
.catch((error: Error) => {
if (current) setStatus(`直接编辑手柄不可用:${error.message}`);
});
return () => {
current = false;
};
}, [editMode, selectedJunction, selectedSegmentId, setStatus, state]);
return {
session: sessionRef.current,
manifest,
setManifest,
preview,
setPreview,
diagnostics,
setDiagnostics,
revision,
touch,
};
}