sn: 침수예측 오버레이 수정
This commit is contained in:
@@ -0,0 +1,16 @@
|
||||
/** 침수위험도 등급을 목록과 지도 오버레이에서 사용하는 고정 의미색으로 변환한다. */
|
||||
export const getFloodRiskGradeClassName = (value: string) => {
|
||||
const grade = String(value ?? "")
|
||||
.trim()
|
||||
.toUpperCase();
|
||||
if (grade.includes("위험") || grade === "DANGER") {
|
||||
return "bg-[#dc2626] text-white";
|
||||
}
|
||||
if (grade.includes("경계") || grade === "WARNING") {
|
||||
return "bg-[#f97316] text-white";
|
||||
}
|
||||
if (grade.includes("주의") || grade === "CAUTION") {
|
||||
return "bg-[#facc15] text-[#713f12]";
|
||||
}
|
||||
return "sn-popup-badge-normal";
|
||||
};
|
||||
@@ -0,0 +1,406 @@
|
||||
"use client";
|
||||
|
||||
import { useCallback, useEffect, useRef, useState } from "react";
|
||||
|
||||
import Overlay from "ol/Overlay.js";
|
||||
|
||||
import GisApp from "@common/business_components/ui/map/lib/gis.core";
|
||||
|
||||
import { getRawJson } from "@/components/lib/api";
|
||||
import { WINDOW_POPUP_MESSAGE_TYPE } from "@/features/windowPopup/model/types";
|
||||
|
||||
import { getFloodRiskGradeClassName } from "./flood-risk-grade";
|
||||
|
||||
const FLOOD_PREDICTION_GRID_LAYER_ID = "SN_FLDNG_PREDICTION_GRID_LABEL";
|
||||
const FLOOD_PREDICTION_LAYER_RETRY_LIMIT = 20;
|
||||
const FLOOD_PREDICTION_LAYER_RETRY_DELAY = 200;
|
||||
|
||||
/** 침수예측현황 행 선택 후 지도에 적용할 위치·행 식별 정보다. */
|
||||
type FloodPredictionSelection = {
|
||||
extent: [number, number, number, number];
|
||||
sggCd: string;
|
||||
frequency: string;
|
||||
analysisDateTime: string;
|
||||
};
|
||||
|
||||
/** 자동 레이어 선택 실패 시 안내를 돌려보낼 침수예측 팝업 정보다. */
|
||||
type FloodPredictionPopupContext = {
|
||||
source: Window | null;
|
||||
origin: string;
|
||||
};
|
||||
|
||||
type FloodPredictionFeature = {
|
||||
get?: (key: string) => unknown;
|
||||
getId?: () => string | number | undefined;
|
||||
};
|
||||
|
||||
type FloodPredictionSource = {
|
||||
getFeatures?: () => FloodPredictionFeature[];
|
||||
once?: (eventName: string, listener: () => void) => void;
|
||||
};
|
||||
|
||||
type FloodPredictionLayer = {
|
||||
get?: (key: string) => unknown;
|
||||
getVisible?: () => boolean;
|
||||
getSource?: () => FloodPredictionSource | null;
|
||||
};
|
||||
|
||||
type FloodPredictionMap = {
|
||||
addOverlay: (overlay: Overlay) => void;
|
||||
removeOverlay: (overlay: Overlay) => void;
|
||||
getLayers: () => { getArray: () => FloodPredictionLayer[] };
|
||||
getView: () => {
|
||||
fit: (
|
||||
extent: [number, number, number, number],
|
||||
options: {
|
||||
duration: number;
|
||||
padding: [number, number, number, number];
|
||||
maxZoom: number;
|
||||
},
|
||||
) => void;
|
||||
};
|
||||
};
|
||||
|
||||
type FloodPredictionOverlayRow = Record<string, unknown> & {
|
||||
analysisDateTime?: unknown;
|
||||
ctpvCd?: unknown;
|
||||
ctpvNm?: unknown;
|
||||
exceededFrequencyYear?: unknown;
|
||||
floodRiskGrade?: unknown;
|
||||
observedAccumulatedRainfall?: unknown;
|
||||
predictedAccumulatedRainfall?: unknown;
|
||||
predictionDateTime?: unknown;
|
||||
rainBeginningDateTime?: unknown;
|
||||
sggCd?: unknown;
|
||||
sggNm?: unknown;
|
||||
};
|
||||
|
||||
type FloodSelectionModule = {
|
||||
resetSelectedFeature?: () => void | Promise<void>;
|
||||
selectFocusedBoundaryFeature?: (
|
||||
feature: FloodPredictionFeature,
|
||||
append: boolean,
|
||||
) => void;
|
||||
};
|
||||
|
||||
type UseFloodPredictionMapOptions = {
|
||||
mapRef: { current: FloodPredictionMap | null };
|
||||
floodLayerType: string;
|
||||
onRequestFloodLayer: () => void;
|
||||
};
|
||||
|
||||
/** 침수예측 오버레이용 12자리 분석시각을 화면 표시 형식으로 변환한다. */
|
||||
const formatFloodPredictionDateTime = (value: unknown) => {
|
||||
const text = String(value ?? "").trim();
|
||||
return /^\d{12}$/.test(text)
|
||||
? `${text.slice(0, 4)}-${text.slice(4, 6)}-${text.slice(6, 8)} ${text.slice(8, 10)}:${text.slice(10, 12)}`
|
||||
: text || "-";
|
||||
};
|
||||
|
||||
/** 팝업 메시지 payload를 검증하여 지도 선택 정보로 변환한다. */
|
||||
const parseFloodPredictionSelection = (
|
||||
payload: unknown,
|
||||
): FloodPredictionSelection | null => {
|
||||
const message =
|
||||
payload && typeof payload === "object"
|
||||
? (payload as Record<string, unknown>)
|
||||
: {};
|
||||
const extent = Array.isArray(message.extent)
|
||||
? message.extent.map(Number)
|
||||
: [];
|
||||
const sggCd = String(message.sggCd ?? "").trim();
|
||||
const frequency = String(message.sbmrgFrqExpln ?? "").trim();
|
||||
const analysisDateTime = String(message.analysisDateTime ?? "").trim();
|
||||
|
||||
if (
|
||||
extent.length !== 4 ||
|
||||
extent.some((value: number) => !Number.isFinite(value)) ||
|
||||
!/^\d{5}$/.test(sggCd) ||
|
||||
!/^(030|050|080|100)$/.test(frequency)
|
||||
) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return {
|
||||
extent: extent as [number, number, number, number],
|
||||
sggCd,
|
||||
frequency,
|
||||
analysisDateTime,
|
||||
};
|
||||
};
|
||||
|
||||
/** 선택 행의 분석값을 표시할 지도 오버레이 DOM을 생성한다. */
|
||||
const createFloodPredictionOverlayElement = (
|
||||
row: FloodPredictionOverlayRow,
|
||||
analysisDateTime: string,
|
||||
onClose: () => void,
|
||||
) => {
|
||||
const observed = Number(row.observedAccumulatedRainfall ?? 0).toFixed(1);
|
||||
const predicted = Number(row.predictedAccumulatedRainfall ?? 0).toFixed(1);
|
||||
const container = document.createElement("div");
|
||||
container.style.cssText =
|
||||
"position:relative; background:rgba(255,255,255,.55); color:#111827; border:1px solid rgba(17,24,39,.7); box-shadow:0 2px 8px rgba(0,0,0,.2); padding:8px 10px; font:400 11px/1.35 sans-serif; width:230px;";
|
||||
|
||||
const close = document.createElement("button");
|
||||
close.type = "button";
|
||||
close.textContent = "×";
|
||||
close.title = "침수예측 오버레이 닫기";
|
||||
close.style.cssText =
|
||||
"position:absolute; right:3px; top:1px; border:0; background:transparent; color:#111827; font-size:16px; line-height:16px; cursor:pointer;";
|
||||
close.addEventListener("click", onClose);
|
||||
|
||||
const table = document.createElement("table");
|
||||
table.style.cssText =
|
||||
"border-collapse:collapse; table-layout:fixed; width:100%;";
|
||||
const colgroup = document.createElement("colgroup");
|
||||
const keyColumn = document.createElement("col");
|
||||
const valueColumn = document.createElement("col");
|
||||
keyColumn.style.width = "55%";
|
||||
valueColumn.style.width = "45%";
|
||||
colgroup.append(keyColumn, valueColumn);
|
||||
table.append(colgroup);
|
||||
|
||||
const title = table.createTHead().insertRow();
|
||||
const titleCell = title.insertCell();
|
||||
titleCell.colSpan = 2;
|
||||
titleCell.textContent = `${row.ctpvNm ?? row.ctpvCd ?? "-"} ${row.sggNm ?? row.sggCd ?? "-"} 침수예측`;
|
||||
titleCell.style.cssText =
|
||||
"font-weight:500; text-align:center; padding:2px 16px 6px 2px; border-bottom:1px solid #9ca3af;";
|
||||
|
||||
const body = table.createTBody();
|
||||
const overlayRows: Array<[string, string]> = [
|
||||
[
|
||||
"분석시각",
|
||||
formatFloodPredictionDateTime(row.analysisDateTime ?? analysisDateTime),
|
||||
],
|
||||
[
|
||||
"강우시작시각",
|
||||
formatFloodPredictionDateTime(row.rainBeginningDateTime),
|
||||
],
|
||||
["관측 누적강수량(mm)", observed],
|
||||
["예측시각", formatFloodPredictionDateTime(row.predictionDateTime)],
|
||||
["예측 누적강수량(mm)", predicted],
|
||||
["초과 빈도", `${row.exceededFrequencyYear ?? "-"}년`],
|
||||
["침수위험도", String(row.floodRiskGrade ?? "-")],
|
||||
];
|
||||
overlayRows.forEach(([label, value]) => {
|
||||
const tr = body.insertRow();
|
||||
const key = tr.insertCell();
|
||||
key.textContent = label;
|
||||
// 목록용 전역 말줄임 규칙이 지도 오버레이 셀에는 적용되지 않게 한다.
|
||||
key.setAttribute("data-sn-cell-wrap", "true");
|
||||
key.style.cssText =
|
||||
"font-weight:400; padding:2px 8px 2px 2px; white-space:nowrap; border-bottom:1px solid #e5e7eb;";
|
||||
|
||||
const val = tr.insertCell();
|
||||
val.setAttribute("data-sn-cell-wrap", "true");
|
||||
val.style.cssText =
|
||||
"font-weight:400; overflow:visible; text-overflow:clip; text-align:right; padding:2px 2px; white-space:nowrap; border-bottom:1px solid #e5e7eb;";
|
||||
if (label === "침수위험도") {
|
||||
// 침수예측현황 목록과 같은 배지 스타일로 등급을 표시한다.
|
||||
const badge = document.createElement("span");
|
||||
badge.textContent = value;
|
||||
badge.className = `sn-popup-badge min-w-[44px] ${getFloodRiskGradeClassName(String(value ?? ""))}`;
|
||||
val.append(badge);
|
||||
} else {
|
||||
val.textContent = value;
|
||||
}
|
||||
});
|
||||
|
||||
container.append(close, table);
|
||||
return container;
|
||||
};
|
||||
|
||||
/** 침수예측현황 팝업과 도시침수지도의 선택·이동·오버레이 흐름을 관리한다. */
|
||||
export const useFloodPredictionMap = ({
|
||||
mapRef,
|
||||
floodLayerType,
|
||||
onRequestFloodLayer,
|
||||
}: UseFloodPredictionMapOptions) => {
|
||||
// 자동 레이어 선택이 완료된 뒤 다시 적용할 침수예측 행을 보관한다.
|
||||
const [pendingSelection, setPendingSelection] =
|
||||
useState<FloodPredictionSelection | null>(null);
|
||||
// 팝업 Window 객체는 렌더링 대상이 아니므로 자동 선택 실패 안내용 ref로 보관한다.
|
||||
const pendingPopupRef = useRef<FloodPredictionPopupContext | null>(null);
|
||||
// 행을 다시 선택할 때 기존 오버레이를 제거할 수 있도록 OpenLayers 객체를 ref로 보관한다.
|
||||
const overlayRef = useRef<Overlay | null>(null);
|
||||
|
||||
/** 기존 침수예측 중앙 오버레이를 제거한다. */
|
||||
const removeFloodPredictionOverlay = useCallback(() => {
|
||||
const core = GisApp.Module.core as unknown as
|
||||
| { deleteLayer?: (layerId: string) => void }
|
||||
| undefined;
|
||||
core?.deleteLayer?.(FLOOD_PREDICTION_GRID_LAYER_ID);
|
||||
const map = mapRef.current;
|
||||
if (map && overlayRef.current) {
|
||||
map.removeOverlay(overlayRef.current);
|
||||
}
|
||||
overlayRef.current = null;
|
||||
}, [mapRef]);
|
||||
|
||||
/** 선택행의 시군구·분석시각으로 도시침수지도 중앙 오버레이를 표시한다. */
|
||||
const loadFloodPredictionOverlay = useCallback(
|
||||
async (selection: FloodPredictionSelection) => {
|
||||
const { sggCd, analysisDateTime, extent } = selection;
|
||||
const map = mapRef.current;
|
||||
if (!map || !/^\d{12}$/.test(analysisDateTime)) return;
|
||||
removeFloodPredictionOverlay();
|
||||
|
||||
try {
|
||||
const response = await getRawJson(
|
||||
`/sewerage-service/api/v1/fldng/predc/prst/gridMap?sggCd=${encodeURIComponent(sggCd)}&analysisDateTime=${encodeURIComponent(analysisDateTime)}`,
|
||||
);
|
||||
const payload = response?.data ?? response;
|
||||
const row =
|
||||
payload && typeof payload === "object" && !Array.isArray(payload)
|
||||
? (payload as FloodPredictionOverlayRow)
|
||||
: null;
|
||||
if (!row) return;
|
||||
|
||||
const center = [
|
||||
(extent[0] + extent[2]) / 2,
|
||||
(extent[1] + extent[3]) / 2,
|
||||
];
|
||||
const overlay = new Overlay({
|
||||
element: createFloodPredictionOverlayElement(
|
||||
row,
|
||||
analysisDateTime,
|
||||
removeFloodPredictionOverlay,
|
||||
),
|
||||
positioning: "center-center",
|
||||
stopEvent: true,
|
||||
});
|
||||
overlay.set("id", FLOOD_PREDICTION_GRID_LAYER_ID);
|
||||
overlay.setPosition(center);
|
||||
map.addOverlay(overlay);
|
||||
overlayRef.current = overlay;
|
||||
} catch (error) {
|
||||
console.error("침수예측지도 오버레이 표시 실패:", error);
|
||||
}
|
||||
},
|
||||
[mapRef, removeFloodPredictionOverlay],
|
||||
);
|
||||
|
||||
/** 활성화된 도시침수지도에서 선택 행의 시군구·빈도 피처를 선택하고 지도와 오버레이를 이동한다. */
|
||||
const applyFloodPredictionSelection = useCallback(
|
||||
async (selection: FloodPredictionSelection) => {
|
||||
const map = mapRef.current;
|
||||
const select = GisApp.Module.select as unknown as
|
||||
| FloodSelectionModule
|
||||
| undefined;
|
||||
const selectFocusedBoundaryFeature =
|
||||
select?.selectFocusedBoundaryFeature;
|
||||
if (!map || !selectFocusedBoundaryFeature) return false;
|
||||
|
||||
const floodLayers = map
|
||||
.getLayers()
|
||||
.getArray()
|
||||
.filter(
|
||||
(layer) =>
|
||||
String(layer.get?.("lyrTyNm") ?? "").trim() === floodLayerType &&
|
||||
layer.getVisible?.() !== false,
|
||||
);
|
||||
if (floodLayers.length === 0) return false;
|
||||
|
||||
await select.resetSelectedFeature?.();
|
||||
const selectedFeatureIds = new Set<string>();
|
||||
/** 현재 로드된 동일 시군구·빈도 피처를 중복 없이 선택한다. */
|
||||
const selectLoadedGroupFeatures = (source: FloodPredictionSource) => {
|
||||
const features = source?.getFeatures?.() ?? [];
|
||||
features.forEach((feature) => {
|
||||
const featureSggCd = String(feature.get?.("sgg_cd") ?? "").trim();
|
||||
const featureFrequency = String(
|
||||
feature.get?.("sbmrg_frq_expln") ?? "",
|
||||
).trim();
|
||||
if (
|
||||
featureSggCd !== selection.sggCd ||
|
||||
featureFrequency !== selection.frequency
|
||||
) {
|
||||
return;
|
||||
}
|
||||
|
||||
const featureId = String(
|
||||
feature.getId?.() ?? feature.get?.("fid") ?? "",
|
||||
);
|
||||
if (featureId && selectedFeatureIds.has(featureId)) return;
|
||||
if (featureId) selectedFeatureIds.add(featureId);
|
||||
selectFocusedBoundaryFeature(feature, true);
|
||||
});
|
||||
};
|
||||
|
||||
floodLayers.forEach((layer) => {
|
||||
const source = layer.getSource?.();
|
||||
if (!source?.getFeatures) return;
|
||||
selectLoadedGroupFeatures(source);
|
||||
source.once?.("featuresloadend", () =>
|
||||
selectLoadedGroupFeatures(source),
|
||||
);
|
||||
});
|
||||
map.getView().fit(selection.extent, {
|
||||
duration: 300,
|
||||
padding: [50, 50, 50, 50],
|
||||
maxZoom: 16,
|
||||
});
|
||||
void loadFloodPredictionOverlay(selection);
|
||||
return true;
|
||||
},
|
||||
[floodLayerType, loadFloodPredictionOverlay, mapRef],
|
||||
);
|
||||
|
||||
/** 침수예측현황 행 선택 메시지를 검증하고, 필요하면 도시침수지도 레이어 활성화를 요청한다. */
|
||||
const handleFloodPredictionPopupSelection = useCallback(
|
||||
async (payload: unknown, popupContext: FloodPredictionPopupContext) => {
|
||||
const selection = parseFloodPredictionSelection(payload);
|
||||
if (!selection) return;
|
||||
if (await applyFloodPredictionSelection(selection)) return;
|
||||
|
||||
pendingPopupRef.current = popupContext;
|
||||
setPendingSelection(selection);
|
||||
onRequestFloodLayer();
|
||||
},
|
||||
[applyFloodPredictionSelection, onRequestFloodLayer],
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
if (!pendingSelection) return;
|
||||
|
||||
let retryTimer: number | null = null;
|
||||
let retryCount = 0;
|
||||
|
||||
/** 자동 체크 요청으로 도시침수지도 레이어가 생성될 때까지 선택 행 적용을 제한적으로 재시도한다. */
|
||||
const applyPendingSelection = async () => {
|
||||
if (await applyFloodPredictionSelection(pendingSelection)) {
|
||||
setPendingSelection((current) =>
|
||||
current === pendingSelection ? null : current,
|
||||
);
|
||||
pendingPopupRef.current = null;
|
||||
return;
|
||||
}
|
||||
|
||||
retryCount += 1;
|
||||
if (retryCount >= FLOOD_PREDICTION_LAYER_RETRY_LIMIT) {
|
||||
const popup = pendingPopupRef.current;
|
||||
popup?.source?.postMessage(
|
||||
{ type: WINDOW_POPUP_MESSAGE_TYPE.MAP_SEARCH_FLOOD_LAYER_REQUIRED },
|
||||
popup.origin,
|
||||
);
|
||||
pendingPopupRef.current = null;
|
||||
setPendingSelection((current) =>
|
||||
current === pendingSelection ? null : current,
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
retryTimer = window.setTimeout(() => {
|
||||
void applyPendingSelection();
|
||||
}, FLOOD_PREDICTION_LAYER_RETRY_DELAY);
|
||||
};
|
||||
|
||||
void applyPendingSelection();
|
||||
return () => {
|
||||
if (retryTimer !== null) window.clearTimeout(retryTimer);
|
||||
};
|
||||
}, [applyFloodPredictionSelection, pendingSelection]);
|
||||
|
||||
return { handleFloodPredictionPopupSelection };
|
||||
};
|
||||
@@ -19,6 +19,7 @@ import { useAlertStore } from "@/shared/lib";
|
||||
import useStore from "@/store/useStore";
|
||||
import { fetchAllPages } from "@/shared/lib/fetch-all-pages";
|
||||
import { downloadFloodPredictionStatusExcel } from "../lib/fldng-predc-prst-excel";
|
||||
import { getFloodRiskGradeClassName } from "../lib/flood-risk-grade";
|
||||
|
||||
type ApiRow = {
|
||||
sggCd: string;
|
||||
@@ -189,23 +190,6 @@ const validateFilters = (filters: Filters) => {
|
||||
const buildRowId = (row: ApiRow) =>
|
||||
`${row.ctpvCd}:${row.sggCd}:${row.rainBeginningDateTime}:${row.analysisDateTime}:${row.predictionHour}`;
|
||||
|
||||
/** 침수위험도 등급을 목록 배지의 고정 의미색으로 변환한다. */
|
||||
export const getFloodRiskGradeClassName = (value: string) => {
|
||||
const grade = String(value ?? "")
|
||||
.trim()
|
||||
.toUpperCase();
|
||||
if (grade.includes("위험") || grade === "DANGER") {
|
||||
return "bg-[#dc2626] text-white";
|
||||
}
|
||||
if (grade.includes("경계") || grade === "WARNING") {
|
||||
return "bg-[#f97316] text-white";
|
||||
}
|
||||
if (grade.includes("주의") || grade === "CAUTION") {
|
||||
return "bg-[#facc15] text-[#713f12]";
|
||||
}
|
||||
return "sn-popup-badge-normal";
|
||||
};
|
||||
|
||||
export default function FldngPredcPrstPopupContent() {
|
||||
const alert = useAlertStore((state) => state.setMessage);
|
||||
const { ctpv, sgg, fetchCtpv, fetchSgg } = useStore();
|
||||
|
||||
Reference in New Issue
Block a user