refactor(sn): modularize map and features and standardize file naming
This commit is contained in:
@@ -0,0 +1,3 @@
|
||||
/** 지도 레이어 메타·표출 조건과 독립 이벤트 구독의 공개 경계다. */
|
||||
export * from "./lib/layer-info";
|
||||
export { subscribeFlowDirectionMoveEnd } from "./lib/flow-direction-listener";
|
||||
@@ -0,0 +1,17 @@
|
||||
/**
|
||||
* 유하방향 moveend 구독 수명을 소유한다. 매 이벤트마다 최신 체크·레이어 상태를 읽는다.
|
||||
* OpenLayers 해제 함수는 주입받아 모델·계약 테스트에서 지도 엔진 없이 검증할 수 있다.
|
||||
*/
|
||||
export const subscribeFlowDirectionMoveEnd = <TLayer, TSubscription>(
|
||||
map: { on: (event: "moveend", listener: () => void) => TSubscription },
|
||||
readState: () => { checked: boolean; layerInfo: TLayer | null },
|
||||
loadLayer: (layerInfo: TLayer) => unknown,
|
||||
unsubscribe: (key: TSubscription) => void,
|
||||
): (() => void) => {
|
||||
const key = map.on("moveend", () => {
|
||||
const state = readState();
|
||||
if (!state.checked || !state.layerInfo) return;
|
||||
loadLayer(state.layerInfo);
|
||||
});
|
||||
return () => unsubscribe(key);
|
||||
};
|
||||
@@ -0,0 +1,76 @@
|
||||
import {
|
||||
FLOW_DIRECTION_DEFAULT_COLOR,
|
||||
type FlowDirectionUsageStyle,
|
||||
withAlpha,
|
||||
} from "./flow-direction-styles";
|
||||
import {
|
||||
getLayerTypeName,
|
||||
isFlowDirectionLayerInfo,
|
||||
getFiniteNumber,
|
||||
} from "./layer-info";
|
||||
import { FLOW_DIRECTION_PIPE_LAYER_TYPE } from "../model/flow-direction-runtime";
|
||||
|
||||
/** 지도 체크 노드에서 유하방향 관종/스타일을 선택하는 순수 변환. */
|
||||
// 레이어 설정의 직접 코드와 filterSql 안의 usg_cd 조건을 모두 관종 코드 후보로 해석한다.
|
||||
export const extractUsageCodesFromLayerInfo = (layerInfo: any) => {
|
||||
const usageCodes = new Set<string>();
|
||||
const directCode = layerInfo?.usgCd ?? layerInfo?.usg_cd;
|
||||
if (directCode) usageCodes.add(String(directCode).trim());
|
||||
|
||||
const filterSql = String(layerInfo?.flterSql ?? layerInfo?.filterSql ?? "");
|
||||
const equalsMatches = filterSql.matchAll(/usg_cd\s*=\s*'([^']+)'/gi);
|
||||
for (const match of equalsMatches) {
|
||||
const code = match[1]?.trim();
|
||||
if (code) usageCodes.add(code);
|
||||
}
|
||||
|
||||
const inMatches = filterSql.matchAll(/usg_cd\s+in\s*\(([^)]+)\)/gi);
|
||||
for (const match of inMatches) {
|
||||
const codeList = match[1];
|
||||
if (!codeList) continue;
|
||||
|
||||
codeList
|
||||
.split(",")
|
||||
.map((item) => item.replace(/'/g, "").trim())
|
||||
.filter(Boolean)
|
||||
.forEach((code) => usageCodes.add(code));
|
||||
}
|
||||
|
||||
return Array.from(usageCodes);
|
||||
};
|
||||
|
||||
// 현재 줌에서 실제 표출 가능한 관로 레이어인지 확인해 숨겨진 관종의 유하방향 요청을 막는다.
|
||||
export const isLayerVisibleAtZoom = (layerInfo: any, zoom: number) => {
|
||||
const minZoom = getFiniteNumber(layerInfo?.minViewSize ?? layerInfo?.minZoom);
|
||||
return minZoom === null || zoom >= minZoom;
|
||||
};
|
||||
|
||||
// 현재 체크되어 화면에 보이는 관로 레이어의 관종 코드와 선 색상을 유하방향 조회/스타일 기준으로 변환한다.
|
||||
export const extractCheckedPipeUsageStyles = (
|
||||
checkedNodesData: any[],
|
||||
zoom: number,
|
||||
) => {
|
||||
const usageStyleMap: Record<string, FlowDirectionUsageStyle> = {};
|
||||
|
||||
checkedNodesData.forEach((node) => {
|
||||
const data = node?.data ?? node;
|
||||
if (!data || isFlowDirectionLayerInfo(data)) return;
|
||||
if (getLayerTypeName(data) !== FLOW_DIRECTION_PIPE_LAYER_TYPE) return;
|
||||
if (!isLayerVisibleAtZoom(data, zoom)) return;
|
||||
|
||||
const usageCodes = extractUsageCodesFromLayerInfo(data);
|
||||
if (usageCodes.length === 0) return;
|
||||
|
||||
const layerColor = String(
|
||||
data.lnColor ?? data.lineColor ?? FLOW_DIRECTION_DEFAULT_COLOR,
|
||||
).trim();
|
||||
usageCodes.forEach((code) => {
|
||||
usageStyleMap[code] = {
|
||||
color: layerColor,
|
||||
lineColor: withAlpha(layerColor, 0.28),
|
||||
};
|
||||
});
|
||||
});
|
||||
|
||||
return usageStyleMap;
|
||||
};
|
||||
@@ -0,0 +1,286 @@
|
||||
/** 유하방향 선/화살표의 색상·대표 선분·중앙 배치를 표출 정책으로 분리한다. */
|
||||
import Style from "ol/style/Style.js";
|
||||
import Stroke from "ol/style/Stroke.js";
|
||||
import Point from "ol/geom/Point.js";
|
||||
export const FLOW_DIRECTION_DEFAULT_COLOR = "rgba(40, 90, 180, 0.84)";
|
||||
|
||||
export const FLOW_DIRECTION_NETWORK_CORRECTION_COLOR =
|
||||
"rgba(0, 168, 132, 0.95)";
|
||||
|
||||
export type FlowDirectionUsageStyle = {
|
||||
color: string;
|
||||
lineColor: string;
|
||||
};
|
||||
|
||||
// 관종별 원본 레이어 색을 유하방향 선/화살표에 재사용할 때 투명도만 조정한다.
|
||||
export const withAlpha = (color: string | null | undefined, alpha: number) => {
|
||||
const resolvedColor = String(color ?? "").trim();
|
||||
if (!resolvedColor) return `rgba(40, 90, 180, ${alpha})`;
|
||||
|
||||
const rgbaMatch = resolvedColor.match(/^rgba?\(([^)]+)\)$/i);
|
||||
if (rgbaMatch) {
|
||||
const [red = "40", green = "90", blue = "180"] = (rgbaMatch[1] ?? "")
|
||||
.split(",")
|
||||
.map((part) => part.trim());
|
||||
return `rgba(${red}, ${green}, ${blue}, ${alpha})`;
|
||||
}
|
||||
|
||||
const hexMatch = resolvedColor.match(/^#([0-9a-f]{3}|[0-9a-f]{6})$/i);
|
||||
if (hexMatch) {
|
||||
const hex = hexMatch[1] ?? "";
|
||||
const normalized =
|
||||
hex.length === 3
|
||||
? hex
|
||||
.split("")
|
||||
.map((char) => char + char)
|
||||
.join("")
|
||||
: hex;
|
||||
const red = parseInt(normalized.slice(0, 2), 16);
|
||||
const green = parseInt(normalized.slice(2, 4), 16);
|
||||
const blue = parseInt(normalized.slice(4, 6), 16);
|
||||
return `rgba(${red}, ${green}, ${blue}, ${alpha})`;
|
||||
}
|
||||
|
||||
return resolvedColor;
|
||||
};
|
||||
|
||||
// 화살표 위치와 대표 선분 선택을 위해 LineString 좌표열의 대략적인 길이를 계산한다.
|
||||
export const estimateLineLength = (coordinates: number[][]) => {
|
||||
let length = 0;
|
||||
for (let i = 1; i < coordinates.length; i += 1) {
|
||||
const previous = coordinates[i - 1];
|
||||
const current = coordinates[i];
|
||||
if (!previous || !current) continue;
|
||||
|
||||
const [x1 = 0, y1 = 0] = previous;
|
||||
const [x2 = 0, y2 = 0] = current;
|
||||
length += Math.hypot(x2 - x1, y2 - y1);
|
||||
}
|
||||
return length;
|
||||
};
|
||||
|
||||
// MultiLineString 관로는 가장 긴 선분을 대표 선으로 삼아 화살표 위치와 각도를 안정적으로 계산한다.
|
||||
export const getRepresentativeLineCoordinates = (geometry: any): number[][] => {
|
||||
const type = geometry?.getType?.();
|
||||
const coordinates = geometry?.getCoordinates?.();
|
||||
|
||||
if (type === "LineString") return coordinates ?? [];
|
||||
if (type === "MultiLineString" && Array.isArray(coordinates)) {
|
||||
return coordinates.reduce(
|
||||
(longest: number[][], current: number[][]) =>
|
||||
estimateLineLength(current) > estimateLineLength(longest)
|
||||
? current
|
||||
: longest,
|
||||
[],
|
||||
);
|
||||
}
|
||||
|
||||
return [];
|
||||
};
|
||||
|
||||
// 관로 중앙 지점이 속한 실제 선분을 찾아 화살표 위치와 해당 선분의 방향각을 함께 계산한다.
|
||||
export const getArrowPlacementAtHalfLength = (coordinates: number[][]) => {
|
||||
if (coordinates.length === 0) return null;
|
||||
if (coordinates.length === 1) {
|
||||
const coordinate = coordinates[0];
|
||||
return coordinate ? { coordinate, angle: 0 } : null;
|
||||
}
|
||||
|
||||
const totalLength = estimateLineLength(coordinates);
|
||||
if (totalLength === 0) {
|
||||
const coordinate = coordinates[Math.floor(coordinates.length / 2)];
|
||||
return coordinate ? { coordinate, angle: 0 } : null;
|
||||
}
|
||||
|
||||
let accumulated = 0;
|
||||
const targetLength = totalLength / 2;
|
||||
let lastSegmentAngle = 0;
|
||||
|
||||
for (let i = 1; i < coordinates.length; i += 1) {
|
||||
const previous = coordinates[i - 1];
|
||||
const current = coordinates[i];
|
||||
if (!previous || !current) continue;
|
||||
|
||||
const [previousX = 0, previousY = 0] = previous;
|
||||
const [currentX = 0, currentY = 0] = current;
|
||||
const segmentLength = Math.hypot(
|
||||
currentX - previousX,
|
||||
currentY - previousY,
|
||||
);
|
||||
if (segmentLength > 0) {
|
||||
lastSegmentAngle = Math.atan2(currentY - previousY, currentX - previousX);
|
||||
}
|
||||
|
||||
if (accumulated + segmentLength >= targetLength) {
|
||||
const ratio =
|
||||
segmentLength === 0 ? 0 : (targetLength - accumulated) / segmentLength;
|
||||
return {
|
||||
coordinate: [
|
||||
previousX + (currentX - previousX) * ratio,
|
||||
previousY + (currentY - previousY) * ratio,
|
||||
],
|
||||
angle: lastSegmentAngle,
|
||||
};
|
||||
}
|
||||
|
||||
accumulated += segmentLength;
|
||||
}
|
||||
|
||||
const coordinate = coordinates[coordinates.length - 1];
|
||||
return coordinate ? { coordinate, angle: lastSegmentAngle } : null;
|
||||
};
|
||||
|
||||
// SVG 없이 Canvas renderer로 짧은 꼬리선과 화살촉을 직접 그려 방향성을 분명하게 만든다.
|
||||
export const createFlowDirectionArrowRenderer = (
|
||||
color: string,
|
||||
angle: number,
|
||||
scale: number,
|
||||
) => {
|
||||
return (coordinates: any, state: any) => {
|
||||
const pixel = Array.isArray(coordinates?.[0])
|
||||
? coordinates[0]
|
||||
: coordinates;
|
||||
const [x, y] = pixel ?? [];
|
||||
const context = state?.context as CanvasRenderingContext2D | undefined;
|
||||
if (!context || !Number.isFinite(x) || !Number.isFinite(y)) return;
|
||||
|
||||
const length = 17 * scale;
|
||||
const tailLength = 9 * scale;
|
||||
const headLength = 7 * scale;
|
||||
const headHalfWidth = 4.5 * scale;
|
||||
const shaftWidth = 2.4 * scale;
|
||||
|
||||
context.save();
|
||||
context.translate(x, y);
|
||||
const viewRotation = Number(state?.rotation ?? 0);
|
||||
const screenAngle =
|
||||
(Number.isFinite(viewRotation) ? viewRotation : 0) - angle;
|
||||
|
||||
context.rotate(screenAngle);
|
||||
context.lineCap = "round";
|
||||
context.lineJoin = "round";
|
||||
|
||||
context.strokeStyle = "rgba(255, 255, 255, 0.9)";
|
||||
context.lineWidth = shaftWidth + 2.4;
|
||||
context.beginPath();
|
||||
context.moveTo(-tailLength, 0);
|
||||
context.lineTo(length - headLength, 0);
|
||||
context.stroke();
|
||||
|
||||
context.fillStyle = "rgba(255, 255, 255, 0.9)";
|
||||
context.beginPath();
|
||||
context.moveTo(length, 0);
|
||||
context.lineTo(length - headLength, -headHalfWidth);
|
||||
context.lineTo(length - headLength, headHalfWidth);
|
||||
context.closePath();
|
||||
context.fill();
|
||||
|
||||
context.strokeStyle = color;
|
||||
context.lineWidth = shaftWidth;
|
||||
context.beginPath();
|
||||
context.moveTo(-tailLength, 0);
|
||||
context.lineTo(length - headLength, 0);
|
||||
context.stroke();
|
||||
|
||||
context.fillStyle = color;
|
||||
context.beginPath();
|
||||
context.moveTo(length, 0);
|
||||
context.lineTo(length - headLength, -headHalfWidth);
|
||||
context.lineTo(length - headLength, headHalfWidth);
|
||||
context.closePath();
|
||||
context.fill();
|
||||
|
||||
context.restore();
|
||||
};
|
||||
};
|
||||
|
||||
// 유하방향 신뢰도와 관종 색상에 따라 선과 화살표 스타일을 만든다. LOW는 운영 검수 대상이라 더 흐리게 표시한다.
|
||||
export const createFlowDirectionStyle = (
|
||||
feature: any,
|
||||
usageStyleMap: Record<string, FlowDirectionUsageStyle>,
|
||||
) => {
|
||||
const confidence = String(
|
||||
feature.get("directionConfidence") ??
|
||||
feature.get("direction_confidence") ??
|
||||
"",
|
||||
).toUpperCase();
|
||||
const geometry = feature.getGeometry();
|
||||
const coordinates = getRepresentativeLineCoordinates(geometry);
|
||||
const arrowPlacement = getArrowPlacementAtHalfLength(coordinates);
|
||||
const usageCode = String(
|
||||
feature.get("usgCd") ?? feature.get("usg_cd") ?? "",
|
||||
).trim();
|
||||
const usageStyle = usageStyleMap[usageCode];
|
||||
const baseColor = usageStyle?.color ?? FLOW_DIRECTION_DEFAULT_COLOR;
|
||||
const isNetworkCorrected =
|
||||
String(
|
||||
feature.get("networkCorrectionYn") ??
|
||||
feature.get("network_correction_yn") ??
|
||||
"",
|
||||
).toUpperCase() === "Y";
|
||||
|
||||
const styleByConfidence: Record<
|
||||
string,
|
||||
{
|
||||
color: string;
|
||||
lineColor: string;
|
||||
scale: number;
|
||||
width: number;
|
||||
lineDash?: number[];
|
||||
}
|
||||
> = {
|
||||
HIGH: {
|
||||
color: baseColor,
|
||||
lineColor: usageStyle?.lineColor ?? withAlpha(baseColor, 0.42),
|
||||
scale: 1,
|
||||
width: 1.3,
|
||||
},
|
||||
MEDIUM: {
|
||||
color: baseColor,
|
||||
lineColor: usageStyle?.lineColor ?? withAlpha(baseColor, 0.42),
|
||||
scale: 1,
|
||||
width: 1.3,
|
||||
},
|
||||
LOW: {
|
||||
color: withAlpha(baseColor, 0.72),
|
||||
lineColor: withAlpha(baseColor, 0.28),
|
||||
scale: 0.9,
|
||||
width: 1.1,
|
||||
},
|
||||
};
|
||||
const style = isNetworkCorrected
|
||||
? {
|
||||
color: FLOW_DIRECTION_NETWORK_CORRECTION_COLOR,
|
||||
lineColor: withAlpha(FLOW_DIRECTION_NETWORK_CORRECTION_COLOR, 0.5),
|
||||
scale: 1.08,
|
||||
width: 2,
|
||||
lineDash: [8, 4],
|
||||
}
|
||||
: (styleByConfidence[confidence] ?? styleByConfidence.LOW!);
|
||||
const styles = [
|
||||
new Style({
|
||||
stroke: new Stroke({
|
||||
color: style.lineColor,
|
||||
width: style.width,
|
||||
lineDash: style.lineDash,
|
||||
lineCap: "round",
|
||||
lineJoin: "round",
|
||||
}),
|
||||
}),
|
||||
];
|
||||
|
||||
if (arrowPlacement) {
|
||||
styles.push(
|
||||
new Style({
|
||||
geometry: new Point(arrowPlacement.coordinate),
|
||||
renderer: createFlowDirectionArrowRenderer(
|
||||
style.color,
|
||||
arrowPlacement.angle,
|
||||
style.scale,
|
||||
),
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
return styles;
|
||||
};
|
||||
@@ -0,0 +1,7 @@
|
||||
/** 지도 API의 래퍼/raw GeoJSON 응답을 같은 feature collection으로 읽는다. */
|
||||
// BE 응답이 FeatureCollection 그대로 오거나 공통 응답 wrapper의 data 안에 들어오는 두 계약을 모두 처리한다.
|
||||
export const getFeatureCollection = (payload: any) => {
|
||||
if (payload?.type === "FeatureCollection") return payload;
|
||||
if (payload?.data?.type === "FeatureCollection") return payload.data;
|
||||
return { type: "FeatureCollection", features: [] };
|
||||
};
|
||||
@@ -0,0 +1,197 @@
|
||||
/** 레이어 설정 응답의 호환 필드·조회 모드·BBOX 계산을 UI 수명과 분리한다. */
|
||||
export const FLOW_DIRECTION_LAYER_TYPE = "tb_sn_swage_ppl_flow_direction";
|
||||
|
||||
export const FLOW_DIRECTION_LAYER_NAME = "유하방향";
|
||||
|
||||
export const FLOW_DIRECTION_DEFAULT_MIN_ZOOM = 13;
|
||||
|
||||
export const FLOW_DIRECTION_BBOX_BUFFER_RATIO = 0.35;
|
||||
|
||||
export type FlowDirectionMode = "PIPE_START_END" | "PIPE_DEPTH";
|
||||
|
||||
// /map은 관로 깊이 기준, /map2는 관로 원천 geometry 시점->종점 기준만 유지한다. 두 화면 모두 BBOX 조회만 사용한다.
|
||||
export const getFlowDirectionModeByPathname = (
|
||||
pathname: string | null,
|
||||
): FlowDirectionMode => {
|
||||
const normalizedPathname = String(pathname ?? "").replace(/\/$/, "");
|
||||
if (normalizedPathname.endsWith("/map2")) return "PIPE_START_END";
|
||||
return "PIPE_DEPTH";
|
||||
};
|
||||
|
||||
export const SWAGE_PRCS_FCLT_LAYER_TYPE = "tb_il_swage_prcs_fclt";
|
||||
export const RAIN_OBSERVATION_LAYER_TYPE = "tb_ms_rain_obsvtr_pstn_info";
|
||||
|
||||
export type SwagePrcsFcltLayerMode = "all" | "gte500" | "lt500" | "none";
|
||||
|
||||
// 레이어 설정 응답이 lyrTyNm/lyrTypeNm/lyr_type_nm처럼 혼재되어 내려오는 경우를 단일 기준으로 정규화한다.
|
||||
export const getLayerTypeName = (layerInfo: any) =>
|
||||
String(
|
||||
layerInfo?.lyrTyNm ?? layerInfo?.lyrTypeNm ?? layerInfo?.lyr_type_nm ?? "",
|
||||
).trim();
|
||||
|
||||
export const getLayerFilterSql = (layerInfo: any) =>
|
||||
String(
|
||||
layerInfo?.filtrSql ??
|
||||
layerInfo?.filtr_sql ??
|
||||
layerInfo?.flterSql ??
|
||||
layerInfo?.filterSql ??
|
||||
layerInfo?.filter_sql ??
|
||||
"",
|
||||
)
|
||||
.replace(/\s+/g, "")
|
||||
.toLowerCase();
|
||||
|
||||
export const getSwagePrcsFcltCapacityKind = (
|
||||
layerInfo: any,
|
||||
): Exclude<SwagePrcsFcltLayerMode, "all" | "none"> | null => {
|
||||
if (getLayerTypeName(layerInfo) !== SWAGE_PRCS_FCLT_LAYER_TYPE) return null;
|
||||
|
||||
const layerName = String(layerInfo?.lyrNm ?? layerInfo?.name ?? "").replace(
|
||||
/\s+/g,
|
||||
"",
|
||||
);
|
||||
const filterSql = getLayerFilterSql(layerInfo);
|
||||
|
||||
if (
|
||||
filterSql.includes("fclt_cpct>=500") ||
|
||||
layerName.includes("500이상") ||
|
||||
layerName.includes("500톤이상")
|
||||
)
|
||||
return "gte500";
|
||||
if (
|
||||
filterSql.includes("fclt_cpct<500") ||
|
||||
layerName.includes("500미만") ||
|
||||
layerName.includes("500톤미만")
|
||||
)
|
||||
return "lt500";
|
||||
|
||||
return null;
|
||||
};
|
||||
|
||||
export const getSwagePrcsFcltLayerMode = (
|
||||
checkedNodesData: any[],
|
||||
): SwagePrcsFcltLayerMode => {
|
||||
const checkedKinds = new Set(
|
||||
checkedNodesData
|
||||
.map((node) => getSwagePrcsFcltCapacityKind(node?.data ?? node))
|
||||
.filter(Boolean),
|
||||
);
|
||||
const hasGte500 = checkedKinds.has("gte500");
|
||||
const hasLt500 = checkedKinds.has("lt500");
|
||||
|
||||
if (hasGte500 && hasLt500) return "all";
|
||||
if (hasGte500) return "gte500";
|
||||
if (hasLt500) return "lt500";
|
||||
return "none";
|
||||
};
|
||||
|
||||
// 유하방향 노드는 타입명 또는 표시명으로 식별한다. DB DML 반영 전후 응답 차이를 모두 흡수하기 위한 판별 함수이다.
|
||||
export const isFlowDirectionLayerInfo = (layerInfo: any) => {
|
||||
const layerTypeName = getLayerTypeName(layerInfo);
|
||||
const layerName = String(layerInfo?.lyrNm ?? layerInfo?.name ?? "").trim();
|
||||
|
||||
return (
|
||||
layerTypeName === FLOW_DIRECTION_LAYER_TYPE ||
|
||||
layerName === FLOW_DIRECTION_LAYER_NAME
|
||||
);
|
||||
};
|
||||
|
||||
// 유하방향 노드를 일반 레이어 토글 대상에서 제외하고, 앱 전용 API vector layer로 처리하도록 속성을 보정한다.
|
||||
export const normalizeFlowDirectionLayerInfos = (data: any[]): any[] => {
|
||||
if (!Array.isArray(data)) return data;
|
||||
|
||||
return data.map((item) => {
|
||||
const children = Array.isArray(item.children)
|
||||
? normalizeFlowDirectionLayerInfos(item.children)
|
||||
: item.children;
|
||||
|
||||
if (!isFlowDirectionLayerInfo(item)) {
|
||||
return { ...item, children };
|
||||
}
|
||||
|
||||
return {
|
||||
...item,
|
||||
children,
|
||||
lyrTyNm:
|
||||
item.lyrTyNm ||
|
||||
item.lyrTypeNm ||
|
||||
item.lyr_type_nm ||
|
||||
FLOW_DIRECTION_LAYER_TYPE,
|
||||
lyrNm: item.lyrNm || FLOW_DIRECTION_LAYER_NAME,
|
||||
gobjTy: item.gobjTy || "line",
|
||||
srvcNm: "api",
|
||||
cmncNm: "bbox",
|
||||
actlLyrYn: "N",
|
||||
clickPsblYn: "N",
|
||||
initEprssYn: "N",
|
||||
minViewSize:
|
||||
item.minViewSize ??
|
||||
item.minZoom ??
|
||||
String(FLOW_DIRECTION_DEFAULT_MIN_ZOOM),
|
||||
};
|
||||
});
|
||||
};
|
||||
|
||||
// 강우관측소는 위치와 라벨만 제공하며, 과거 DB 설정값이 Y여도 일반 속성 패널 선택 대상에서는 제외한다.
|
||||
export const normalizeRainObservationLayerInteraction = (
|
||||
data: any[],
|
||||
): any[] => {
|
||||
if (!Array.isArray(data)) return data;
|
||||
|
||||
return data.map((item) => {
|
||||
const children = Array.isArray(item.children)
|
||||
? normalizeRainObservationLayerInteraction(item.children)
|
||||
: item.children;
|
||||
|
||||
return getLayerTypeName(item) === RAIN_OBSERVATION_LAYER_TYPE
|
||||
? { ...item, children, clickPsblYn: "N" }
|
||||
: { ...item, children };
|
||||
});
|
||||
};
|
||||
|
||||
// 레이어 설정의 최소 표출 줌을 읽되, 값이 없으면 유하방향 기본 줌 기준을 적용한다.
|
||||
export const getFiniteNumber = (value: unknown) => {
|
||||
if (value === null || value === undefined || String(value).trim() === "")
|
||||
return null;
|
||||
const parsed = Number(value);
|
||||
return Number.isFinite(parsed) ? parsed : null;
|
||||
};
|
||||
|
||||
export const getFlowDirectionMinZoom = (layerInfo: any) => {
|
||||
return (
|
||||
getFiniteNumber(layerInfo?.minViewSize ?? layerInfo?.minZoom) ??
|
||||
FLOW_DIRECTION_DEFAULT_MIN_ZOOM
|
||||
);
|
||||
};
|
||||
|
||||
// 유하방향 화살표는 관로 위에 얹는 보조 레이어라 레이어 설정의 drawOrdr를 우선 사용하고 없으면 높은 zIndex를 준다.
|
||||
export const getFlowDirectionZIndex = (layerInfo: any) => {
|
||||
return getFiniteNumber(layerInfo?.drawOrdr) ?? 9998;
|
||||
};
|
||||
|
||||
// 현재 지도 화면 BBOX 주변을 함께 조회해 이동 직후 가장자리 유하방향이 비어 보이는 현상을 줄인다.
|
||||
export const expandFlowDirectionExtent = (extent: number[]) => {
|
||||
const [minX = 0, minY = 0, maxX = 0, maxY = 0] = extent;
|
||||
const width = Math.max(0, maxX - minX);
|
||||
const height = Math.max(0, maxY - minY);
|
||||
const bufferX = width * FLOW_DIRECTION_BBOX_BUFFER_RATIO;
|
||||
const bufferY = height * FLOW_DIRECTION_BBOX_BUFFER_RATIO;
|
||||
return [minX - bufferX, minY - bufferY, maxX + bufferX, maxY + bufferY];
|
||||
};
|
||||
|
||||
// API 요청과 디버깅 출력에 같은 BBOX 문자열 포맷을 사용해 FE 계산값과 네트워크 파라미터를 쉽게 대조한다.
|
||||
export const formatFlowDirectionBbox = (extent: number[]) =>
|
||||
extent.map((value: number) => value.toFixed(3)).join(",");
|
||||
|
||||
// 유하방향 캐시 중복 제거 키이다. BE 응답은 같은 관로 id가 여러 geometry로 반복될 수 있어 geometry까지 포함한다.
|
||||
export const getFlowDirectionFeatureCacheKey = (feature: any) => {
|
||||
const featureId = feature.getId?.();
|
||||
const fcltMngNo = feature.get("fcltMngNo") ?? feature.get("fclt_mng_no");
|
||||
const usageCode = feature.get("usgCd") ?? feature.get("usg_cd") ?? "";
|
||||
const coordinates = feature.getGeometry?.()?.getCoordinates?.();
|
||||
const geometryKey = JSON.stringify(coordinates);
|
||||
|
||||
if (featureId) return `id:${String(featureId)}:${geometryKey}`;
|
||||
if (fcltMngNo) return `fclt:${String(fcltMngNo).trim()}:${geometryKey}`;
|
||||
return `geom:${String(usageCode).trim()}:${geometryKey}`;
|
||||
};
|
||||
@@ -0,0 +1,518 @@
|
||||
"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 };
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
/** 유하방향 원천 레이어와 API 좌표계 계약. 기존 값을 유지한다. */
|
||||
export const FLOW_DIRECTION_PIPE_LAYER_TYPE = "tb_ms_swage_ppl";
|
||||
export const FLOW_DIRECTION_SRS = "EPSG:5179";
|
||||
Reference in New Issue
Block a user