224 lines
8.2 KiB
JavaScript
224 lines
8.2 KiB
JavaScript
// Overlay manager (no React here)
|
|
import Overlay from 'ol/Overlay';
|
|
import { getFeatureLabelCoordinate } from '../map/lib/util';
|
|
import { buildCoordinateKeyFactory } from '../map/lib/util';
|
|
|
|
// ---- main factory ----
|
|
export default function createOverlayManager(map, vectorLayer, overlayFormatter, options = {}) {
|
|
const coordPrecision = Math.max(0, Math.min(12, Number.isFinite(options.coordPrecision) ? options.coordPrecision : 6));
|
|
const maxOverlaysPerViewport = Number.isFinite(options.maxOverlaysPerViewport) ? options.maxOverlaysPerViewport : Infinity;
|
|
const getCoordinateKey = buildCoordinateKeyFactory(coordPrecision);
|
|
|
|
let currentFormatter = overlayFormatter;
|
|
const overlayMap = new Map(); // feature -> Overlay
|
|
const overlayElementMap = new Map(); // feature -> HTMLElement
|
|
const vectorSource = vectorLayer?.getSource?.();
|
|
|
|
const SYNC_MIN_INTERVAL = 120;
|
|
let lastSyncAt = 0;
|
|
|
|
let isMounted = false;
|
|
let isActive = false; // when false, event handlers no-op
|
|
let rafId = null;
|
|
let idleClearId = null;
|
|
|
|
|
|
|
|
const clearAllOverlaysAsync = (batch = 150) => {
|
|
const features = Array.from(overlayMap.keys());
|
|
if (!features.length) return;
|
|
|
|
// 재귀로 사용하는 이유 한번에 다지운는ㄴ것이아닌 150개 이상 더있을경우를 대비해서 다시 호출하기 위해(지도가 계속 멈춤)
|
|
const step = () => {
|
|
let iNum = 0;
|
|
const end = Math.min(iNum + batch, features.length);
|
|
for (; iNum < end; iNum++) {
|
|
const feat = features[iNum];
|
|
const ov = overlayMap.get(feat);
|
|
try { if (ov) map.removeOverlay(ov); } catch {}
|
|
overlayMap.delete(feat);
|
|
const el = overlayElementMap.get(feat);
|
|
if (el) { try { el.remove?.(); } catch {} overlayElementMap.delete(feat); }
|
|
}
|
|
if (iNum < features.length) {
|
|
(typeof requestAnimationFrame === 'function' ? requestAnimationFrame : setTimeout)(step, 0);
|
|
}
|
|
};
|
|
|
|
step();
|
|
};
|
|
|
|
const scheduleSync = () => {
|
|
if (!isActive) return;
|
|
const now = Date.now();
|
|
const since = now - lastSyncAt;
|
|
const run = () => {
|
|
if (rafId) cancelAnimationFrame(rafId);
|
|
rafId = requestAnimationFrame(() => {
|
|
try { syncOverlays(); } finally { lastSyncAt = Date.now(); }
|
|
});
|
|
};
|
|
if (since >= SYNC_MIN_INTERVAL) run(); else run();
|
|
};
|
|
|
|
const onVisibleChange = () => { if (!isActive) return; scheduleSync(); };
|
|
const onAddFeature = () => { if (!isActive) return; scheduleSync(); };
|
|
const onChangeFeature = () => { if (!isActive) return; scheduleSync(); };
|
|
const onRemoveFeature = () => { if (!isActive) return; scheduleSync(); };
|
|
|
|
const clearAllOverlays = () => {
|
|
overlayMap.forEach((ov) => { try { map.removeOverlay(ov); } catch {} });
|
|
overlayMap.clear();
|
|
overlayElementMap.clear();
|
|
};
|
|
|
|
const ensureOverlay = (feature, properties) => {
|
|
const coord = getFeatureLabelCoordinate(feature);
|
|
if (!Array.isArray(coord)) return null;
|
|
|
|
let el = overlayElementMap.get(feature);
|
|
if (!el) {
|
|
if (!currentFormatter || typeof currentFormatter !== 'function') return null;
|
|
|
|
const maybeEl = currentFormatter(feature, properties);
|
|
|
|
// 1) 동기 HTMLElement
|
|
if (maybeEl && typeof maybeEl === 'object' && (maybeEl.nodeType === 1 || maybeEl.tagName)) {
|
|
el = maybeEl;
|
|
overlayElementMap.set(feature, el);
|
|
}
|
|
// 2) 비동기 Promise<HTMLDivElement|null>
|
|
else if (maybeEl && typeof maybeEl.then === 'function') {
|
|
maybeEl.then((resolvedEl) => {
|
|
if (!resolvedEl || !(resolvedEl.nodeType === 1 || resolvedEl.tagName)) return;
|
|
// 이미 다른 사이클에서 만들어졌으면 덮어쓰지 않음
|
|
if (!overlayElementMap.has(feature)) overlayElementMap.set(feature, resolvedEl);
|
|
|
|
let ov = overlayMap.get(feature);
|
|
if (!ov) {
|
|
ov = new Overlay({ element: resolvedEl, positioning: 'bottom-center', offset: [0, -18], stopEvent: true });
|
|
overlayMap.set(feature, ov);
|
|
try { map.addOverlay(ov); } catch {}
|
|
} else {
|
|
try { ov.setElement(resolvedEl); } catch {}
|
|
}
|
|
ov.setPosition(coord);
|
|
if (resolvedEl.style) resolvedEl.style.display = 'block';
|
|
}).catch(() => {});
|
|
return null; // 지금은 안 만듦
|
|
}
|
|
// 3) 그 외(null/undefined 등) → 안 만듦
|
|
else {
|
|
return null;
|
|
}
|
|
}
|
|
|
|
// 여기까지 왔으면 el은 HTMLElement
|
|
let ov = overlayMap.get(feature);
|
|
if (!ov) {
|
|
ov = new Overlay({ element: el, positioning: 'bottom-center', offset: [0, -18], stopEvent: true });
|
|
overlayMap.set(feature, ov);
|
|
map.addOverlay(ov);
|
|
}
|
|
ov.setPosition(coord);
|
|
if (el.style) el.style.display = 'block';
|
|
return ov;
|
|
};
|
|
|
|
const syncOverlays = () => {
|
|
if (!vectorLayer?.getVisible?.()) { clearAllOverlays(); return; }
|
|
const view = map.getView?.();
|
|
const size = map.getSize?.();
|
|
const viewExtent = view && size ? view.calculateExtent(size) : null;
|
|
|
|
const features = [];
|
|
const pushFeature = (f) => features.push(f);
|
|
if (vectorSource?.forEachFeatureInExtent && viewExtent) {
|
|
vectorSource.forEachFeatureInExtent(viewExtent, pushFeature);
|
|
} else {
|
|
vectorSource?.forEachFeature(pushFeature);
|
|
}
|
|
|
|
let selected = features;
|
|
if (isFinite(maxOverlaysPerViewport) && features.length > maxOverlaysPerViewport) {
|
|
const step = Math.ceil(features.length / maxOverlaysPerViewport);
|
|
selected = [];
|
|
for (let i = 0; i < features.length && selected.length < maxOverlaysPerViewport; i += step) {
|
|
selected.push(features[i]);
|
|
}
|
|
}
|
|
|
|
for (const f of selected) {
|
|
const props = f.getProperties?.() ?? {};
|
|
ensureOverlay(f, props);
|
|
}
|
|
|
|
const keep = new Set(selected);
|
|
for (const [feat, ov] of overlayMap.entries()) {
|
|
if (!keep.has(feat)) {
|
|
try { map.removeOverlay(ov); } catch {}
|
|
overlayMap.delete(feat);
|
|
const el = overlayElementMap.get(feat);
|
|
if (el) { try { el.remove?.(); } catch {} overlayElementMap.delete(feat); }
|
|
}
|
|
}
|
|
};
|
|
|
|
const mount = () => {
|
|
if (isMounted) return;
|
|
vectorLayer?.on?.('change:visible', onVisibleChange);
|
|
vectorSource?.on?.('addfeature', onAddFeature);
|
|
vectorSource?.on?.('changefeature', onChangeFeature);
|
|
vectorSource?.on?.('removefeature', onRemoveFeature);
|
|
isMounted = true;
|
|
};
|
|
|
|
// Backward-compat: make dispose lightweight so it doesn't freeze the map
|
|
const dispose = () => {
|
|
isActive = false; // pause reactions
|
|
setVisible(false); // hide our labels only
|
|
const run = () => { clearAllOverlaysAsync(150); idleClearId = null; };
|
|
if (typeof requestIdleCallback === 'function') idleClearId = requestIdleCallback(run, { timeout: 250 });
|
|
else idleClearId = setTimeout(run, 180);
|
|
};
|
|
|
|
// Explicit lifecycle controls
|
|
const enable = () => {
|
|
isActive = true;
|
|
setVisible(true);
|
|
scheduleSync();
|
|
};
|
|
|
|
const disable = ({ clear = false, delayed = true } = {}) => {
|
|
isActive = false;
|
|
setVisible(false);
|
|
if (clear) {
|
|
const run = () => { clearAllOverlaysAsync(150); idleClearId = null; };
|
|
if (delayed && typeof requestIdleCallback === 'function') idleClearId = requestIdleCallback(run, { timeout: 250 });
|
|
else idleClearId = setTimeout(run, delayed ? 180 : 0);
|
|
}
|
|
};
|
|
|
|
const destroy = () => {
|
|
if (!isMounted) return;
|
|
vectorLayer?.un?.('change:visible', onVisibleChange);
|
|
vectorSource?.un?.('addfeature', onAddFeature);
|
|
vectorSource?.un?.('changefeature', onChangeFeature);
|
|
vectorSource?.un?.('removefeature', onRemoveFeature);
|
|
isMounted = false;
|
|
if (rafId) cancelAnimationFrame(rafId), rafId = null;
|
|
if (idleClearId) { (typeof cancelIdleCallback === 'function' ? cancelIdleCallback : clearTimeout)(idleClearId); idleClearId = null; }
|
|
clearAllOverlaysAsync(200);
|
|
};
|
|
|
|
const setFormatter = (nextFormatter) => { currentFormatter = nextFormatter; syncOverlays(); };
|
|
|
|
const setVisible = (visible) => {
|
|
const display = visible ? 'block' : 'none';
|
|
for (const el of overlayElementMap.values()) {
|
|
try { if (el && el.style) el.style.display = display; } catch {}
|
|
}
|
|
};
|
|
|
|
return { mount, dispose, enable, disable, destroy, setFormatter, syncOverlays, setVisible };
|
|
} |