519 lines
20 KiB
TypeScript
519 lines
20 KiB
TypeScript
"use client";
|
|
|
|
import {
|
|
useCallback,
|
|
useEffect,
|
|
useRef,
|
|
useState,
|
|
type MutableRefObject,
|
|
} from "react";
|
|
import GeoJSON from "ol/format/GeoJSON.js";
|
|
import VectorLayer from "ol/layer/Vector.js";
|
|
import VectorSource from "ol/source/Vector.js";
|
|
import { unByKey } from "ol/Observable.js";
|
|
import GisApp from "@common/business_components/ui/map/lib/gis.core";
|
|
import { getRawJson } from "@/shared/api/sewerage-api";
|
|
import {
|
|
FLOW_DIRECTION_LAYER_TYPE,
|
|
FLOW_DIRECTION_LAYER_NAME,
|
|
getFlowDirectionMinZoom,
|
|
getFlowDirectionZIndex,
|
|
expandFlowDirectionExtent,
|
|
formatFlowDirectionBbox,
|
|
getFlowDirectionFeatureCacheKey,
|
|
getFlowDirectionModeByPathname,
|
|
} from "./layer-info";
|
|
import { subscribeFlowDirectionMoveEnd } from "./flow-direction-listener";
|
|
import {
|
|
createFlowDirectionStyle,
|
|
type FlowDirectionUsageStyle,
|
|
} from "./flow-direction-styles";
|
|
import { FLOW_DIRECTION_SRS } from "../model/flow-direction-runtime";
|
|
import { getFeatureCollection } from "./geojson-response";
|
|
import { extractCheckedPipeUsageStyles } from "./flow-direction-selection";
|
|
import { isFlowDirectionLayerInfo } from "./layer-info";
|
|
|
|
type FlowDirectionOptions = {
|
|
gisMaps: MutableRefObject<any>;
|
|
checkedNodesDataRef: MutableRefObject<any[]>;
|
|
mapReady: boolean;
|
|
flowDirectionMode: ReturnType<typeof getFlowDirectionModeByPathname>;
|
|
};
|
|
|
|
/** 유하방향의 요청·캐시·레이어·이벤트 수명을 소유한다. 외부에는 선택 명령과 표시 상태만 제공한다. */
|
|
export function useFlowDirectionLayer({
|
|
gisMaps,
|
|
checkedNodesDataRef,
|
|
mapReady,
|
|
flowDirectionMode,
|
|
}: FlowDirectionOptions) {
|
|
// 유하방향 레이어 체크 여부를 React 렌더링 흐름에 반영하기 위한 state이다.
|
|
const [isFlowDirectionChecked, setIsFlowDirectionChecked] = useState(false);
|
|
|
|
// 체크된 유하방향 트리 노드의 레이어 설정을 보관해 API 조회와 vector layer 스타일에 사용한다.
|
|
const [flowDirectionLayerInfo, setFlowDirectionLayerInfo] = useState<
|
|
any | null
|
|
>(null);
|
|
|
|
// 관종 레이어 체크 변경도 유하방향 재조회 조건이므로 별도 버전 state로 effect를 다시 실행한다.
|
|
const [flowDirectionSelectionVersion, setFlowDirectionSelectionVersion] =
|
|
useState(0);
|
|
|
|
// moveend 이벤트 핸들러는 최신 state closure를 보장하지 않으므로 현재 체크 여부를 ref로 함께 보관한다.
|
|
const flowDirectionCheckedRef = useRef(false);
|
|
|
|
// 지도 이동 후 재조회할 때 최신 유하방향 레이어 설정을 참조하기 위한 ref이다.
|
|
const flowDirectionLayerInfoRef = useRef<any | null>(null);
|
|
|
|
// 유하방향 전용 vector layer/source를 유지해 지도 이동 시 기존 피처를 지우지 않고 새 BBOX 응답만 병합한다.
|
|
const flowDirectionLayerRef = useRef<any | null>(null);
|
|
|
|
const flowDirectionSourceRef = useRef<VectorSource | null>(null);
|
|
|
|
// 같은 관로가 겹치는 BBOX에서 반복 조회될 수 있으므로 고유키와 삽입 순서를 캐시로 관리한다.
|
|
const flowDirectionFeatureKeySetRef = useRef<Set<string>>(new Set());
|
|
|
|
const flowDirectionFeatureKeyQueueRef = useRef<string[]>([]);
|
|
|
|
// 관종 체크 변경 시 다른 관종 유하방향을 유지하기 위해 현재 source에 남겨둘 관종 코드를 별도로 추적한다.
|
|
const flowDirectionVisibleUsageCodesRef = useRef<Set<string>>(new Set());
|
|
|
|
// 관종 체크 변경으로 새로 켜진 usgCd만 다음 조회 대상으로 넘겨 기존 관종 재요청을 막는다.
|
|
const flowDirectionSelectionRequestUsageCodesRef = useRef<string[] | null>(
|
|
null,
|
|
);
|
|
|
|
// 체크 해제나 재조회 중 늦게 도착한 이전 API 응답이 레이어를 다시 그리지 못하도록 요청 순번을 관리한다.
|
|
const flowDirectionRequestSeqRef = useRef(0);
|
|
|
|
// 지도 이동이 연속으로 발생하면 이전 유하방향 요청을 중단해 늦은 응답과 불필요한 네트워크 대기를 줄인다.
|
|
const flowDirectionAbortControllerRef = useRef<AbortController | null>(null);
|
|
|
|
// 같은 장애 상황에서 alert가 반복 노출되지 않도록 실패 안내 여부를 기억한다.
|
|
const flowDirectionFailureAlertedRef = useRef(false);
|
|
|
|
// 유하방향은 일반 Gis core 레이어 등록 흐름을 타지 않으므로 전용 layer/source/cache를 직접 정리한다.
|
|
const removeFlowDirectionLayer = useCallback(() => {
|
|
const core = GisApp.Module.core as any;
|
|
core?.deleteLayer?.(FLOW_DIRECTION_LAYER_TYPE);
|
|
flowDirectionLayerRef.current = null;
|
|
flowDirectionSourceRef.current = null;
|
|
flowDirectionFeatureKeySetRef.current.clear();
|
|
flowDirectionFeatureKeyQueueRef.current = [];
|
|
flowDirectionVisibleUsageCodesRef.current.clear();
|
|
}, []);
|
|
|
|
// 유하방향 cache/source만 비워 관종 변경처럼 조건이 달라진 경우 이전 조건의 피처가 남지 않게 한다.
|
|
const clearFlowDirectionFeatureCache = useCallback(() => {
|
|
flowDirectionSourceRef.current?.clear();
|
|
flowDirectionFeatureKeySetRef.current.clear();
|
|
flowDirectionFeatureKeyQueueRef.current = [];
|
|
flowDirectionVisibleUsageCodesRef.current.clear();
|
|
}, []);
|
|
|
|
// 체크 해제된 관종의 유하방향 feature/cache만 제거하고, 새로 체크된 관종 코드만 다음 요청 대상으로 돌려준다.
|
|
const retainFlowDirectionUsageCodes = useCallback((usageCodes: string[]) => {
|
|
const nextUsageCodes = new Set(usageCodes);
|
|
const addedUsageCodes = usageCodes.filter(
|
|
(usageCode) => !flowDirectionVisibleUsageCodesRef.current.has(usageCode),
|
|
);
|
|
const source = flowDirectionSourceRef.current;
|
|
if (source) {
|
|
source.getFeatures().forEach((feature: any) => {
|
|
const usageCode = String(
|
|
feature.get("usgCd") ?? feature.get("usg_cd") ?? "",
|
|
).trim();
|
|
if (nextUsageCodes.has(usageCode)) return;
|
|
|
|
const featureKey = feature.get("flowDirectionCacheKey");
|
|
if (featureKey) {
|
|
flowDirectionFeatureKeySetRef.current.delete(String(featureKey));
|
|
}
|
|
source.removeFeature(feature);
|
|
});
|
|
flowDirectionFeatureKeyQueueRef.current =
|
|
flowDirectionFeatureKeyQueueRef.current.filter((featureKey) =>
|
|
flowDirectionFeatureKeySetRef.current.has(featureKey),
|
|
);
|
|
}
|
|
flowDirectionVisibleUsageCodesRef.current = new Set(
|
|
Array.from(flowDirectionVisibleUsageCodesRef.current).filter(
|
|
(usageCode) => nextUsageCodes.has(usageCode),
|
|
),
|
|
);
|
|
return addedUsageCodes;
|
|
}, []);
|
|
|
|
// 유하방향 레이어는 하나만 유지하고 source에 피처를 누적한다.
|
|
const ensureFlowDirectionLayer = useCallback((layerInfo: any) => {
|
|
const map = gisMaps.current;
|
|
if (!map) return null;
|
|
|
|
if (flowDirectionLayerRef.current && flowDirectionSourceRef.current) {
|
|
flowDirectionLayerRef.current.setMinZoom?.(
|
|
getFlowDirectionMinZoom(layerInfo),
|
|
);
|
|
flowDirectionLayerRef.current.setZIndex?.(
|
|
getFlowDirectionZIndex(layerInfo),
|
|
);
|
|
return flowDirectionSourceRef.current;
|
|
}
|
|
|
|
const source = new VectorSource();
|
|
const layer = new VectorLayer({
|
|
source,
|
|
minZoom: getFlowDirectionMinZoom(layerInfo),
|
|
zIndex: getFlowDirectionZIndex(layerInfo),
|
|
updateWhileAnimating: false,
|
|
updateWhileInteracting: false,
|
|
});
|
|
|
|
layer.set("id", FLOW_DIRECTION_LAYER_TYPE);
|
|
layer.set("lyrNm", FLOW_DIRECTION_LAYER_NAME);
|
|
layer.set("lyrTyNm", FLOW_DIRECTION_LAYER_TYPE);
|
|
layer.set("typeName", FLOW_DIRECTION_LAYER_TYPE);
|
|
layer.set("clickPsblYn", "N");
|
|
layer.set("chcYn", "N");
|
|
|
|
const core = GisApp.Module.core as any;
|
|
core?.deleteLayer?.(FLOW_DIRECTION_LAYER_TYPE);
|
|
map.addLayer(layer);
|
|
flowDirectionLayerRef.current = layer;
|
|
flowDirectionSourceRef.current = source;
|
|
return source;
|
|
}, []);
|
|
|
|
// BE에서 받은 보정 GeoJSON을 OpenLayers feature로 변환해 기존 유하방향 source에 중복 없이 병합한다.
|
|
const renderFlowDirectionLayer = useCallback(
|
|
(
|
|
featureCollection: any,
|
|
layerInfo: any,
|
|
usageStyleMap: Record<string, FlowDirectionUsageStyle>,
|
|
) => {
|
|
const source = ensureFlowDirectionLayer(layerInfo);
|
|
if (!source) return;
|
|
|
|
const features = new GeoJSON().readFeatures(featureCollection, {
|
|
dataProjection: FLOW_DIRECTION_SRS,
|
|
featureProjection: GisApp.TO_PROJ,
|
|
});
|
|
|
|
const nextFeatures = features.filter((feature) => {
|
|
const featureKey = getFlowDirectionFeatureCacheKey(feature);
|
|
if (flowDirectionFeatureKeySetRef.current.has(featureKey)) return false;
|
|
|
|
feature.set("flowDirectionCacheKey", featureKey);
|
|
feature.setId(featureKey);
|
|
feature.setStyle(createFlowDirectionStyle(feature, usageStyleMap));
|
|
flowDirectionFeatureKeySetRef.current.add(featureKey);
|
|
flowDirectionFeatureKeyQueueRef.current.push(featureKey);
|
|
return true;
|
|
});
|
|
|
|
if (nextFeatures.length > 0) {
|
|
source.addFeatures(nextFeatures);
|
|
}
|
|
},
|
|
[ensureFlowDirectionLayer],
|
|
);
|
|
|
|
// 현재 지도 BBOX와 체크된 관종별 필터로 유하방향 GeoJSON을 각각 조회하고, 최신 요청만 지도에 반영한다.
|
|
const loadFlowDirectionLayer = useCallback(
|
|
async (layerInfo: any, requestOnlyUsageCodes?: string[]) => {
|
|
const map = gisMaps.current;
|
|
if (!map) return;
|
|
|
|
const requestSeq = flowDirectionRequestSeqRef.current + 1;
|
|
flowDirectionRequestSeqRef.current = requestSeq;
|
|
flowDirectionAbortControllerRef.current?.abort();
|
|
const abortController = new AbortController();
|
|
flowDirectionAbortControllerRef.current = abortController;
|
|
|
|
const view = map.getView();
|
|
const zoom = view.getZoom() ?? 0;
|
|
const minZoom = getFlowDirectionMinZoom(layerInfo);
|
|
|
|
if (zoom < minZoom) {
|
|
removeFlowDirectionLayer();
|
|
return;
|
|
}
|
|
|
|
const size = map.getSize();
|
|
if (!size) return;
|
|
|
|
const usageStyleMap = extractCheckedPipeUsageStyles(
|
|
checkedNodesDataRef.current,
|
|
zoom,
|
|
);
|
|
const usageCodes = Object.keys(usageStyleMap);
|
|
if (usageCodes.length === 0) {
|
|
removeFlowDirectionLayer();
|
|
return;
|
|
}
|
|
retainFlowDirectionUsageCodes(usageCodes);
|
|
|
|
const usageCodeSet = new Set(usageCodes);
|
|
const requestUsageCodes = requestOnlyUsageCodes
|
|
? requestOnlyUsageCodes.filter((usageCode) =>
|
|
usageCodeSet.has(usageCode),
|
|
)
|
|
: usageCodes;
|
|
const isPartialUsageRequest = Array.isArray(requestOnlyUsageCodes);
|
|
if (requestUsageCodes.length === 0) {
|
|
if (flowDirectionAbortControllerRef.current === abortController) {
|
|
flowDirectionAbortControllerRef.current = null;
|
|
}
|
|
return;
|
|
}
|
|
|
|
const screenExtent = view.calculateExtent(size);
|
|
const requestExtent = expandFlowDirectionExtent(screenExtent);
|
|
const screenBbox = formatFlowDirectionBbox(screenExtent);
|
|
const requestBbox = formatFlowDirectionBbox(requestExtent);
|
|
const baseParams = new URLSearchParams({
|
|
srs: FLOW_DIRECTION_SRS,
|
|
directionMode: flowDirectionMode,
|
|
searchStrategy: "BBOX",
|
|
bbox: requestBbox,
|
|
});
|
|
|
|
try {
|
|
const settledResponses = await Promise.allSettled(
|
|
requestUsageCodes.map(async (usageCode) => {
|
|
const params = new URLSearchParams(baseParams);
|
|
params.set("usgCd", usageCode);
|
|
const payload = await getRawJson(
|
|
`/sewerage-service/api/v1/map/flowDirectionGeometry?${params.toString()}`,
|
|
{ signal: abortController.signal },
|
|
);
|
|
return {
|
|
usageCode,
|
|
featureCollection: getFeatureCollection(payload),
|
|
};
|
|
}),
|
|
);
|
|
if (requestSeq !== flowDirectionRequestSeqRef.current) return;
|
|
if (abortController.signal.aborted) return;
|
|
|
|
const responses = settledResponses
|
|
.filter(
|
|
(
|
|
result,
|
|
): result is PromiseFulfilledResult<{
|
|
usageCode: string;
|
|
featureCollection: any;
|
|
}> => result.status === "fulfilled",
|
|
)
|
|
.map((result) => result.value);
|
|
const failedResponses = settledResponses.filter(
|
|
(result) => result.status === "rejected",
|
|
);
|
|
|
|
if (responses.length === 0) {
|
|
if (!isPartialUsageRequest) {
|
|
removeFlowDirectionLayer();
|
|
}
|
|
throw (
|
|
failedResponses[0]?.reason ??
|
|
new Error("유하방향 관종별 조회 결과가 없습니다.")
|
|
);
|
|
}
|
|
|
|
if (failedResponses.length > 0) {
|
|
console.error(
|
|
"유하방향 일부 관종 조회 실패:",
|
|
failedResponses.map((result) => result.reason),
|
|
);
|
|
if (!flowDirectionFailureAlertedRef.current) {
|
|
flowDirectionFailureAlertedRef.current = true;
|
|
}
|
|
}
|
|
|
|
responses.forEach(({ usageCode, featureCollection }) => {
|
|
renderFlowDirectionLayer(featureCollection, layerInfo, usageStyleMap);
|
|
flowDirectionVisibleUsageCodesRef.current.add(usageCode);
|
|
});
|
|
const returnedFeaturesByUsage = responses.reduce<
|
|
Record<string, number>
|
|
>((acc, { usageCode, featureCollection }) => {
|
|
acc[usageCode] = featureCollection.features?.length ?? 0;
|
|
return acc;
|
|
}, {});
|
|
const networkCorrectedFeatures = responses.reduce(
|
|
(count, { featureCollection }) => {
|
|
const correctedCount =
|
|
featureCollection.features?.filter(
|
|
(feature: any) =>
|
|
String(
|
|
feature?.properties?.networkCorrectionYn ??
|
|
feature?.properties?.network_correction_yn ??
|
|
"",
|
|
).toUpperCase() === "Y",
|
|
).length ?? 0;
|
|
return count + correctedCount;
|
|
},
|
|
0,
|
|
);
|
|
(window as any).__SN_FLOW_DIRECTION_DEBUG__ = {
|
|
screenBbox,
|
|
requestBbox,
|
|
requestSeq,
|
|
zoom,
|
|
directionMode: flowDirectionMode,
|
|
searchStrategy: "BBOX",
|
|
usageCodes,
|
|
requestUsageCodes,
|
|
requestCount: responses.length,
|
|
returnedFeaturesByUsage,
|
|
returnedFeatures: Object.values(returnedFeaturesByUsage).reduce(
|
|
(sum, count) => sum + count,
|
|
0,
|
|
),
|
|
networkCorrectedFeatures,
|
|
cachedFeatures:
|
|
flowDirectionSourceRef.current?.getFeatures?.().length ?? 0,
|
|
};
|
|
if (failedResponses.length === 0) {
|
|
flowDirectionFailureAlertedRef.current = false;
|
|
}
|
|
} catch (error) {
|
|
if (requestSeq !== flowDirectionRequestSeqRef.current) return;
|
|
if (
|
|
typeof error === "object" &&
|
|
error !== null &&
|
|
"name" in error &&
|
|
error.name === "AbortError"
|
|
)
|
|
return;
|
|
|
|
console.error("유하방향 레이어 조회 실패:", error);
|
|
if (!isPartialUsageRequest) {
|
|
removeFlowDirectionLayer();
|
|
}
|
|
if (!flowDirectionFailureAlertedRef.current) {
|
|
flowDirectionFailureAlertedRef.current = true;
|
|
}
|
|
} finally {
|
|
if (flowDirectionAbortControllerRef.current === abortController) {
|
|
flowDirectionAbortControllerRef.current = null;
|
|
}
|
|
}
|
|
},
|
|
[
|
|
flowDirectionMode,
|
|
removeFlowDirectionLayer,
|
|
renderFlowDirectionLayer,
|
|
retainFlowDirectionUsageCodes,
|
|
],
|
|
);
|
|
const updateSelection = useCallback(
|
|
(checkedNodesData: any[]) => {
|
|
// 유하방향은 일반 setLayerOnMap 대상이 아니므로 체크 노드 여부를 별도로 추적한다.
|
|
const flowDirectionNode = checkedNodesData.find((node) =>
|
|
isFlowDirectionLayerInfo(node?.data ?? node),
|
|
);
|
|
const nextFlowDirectionLayerInfo =
|
|
flowDirectionNode?.data ?? flowDirectionNode ?? null;
|
|
flowDirectionCheckedRef.current = Boolean(nextFlowDirectionLayerInfo);
|
|
flowDirectionLayerInfoRef.current = nextFlowDirectionLayerInfo;
|
|
setIsFlowDirectionChecked(Boolean(nextFlowDirectionLayerInfo));
|
|
setFlowDirectionLayerInfo(nextFlowDirectionLayerInfo);
|
|
if (nextFlowDirectionLayerInfo) {
|
|
const map = gisMaps.current;
|
|
const zoom = map?.getView?.()?.getZoom?.() ?? 0;
|
|
const nextUsageStyleMap = extractCheckedPipeUsageStyles(
|
|
checkedNodesData,
|
|
zoom,
|
|
);
|
|
const requestUsageCodes = retainFlowDirectionUsageCodes(
|
|
Object.keys(nextUsageStyleMap),
|
|
);
|
|
flowDirectionSelectionRequestUsageCodesRef.current = requestUsageCodes;
|
|
if (requestUsageCodes.length === 0) {
|
|
flowDirectionRequestSeqRef.current += 1;
|
|
flowDirectionAbortControllerRef.current?.abort();
|
|
flowDirectionAbortControllerRef.current = null;
|
|
}
|
|
setFlowDirectionSelectionVersion((version) => version + 1);
|
|
}
|
|
|
|
if (!nextFlowDirectionLayerInfo) {
|
|
// 해제 직후 pending API 응답이 늦게 도착해도 renderFlowDirectionLayer가 실행되지 않도록 순번을 무효화한다.
|
|
flowDirectionSelectionRequestUsageCodesRef.current = null;
|
|
flowDirectionRequestSeqRef.current += 1;
|
|
flowDirectionAbortControllerRef.current?.abort();
|
|
flowDirectionAbortControllerRef.current = null;
|
|
flowDirectionFailureAlertedRef.current = false;
|
|
removeFlowDirectionLayer();
|
|
}
|
|
},
|
|
[gisMaps, removeFlowDirectionLayer, retainFlowDirectionUsageCodes],
|
|
);
|
|
|
|
useEffect(() => {
|
|
if (!flowDirectionCheckedRef.current) return;
|
|
clearFlowDirectionFeatureCache();
|
|
flowDirectionSelectionRequestUsageCodesRef.current = null;
|
|
setFlowDirectionSelectionVersion((version) => version + 1);
|
|
}, [clearFlowDirectionFeatureCache, flowDirectionMode]);
|
|
|
|
useEffect(() => {
|
|
if (!mapReady || !flowDirectionLayerInfo) return;
|
|
|
|
// 트리 체크 상태나 관종 레이어 선택이 바뀌면 유하방향 API vector layer를 추가/갱신/제거한다.
|
|
if (isFlowDirectionChecked) {
|
|
const requestUsageCodes =
|
|
flowDirectionSelectionRequestUsageCodesRef.current;
|
|
flowDirectionSelectionRequestUsageCodesRef.current = null;
|
|
if (requestUsageCodes && requestUsageCodes.length === 0) return;
|
|
loadFlowDirectionLayer(
|
|
flowDirectionLayerInfo,
|
|
requestUsageCodes ?? undefined,
|
|
);
|
|
} else {
|
|
removeFlowDirectionLayer();
|
|
}
|
|
}, [
|
|
flowDirectionLayerInfo,
|
|
flowDirectionSelectionVersion,
|
|
isFlowDirectionChecked,
|
|
loadFlowDirectionLayer,
|
|
mapReady,
|
|
removeFlowDirectionLayer,
|
|
]);
|
|
|
|
useEffect(() => {
|
|
if (!mapReady || !gisMaps.current) return;
|
|
|
|
// 유하방향이 켜진 상태에서 지도 이동/확대축소가 끝나면 현재 BBOX 기준으로 다시 조회한다.
|
|
return subscribeFlowDirectionMoveEnd(
|
|
gisMaps.current,
|
|
() => ({
|
|
checked: flowDirectionCheckedRef.current,
|
|
layerInfo: flowDirectionLayerInfoRef.current,
|
|
}),
|
|
loadFlowDirectionLayer,
|
|
unByKey,
|
|
);
|
|
}, [loadFlowDirectionLayer, mapReady]);
|
|
|
|
// 화면 이탈 후 지연 응답이 제거된 지도에 레이어를 되살리지 않도록 무효화한다.
|
|
useEffect(
|
|
() => () => {
|
|
flowDirectionRequestSeqRef.current += 1;
|
|
flowDirectionAbortControllerRef.current?.abort();
|
|
flowDirectionAbortControllerRef.current = null;
|
|
const ownedLayer = flowDirectionLayerRef.current;
|
|
if (ownedLayer) gisMaps.current?.removeLayer?.(ownedLayer);
|
|
flowDirectionLayerRef.current = null;
|
|
flowDirectionSourceRef.current = null;
|
|
flowDirectionFeatureKeySetRef.current.clear();
|
|
flowDirectionFeatureKeyQueueRef.current = [];
|
|
flowDirectionVisibleUsageCodesRef.current.clear();
|
|
},
|
|
[gisMaps],
|
|
);
|
|
|
|
return { isFlowDirectionChecked, flowDirectionLayerInfo, updateSelection };
|
|
}
|