Compare commits

...

47 커밋

작성자 SHA1 메시지 날짜
c23264c3ba Merge pull request 'feature/dual-rendering' (#12) from feature/dual-rendering into develop 2026-02-16 16:26:10 +09:00
c423b59244 Merge remote-tracking branch 'origin/develop' into feature/dual-rendering
# Conflicts:
#	apps/web/src/pages/dashboard/DashboardPage.tsx
2026-02-16 16:25:38 +09:00
fe5ec7100b docs: CLAUDE.md 최신 구조 반영
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-16 16:24:52 +09:00
c03dee0ade fix(map): globe 노란벽 해결 + 심해색 복구
- deck-globe 렌더 파이프라인 비활성화로 노란벽 해소
- 베이스 수색 원복 (#14606e/#114f5c)
- globe 필터 로직 제거 (불필요)

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-16 16:04:58 +09:00
1fd9f3da82 fix(map): fill 단일화 + globe 배경색 심해색 통일
- fill 3-tier 제거 → 단일 레이어(전체 depth) 복원
- setSky: sky/horizon/fog를 심해색(#010610)으로 설정
- 캔버스/map-area 배경: #010610 (타일 gap seam 비가시화)
- 타일 경계 gap으로 배경이 비칠 때 색상 차이를 제거

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-16 15:34:49 +09:00
3a001ca9b6 fix(map): fill 3-tier LOD로 타일 seam 해결
- 심해 fill 폴리곤이 globe 타일 경계에서 seam 아티팩트 발생
- bathymetry-fill: z3-7 (depth >= -2000, 천해만)
- bathymetry-fill-medium: z7-9 (depth >= -4000)
- bathymetry-fill-deep: z9+ (전체 depth)
- applyDepthGradient: 3개 fill 레이어 모두 적용

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-16 15:28:23 +09:00
2095503e50 fix(map): 심해 등심선 복원 + 전체 depth LOD
- shallowFilter 제거: 전체 depth 범위 렌더링 복원
- bathyFillColor: -8000m, -4000m 색상 stop 복원
- DEPTHS_MEDIUM: -4000m 추가 (z7-9)
- DEPTHS_DETAIL: -4000m, -8000m 추가 (z9+)
- 줌 기반 LOD가 vertex 제어 담당 (depth 필터 불필요)

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-16 15:21:46 +09:00
f50c227fd4 fix(map): globe 모드 수역 fill/text 복구
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-16 15:15:45 +09:00
b022e4bc36 perf(map): 줌 기반 LOD + 심해 등심선 제거
- applyLandLayerLOD: 베이스맵 육지 레이어에 minzoom 적용
  (landcover z9, transportation z8, building z14 등)
- 수심 3-tier LOD: coarse(z3-7), medium(z7-9), detail(z9+)
- shallowFilter: depth >= -2000, 심해 feature GPU 미전달
- applyDepthGradient ascending order 에러 수정
- vertex 경고 passthrough (디버깅용 유지)

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-16 15:15:31 +09:00
d5700ba587 fix(map): zone 간소화를 projectionBusy 앞으로 이동
소스 데이터 간소화가 projectionBusy 가드 뒤에 있어서
globe 전환 시 원본 데이터(2100+ vertex)로 tessellation 진행 →
73,000+ vertex 폭증. setData를 가드 앞으로 이동하고
useMemo로 간소화 데이터 캐싱.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-16 13:59:21 +09:00
7bec1ae86d fix(map): globe 수역 line vertex 초과 해결
zones-line도 globe tessellation에서 73,300+ vertex로 폭증.
globe 모드에서 수역 소스 데이터를 ring당 60점으로 서브샘플링.
원본 2100+ vertex → ~240 vertex → globe tessellation 후 65535 이내.
mercator 모드에서는 원본 데이터 유지.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-16 13:44:26 +09:00
99d714582b fix(map): globe 모드 zones-fill 숨김 + 라벨 가드
- globe tessellation에서 수역 fill polygon vertex 65535 초과
  (해안선 2100 vertex → globe에서 108890+로 폭증) → 노란 막대
- globe 모드에서 zones-fill visibility: none으로 설정
- guardedSetVisibility 적용으로 수역 라벨 사라짐 방지

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-16 13:38:37 +09:00
95d9ea8aef fix(map): 라벨 사라짐 + easing 경고 + vertex 경고 수정
- guardedSetVisibility 도입: 현재 값과 동일하면 setLayoutProperty
  호출 생략하여 style._changed 트리거 방지 → symbol 재배치로 인한
  text-allow-overlap:false 라벨 사라짐 현상 해결
- useGlobeShips 기존 레이어 else 블록의 중복 expression 재설정 제거
  (data-driven 표현식은 addLayer 시 1회 설정으로 충분)
- _render 래퍼에서 globe scrollZoom easing 경고 억제
- fleet-circles-ml-fill 레이어 완전 제거 (vertex 65535 초과 원인)

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-16 13:34:42 +09:00
91df90b528 perf(map): Globe/Mercator 양방향 동시 렌더링
- overlay 파괴/재생성 대신 layers 비움으로 전환
- globe ship 레이어 visibility 즉시 토글 (projectionBusy 우회)
- fleet circles fill vertex 초과 수정 (steps 72→36/24)
- globe scrollZoom easing 경고 수정
- projection 비영속화 (항상 mercator 시작)
- globe 레이어 준비 전까지 3D 토글 비활성화

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-16 13:08:54 +09:00
4cf0f20504 Merge branch 'feature/globe-ship-precompute' into develop 2026-02-16 12:26:47 +09:00
d88c89403d perf(map): globe 선박 렌더링 사전계산 최적화
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-16 12:26:42 +09:00
77e3a531e8 Merge branch 'feature/chnprmship-polling' into develop 2026-02-16 12:23:23 +09:00
39d9cc9db1 feat(ais): 초기 로드를 chnprmship API로 전환
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-16 12:23:18 +09:00
8dc216ae1c Merge branch 'feature/persist-user-state' into develop 2026-02-16 12:18:46 +09:00
16ebf3abca feat: 사용자 설정 영속화 + 지도 뷰 저장
usePersistedState hook으로 대시보드 상태를
localStorage에 자동 저장. 지도 뷰(중심/줌/방위)도
60초 주기 + 언마운트 시 저장하여 새로고침 복원.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-16 12:18:39 +09:00
bd3b3f9a8c Merge branch 'feature/kst-timestamp' into develop 2026-02-16 12:12:50 +09:00
cc807bb5f6 feat: KST 타임스탬프 포맷 유틸 적용
shared/lib/datetime.ts에 KST 고정 포맷 함수 추가.
AIS 정보, 선박 목록, 대시보드 등의 날짜 표시를
로컬 포맷에서 KST 명시적 포맷으로 통일.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-16 12:12:43 +09:00
ca43bbcebb Merge pull request 'feat(auth): Google OAuth 로그인 구현' (#7) from feature/auth-login into develop 2026-02-16 08:48:24 +09:00
20db4cb0cf style(auth): 로그인 페이지 UI 조정
- 로고: WING → GC WING + demo 라벨
- 하단: GC Surveillance → GC SI Team

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-16 08:47:50 +09:00
79b21c7d44 feat(auth): Google OAuth 로그인 구현
- shared/auth 모듈: AuthProvider, ProtectedRoute, useAuth, authApi
- 페이지: LoginPage(Google OAuth), PendingPage, DeniedPage
- WING_PERMIT 역할 기반 접근 제어
- Topbar에 사용자 이름 + 로그아웃 버튼 추가
- App.tsx에 react-router 라우팅 + AuthProvider 래핑
- DEV 모드 Mock 로그인 지원 (김개발)

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-16 08:44:25 +09:00
22099862e6 Merge pull request 'ci: 빌드 시 MapTiler API 키 환경변수 전달' (#5) from ci/actions-trigger into develop 2026-02-16 07:52:35 +09:00
705cc696f9 ci: 빌드 시 MapTiler API 키 환경변수 전달
프로덕션 빌드에서 VITE_MAPTILER_KEY가 누락되어
OSM 폴백 스타일로 로드되던 문제 해결

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-16 07:50:17 +09:00
fd3cedc6c1 Merge pull request 'ci: Actions 활성화 후 CI/CD 트리거 확인' (#3) from ci/actions-trigger into develop 2026-02-16 07:39:45 +09:00
ec83ce8ea0 ci: Actions 활성화 후 CI/CD 트리거 확인
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-16 07:39:15 +09:00
aeb57e9bb8 Merge pull request 'ci: Gitea Actions CI/CD 파이프라인 + 기능 업데이트' (#2) from develop into main 2026-02-16 07:35:54 +09:00
fb8d65f83f Merge pull request 'ci: Gitea Actions 자동 빌드/배포 워크플로우 추가' (#1) from codex/subcables-static into develop 2026-02-16 07:16:46 +09:00
9fd0567ccf ci: Gitea Actions 자동 빌드/배포 워크플로우 추가
main push 시 모노레포 @wing/web 빌드 후 wing.gc-si.dev에 자동 배포

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-16 07:06:41 +09:00
3acda7432e refactor(map): UI 개선 — 3D 명칭, 수심 줌, 레거시 비활성
- "지구본" → "3D" 명칭 변경, 헤더 우측으로 이동
- 레거시 베이스맵 비활성 (주석처리)
- 수심 minzoom 통일: fill 3, borders 5, major 3
- NavigationControl 통합, 기어 버튼 겹침 수정
- constants.ts 미사용 BATHY_ZOOM_RANGES 제거

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-16 07:04:31 +09:00
d2178a6134 fix(map): 육지색 적용에서 수역/선박 등 커스텀 레이어 제외
zones, ships, pair, fc, fleet, predict, deck-globe 레이어를
applyLandColor에서 제외하여 수역 표시 복원

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-16 06:27:48 +09:00
1a3dd82eb4 fix(map): 지도 설정 패널 개선
- 육지색 적용 범위 확대 (background + 전체 fill 레이어)
- UI 가독성 개선: 라벨 10px, 색상 대비 강화
- 수심 구간 '자동채우기' 토글 추가 (최소/최대 기준 보간)

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-16 06:23:55 +09:00
650888adb7 feat(map): 지도 설정 패널 + 수심 범례 구현
- 나침반/줌 컨트롤 분리, 기어 버튼으로 설정 패널 토글
- 설정 항목: 레이블 언어, 육지/물/수심 색상, 수심 폰트 크기/색상
- 런타임 map.setPaintProperty/setLayoutProperty로 즉시 적용
- 수심 색상 범례 (좌하단 그라데이션 바 + 눈금)
- 초기화 버튼으로 디폴트 복원

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-16 06:17:20 +09:00
4c257a2883 fix(map): 수심 레이블이 한글 변환에 의해 덮어쓰이는 버그 수정
applyKoreanLabels를 injectOceanBathymetryLayers보다 먼저 호출하여
수심 text-field가 보존되도록 순서 변경

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-16 05:57:22 +09:00
289f1bebc0 feat(map): 수심 레이블 개선 + 한글 지명 적용
- 수심 레이블: minzoom 10→7, 텍스트 크기 확대, halo 가독성 개선
- 해저 지형명: minzoom 8→6, 텍스트 크기 확대
- MapTiler 베이스맵 한글 지명 적용 (name:ko fallback)

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-16 05:47:16 +09:00
f5ef24c02f perf(map): 해저케이블 렌더링 최적화
- GeoJSON source tolerance:1, buffer:64 (저줌 vertex 단순화)
- hitarea/casing/glow 레이어 minzoom:3 (저줌 렌더 제외)
- ensureGeoJsonSource에 source options 파라미터 추가
- NativeSourceConfig에 options 필드 추가

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-16 05:28:44 +09:00
a16ccc9a01 feat(map): 통합 레이어 모듈 구현
- useNativeMapLayers 범용 hook 생성
  - source/layer 생성, visibility, cleanup 자동화
  - projectionBusy/isStyleLoaded 가드 내장
  - Globe 레이어 순서 관리 내장
  - beforeLayer 후보 배열 지원
- useSubcablesLayer를 useNativeMapLayers로 전환
- React Compiler ref 접근 규칙 준수 (useEffect 내 할당)

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-16 05:21:53 +09:00
fb1334ce45 fix(map): 해저케이블 호버/프로젝션 버그
- useEffect 3개 분리 (레이어생성/호버/이벤트)
- hoveredCableId를 레이어 생성 deps에서 분리하여 깜박임 제거
- 이벤트 바인딩에 retry 로직 추가 (프로젝션 전환 후)
- paint 기본값을 상수로 추출하여 일관성 보장

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-16 02:36:20 +09:00
7eff97afd4 fix(map): 해저케이블 시인성 개선
- MapLibre 중첩 interpolate 표현식 에러 수정
- 6레이어 구조: hitarea, casing, line, glow, points, label
- 호버 시 flat value 사용 (case 내 interpolate 제거)
- Globe/Mercator 양쪽 프로젝션 레이어 순서 지원
- 진한 색상, 굵은 라인, 포인트 마커로 시인성 향상

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-16 02:28:11 +09:00
ca5560aff2 feat(map): 해저케이블 레이어 및 정보 패널 구현
- subcable entity 생성 (타입 정의 + 데이터 로딩 hook)
- MapLibre 레이어: 케이블 라인 + 호버 하이라이트 + 라벨
- 지도 표시 설정에 해저케이블 토글 추가
- 클릭 시 우측 정보 패널 (길이, 개통, 운영사, landing points)
- Map3D + DashboardPage 통합

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-16 02:17:58 +09:00
621a5037c2 chore(data): vendor submarine cable geojson/details 2026-02-16 02:17:55 +09:00
3ba6c02ba0 feat(map): 선박 외곽선 대비 및 줌 스케일링 개선 2026-02-16 01:10:45 +09:00
864fc44d0e refactor(map): Map3D.tsx hooks 추출 완료 (4558줄 → 510줄) 2026-02-16 00:41:11 +09:00
324c6267f0 refactor(map): Map3D 모듈 분리 및 버그 수정 2026-02-15 23:57:38 +09:00
69개의 변경된 파일7974개의 추가작업 그리고 5539개의 파일을 삭제

파일 보기

@ -0,0 +1,41 @@
name: Build and Deploy Wing
on:
push:
branches:
- main
jobs:
build-and-deploy:
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v4
- name: Setup Node.js
uses: actions/setup-node@v4
with:
node-version: '24'
- name: Configure npm registry
run: |
echo "registry=https://nexus.gc-si.dev/repository/npm-public/" > .npmrc
echo "//nexus.gc-si.dev/repository/npm-public/:_auth=${{ secrets.NEXUS_NPM_AUTH }}" >> .npmrc
- name: Install dependencies
run: npm ci
- name: Build web
env:
VITE_MAPTILER_KEY: ${{ secrets.MAPTILER_KEY }}
VITE_MAPTILER_BASE_MAP_ID: dataviz-dark
VITE_AUTH_API_URL: https://guide.gc-si.dev
VITE_GOOGLE_CLIENT_ID: ${{ secrets.GOOGLE_CLIENT_ID }}
run: npm -w @wing/web run build
- name: Deploy to server
run: |
rm -rf /deploy/wing/*
cp -r apps/web/dist/* /deploy/wing/
echo "Deployed at $(date '+%Y-%m-%d %H:%M:%S')"
ls -la /deploy/wing/

파일 보기

@ -2,34 +2,22 @@
## 프로젝트 개요
- **타입**: React + TypeScript + Vite (모노레포)
- **타입**: React 19 + TypeScript 5.9 + Vite 7 (모노레포)
- **Node.js**: `.node-version` 참조 (v24)
- **패키지 매니저**: npm (workspaces)
- **구조**: apps/web (프론트엔드) + apps/api (백엔드 API)
- **구조**: apps/web (프론트엔드) + apps/api (백엔드 API 프록시)
## 빌드 및 실행
```bash
# 의존성 설치
npm install
# 전체 개발 서버
npm run dev
# 개별 개발 서버
npm run dev:web # 프론트엔드 (Vite)
npm run dev:api # 백엔드 (Fastify + tsx watch)
# 빌드
npm run build # 전체 빌드 (web + api)
npm run build:web # 프론트엔드만
npm run build:api # 백엔드만
# 린트
npm run lint # apps/web ESLint
# 데이터 준비
npm run prepare:data
npm install # 의존성 설치
npm run dev # 전체 개발 서버
npm run dev:web # 프론트엔드 (Vite)
npm run dev:api # 백엔드 (Fastify + tsx watch)
npm run build # 전체 빌드 (web + api)
npm run build:web # 프론트엔드만
npm run lint # apps/web ESLint
npm run prepare:data # 정적 데이터 준비
```
## 프로젝트 구조
@ -37,19 +25,18 @@ npm run prepare:data
```
gc-wing-dev/
├── apps/
│ ├── web/ # React 19 + Vite 7 + MapLibre + Deck.gl
│ ├── web/ # @wing/web - React 19 + Vite 7
│ │ └── src/
│ │ ├── app/ # App.tsx, styles
│ │ ├── entities/ # 도메인 모델 (vessel, zone, aisTarget, legacyVessel)
│ │ ├── features/ # 기능 단위 (mapToggles, typeFilter, aisPolling 등)
│ │ ├── pages/ # 페이지 (DashboardPage)
│ │ ├── shared/ # 공통 유틸 (lib/geo, lib/color, lib/map)
│ │ └── widgets/ # UI 위젯 (map3d, vesselList, info, alarms 등)
│ └── api/ # Fastify 5 + TypeScript
│ └── src/
│ └── index.ts
│ │ ├── app/ # App.tsx, styles.css
│ │ ├── entities/ # 도메인 모델 (aisTarget, vessel, zone, legacyVessel, subcable)
│ │ ├── features/ # 기능 모듈 (aisPolling, legacyDashboard, map3dSettings, mapSettings, mapToggles, typeFilter)
│ │ ├── pages/ # dashboard, login, denied, pending
│ │ ├── shared/ # auth (Google OAuth), lib (geo, color, map), hooks (usePersistedState)
│ │ └── widgets/ # map3d, vesselList, info, alarms, relations, aisInfo, aisTargetList, topbar, speed, legend, subcableInfo
│ └── api/ # @wing/api - Fastify 5
│ └── src/index.ts # AIS 프록시 + zones 엔드포인트
├── data/ # 정적 데이터
├── scripts/ # 빌드 스크립트 (prepare-zones, prepare-legacy)
├── scripts/ # prepare-zones.mjs, prepare-legacy.mjs
└── legacy/ # 레거시 데이터
```
@ -59,6 +46,7 @@ gc-wing-dev/
|------|------|
| 프론트엔드 | React 19, Vite 7, TypeScript 5.9 |
| 지도 | MapLibre GL JS 5, Deck.gl 9 |
| 인증 | Google OAuth (AuthProvider + ProtectedRoute) |
| 백엔드 | Fastify 5, TypeScript |
| 린트 | ESLint 9, Prettier |

파일 보기

@ -14,9 +14,11 @@
"@deck.gl/core": "^9.2.7",
"@deck.gl/layers": "^9.2.7",
"@deck.gl/mapbox": "^9.2.7",
"@react-oauth/google": "^0.13.4",
"maplibre-gl": "^5.18.0",
"react": "^19.2.0",
"react-dom": "^19.2.0"
"react-dom": "^19.2.0",
"react-router": "^7.13.0"
},
"devDependencies": {
"@eslint/js": "^9.39.1",

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

파일 보기

@ -1,6 +1,7 @@
{
"version": 8,
"name": "CARTO Dark (Legacy)",
"glyphs": "https://demotiles.maplibre.org/font/{fontstack}/{range}.pbf",
"sources": {
"carto-dark": {
"type": "raster",

파일 보기

@ -1,6 +1,7 @@
{
"version": 8,
"name": "OSM Raster + OpenSeaMap",
"glyphs": "https://demotiles.maplibre.org/font/{fontstack}/{range}.pbf",
"sources": {
"osm": {
"type": "raster",

파일 보기

@ -1,6 +1,23 @@
import { BrowserRouter, Route, Routes } from "react-router";
import { AuthProvider, ProtectedRoute } from "../shared/auth";
import { DashboardPage } from "../pages/dashboard/DashboardPage";
import { LoginPage } from "../pages/login/LoginPage";
import { PendingPage } from "../pages/pending/PendingPage";
import { DeniedPage } from "../pages/denied/DeniedPage";
export default function App() {
return <DashboardPage />;
return (
<AuthProvider>
<BrowserRouter>
<Routes>
<Route path="/login" element={<LoginPage />} />
<Route path="/pending" element={<PendingPage />} />
<Route path="/denied" element={<DeniedPage />} />
<Route element={<ProtectedRoute />}>
<Route index element={<DashboardPage />} />
</Route>
</Routes>
</BrowserRouter>
</AuthProvider>
);
}

파일 보기

@ -105,6 +105,7 @@ body {
.map-area {
position: relative;
background: #010610;
}
.sb {
@ -921,6 +922,343 @@ body {
border-radius: 8px;
}
/* ── Map Settings Panel ────────────────────────────────────────────── */
.map-settings-gear {
position: absolute;
top: 100px;
left: 10px;
z-index: 850;
width: 29px;
height: 29px;
border-radius: 4px;
border: 1px solid var(--border);
background: rgba(15, 23, 42, 0.92);
backdrop-filter: blur(8px);
color: var(--muted);
cursor: pointer;
display: flex;
align-items: center;
justify-content: center;
font-size: 16px;
transition: color 0.15s, border-color 0.15s;
user-select: none;
padding: 0;
}
.map-settings-gear:hover {
color: var(--text);
border-color: var(--accent);
}
.map-settings-gear.open {
color: var(--accent);
border-color: var(--accent);
}
.map-settings-panel {
position: absolute;
top: 10px;
left: 48px;
z-index: 850;
background: rgba(15, 23, 42, 0.95);
backdrop-filter: blur(8px);
border: 1px solid var(--border);
border-radius: 8px;
padding: 12px;
width: 240px;
max-height: calc(100vh - 80px);
overflow-y: auto;
}
.map-settings-panel .ms-title {
font-size: 11px;
font-weight: 700;
color: var(--text);
letter-spacing: 1px;
margin-bottom: 10px;
}
.map-settings-panel .ms-section {
margin-bottom: 10px;
}
.map-settings-panel .ms-label {
font-size: 10px;
font-weight: 600;
color: var(--text);
letter-spacing: 0.5px;
margin-bottom: 5px;
}
.map-settings-panel .ms-row {
display: flex;
align-items: center;
gap: 8px;
margin-bottom: 4px;
}
.map-settings-panel .ms-color-input {
width: 24px;
height: 24px;
border: 1px solid var(--border);
border-radius: 4px;
padding: 0;
cursor: pointer;
background: transparent;
flex-shrink: 0;
}
.map-settings-panel .ms-color-input::-webkit-color-swatch-wrapper {
padding: 1px;
}
.map-settings-panel .ms-color-input::-webkit-color-swatch {
border: none;
border-radius: 2px;
}
.map-settings-panel .ms-hex {
font-size: 9px;
color: #94a3b8;
font-family: monospace;
}
.map-settings-panel .ms-depth-label {
font-size: 10px;
color: var(--text);
min-width: 48px;
text-align: right;
}
.map-settings-panel select {
font-size: 10px;
padding: 4px 8px;
border-radius: 4px;
border: 1px solid var(--border);
background: var(--card);
color: var(--text);
cursor: pointer;
outline: none;
width: 100%;
}
.map-settings-panel select:focus {
border-color: var(--accent);
}
.map-settings-panel .ms-reset {
width: 100%;
font-size: 9px;
padding: 5px 8px;
border-radius: 4px;
border: 1px solid var(--border);
background: var(--card);
color: var(--muted);
cursor: pointer;
transition: all 0.15s;
margin-top: 4px;
}
.map-settings-panel .ms-reset:hover {
color: var(--text);
border-color: var(--accent);
}
/* ── Depth Legend ──────────────────────────────────────────────────── */
.depth-legend {
position: absolute;
bottom: 44px;
left: 10px;
z-index: 800;
background: rgba(15, 23, 42, 0.92);
backdrop-filter: blur(8px);
border: 1px solid var(--border);
border-radius: 8px;
padding: 8px;
display: flex;
gap: 6px;
align-items: stretch;
}
.depth-legend__bar {
width: 14px;
border-radius: 3px;
min-height: 120px;
}
.depth-legend__ticks {
display: flex;
flex-direction: column;
justify-content: space-between;
font-size: 8px;
color: var(--muted);
font-family: monospace;
padding: 1px 0;
}
/* ── Auth pages ──────────────────────────────────────────────────── */
.auth-page {
height: 100vh;
display: flex;
align-items: center;
justify-content: center;
background: linear-gradient(135deg, #020617 0%, #0f172a 50%, #020617 100%);
}
.auth-card {
background: var(--panel);
border: 1px solid var(--border);
border-radius: 16px;
padding: 40px 36px;
width: 360px;
text-align: center;
}
.auth-logo {
font-size: 36px;
font-weight: 900;
color: var(--accent);
letter-spacing: 4px;
margin-bottom: 4px;
}
.auth-title {
font-size: 16px;
font-weight: 700;
color: var(--text);
margin-bottom: 8px;
}
.auth-subtitle {
font-size: 12px;
color: var(--muted);
margin-bottom: 24px;
}
.auth-error {
font-size: 11px;
color: var(--crit);
background: rgba(239, 68, 68, 0.08);
border: 1px solid rgba(239, 68, 68, 0.2);
border-radius: 8px;
padding: 8px 12px;
margin-bottom: 16px;
}
.auth-google-btn {
display: flex;
justify-content: center;
margin-bottom: 12px;
}
.auth-dev-btn {
width: 100%;
padding: 10px;
border-radius: 8px;
border: 1px solid var(--border);
background: var(--card);
color: var(--muted);
font-size: 12px;
cursor: pointer;
transition: all 0.15s;
margin-bottom: 12px;
}
.auth-dev-btn:hover {
color: var(--text);
border-color: var(--accent);
}
.auth-footer {
font-size: 10px;
color: var(--muted);
margin-top: 16px;
}
.auth-status-icon {
font-size: 48px;
margin-bottom: 12px;
}
.auth-message {
font-size: 13px;
color: var(--muted);
line-height: 1.6;
margin-bottom: 16px;
}
.auth-message b {
color: var(--text);
}
.auth-link-btn {
background: none;
border: none;
color: var(--accent);
font-size: 12px;
cursor: pointer;
text-decoration: underline;
padding: 4px 8px;
}
.auth-link-btn:hover {
color: var(--text);
}
.auth-loading {
height: 100vh;
display: flex;
align-items: center;
justify-content: center;
background: var(--bg);
}
.auth-loading__spinner {
width: 32px;
height: 32px;
border: 3px solid rgba(148, 163, 184, 0.28);
border-top-color: var(--accent);
border-radius: 50%;
animation: map-loader-spin 0.7s linear infinite;
}
/* ── Topbar user ─────────────────────────────────────────────────── */
.topbar-user {
display: flex;
align-items: center;
gap: 8px;
margin-left: 10px;
flex-shrink: 0;
}
.topbar-user__name {
font-size: 10px;
color: var(--text);
font-weight: 500;
white-space: nowrap;
}
.topbar-user__logout {
font-size: 9px;
color: var(--muted);
background: none;
border: 1px solid var(--border);
border-radius: 3px;
padding: 2px 6px;
cursor: pointer;
transition: all 0.15s;
white-space: nowrap;
}
.topbar-user__logout:hover {
color: var(--text);
border-color: var(--accent);
}
@media (max-width: 920px) {
.app {
grid-template-columns: 1fr;

파일 보기

@ -0,0 +1,32 @@
import type { AisTargetSearchResponse } from '../model/types';
export async function searchChnprmship(
params: { minutes: number },
signal?: AbortSignal,
): Promise<AisTargetSearchResponse> {
const base = (import.meta.env.VITE_API_URL || '/snp-api').replace(/\/$/, '');
const u = new URL(`${base}/api/ais-target/chnprmship`, window.location.origin);
u.searchParams.set('minutes', String(params.minutes));
const res = await fetch(u, { signal, headers: { accept: 'application/json' } });
const txt = await res.text();
let json: unknown = null;
try {
json = JSON.parse(txt);
} catch {
// ignore
}
if (!res.ok) {
const msg =
json && typeof json === 'object' && typeof (json as { message?: unknown }).message === 'string'
? (json as { message: string }).message
: txt.slice(0, 200) || res.statusText;
throw new Error(`chnprmship API failed: ${res.status} ${msg}`);
}
if (!json || typeof json !== 'object') throw new Error('chnprmship API returned invalid payload');
const parsed = json as AisTargetSearchResponse;
if (!parsed.success) throw new Error(parsed.message || 'chnprmship API returned success=false');
return parsed;
}

파일 보기

@ -0,0 +1,52 @@
import { useEffect, useState } from 'react';
import type { SubcableGeoJson, SubcableDetailsIndex, SubcableDetail } from '../model/types';
interface SubcableData {
geo: SubcableGeoJson;
details: Map<string, SubcableDetail>;
}
export function useSubcables(
geoUrl = '/data/subcables/cable-geo.json',
detailsUrl = '/data/subcables/cable-details.min.json',
) {
const [data, setData] = useState<SubcableData | null>(null);
const [error, setError] = useState<string | null>(null);
useEffect(() => {
let cancelled = false;
async function run() {
try {
setError(null);
const [geoRes, detailsRes] = await Promise.all([
fetch(geoUrl),
fetch(detailsUrl),
]);
if (!geoRes.ok) throw new Error(`Failed to load subcable geo: ${geoRes.status}`);
if (!detailsRes.ok) throw new Error(`Failed to load subcable details: ${detailsRes.status}`);
const geo = (await geoRes.json()) as SubcableGeoJson;
const detailsJson = (await detailsRes.json()) as SubcableDetailsIndex;
if (cancelled) return;
const details = new Map<string, SubcableDetail>();
for (const [id, detail] of Object.entries(detailsJson.by_id)) {
details.set(id, detail);
}
setData({ geo, details });
} catch (e) {
if (cancelled) return;
setError(e instanceof Error ? e.message : String(e));
}
}
void run();
return () => {
cancelled = true;
};
}, [geoUrl, detailsUrl]);
return { data, error };
}

파일 보기

@ -0,0 +1,39 @@
export interface SubcableFeatureProperties {
id: string;
name: string;
color: string;
feature_id: string;
coordinates: [number, number];
}
export type SubcableGeoJson = GeoJSON.FeatureCollection<
GeoJSON.MultiLineString,
SubcableFeatureProperties
>;
export interface SubcableLandingPoint {
id: string;
name: string;
country: string;
is_tbd: boolean;
}
export interface SubcableDetail {
id: string;
name: string;
length: string | null;
rfs: string | null;
rfs_year: number | null;
is_planned: boolean;
owners: string | null;
suppliers: string | null;
landing_points: SubcableLandingPoint[];
notes: string | null;
url: string | null;
}
export interface SubcableDetailsIndex {
version: number;
generated_at: string;
by_id: Record<string, SubcableDetail>;
}

파일 보기

@ -1,5 +1,6 @@
import { useEffect, useMemo, useRef, useState } from "react";
import { searchAisTargets } from "../../entities/aisTarget/api/searchAisTargets";
import { searchChnprmship } from "../../entities/aisTarget/api/searchChnprmship";
import type { AisTarget } from "../../entities/aisTarget/model/types";
export type AisPollingStatus = "idle" | "loading" | "ready" | "error";
@ -17,14 +18,21 @@ export type AisPollingSnapshot = {
};
export type AisPollingOptions = {
initialMinutes?: number;
bootstrapMinutes?: number;
/** 초기 chnprmship API 호출 시 minutes (기본 120) */
chnprmshipMinutes?: number;
/** 주기적 폴링 시 search API minutes (기본 2) */
incrementalMinutes?: number;
/** 폴링 주기 ms (기본 60_000) */
intervalMs?: number;
/** 보존 기간 (기본 chnprmshipMinutes) */
retentionMinutes?: number;
/** incremental 폴링 시 bbox 필터 */
bbox?: string;
/** incremental 폴링 시 중심 경도 */
centerLon?: number;
/** incremental 폴링 시 중심 위도 */
centerLat?: number;
/** incremental 폴링 시 반경(m) */
radiusMeters?: number;
enabled?: boolean;
};
@ -112,11 +120,10 @@ function pruneStore(store: Map<number, AisTarget>, retentionMinutes: number, bbo
}
export function useAisTargetPolling(opts: AisPollingOptions = {}) {
const initialMinutes = opts.initialMinutes ?? 60;
const bootstrapMinutes = opts.bootstrapMinutes ?? initialMinutes;
const incrementalMinutes = opts.incrementalMinutes ?? 1;
const chnprmshipMinutes = opts.chnprmshipMinutes ?? 120;
const incrementalMinutes = opts.incrementalMinutes ?? 2;
const intervalMs = opts.intervalMs ?? 60_000;
const retentionMinutes = opts.retentionMinutes ?? initialMinutes;
const retentionMinutes = opts.retentionMinutes ?? chnprmshipMinutes;
const enabled = opts.enabled ?? true;
const bbox = opts.bbox;
const centerLon = opts.centerLon;
@ -146,50 +153,60 @@ export function useAisTargetPolling(opts: AisPollingOptions = {}) {
const controller = new AbortController();
const generation = ++generationRef.current;
async function run(minutes: number, context: "bootstrap" | "initial" | "incremental") {
function applyResult(res: { data: AisTarget[]; message: string }, minutes: number) {
if (cancelled || generation !== generationRef.current) return;
const { inserted, upserted } = upsertByMmsi(storeRef.current, res.data);
const deleted = pruneStore(storeRef.current, retentionMinutes, bbox);
const total = storeRef.current.size;
setSnapshot({
status: "ready",
error: null,
lastFetchAt: new Date().toISOString(),
lastFetchMinutes: minutes,
lastMessage: res.message,
total,
lastUpserted: upserted,
lastInserted: inserted,
lastDeleted: deleted,
});
setRev((r) => r + 1);
}
async function runInitial(minutes: number) {
try {
setSnapshot((s) => ({ ...s, status: s.status === "idle" ? "loading" : s.status, error: null }));
const res = await searchAisTargets(
{
minutes,
bbox,
centerLon,
centerLat,
radiusMeters,
},
controller.signal,
);
if (cancelled || generation !== generationRef.current) return;
const { inserted, upserted } = upsertByMmsi(storeRef.current, res.data);
const deleted = pruneStore(storeRef.current, retentionMinutes, bbox);
const total = storeRef.current.size;
const lastFetchAt = new Date().toISOString();
setSnapshot({
status: "ready",
error: null,
lastFetchAt,
lastFetchMinutes: minutes,
lastMessage: res.message,
total,
lastUpserted: upserted,
lastInserted: inserted,
lastDeleted: deleted,
});
setRev((r) => r + 1);
setSnapshot((s) => ({ ...s, status: "loading", error: null }));
const res = await searchChnprmship({ minutes }, controller.signal);
applyResult(res, minutes);
} catch (e) {
if (cancelled || generation !== generationRef.current) return;
setSnapshot((s) => ({
...s,
status: context === "incremental" ? s.status : "error",
status: "error",
error: e instanceof Error ? e.message : String(e),
}));
}
}
// Reset store when polling config changes (bbox, retention, etc).
async function runIncremental(minutes: number) {
try {
setSnapshot((s) => ({ ...s, error: null }));
const res = await searchAisTargets(
{ minutes, bbox, centerLon, centerLat, radiusMeters },
controller.signal,
);
applyResult(res, minutes);
} catch (e) {
if (cancelled || generation !== generationRef.current) return;
setSnapshot((s) => ({
...s,
error: e instanceof Error ? e.message : String(e),
}));
}
}
// Reset store when polling config changes.
storeRef.current = new Map();
setSnapshot({
status: "loading",
@ -204,12 +221,11 @@ export function useAisTargetPolling(opts: AisPollingOptions = {}) {
});
setRev((r) => r + 1);
void run(bootstrapMinutes, "bootstrap");
if (bootstrapMinutes !== initialMinutes) {
void run(initialMinutes, "initial");
}
// 초기 로드: chnprmship API 1회 호출
void runInitial(chnprmshipMinutes);
const id = window.setInterval(() => void run(incrementalMinutes, "incremental"), intervalMs);
// 주기적 폴링: search API로 incremental 업데이트
const id = window.setInterval(() => void runIncremental(incrementalMinutes), intervalMs);
return () => {
cancelled = true;
@ -217,8 +233,7 @@ export function useAisTargetPolling(opts: AisPollingOptions = {}) {
window.clearInterval(id);
};
}, [
initialMinutes,
bootstrapMinutes,
chnprmshipMinutes,
incrementalMinutes,
intervalMs,
retentionMinutes,

파일 보기

@ -0,0 +1,221 @@
import { useState } from 'react';
import type { MapStyleSettings, MapLabelLanguage, DepthFontSize, DepthColorStop } from './types';
import { DEFAULT_MAP_STYLE_SETTINGS } from './types';
interface MapSettingsPanelProps {
value: MapStyleSettings;
onChange: (next: MapStyleSettings) => void;
}
const LANGUAGES: { value: MapLabelLanguage; label: string }[] = [
{ value: 'ko', label: '한국어' },
{ value: 'en', label: 'English' },
{ value: 'ja', label: '日本語' },
{ value: 'zh', label: '中文' },
{ value: 'local', label: '현지어' },
];
const FONT_SIZES: { value: DepthFontSize; label: string }[] = [
{ value: 'small', label: '소' },
{ value: 'medium', label: '중' },
{ value: 'large', label: '대' },
];
function depthLabel(depth: number): string {
return `${Math.abs(depth).toLocaleString()}m`;
}
function hexToRgb(hex: string): [number, number, number] {
return [
parseInt(hex.slice(1, 3), 16),
parseInt(hex.slice(3, 5), 16),
parseInt(hex.slice(5, 7), 16),
];
}
function rgbToHex(r: number, g: number, b: number): string {
return `#${[r, g, b].map((c) => Math.round(Math.max(0, Math.min(255, c))).toString(16).padStart(2, '0')).join('')}`;
}
function interpolateGradient(stops: DepthColorStop[]): DepthColorStop[] {
if (stops.length < 2) return stops;
const sorted = [...stops].sort((a, b) => a.depth - b.depth);
const first = sorted[0];
const last = sorted[sorted.length - 1];
const [r1, g1, b1] = hexToRgb(first.color);
const [r2, g2, b2] = hexToRgb(last.color);
return sorted.map((stop, i) => {
if (i === 0 || i === sorted.length - 1) return stop;
const t = i / (sorted.length - 1);
return {
depth: stop.depth,
color: rgbToHex(
r1 + (r2 - r1) * t,
g1 + (g2 - g1) * t,
b1 + (b2 - b1) * t,
),
};
});
}
export function MapSettingsPanel({ value, onChange }: MapSettingsPanelProps) {
const [open, setOpen] = useState(false);
const [autoGradient, setAutoGradient] = useState(false);
const update = <K extends keyof MapStyleSettings>(key: K, val: MapStyleSettings[K]) => {
onChange({ ...value, [key]: val });
};
const updateDepthStop = (index: number, color: string) => {
const next = value.depthStops.map((s, i) => (i === index ? { ...s, color } : s));
if (autoGradient && (index === 0 || index === next.length - 1)) {
update('depthStops', interpolateGradient(next));
} else {
update('depthStops', next);
}
};
const toggleAutoGradient = () => {
const next = !autoGradient;
setAutoGradient(next);
if (next) {
update('depthStops', interpolateGradient(value.depthStops));
}
};
return (
<>
<button
className={`map-settings-gear${open ? ' open' : ''}`}
onClick={() => setOpen((p) => !p)}
title="지도 설정"
type="button"
>
</button>
{open && (
<div className="map-settings-panel">
<div className="ms-title"> </div>
{/* ── Language ──────────────────────────────────── */}
<div className="ms-section">
<div className="ms-label"> </div>
<select
value={value.labelLanguage}
onChange={(e) => update('labelLanguage', e.target.value as MapLabelLanguage)}
>
{LANGUAGES.map((l) => (
<option key={l.value} value={l.value}>
{l.label}
</option>
))}
</select>
</div>
{/* ── Land color ────────────────────────────────── */}
<div className="ms-section">
<div className="ms-label"> </div>
<div className="ms-row">
<input
type="color"
className="ms-color-input"
value={value.landColor}
onChange={(e) => update('landColor', e.target.value)}
/>
<span className="ms-hex">{value.landColor}</span>
</div>
</div>
{/* ── Water color ───────────────────────────────── */}
<div className="ms-section">
<div className="ms-label"> </div>
<div className="ms-row">
<input
type="color"
className="ms-color-input"
value={value.waterBaseColor}
onChange={(e) => update('waterBaseColor', e.target.value)}
/>
<span className="ms-hex">{value.waterBaseColor}</span>
</div>
</div>
{/* ── Depth gradient ────────────────────────────── */}
<div className="ms-section">
<div className="ms-label" style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
<span
className={`tog-btn${autoGradient ? ' on' : ''}`}
style={{ fontSize: 8, padding: '1px 5px', marginLeft: 8 }}
onClick={toggleAutoGradient}
title="최소/최대 색상 기준으로 중간 구간을 자동 보간합니다"
>
</span>
</div>
{value.depthStops.map((stop, i) => {
const isEdge = i === 0 || i === value.depthStops.length - 1;
const dimmed = autoGradient && !isEdge;
return (
<div className="ms-row" key={stop.depth} style={dimmed ? { opacity: 0.5 } : undefined}>
<span className="ms-depth-label">{depthLabel(stop.depth)}</span>
<input
type="color"
className="ms-color-input"
value={stop.color}
onChange={(e) => updateDepthStop(i, e.target.value)}
disabled={dimmed}
/>
<span className="ms-hex">{stop.color}</span>
</div>
);
})}
</div>
{/* ── Depth font size ───────────────────────────── */}
<div className="ms-section">
<div className="ms-label"> </div>
<div className="tog" style={{ gap: 3 }}>
{FONT_SIZES.map((fs) => (
<div
key={fs.value}
className={`tog-btn${value.depthFontSize === fs.value ? ' on' : ''}`}
onClick={() => update('depthFontSize', fs.value)}
>
{fs.label}
</div>
))}
</div>
</div>
{/* ── Depth font color ──────────────────────────── */}
<div className="ms-section">
<div className="ms-label"> </div>
<div className="ms-row">
<input
type="color"
className="ms-color-input"
value={value.depthFontColor}
onChange={(e) => update('depthFontColor', e.target.value)}
/>
<span className="ms-hex">{value.depthFontColor}</span>
</div>
</div>
{/* ── Reset ─────────────────────────────────────── */}
<button
className="ms-reset"
type="button"
onClick={() => {
onChange(DEFAULT_MAP_STYLE_SETTINGS);
setAutoGradient(false);
}}
>
</button>
</div>
)}
</>
);
}

파일 보기

@ -0,0 +1,32 @@
export type MapLabelLanguage = 'ko' | 'en' | 'ja' | 'zh' | 'local';
export type DepthFontSize = 'small' | 'medium' | 'large';
export interface DepthColorStop {
depth: number;
color: string;
}
export interface MapStyleSettings {
labelLanguage: MapLabelLanguage;
landColor: string;
waterBaseColor: string;
depthStops: DepthColorStop[];
depthFontSize: DepthFontSize;
depthFontColor: string;
}
export const DEFAULT_MAP_STYLE_SETTINGS: MapStyleSettings = {
labelLanguage: 'ko',
landColor: '#1a1a2e',
waterBaseColor: '#14606e',
depthStops: [
{ depth: -8000, color: '#010610' },
{ depth: -4000, color: '#030c1c' },
{ depth: -2000, color: '#041022' },
{ depth: -1000, color: '#051529' },
{ depth: -500, color: '#061a30' },
{ depth: -100, color: '#08263d' },
],
depthFontSize: 'medium',
depthFontColor: '#e2e8f0',
};

파일 보기

@ -6,6 +6,7 @@ export type MapToggleState = {
fleetCircles: boolean;
predictVectors: boolean;
shipLabels: boolean;
subcables: boolean;
};
type Props = {
@ -22,6 +23,7 @@ export function MapToggles({ value, onToggle }: Props) {
{ id: "zones", label: "수역 표시" },
{ id: "predictVectors", label: "예측 벡터" },
{ id: "shipLabels", label: "선박명 표시" },
{ id: "subcables", label: "해저케이블" },
];
return (

파일 보기

@ -1,4 +1,6 @@
import { useEffect, useMemo, useRef, useState } from "react";
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { useAuth } from "../../shared/auth";
import { usePersistedState } from "../../shared/hooks";
import { useAisTargetPolling } from "../../features/aisPolling/useAisTargetPolling";
import { Map3DSettingsToggles } from "../../features/map3dSettings/Map3DSettingsToggles";
import type { MapToggleState } from "../../features/mapToggles/MapToggles";
@ -11,17 +13,25 @@ import { buildLegacyVesselIndex } from "../../entities/legacyVessel/lib";
import type { LegacyVesselIndex } from "../../entities/legacyVessel/lib";
import type { LegacyVesselDataset } from "../../entities/legacyVessel/model/types";
import { useZones } from "../../entities/zone/api/useZones";
import { useSubcables } from "../../entities/subcable/api/useSubcables";
import type { VesselTypeCode } from "../../entities/vessel/model/types";
import { AisInfoPanel } from "../../widgets/aisInfo/AisInfoPanel";
import { AisTargetList } from "../../widgets/aisTargetList/AisTargetList";
import { AlarmsPanel } from "../../widgets/alarms/AlarmsPanel";
import { MapLegend } from "../../widgets/legend/MapLegend";
import { Map3D, type BaseMapId, type Map3DSettings, type MapProjectionId } from "../../widgets/map3d/Map3D";
import type { MapViewState } from "../../widgets/map3d/types";
import { RelationsPanel } from "../../widgets/relations/RelationsPanel";
import { SpeedProfilePanel } from "../../widgets/speed/SpeedProfilePanel";
import { Topbar } from "../../widgets/topbar/Topbar";
import { VesselInfoPanel } from "../../widgets/info/VesselInfoPanel";
import { SubcableInfoPanel } from "../../widgets/subcableInfo/SubcableInfoPanel";
import { VesselList } from "../../widgets/vesselList/VesselList";
import { MapSettingsPanel } from "../../features/mapSettings/MapSettingsPanel";
import { DepthLegend } from "../../widgets/legend/DepthLegend";
import { DEFAULT_MAP_STYLE_SETTINGS } from "../../features/mapSettings/types";
import type { MapStyleSettings } from "../../features/mapSettings/types";
import { fmtDateTimeFull, fmtIsoFull } from "../../shared/lib/datetime";
import {
buildLegacyHitMap,
computeCountsByType,
@ -41,13 +51,6 @@ const AIS_CENTER = {
radiusMeters: 2_000_000,
};
function fmtLocal(iso: string | null) {
if (!iso) return "-";
const d = new Date(iso);
if (Number.isNaN(d.getTime())) return iso;
return d.toLocaleString("ko-KR", { hour12: false });
}
type Bbox = [number, number, number, number]; // [lonMin, latMin, lonMax, latMax]
type FleetRelationSortMode = "count" | "range";
@ -68,8 +71,10 @@ function useLegacyIndex(data: LegacyVesselDataset | null): LegacyVesselIndex | n
}
export function DashboardPage() {
const { user, logout } = useAuth();
const { data: zones, error: zonesError } = useZones();
const { data: legacyData, error: legacyError } = useLegacyVessels();
const { data: subcableData } = useSubcables();
const legacyIndex = useLegacyIndex(legacyData);
const [viewBbox, setViewBbox] = useState<Bbox | null>(null);
@ -78,11 +83,10 @@ export function DashboardPage() {
const [apiBbox, setApiBbox] = useState<string | undefined>(undefined);
const { targets, snapshot } = useAisTargetPolling({
initialMinutes: 60,
bootstrapMinutes: 10,
chnprmshipMinutes: 120,
incrementalMinutes: 2,
intervalMs: 60_000,
retentionMinutes: 90,
retentionMinutes: 120,
bbox: useApiBbox ? apiBbox : undefined,
centerLon: useApiBbox ? undefined : AIS_CENTER.lon,
centerLat: useApiBbox ? undefined : AIS_CENTER.lat,
@ -95,48 +99,54 @@ export function DashboardPage() {
const [hoveredFleetMmsiSet, setHoveredFleetMmsiSet] = useState<number[]>([]);
const [hoveredPairMmsiSet, setHoveredPairMmsiSet] = useState<number[]>([]);
const [hoveredFleetOwnerKey, setHoveredFleetOwnerKey] = useState<string | null>(null);
const [typeEnabled, setTypeEnabled] = useState<Record<VesselTypeCode, boolean>>({
PT: true,
"PT-S": true,
GN: true,
OT: true,
PS: true,
FC: true,
});
const [showTargets, setShowTargets] = useState(true);
const [showOthers, setShowOthers] = useState(false);
const uid = null;
const [typeEnabled, setTypeEnabled] = usePersistedState<Record<VesselTypeCode, boolean>>(
uid, 'typeEnabled', { PT: true, "PT-S": true, GN: true, OT: true, PS: true, FC: true },
);
const [showTargets, setShowTargets] = usePersistedState(uid, 'showTargets', true);
const [showOthers, setShowOthers] = usePersistedState(uid, 'showOthers', false);
const [baseMap, setBaseMap] = useState<BaseMapId>("enhanced");
const [projection, setProjection] = useState<MapProjectionId>("mercator");
// 레거시 베이스맵 비활성 — 향후 위성/라이트 등 추가 시 재활용
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const [baseMap, _setBaseMap] = useState<BaseMapId>("enhanced");
// 항상 mercator로 시작 — 3D 전환은 globe 레이어 준비 후 사용자가 수동 전환
const [projection, setProjection] = useState<MapProjectionId>('mercator');
const [mapStyleSettings, setMapStyleSettings] = usePersistedState<MapStyleSettings>(uid, 'mapStyleSettings', DEFAULT_MAP_STYLE_SETTINGS);
const [overlays, setOverlays] = useState<MapToggleState>({
pairLines: true,
pairRange: true,
fcLines: true,
zones: true,
fleetCircles: true,
predictVectors: false,
shipLabels: false,
const [overlays, setOverlays] = usePersistedState<MapToggleState>(uid, 'overlays', {
pairLines: true, pairRange: true, fcLines: true, zones: true,
fleetCircles: true, predictVectors: true, shipLabels: true, subcables: false,
});
const [fleetRelationSortMode, setFleetRelationSortMode] = useState<FleetRelationSortMode>("count");
const [fleetRelationSortMode, setFleetRelationSortMode] = usePersistedState<FleetRelationSortMode>(uid, 'sortMode', "count");
const [alarmKindEnabled, setAlarmKindEnabled] = useState<Record<LegacyAlarmKind, boolean>>(() => {
return Object.fromEntries(LEGACY_ALARM_KINDS.map((k) => [k, true])) as Record<LegacyAlarmKind, boolean>;
});
const [alarmKindEnabled, setAlarmKindEnabled] = usePersistedState<Record<LegacyAlarmKind, boolean>>(
uid, 'alarmKindEnabled',
() => Object.fromEntries(LEGACY_ALARM_KINDS.map((k) => [k, true])) as Record<LegacyAlarmKind, boolean>,
);
const [fleetFocus, setFleetFocus] = useState<{ id: string | number; center: [number, number]; zoom?: number } | undefined>(undefined);
const [settings, setSettings] = useState<Map3DSettings>({
showShips: true,
showDensity: false,
showSeamark: false,
const [hoveredCableId, setHoveredCableId] = useState<string | null>(null);
const [selectedCableId, setSelectedCableId] = useState<string | null>(null);
const [settings, setSettings] = usePersistedState<Map3DSettings>(uid, 'map3dSettings', {
showShips: true, showDensity: false, showSeamark: false,
});
const [mapView, setMapView] = usePersistedState<MapViewState | null>(uid, 'mapView', null);
const [isProjectionLoading, setIsProjectionLoading] = useState(false);
// 초기값 false: globe 레이어가 백그라운드에서 준비될 때까지 토글 비활성화
const [isGlobeShipsReady, setIsGlobeShipsReady] = useState(false);
const handleProjectionLoadingChange = useCallback((loading: boolean) => {
setIsProjectionLoading(loading);
}, []);
const showMapLoader = isProjectionLoading;
// globe 레이어 미준비 또는 전환 중일 때 토글 비활성화
const isProjectionToggleDisabled = !isGlobeShipsReady || isProjectionLoading;
const [clock, setClock] = useState(() => new Date().toLocaleString("ko-KR", { hour12: false }));
const [clock, setClock] = useState(() => fmtDateTimeFull(new Date()));
useEffect(() => {
const id = window.setInterval(() => setClock(new Date().toLocaleString("ko-KR", { hour12: false })), 1000);
const id = window.setInterval(() => setClock(fmtDateTimeFull(new Date())), 1000);
return () => window.clearInterval(id);
}, []);
@ -296,6 +306,8 @@ export function DashboardPage() {
clock={clock}
adminMode={adminMode}
onLogoClick={onLogoClick}
userName={user?.name}
onLogout={logout}
/>
<div className="sidebar">
@ -345,30 +357,28 @@ export function DashboardPage() {
</div>
<div className="sb">
<div className="sb-t"> </div>
<MapToggles value={overlays} onToggle={(k) => setOverlays((prev) => ({ ...prev, [k]: !prev[k] }))} />
<div style={{ fontSize: 9, fontWeight: 700, color: "var(--muted)", letterSpacing: 1.5, marginTop: 8, marginBottom: 6 }}>
<div className="sb-t" style={{ display: "flex", alignItems: "center" }}>
<div style={{ flex: 1 }} />
<div
className={`tog-btn ${projection === "globe" ? "on" : ""}${isProjectionToggleDisabled ? " disabled" : ""}`}
onClick={isProjectionToggleDisabled ? undefined : () => setProjection((p) => (p === "globe" ? "mercator" : "globe"))}
title={isProjectionToggleDisabled ? "3D 모드 준비 중..." : "3D 지구본 투영: 드래그로 회전, 휠로 확대/축소"}
style={{ fontSize: 9, padding: "2px 8px", opacity: isProjectionToggleDisabled ? 0.4 : 1, cursor: isProjectionToggleDisabled ? "not-allowed" : "pointer" }}
>
3D
</div>
</div>
<div className="tog" style={{ flexWrap: "nowrap", alignItems: "center" }}>
<MapToggles value={overlays} onToggle={(k) => setOverlays((prev) => ({ ...prev, [k]: !prev[k] }))} />
{/* enhanced ,
<div className="tog" style={{ flexWrap: "nowrap", alignItems: "center", marginTop: 8 }}>
<div className={`tog-btn ${baseMap === "enhanced" ? "on" : ""}`} onClick={() => setBaseMap("enhanced")} title="현재 지도(해저지형/3D 표현 포함)">
</div>
<div className={`tog-btn ${baseMap === "legacy" ? "on" : ""}`} onClick={() => setBaseMap("legacy")} title="레거시 대시보드(Carto Dark) 베이스맵">
</div>
<div style={{ flex: 1 }} />
<div
className={`tog-btn ${projection === "globe" ? "on" : ""}`}
onClick={() => setProjection((p) => (p === "globe" ? "mercator" : "globe"))}
title="지구본(globe) 투영: 드래그로 회전, 휠로 확대/축소"
>
</div>
</div>
{/* Attribution (license) stays visible in the map UI; no need to repeat it here. */}
</div> */}
</div>
<div className="sb">
@ -531,7 +541,7 @@ export function DashboardPage() {
</div>
<div style={{ marginTop: 6, color: "var(--muted)", fontSize: 10 }}> fetch</div>
<div>
{fmtLocal(snapshot.lastFetchAt)}{" "}
{fmtIsoFull(snapshot.lastFetchAt)}{" "}
<span style={{ color: "var(--muted)", fontSize: 10 }}>
({snapshot.lastFetchMinutes ?? "-"}m, inserted {snapshot.lastInserted}, upserted {snapshot.lastUpserted})
</span>
@ -555,7 +565,7 @@ export function DashboardPage() {
<span style={{ color: "var(--muted)", fontSize: 10 }}>/ {targetsInScope.length}</span>
</div>
<div style={{ marginTop: 6, color: "var(--muted)", fontSize: 10 }}></div>
<div style={{ fontSize: 10, color: "var(--text)" }}>{legacyData?.generatedAt ? fmtLocal(legacyData.generatedAt) : "loading..."}</div>
<div style={{ fontSize: 10, color: "var(--text)" }}>{legacyData?.generatedAt ? fmtIsoFull(legacyData.generatedAt) : "loading..."}</div>
</div>
)}
</div>
@ -666,7 +676,7 @@ export function DashboardPage() {
</div>
<div className="map-area">
{isProjectionLoading ? (
{showMapLoader ? (
<div className="map-loader-overlay" role="status" aria-live="polite">
<div className="map-loader-overlay__panel">
<div className="map-loader-overlay__spinner" />
@ -698,7 +708,8 @@ export function DashboardPage() {
fcLinks={fcLinksForMap}
fleetCircles={fleetCirclesForMap}
fleetFocus={fleetFocus}
onProjectionLoadingChange={setIsProjectionLoading}
onProjectionLoadingChange={handleProjectionLoadingChange}
onGlobeShipsReady={setIsGlobeShipsReady}
onHoverMmsi={(mmsis) => setHoveredMmsiSet(setUniqueSorted(mmsis))}
onClearMmsiHover={() => setHoveredMmsiSet((prev) => (prev.length === 0 ? prev : []))}
onHoverPair={(pairMmsis) => setHoveredPairMmsiSet(setUniqueSorted(pairMmsis))}
@ -711,13 +722,29 @@ export function DashboardPage() {
setHoveredFleetOwnerKey(null);
setHoveredFleetMmsiSet((prev) => (prev.length === 0 ? prev : []));
}}
subcableGeo={subcableData?.geo ?? null}
hoveredCableId={hoveredCableId}
onHoverCable={setHoveredCableId}
onClickCable={(id) => setSelectedCableId((prev) => (prev === id ? null : id))}
mapStyleSettings={mapStyleSettings}
initialView={mapView}
onViewStateChange={setMapView}
/>
<MapSettingsPanel value={mapStyleSettings} onChange={setMapStyleSettings} />
<DepthLegend depthStops={mapStyleSettings.depthStops} />
<MapLegend />
{selectedLegacyVessel ? (
<VesselInfoPanel vessel={selectedLegacyVessel} allVessels={legacyVesselsAll} onClose={() => setSelectedMmsi(null)} onSelectMmsi={setSelectedMmsi} />
) : selectedTarget ? (
<AisInfoPanel target={selectedTarget} legacy={selectedLegacyInfo} onClose={() => setSelectedMmsi(null)} />
) : null}
{selectedCableId && subcableData?.details.get(selectedCableId) ? (
<SubcableInfoPanel
detail={subcableData.details.get(selectedCableId)!}
color={subcableData.geo.features.find((f) => f.properties.id === selectedCableId)?.properties.color}
onClose={() => setSelectedCableId(null)}
/>
) : null}
</div>
</div>
);

파일 보기

@ -0,0 +1,44 @@
import { Navigate } from 'react-router';
import { useAuth } from '../../shared/auth';
export function DeniedPage() {
const { user, loading, logout } = useAuth();
if (loading) {
return (
<div className="auth-loading">
<div className="auth-loading__spinner" />
</div>
);
}
if (!user) {
return <Navigate to="/login" replace />;
}
const isRejectedOrDisabled =
user.status === 'REJECTED' || user.status === 'DISABLED';
const hasWingPermit = user.roles.some((r) => r.name === 'WING_PERMIT');
return (
<div className="auth-page">
<div className="auth-card">
<div className="auth-status-icon">&#128683;</div>
<div className="auth-title"> </div>
<div className="auth-message">
{isRejectedOrDisabled
? `계정이 ${user.status === 'REJECTED' ? '거절' : '비활성화'}되었습니다.`
: !hasWingPermit
? 'WING 대시보드 접근 권한이 없습니다. 관리자에게 WING_PERMIT 역할을 요청하세요.'
: '접근이 거부되었습니다.'}
</div>
<div className="auth-message" style={{ fontSize: 11, marginTop: 8 }}>
{user.email}
</div>
<button className="auth-link-btn" onClick={logout}>
</button>
</div>
</div>
);
}

파일 보기

@ -0,0 +1,70 @@
import { useState } from 'react';
import { Navigate } from 'react-router';
import { GoogleLogin, GoogleOAuthProvider } from '@react-oauth/google';
import { useAuth } from '../../shared/auth';
const GOOGLE_CLIENT_ID = import.meta.env.VITE_GOOGLE_CLIENT_ID || '';
export function LoginPage() {
const { user, login, devLogin, loading } = useAuth();
const [error, setError] = useState<string | null>(null);
if (loading) {
return (
<div className="auth-loading">
<div className="auth-loading__spinner" />
</div>
);
}
if (user) {
return <Navigate to="/" replace />;
}
const handleSuccess = async (credentialResponse: { credential?: string }) => {
if (!credentialResponse.credential) {
setError('Google 인증 토큰을 받지 못했습니다.');
return;
}
try {
setError(null);
await login(credentialResponse.credential);
} catch (e) {
setError(e instanceof Error ? e.message : '로그인에 실패했습니다.');
}
};
return (
<div className="auth-page">
<div className="auth-card">
<div className="auth-logo"><span style={{ position: 'relative' }}>GC WING<span style={{ position: 'absolute', right: -48, bottom: 0, color: '#F59E0B', fontSize: 12, fontWeight: 600 }}>demo</span></span></div>
<div className="auth-title"> </div>
<div className="auth-subtitle">@gcsc.co.kr </div>
{error && <div className="auth-error">{error}</div>}
<div className="auth-google-btn">
<GoogleOAuthProvider clientId={GOOGLE_CLIENT_ID}>
<GoogleLogin
onSuccess={handleSuccess}
onError={() => setError('Google 로그인에 실패했습니다.')}
theme="filled_black"
size="large"
width="280"
/>
</GoogleOAuthProvider>
</div>
{devLogin && (
<button className="auth-dev-btn" onClick={devLogin}>
DEV Mock
</button>
)}
<div className="auth-footer">
GC SI Team &middot; Wing Fleet Dashboard
</div>
</div>
</div>
);
}

파일 보기

@ -0,0 +1,39 @@
import { Navigate } from 'react-router';
import { useAuth } from '../../shared/auth';
export function PendingPage() {
const { user, loading, logout } = useAuth();
if (loading) {
return (
<div className="auth-loading">
<div className="auth-loading__spinner" />
</div>
);
}
if (!user) {
return <Navigate to="/login" replace />;
}
if (user.status !== 'PENDING') {
return <Navigate to="/" replace />;
}
return (
<div className="auth-page">
<div className="auth-card">
<div className="auth-status-icon">&#9203;</div>
<div className="auth-title"> </div>
<div className="auth-message">
<b>{user.email}</b> .
<br />
.
</div>
<button className="auth-link-btn" onClick={logout}>
</button>
</div>
</div>
);
}

파일 보기

@ -0,0 +1,19 @@
import { createContext } from 'react';
import type { User } from './types';
export interface AuthContextValue {
user: User | null;
token: string | null;
loading: boolean;
login: (googleToken: string) => Promise<void>;
devLogin?: () => void;
logout: () => void;
}
export const AuthContext = createContext<AuthContextValue>({
user: null,
token: null,
loading: true,
login: async () => {},
logout: () => {},
});

파일 보기

@ -0,0 +1,99 @@
import { useCallback, useEffect, useMemo, useState, type ReactNode } from 'react';
import type { AuthResponse, User } from './types';
import { authApi } from './authApi';
import { AuthContext } from './AuthContext';
const DEV_MOCK_USER: User = {
id: 1,
email: 'htlee@gcsc.co.kr',
name: '김개발 (DEV)',
avatarUrl: null,
status: 'ACTIVE',
isAdmin: true,
roles: [
{ id: 1, name: 'ADMIN', description: '관리자', urlPatterns: ['/**'] },
{ id: 99, name: 'WING_PERMIT', description: 'Wing 접근 권한', urlPatterns: [] },
],
createdAt: new Date().toISOString(),
lastLoginAt: new Date().toISOString(),
};
function isDevMockSession(): boolean {
return import.meta.env.DEV && localStorage.getItem('dev-user') === 'true';
}
export function AuthProvider({ children }: { children: ReactNode }) {
const [user, setUser] = useState<User | null>(() =>
isDevMockSession() ? DEV_MOCK_USER : null,
);
const [token, setToken] = useState<string | null>(
() => localStorage.getItem('token'),
);
const [initialized, setInitialized] = useState(
() => isDevMockSession() || !localStorage.getItem('token'),
);
const logout = useCallback(() => {
const hadToken = !!localStorage.getItem('token') && !isDevMockSession();
localStorage.removeItem('token');
localStorage.removeItem('dev-user');
setToken(null);
setUser(null);
if (hadToken) {
authApi.post('/auth/logout').catch(() => {});
}
}, []);
const devLogin = useCallback(() => {
localStorage.setItem('dev-user', 'true');
localStorage.setItem('token', 'dev-mock-token');
setToken('dev-mock-token');
setUser(DEV_MOCK_USER);
setInitialized(true);
}, []);
const login = useCallback(async (googleToken: string) => {
const res = await authApi.post<AuthResponse>('/auth/google', {
idToken: googleToken,
});
localStorage.setItem('token', res.token);
setToken(res.token);
setUser(res.user);
}, []);
useEffect(() => {
if (!token || isDevMockSession()) return;
let cancelled = false;
authApi
.get<User>('/auth/me')
.then((data) => {
if (!cancelled) setUser(data);
})
.catch(() => {
if (!cancelled) logout();
})
.finally(() => {
if (!cancelled) setInitialized(true);
});
return () => {
cancelled = true;
};
}, [token, logout]);
const loading = !initialized;
const value = useMemo(
() => ({
user,
token,
loading,
login,
devLogin: import.meta.env.DEV ? devLogin : undefined,
logout,
}),
[user, token, loading, login, devLogin, logout],
);
return <AuthContext.Provider value={value}>{children}</AuthContext.Provider>;
}

파일 보기

@ -0,0 +1,35 @@
import { Navigate, Outlet } from 'react-router';
import { useAuth } from './useAuth';
const REQUIRED_ROLE = 'WING_PERMIT';
export function ProtectedRoute() {
const { user, loading } = useAuth();
if (loading) {
return (
<div className="auth-loading">
<div className="auth-loading__spinner" />
</div>
);
}
if (!user) {
return <Navigate to="/login" replace />;
}
if (user.status === 'PENDING') {
return <Navigate to="/pending" replace />;
}
if (user.status === 'REJECTED' || user.status === 'DISABLED') {
return <Navigate to="/denied" replace />;
}
const hasPermit = user.roles.some((r) => r.name === REQUIRED_ROLE);
if (!hasPermit) {
return <Navigate to="/denied" replace />;
}
return <Outlet />;
}

파일 보기

@ -0,0 +1,34 @@
const API_BASE = (import.meta.env.VITE_AUTH_API_URL || '').replace(/\/$/, '') + '/api';
async function request<T>(path: string, options?: RequestInit): Promise<T> {
const token = localStorage.getItem('token');
const headers: Record<string, string> = {
'Content-Type': 'application/json',
...(token ? { Authorization: `Bearer ${token}` } : {}),
};
const res = await fetch(`${API_BASE}${path}`, { ...options, headers });
if (res.status === 401) {
localStorage.removeItem('token');
window.location.href = '/login';
throw new Error('Unauthorized');
}
if (!res.ok) {
const body = await res.text();
throw new Error(body || `HTTP ${res.status}`);
}
if (res.status === 204 || res.headers.get('content-length') === '0') {
return undefined as T;
}
return res.json();
}
export const authApi = {
get: <T>(path: string) => request<T>(path),
post: <T>(path: string, body?: unknown) =>
request<T>(path, { method: 'POST', body: JSON.stringify(body) }),
};

파일 보기

@ -0,0 +1,4 @@
export { AuthProvider } from './AuthProvider';
export { useAuth } from './useAuth';
export { ProtectedRoute } from './ProtectedRoute';
export type { User, Role, AuthResponse, UserStatus } from './types';

파일 보기

@ -0,0 +1,25 @@
export type UserStatus = 'PENDING' | 'ACTIVE' | 'REJECTED' | 'DISABLED';
export interface Role {
id: number;
name: string;
description: string;
urlPatterns: string[];
}
export interface User {
id: number;
email: string;
name: string;
avatarUrl: string | null;
status: UserStatus;
isAdmin: boolean;
roles: Role[];
createdAt: string;
lastLoginAt: string | null;
}
export interface AuthResponse {
token: string;
user: User;
}

파일 보기

@ -0,0 +1,6 @@
import { useContext } from 'react';
import { AuthContext } from './AuthContext';
export function useAuth() {
return useContext(AuthContext);
}

파일 보기

@ -0,0 +1 @@
export { usePersistedState } from './usePersistedState';

파일 보기

@ -0,0 +1,103 @@
import { useState, useEffect, useRef, type Dispatch, type SetStateAction } from 'react';
const PREFIX = 'wing';
function buildKey(userId: number, name: string): string {
return `${PREFIX}:${userId}:${name}`;
}
function readStorage<T>(key: string, fallback: T): T {
try {
const raw = localStorage.getItem(key);
if (raw === null) return fallback;
return JSON.parse(raw) as T;
} catch {
return fallback;
}
}
function writeStorage<T>(key: string, value: T): void {
try {
localStorage.setItem(key, JSON.stringify(value));
} catch {
// quota exceeded or unavailable — silent
}
}
function resolveDefault<T>(d: T | (() => T)): T {
return typeof d === 'function' ? (d as () => T)() : d;
}
/**
* useState와 API, localStorage .
*
* @param userId null이면 useState처럼 ()
* @param name (e.g. 'typeEnabled')
* @param defaultValue lazy initializer
* @param debounceMs localStorage ( 300ms)
*/
export function usePersistedState<T>(
userId: number | null,
name: string,
defaultValue: T | (() => T),
debounceMs = 300,
): [T, Dispatch<SetStateAction<T>>] {
const resolved = resolveDefault(defaultValue);
const [state, setState] = useState<T>(() => {
if (userId == null) return resolved;
return readStorage(buildKey(userId, name), resolved);
});
const timerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
const stateRef = useRef(state);
const userIdRef = useRef(userId);
const nameRef = useRef(name);
stateRef.current = state;
userIdRef.current = userId;
nameRef.current = name;
// userId 변경 시 해당 사용자의 저장값 재로드
useEffect(() => {
if (userId == null) return;
const stored = readStorage(buildKey(userId, name), resolved);
setState(stored);
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [userId]);
// debounced write
useEffect(() => {
if (userId == null) return;
const key = buildKey(userId, name);
if (timerRef.current != null) clearTimeout(timerRef.current);
timerRef.current = setTimeout(() => {
writeStorage(key, state);
timerRef.current = null;
}, debounceMs);
return () => {
if (timerRef.current != null) {
clearTimeout(timerRef.current);
timerRef.current = null;
}
};
}, [state, userId, name, debounceMs]);
// unmount 시 pending write flush
useEffect(() => {
return () => {
if (timerRef.current != null) {
clearTimeout(timerRef.current);
timerRef.current = null;
}
if (userIdRef.current != null) {
writeStorage(buildKey(userIdRef.current, nameRef.current), stateRef.current);
}
};
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
return [state, setState];
}

파일 보기

@ -0,0 +1,50 @@
/**
* &
*
* KST . DISPLAY_TZ .
*/
/** 표시용 타임존. 'UTC' | 'Asia/Seoul' 등 IANA tz 문자열. */
export const DISPLAY_TZ = 'Asia/Seoul' as const;
/** 표시 레이블 (예: "KST") */
export const DISPLAY_TZ_LABEL = 'KST' as const;
/* ── 포맷 함수 ─────────────────────────────────────────────── */
const pad2 = (n: number) => String(n).padStart(2, '0');
/** DISPLAY_TZ 기준으로 Date → "YYYY년 MM월 DD일 HH시 mm분 ss초" */
export function fmtDateTimeFull(date: Date): string {
const parts = new Intl.DateTimeFormat('ko-KR', {
timeZone: DISPLAY_TZ,
year: 'numeric',
month: '2-digit',
day: '2-digit',
hour: '2-digit',
minute: '2-digit',
second: '2-digit',
hour12: false,
}).formatToParts(date);
const p: Record<string, string> = {};
for (const { type, value } of parts) p[type] = value;
return `${p.year}${p.month}${p.day}${p.hour}${pad2(Number(p.minute))}${pad2(Number(p.second))}`;
}
/** ISO 문자열 → "YYYY년 MM월 DD일 HH시 mm분 ss초" (파싱 실패 시 fallback) */
export function fmtIsoFull(iso: string | null | undefined): string {
if (!iso) return '-';
const d = new Date(iso);
if (Number.isNaN(d.getTime())) return String(iso);
return fmtDateTimeFull(d);
}
/** ISO 문자열 → "HH:mm:ss" (시간만) */
export function fmtIsoTime(iso: string | null | undefined): string {
if (!iso) return '';
const d = new Date(iso);
if (Number.isNaN(d.getTime())) return String(iso);
return d.toLocaleTimeString('ko-KR', { timeZone: DISPLAY_TZ, hour12: false });
}

파일 보기

@ -1,5 +1,6 @@
import type { AisTarget } from "../../entities/aisTarget/model/types";
import type { LegacyVesselInfo } from "../../entities/legacyVessel/model/types";
import { fmtIsoFull } from "../../shared/lib/datetime";
type Props = {
target: AisTarget;
@ -85,11 +86,11 @@ export function AisInfoPanel({ target: t, legacy, onClose }: Props) {
</div>
<div className="ir">
<span className="il">Msg TS</span>
<span className="iv">{t.messageTimestamp || "-"}</span>
<span className="iv">{fmtIsoFull(t.messageTimestamp)}</span>
</div>
<div className="ir">
<span className="il">Received</span>
<span className="iv">{t.receivedDate || "-"}</span>
<span className="iv">{fmtIsoFull(t.receivedDate)}</span>
</div>
</div>
);

파일 보기

@ -2,6 +2,7 @@ import { useMemo, useState } from "react";
import type { AisTarget } from "../../entities/aisTarget/model/types";
import type { LegacyVesselIndex } from "../../entities/legacyVessel/lib";
import { matchLegacyVessel } from "../../entities/legacyVessel/lib";
import { fmtIsoTime } from "../../shared/lib/datetime";
type SortMode = "recent" | "speed";
@ -23,13 +24,6 @@ function getSpeedColor(sog: unknown) {
return "#64748B";
}
function fmtLocalTime(iso: string | null | undefined) {
if (!iso) return "";
const d = new Date(iso);
if (Number.isNaN(d.getTime())) return String(iso);
return d.toLocaleTimeString("ko-KR", { hour12: false });
}
export function AisTargetList({ targets, selectedMmsi, onSelectMmsi, legacyIndex }: Props) {
const [q, setQ] = useState("");
const [mode, setMode] = useState<SortMode>("recent");
@ -96,7 +90,7 @@ export function AisTargetList({ targets, selectedMmsi, onSelectMmsi, legacyIndex
const sel = selectedMmsi && t.mmsi === selectedMmsi;
const sp = isFiniteNumber(t.sog) ? t.sog.toFixed(1) : "?";
const sc = getSpeedColor(t.sog);
const ts = fmtLocalTime(t.messageTimestamp);
const ts = fmtIsoTime(t.messageTimestamp);
const legacy = legacyIndex ? matchLegacyVessel(t, legacyIndex) : null;
const legacyCode = legacy?.shipCode || "";

파일 보기

@ -1,6 +1,7 @@
import { ZONE_META } from "../../entities/zone/model/meta";
import { SPEED_MAX, VESSEL_TYPES } from "../../entities/vessel/model/meta";
import type { DerivedLegacyVessel } from "../../features/legacyDashboard/model/types";
import { fmtIsoFull } from "../../shared/lib/datetime";
import { haversineNm } from "../../shared/lib/geo/haversineNm";
import { OVERLAY_RGB, rgbToHex } from "../../shared/lib/map/palette";
@ -75,7 +76,7 @@ export function VesselInfoPanel({ vessel: v, allVessels, onClose, onSelectMmsi }
</div>
<div className="ir">
<span className="il">Msg TS</span>
<span className="iv">{v.messageTimestamp || "-"}</span>
<span className="iv">{fmtIsoFull(v.messageTimestamp)}</span>
</div>
<div className="ir">
<span className="il"></span>

파일 보기

@ -0,0 +1,33 @@
import { useMemo } from 'react';
import type { DepthColorStop } from '../../features/mapSettings/types';
interface DepthLegendProps {
depthStops: DepthColorStop[];
}
export function DepthLegend({ depthStops }: DepthLegendProps) {
const sorted = useMemo(
() => [...depthStops].sort((a, b) => a.depth - b.depth),
[depthStops],
);
const gradient = useMemo(() => {
if (sorted.length === 0) return 'transparent';
const stops = sorted.map((s, i) => {
const pct = (i / (sorted.length - 1)) * 100;
return `${s.color} ${pct.toFixed(0)}%`;
});
return `linear-gradient(to bottom, ${stops.join(', ')})`;
}, [sorted]);
return (
<div className="depth-legend">
<div className="depth-legend__bar" style={{ background: gradient }} />
<div className="depth-legend__ticks">
{sorted.map((s) => (
<span key={s.depth}>{Math.abs(s.depth).toLocaleString()}m</span>
))}
</div>
</div>
);
}

파일 크기가 너무 크기때문에 변경 상태를 표시하지 않습니다. Load Diff

파일 보기

@ -0,0 +1,161 @@
import {
LEGACY_CODE_COLORS_RGB,
OVERLAY_RGB,
rgba as rgbaCss,
} from '../../shared/lib/map/palette';
// ── Re-export palette aliases used throughout Map3D ──
export const LEGACY_CODE_COLORS = LEGACY_CODE_COLORS_RGB;
const OVERLAY_PAIR_NORMAL_RGB = OVERLAY_RGB.pairNormal;
const OVERLAY_PAIR_WARN_RGB = OVERLAY_RGB.pairWarn;
const OVERLAY_FC_TRANSFER_RGB = OVERLAY_RGB.fcTransfer;
const OVERLAY_FLEET_RANGE_RGB = OVERLAY_RGB.fleetRange;
const OVERLAY_SUSPICIOUS_RGB = OVERLAY_RGB.suspicious;
// ── Ship icon mapping (Deck.gl IconLayer) ──
export const SHIP_ICON_MAPPING = {
ship: {
x: 0,
y: 0,
width: 128,
height: 128,
anchorX: 64,
anchorY: 64,
mask: true,
},
} as const;
// ── Ship constants ──
export const ANCHOR_SPEED_THRESHOLD_KN = 1;
export const ANCHORED_SHIP_ICON_ID = 'ship-globe-anchored-icon';
// ── Geometry constants ──
export const DEG2RAD = Math.PI / 180;
export const RAD2DEG = 180 / Math.PI;
export const EARTH_RADIUS_M = 6371008.8; // MapLibre's `earthRadius`
export const GLOBE_ICON_HEADING_OFFSET_DEG = 0;
// ── Ship color constants ──
export const MAP_SELECTED_SHIP_RGB: [number, number, number] = [34, 211, 238];
export const MAP_HIGHLIGHT_SHIP_RGB: [number, number, number] = [245, 158, 11];
export const MAP_DEFAULT_SHIP_RGB: [number, number, number] = [100, 116, 139];
// ── Ship outline / halo contrast colors ──
export const HALO_OUTLINE_COLOR: [number, number, number, number] = [210, 225, 240, 155];
export const HALO_OUTLINE_COLOR_SELECTED: [number, number, number, number] = [14, 234, 255, 230];
export const HALO_OUTLINE_COLOR_HIGHLIGHTED: [number, number, number, number] = [245, 158, 11, 210];
export const GLOBE_OUTLINE_PERMITTED = 'rgba(210,225,240,0.62)';
export const GLOBE_OUTLINE_OTHER = 'rgba(160,175,195,0.35)';
// ── Flat map icon sizes ──
export const FLAT_SHIP_ICON_SIZE = 19;
export const FLAT_SHIP_ICON_SIZE_SELECTED = 28;
export const FLAT_SHIP_ICON_SIZE_HIGHLIGHTED = 25;
export const FLAT_LEGACY_HALO_RADIUS = 14;
export const FLAT_LEGACY_HALO_RADIUS_SELECTED = 18;
export const FLAT_LEGACY_HALO_RADIUS_HIGHLIGHTED = 16;
export const EMPTY_MMSI_SET = new Set<number>();
// ── Deck.gl view ID ──
export const DECK_VIEW_ID = 'mapbox';
// ── Depth params ──
export const DEPTH_DISABLED_PARAMS = {
depthCompare: 'always',
depthWriteEnabled: false,
} as const;
export const GLOBE_OVERLAY_PARAMS = {
depthCompare: 'less-equal',
depthWriteEnabled: false,
} as const;
// ── Deck.gl color constants (avoid per-object allocations inside accessors) ──
export const PAIR_RANGE_NORMAL_DECK: [number, number, number, number] = [
OVERLAY_PAIR_NORMAL_RGB[0], OVERLAY_PAIR_NORMAL_RGB[1], OVERLAY_PAIR_NORMAL_RGB[2], 110,
];
export const PAIR_RANGE_WARN_DECK: [number, number, number, number] = [
OVERLAY_PAIR_WARN_RGB[0], OVERLAY_PAIR_WARN_RGB[1], OVERLAY_PAIR_WARN_RGB[2], 170,
];
export const PAIR_LINE_NORMAL_DECK: [number, number, number, number] = [
OVERLAY_PAIR_NORMAL_RGB[0], OVERLAY_PAIR_NORMAL_RGB[1], OVERLAY_PAIR_NORMAL_RGB[2], 85,
];
export const PAIR_LINE_WARN_DECK: [number, number, number, number] = [
OVERLAY_PAIR_WARN_RGB[0], OVERLAY_PAIR_WARN_RGB[1], OVERLAY_PAIR_WARN_RGB[2], 220,
];
export const FC_LINE_NORMAL_DECK: [number, number, number, number] = [
OVERLAY_FC_TRANSFER_RGB[0], OVERLAY_FC_TRANSFER_RGB[1], OVERLAY_FC_TRANSFER_RGB[2], 200,
];
export const FC_LINE_SUSPICIOUS_DECK: [number, number, number, number] = [
OVERLAY_SUSPICIOUS_RGB[0], OVERLAY_SUSPICIOUS_RGB[1], OVERLAY_SUSPICIOUS_RGB[2], 220,
];
export const FLEET_RANGE_LINE_DECK: [number, number, number, number] = [
OVERLAY_FLEET_RANGE_RGB[0], OVERLAY_FLEET_RANGE_RGB[1], OVERLAY_FLEET_RANGE_RGB[2], 140,
];
export const FLEET_RANGE_FILL_DECK: [number, number, number, number] = [
OVERLAY_FLEET_RANGE_RGB[0], OVERLAY_FLEET_RANGE_RGB[1], OVERLAY_FLEET_RANGE_RGB[2], 6,
];
// ── Highlighted variants ──
export const PAIR_RANGE_NORMAL_DECK_HL: [number, number, number, number] = [
OVERLAY_PAIR_NORMAL_RGB[0], OVERLAY_PAIR_NORMAL_RGB[1], OVERLAY_PAIR_NORMAL_RGB[2], 200,
];
export const PAIR_RANGE_WARN_DECK_HL: [number, number, number, number] = [
OVERLAY_PAIR_WARN_RGB[0], OVERLAY_PAIR_WARN_RGB[1], OVERLAY_PAIR_WARN_RGB[2], 240,
];
export const PAIR_LINE_NORMAL_DECK_HL: [number, number, number, number] = [
OVERLAY_PAIR_NORMAL_RGB[0], OVERLAY_PAIR_NORMAL_RGB[1], OVERLAY_PAIR_NORMAL_RGB[2], 245,
];
export const PAIR_LINE_WARN_DECK_HL: [number, number, number, number] = [
OVERLAY_PAIR_WARN_RGB[0], OVERLAY_PAIR_WARN_RGB[1], OVERLAY_PAIR_WARN_RGB[2], 245,
];
export const FC_LINE_NORMAL_DECK_HL: [number, number, number, number] = [
OVERLAY_FC_TRANSFER_RGB[0], OVERLAY_FC_TRANSFER_RGB[1], OVERLAY_FC_TRANSFER_RGB[2], 235,
];
export const FC_LINE_SUSPICIOUS_DECK_HL: [number, number, number, number] = [
OVERLAY_SUSPICIOUS_RGB[0], OVERLAY_SUSPICIOUS_RGB[1], OVERLAY_SUSPICIOUS_RGB[2], 245,
];
export const FLEET_RANGE_LINE_DECK_HL: [number, number, number, number] = [
OVERLAY_FLEET_RANGE_RGB[0], OVERLAY_FLEET_RANGE_RGB[1], OVERLAY_FLEET_RANGE_RGB[2], 220,
];
export const FLEET_RANGE_FILL_DECK_HL: [number, number, number, number] = [
OVERLAY_FLEET_RANGE_RGB[0], OVERLAY_FLEET_RANGE_RGB[1], OVERLAY_FLEET_RANGE_RGB[2], 42,
];
// ── MapLibre overlay colors ──
export const PAIR_LINE_NORMAL_ML = rgbaCss(OVERLAY_PAIR_NORMAL_RGB, 0.55);
export const PAIR_LINE_WARN_ML = rgbaCss(OVERLAY_PAIR_WARN_RGB, 0.95);
export const PAIR_LINE_NORMAL_ML_HL = rgbaCss(OVERLAY_PAIR_NORMAL_RGB, 0.95);
export const PAIR_LINE_WARN_ML_HL = rgbaCss(OVERLAY_PAIR_WARN_RGB, 0.98);
export const PAIR_RANGE_NORMAL_ML = rgbaCss(OVERLAY_PAIR_NORMAL_RGB, 0.45);
export const PAIR_RANGE_WARN_ML = rgbaCss(OVERLAY_PAIR_WARN_RGB, 0.75);
export const PAIR_RANGE_NORMAL_ML_HL = rgbaCss(OVERLAY_PAIR_NORMAL_RGB, 0.92);
export const PAIR_RANGE_WARN_ML_HL = rgbaCss(OVERLAY_PAIR_WARN_RGB, 0.92);
export const FC_LINE_NORMAL_ML = rgbaCss(OVERLAY_FC_TRANSFER_RGB, 0.92);
export const FC_LINE_SUSPICIOUS_ML = rgbaCss(OVERLAY_SUSPICIOUS_RGB, 0.95);
export const FC_LINE_NORMAL_ML_HL = rgbaCss(OVERLAY_FC_TRANSFER_RGB, 0.98);
export const FC_LINE_SUSPICIOUS_ML_HL = rgbaCss(OVERLAY_SUSPICIOUS_RGB, 0.98);
export const FLEET_FILL_ML = rgbaCss(OVERLAY_FLEET_RANGE_RGB, 0.02);
export const FLEET_FILL_ML_HL = rgbaCss(OVERLAY_FLEET_RANGE_RGB, 0.16);
export const FLEET_LINE_ML = rgbaCss(OVERLAY_FLEET_RANGE_RGB, 0.65);
export const FLEET_LINE_ML_HL = rgbaCss(OVERLAY_FLEET_RANGE_RGB, 0.95);
// ── Bathymetry zoom ranges ──
// NOTE: BATHY_ZOOM_RANGES는 bathymetry.ts에서 로컬 정의 + applyBathymetryZoomProfile()에서 사용
// 이 파일의 export는 사용처가 없어 제거됨 (2026-02-16)

파일 보기

@ -0,0 +1,132 @@
import { useEffect, useRef, type MutableRefObject } from 'react';
import type maplibregl from 'maplibre-gl';
import type { BaseMapId, MapProjectionId } from '../types';
import { kickRepaint, onMapStyleReady, getLayerId } from '../lib/mapCore';
import { ensureSeamarkOverlay } from '../layers/seamark';
import { applyBathymetryZoomProfile, resolveMapStyle } from '../layers/bathymetry';
export function useBaseMapToggle(
mapRef: MutableRefObject<maplibregl.Map | null>,
opts: {
baseMap: BaseMapId;
projection: MapProjectionId;
showSeamark: boolean;
mapSyncEpoch: number;
pulseMapSync: () => void;
},
) {
const { baseMap, projection, showSeamark, mapSyncEpoch, pulseMapSync } = opts;
const showSeamarkRef = useRef(showSeamark);
const bathyZoomProfileKeyRef = useRef<string>('');
useEffect(() => {
showSeamarkRef.current = showSeamark;
}, [showSeamark]);
// Base map style toggle
useEffect(() => {
const map = mapRef.current;
if (!map) return;
let cancelled = false;
const controller = new AbortController();
let stop: (() => void) | null = null;
(async () => {
try {
const style = await resolveMapStyle(baseMap, controller.signal);
if (cancelled) return;
map.setStyle(style, { diff: false });
stop = onMapStyleReady(map, () => {
kickRepaint(map);
requestAnimationFrame(() => kickRepaint(map));
pulseMapSync();
});
} catch (e) {
if (cancelled) return;
console.warn('Base map switch failed:', e);
}
})();
return () => {
cancelled = true;
controller.abort();
stop?.();
};
}, [baseMap]);
// Bathymetry zoom profile + water layer visibility
useEffect(() => {
const map = mapRef.current;
if (!map) return;
const apply = () => {
if (!map.isStyleLoaded()) return;
const seaVisibility = 'visible' as const;
const seaRegex = /(water|sea|ocean|river|lake|coast|bay)/i;
const nextProfileKey = `bathyZoomV1|${baseMap}|${projection}`;
if (bathyZoomProfileKeyRef.current !== nextProfileKey) {
applyBathymetryZoomProfile(map, baseMap, projection);
bathyZoomProfileKeyRef.current = nextProfileKey;
kickRepaint(map);
}
try {
const style = map.getStyle();
const styleLayers = style && Array.isArray(style.layers) ? style.layers : [];
for (const layer of styleLayers) {
const id = getLayerId(layer);
if (!id) continue;
const sourceLayer = String((layer as Record<string, unknown>)['source-layer'] ?? '').toLowerCase();
const source = String((layer as { source?: unknown }).source ?? '').toLowerCase();
const type = String((layer as { type?: unknown }).type ?? '').toLowerCase();
const isSea = seaRegex.test(id) || seaRegex.test(sourceLayer) || seaRegex.test(source);
const isRaster = type === 'raster';
if (!isSea) continue;
if (!map.getLayer(id)) continue;
if (isRaster && id === 'seamark') continue;
try {
map.setLayoutProperty(id, 'visibility', seaVisibility);
} catch {
// ignore
}
}
} catch {
// ignore
}
};
const stop = onMapStyleReady(map, apply);
return () => {
stop();
};
}, [projection, baseMap, mapSyncEpoch]);
// Seamark toggle
useEffect(() => {
const map = mapRef.current;
if (!map) return;
if (showSeamark) {
try {
ensureSeamarkOverlay(map, 'bathymetry-lines-coarse');
map.setPaintProperty('seamark', 'raster-opacity', 0.85);
} catch {
// ignore until style is ready
}
return;
}
try {
if (map.getLayer('seamark')) map.removeLayer('seamark');
} catch {
// ignore
}
try {
if (map.getSource('seamark')) map.removeSource('seamark');
} catch {
// ignore
}
}, [showSeamark]);
}

파일 보기

@ -0,0 +1,678 @@
import { useEffect, useMemo, type MutableRefObject } from 'react';
import { HexagonLayer } from '@deck.gl/aggregation-layers';
import { IconLayer, LineLayer, ScatterplotLayer } from '@deck.gl/layers';
import { MapboxOverlay } from '@deck.gl/mapbox';
import { type PickingInfo } from '@deck.gl/core';
import type { AisTarget } from '../../../entities/aisTarget/model/types';
import type { LegacyVesselInfo } from '../../../entities/legacyVessel/model/types';
import type { FcLink, FleetCircle, PairLink } from '../../../features/legacyDashboard/model/types';
import type { MapToggleState } from '../../../features/mapToggles/MapToggles';
import type { DashSeg, Map3DSettings, MapProjectionId, PairRangeCircle } from '../types';
import { MaplibreDeckCustomLayer } from '../MaplibreDeckCustomLayer';
import {
SHIP_ICON_MAPPING,
FLAT_SHIP_ICON_SIZE,
FLAT_SHIP_ICON_SIZE_SELECTED,
FLAT_SHIP_ICON_SIZE_HIGHLIGHTED,
FLAT_LEGACY_HALO_RADIUS,
FLAT_LEGACY_HALO_RADIUS_SELECTED,
FLAT_LEGACY_HALO_RADIUS_HIGHLIGHTED,
EMPTY_MMSI_SET,
DEPTH_DISABLED_PARAMS,
GLOBE_OVERLAY_PARAMS,
HALO_OUTLINE_COLOR,
HALO_OUTLINE_COLOR_SELECTED,
HALO_OUTLINE_COLOR_HIGHLIGHTED,
PAIR_RANGE_NORMAL_DECK,
PAIR_RANGE_WARN_DECK,
PAIR_LINE_NORMAL_DECK,
PAIR_LINE_WARN_DECK,
FC_LINE_NORMAL_DECK,
FC_LINE_SUSPICIOUS_DECK,
FLEET_RANGE_LINE_DECK,
FLEET_RANGE_FILL_DECK,
PAIR_RANGE_NORMAL_DECK_HL,
PAIR_RANGE_WARN_DECK_HL,
PAIR_LINE_NORMAL_DECK_HL,
PAIR_LINE_WARN_DECK_HL,
FC_LINE_NORMAL_DECK_HL,
FC_LINE_SUSPICIOUS_DECK_HL,
FLEET_RANGE_LINE_DECK_HL,
FLEET_RANGE_FILL_DECK_HL,
} from '../constants';
import { toSafeNumber } from '../lib/setUtils';
import { getDisplayHeading, getShipColor } from '../lib/shipUtils';
import {
getShipTooltipHtml,
getPairLinkTooltipHtml,
getFcLinkTooltipHtml,
getRangeTooltipHtml,
getFleetCircleTooltipHtml,
} from '../lib/tooltips';
import { sanitizeDeckLayerList } from '../lib/mapCore';
// NOTE:
// Globe mode now relies on MapLibre native overlays (useGlobeOverlays/useGlobeShips).
// Keep Deck custom-layer rendering disabled in globe to avoid projection-space artifacts.
const ENABLE_GLOBE_DECK_OVERLAYS = false;
export function useDeckLayers(
mapRef: MutableRefObject<import('maplibre-gl').Map | null>,
overlayRef: MutableRefObject<MapboxOverlay | null>,
globeDeckLayerRef: MutableRefObject<MaplibreDeckCustomLayer | null>,
projectionBusyRef: MutableRefObject<boolean>,
opts: {
projection: MapProjectionId;
settings: Map3DSettings;
shipLayerData: AisTarget[];
shipOverlayLayerData: AisTarget[];
shipData: AisTarget[];
legacyHits: Map<number, LegacyVesselInfo> | null | undefined;
pairLinks: PairLink[] | undefined;
fcLinks: FcLink[] | undefined;
fcDashed: DashSeg[];
fleetCircles: FleetCircle[] | undefined;
pairRanges: PairRangeCircle[];
pairLinksInteractive: PairLink[];
pairRangesInteractive: PairRangeCircle[];
fcLinesInteractive: DashSeg[];
fleetCirclesInteractive: FleetCircle[];
overlays: MapToggleState;
shipByMmsi: Map<number, AisTarget>;
selectedMmsi: number | null;
shipHighlightSet: Set<number>;
isHighlightedFleet: (ownerKey: string, vesselMmsis: number[]) => boolean;
isHighlightedPair: (aMmsi: number, bMmsi: number) => boolean;
isHighlightedMmsi: (mmsi: number) => boolean;
clearDeckHoverPairs: () => void;
clearDeckHoverMmsi: () => void;
clearMapFleetHoverState: () => void;
setDeckHoverPairs: (next: number[]) => void;
setDeckHoverMmsi: (next: number[]) => void;
setMapFleetHoverState: (ownerKey: string | null, vesselMmsis: number[]) => void;
toFleetMmsiList: (value: unknown) => number[];
touchDeckHoverState: (isHover: boolean) => void;
hasAuxiliarySelectModifier: (ev?: { shiftKey?: boolean; ctrlKey?: boolean; metaKey?: boolean } | null) => boolean;
onDeckSelectOrHighlight: (info: unknown, allowMultiSelect?: boolean) => void;
onSelectMmsi: (mmsi: number | null) => void;
onToggleHighlightMmsi?: (mmsi: number) => void;
ensureMercatorOverlay: () => MapboxOverlay | null;
projectionRef: MutableRefObject<MapProjectionId>;
},
) {
const {
projection, settings, shipLayerData, shipOverlayLayerData, shipData,
legacyHits, pairLinks, fcDashed, fleetCircles, pairRanges,
pairLinksInteractive, pairRangesInteractive, fcLinesInteractive, fleetCirclesInteractive,
overlays, shipByMmsi, selectedMmsi, shipHighlightSet,
isHighlightedFleet, isHighlightedPair, isHighlightedMmsi,
clearDeckHoverPairs, clearDeckHoverMmsi, clearMapFleetHoverState,
setDeckHoverPairs, setDeckHoverMmsi, setMapFleetHoverState,
toFleetMmsiList, touchDeckHoverState, hasAuxiliarySelectModifier,
onDeckSelectOrHighlight, onSelectMmsi, onToggleHighlightMmsi,
ensureMercatorOverlay, projectionRef,
} = opts;
const legacyTargets = useMemo(() => {
if (!legacyHits) return [];
return shipData.filter((t) => legacyHits.has(t.mmsi));
}, [shipData, legacyHits]);
const legacyTargetsOrdered = useMemo(() => {
if (legacyTargets.length === 0) return legacyTargets;
const layer = [...legacyTargets];
layer.sort((a, b) => a.mmsi - b.mmsi);
return layer;
}, [legacyTargets]);
const legacyOverlayTargets = useMemo(() => {
if (shipHighlightSet.size === 0) return [];
return legacyTargets.filter((target) => shipHighlightSet.has(target.mmsi));
}, [legacyTargets, shipHighlightSet]);
// Mercator Deck layers
useEffect(() => {
const map = mapRef.current;
if (!map) return;
if (projection !== 'mercator' || projectionBusyRef.current) {
if (projection !== 'mercator') {
try {
if (overlayRef.current) overlayRef.current.setProps({ layers: [] } as never);
} catch {
// ignore
}
}
return;
}
const deckTarget = ensureMercatorOverlay();
if (!deckTarget) return;
const layers: unknown[] = [];
const overlayParams = DEPTH_DISABLED_PARAMS;
const clearDeckHover = () => {
touchDeckHoverState(false);
};
const isTargetShip = (mmsi: number) => (legacyHits ? legacyHits.has(mmsi) : false);
const shipOtherData: AisTarget[] = [];
const shipTargetData: AisTarget[] = [];
for (const t of shipLayerData) {
if (isTargetShip(t.mmsi)) shipTargetData.push(t);
else shipOtherData.push(t);
}
const shipOverlayOtherData: AisTarget[] = [];
const shipOverlayTargetData: AisTarget[] = [];
for (const t of shipOverlayLayerData) {
if (isTargetShip(t.mmsi)) shipOverlayTargetData.push(t);
else shipOverlayOtherData.push(t);
}
if (settings.showDensity) {
layers.push(
new HexagonLayer<AisTarget>({
id: 'density',
data: shipLayerData,
pickable: true,
extruded: true,
radius: 2500,
elevationScale: 35,
coverage: 0.92,
opacity: 0.35,
getPosition: (d) => [d.lon, d.lat],
}),
);
}
if (overlays.pairRange && pairRanges.length > 0) {
layers.push(
new ScatterplotLayer<PairRangeCircle>({
id: 'pair-range',
data: pairRanges,
pickable: true,
billboard: false,
parameters: overlayParams,
filled: false,
stroked: true,
radiusUnits: 'meters',
getRadius: (d) => d.radiusNm * 1852,
radiusMinPixels: 10,
lineWidthUnits: 'pixels',
getLineWidth: () => 1,
getLineColor: (d) => (d.warn ? PAIR_RANGE_WARN_DECK : PAIR_RANGE_NORMAL_DECK),
getPosition: (d) => d.center,
onHover: (info) => {
if (!info.object) { clearDeckHover(); return; }
touchDeckHoverState(true);
const p = info.object as PairRangeCircle;
setDeckHoverPairs([p.aMmsi, p.bMmsi]);
setDeckHoverMmsi([p.aMmsi, p.bMmsi]);
clearMapFleetHoverState();
},
onClick: (info) => {
if (!info.object) { onSelectMmsi(null); return; }
const obj = info.object as PairRangeCircle;
const sourceEvent = (info as { srcEvent?: { shiftKey?: boolean; ctrlKey?: boolean; metaKey?: boolean } | null }).srcEvent;
if (sourceEvent && hasAuxiliarySelectModifier(sourceEvent)) {
onToggleHighlightMmsi?.(obj.aMmsi);
onToggleHighlightMmsi?.(obj.bMmsi);
return;
}
onDeckSelectOrHighlight({ mmsi: obj.aMmsi });
},
}),
);
}
if (overlays.pairLines && (pairLinks?.length ?? 0) > 0) {
layers.push(
new LineLayer<PairLink>({
id: 'pair-lines',
data: pairLinks,
pickable: true,
parameters: overlayParams,
getSourcePosition: (d) => d.from,
getTargetPosition: (d) => d.to,
getColor: (d) => (d.warn ? PAIR_LINE_WARN_DECK : PAIR_LINE_NORMAL_DECK),
getWidth: (d) => (d.warn ? 2.2 : 1.4),
widthUnits: 'pixels',
onHover: (info) => {
if (!info.object) { clearDeckHover(); return; }
touchDeckHoverState(true);
const obj = info.object as PairLink;
setDeckHoverPairs([obj.aMmsi, obj.bMmsi]);
setDeckHoverMmsi([obj.aMmsi, obj.bMmsi]);
clearMapFleetHoverState();
},
onClick: (info) => {
if (!info.object) return;
const obj = info.object as PairLink;
const sourceEvent = (info as { srcEvent?: { shiftKey?: boolean; ctrlKey?: boolean; metaKey?: boolean } | null }).srcEvent;
if (sourceEvent && hasAuxiliarySelectModifier(sourceEvent)) {
onToggleHighlightMmsi?.(obj.aMmsi);
onToggleHighlightMmsi?.(obj.bMmsi);
return;
}
onDeckSelectOrHighlight({ mmsi: obj.aMmsi });
},
}),
);
}
if (overlays.fcLines && fcDashed.length > 0) {
layers.push(
new LineLayer<DashSeg>({
id: 'fc-lines',
data: fcDashed,
pickable: true,
parameters: overlayParams,
getSourcePosition: (d) => d.from,
getTargetPosition: (d) => d.to,
getColor: (d) => (d.suspicious ? FC_LINE_SUSPICIOUS_DECK : FC_LINE_NORMAL_DECK),
getWidth: () => 1.3,
widthUnits: 'pixels',
onHover: (info) => {
if (!info.object) { clearDeckHover(); return; }
touchDeckHoverState(true);
const obj = info.object as DashSeg;
if (obj.fromMmsi == null || obj.toMmsi == null) { clearDeckHover(); return; }
setDeckHoverPairs([obj.fromMmsi, obj.toMmsi]);
setDeckHoverMmsi([obj.fromMmsi, obj.toMmsi]);
clearMapFleetHoverState();
},
onClick: (info) => {
if (!info.object) return;
const obj = info.object as DashSeg;
if (obj.fromMmsi == null || obj.toMmsi == null) return;
const sourceEvent = (info as { srcEvent?: { shiftKey?: boolean; ctrlKey?: boolean; metaKey?: boolean } | null }).srcEvent;
if (sourceEvent && hasAuxiliarySelectModifier(sourceEvent)) {
onToggleHighlightMmsi?.(obj.fromMmsi);
onToggleHighlightMmsi?.(obj.toMmsi);
return;
}
onDeckSelectOrHighlight({ mmsi: obj.fromMmsi });
},
}),
);
}
if (overlays.fleetCircles && (fleetCircles?.length ?? 0) > 0) {
layers.push(
new ScatterplotLayer<FleetCircle>({
id: 'fleet-circles',
data: fleetCircles,
pickable: true,
billboard: false,
parameters: overlayParams,
filled: false,
stroked: true,
radiusUnits: 'meters',
getRadius: (d) => d.radiusNm * 1852,
lineWidthUnits: 'pixels',
getLineWidth: () => 1.1,
getLineColor: () => FLEET_RANGE_LINE_DECK,
getPosition: (d) => d.center,
onHover: (info) => {
if (!info.object) { clearDeckHover(); return; }
touchDeckHoverState(true);
const obj = info.object as FleetCircle;
const list = toFleetMmsiList(obj.vesselMmsis);
setMapFleetHoverState(obj.ownerKey || null, list);
setDeckHoverMmsi(list);
clearDeckHoverPairs();
},
onClick: (info) => {
if (!info.object) return;
const obj = info.object as FleetCircle;
const list = toFleetMmsiList(obj.vesselMmsis);
const sourceEvent = (info as { srcEvent?: { shiftKey?: boolean; ctrlKey?: boolean; metaKey?: boolean } | null }).srcEvent;
if (sourceEvent && hasAuxiliarySelectModifier(sourceEvent)) {
for (const mmsi of list) onToggleHighlightMmsi?.(mmsi);
return;
}
const first = list[0];
if (first != null) onDeckSelectOrHighlight({ mmsi: first });
},
}),
);
layers.push(
new ScatterplotLayer<FleetCircle>({
id: 'fleet-circles-fill',
data: fleetCircles,
pickable: false,
billboard: false,
parameters: overlayParams,
filled: true,
stroked: false,
radiusUnits: 'meters',
getRadius: (d) => d.radiusNm * 1852,
getFillColor: () => FLEET_RANGE_FILL_DECK,
getPosition: (d) => d.center,
}),
);
}
if (settings.showShips) {
const shipOnHover = (info: PickingInfo) => {
if (!info.object) { clearDeckHover(); return; }
touchDeckHoverState(true);
const obj = info.object as AisTarget;
setDeckHoverMmsi([obj.mmsi]);
clearDeckHoverPairs();
clearMapFleetHoverState();
};
const shipOnClick = (info: PickingInfo) => {
if (!info.object) { onSelectMmsi(null); return; }
onDeckSelectOrHighlight(
{
mmsi: (info.object as AisTarget).mmsi,
srcEvent: (info as { srcEvent?: { shiftKey?: boolean; ctrlKey?: boolean; metaKey?: boolean } | null }).srcEvent,
},
true,
);
};
if (shipOtherData.length > 0) {
layers.push(
new IconLayer<AisTarget>({
id: 'ships-other',
data: shipOtherData,
pickable: true,
billboard: false,
parameters: overlayParams,
iconAtlas: '/assets/ship.svg',
iconMapping: SHIP_ICON_MAPPING,
getIcon: () => 'ship',
getPosition: (d) => [d.lon, d.lat] as [number, number],
getAngle: (d) => -getDisplayHeading({ cog: d.cog, heading: d.heading }),
sizeUnits: 'pixels',
getSize: () => FLAT_SHIP_ICON_SIZE,
getColor: (d) => getShipColor(d, null, null, EMPTY_MMSI_SET),
onHover: shipOnHover,
onClick: shipOnClick,
alphaCutoff: 0.05,
}),
);
}
if (shipOverlayOtherData.length > 0) {
layers.push(
new IconLayer<AisTarget>({
id: 'ships-overlay-other',
data: shipOverlayOtherData,
pickable: false,
billboard: false,
parameters: overlayParams,
iconAtlas: '/assets/ship.svg',
iconMapping: SHIP_ICON_MAPPING,
getIcon: () => 'ship',
getPosition: (d) => [d.lon, d.lat] as [number, number],
getAngle: (d) => -getDisplayHeading({ cog: d.cog, heading: d.heading }),
sizeUnits: 'pixels',
getSize: (d) => {
if (selectedMmsi != null && d.mmsi === selectedMmsi) return FLAT_SHIP_ICON_SIZE_SELECTED;
if (shipHighlightSet.has(d.mmsi)) return FLAT_SHIP_ICON_SIZE_HIGHLIGHTED;
return 0;
},
getColor: (d) => getShipColor(d, selectedMmsi, null, shipHighlightSet),
alphaCutoff: 0.05,
}),
);
}
if (legacyTargetsOrdered.length > 0) {
layers.push(
new ScatterplotLayer<AisTarget>({
id: 'legacy-halo',
data: legacyTargetsOrdered,
pickable: false,
billboard: false,
parameters: overlayParams,
filled: false,
stroked: true,
radiusUnits: 'pixels',
getRadius: () => FLAT_LEGACY_HALO_RADIUS,
lineWidthUnits: 'pixels',
getLineWidth: () => 2,
getLineColor: () => HALO_OUTLINE_COLOR,
getPosition: (d) => [d.lon, d.lat] as [number, number],
}),
);
}
if (shipTargetData.length > 0) {
layers.push(
new IconLayer<AisTarget>({
id: 'ships-target',
data: shipTargetData,
pickable: true,
billboard: false,
parameters: overlayParams,
iconAtlas: '/assets/ship.svg',
iconMapping: SHIP_ICON_MAPPING,
getIcon: () => 'ship',
getPosition: (d) => [d.lon, d.lat] as [number, number],
getAngle: (d) => -getDisplayHeading({ cog: d.cog, heading: d.heading }),
sizeUnits: 'pixels',
getSize: () => FLAT_SHIP_ICON_SIZE,
getColor: (d) => getShipColor(d, null, legacyHits?.get(d.mmsi)?.shipCode ?? null, EMPTY_MMSI_SET),
onHover: shipOnHover,
onClick: shipOnClick,
alphaCutoff: 0.05,
}),
);
}
}
if (overlays.pairRange && pairRangesInteractive.length > 0) {
layers.push(new ScatterplotLayer<PairRangeCircle>({ id: 'pair-range-overlay', data: pairRangesInteractive, pickable: false, billboard: false, parameters: overlayParams, filled: false, stroked: true, radiusUnits: 'meters', getRadius: (d) => d.radiusNm * 1852, radiusMinPixels: 10, lineWidthUnits: 'pixels', getLineWidth: () => 2.2, getLineColor: (d) => (d.warn ? PAIR_RANGE_WARN_DECK_HL : PAIR_RANGE_NORMAL_DECK_HL), getPosition: (d) => d.center }));
}
if (overlays.pairLines && pairLinksInteractive.length > 0) {
layers.push(new LineLayer<PairLink>({ id: 'pair-lines-overlay', data: pairLinksInteractive, pickable: false, parameters: overlayParams, getSourcePosition: (d) => d.from, getTargetPosition: (d) => d.to, getColor: (d) => (d.warn ? PAIR_LINE_WARN_DECK_HL : PAIR_LINE_NORMAL_DECK_HL), getWidth: () => 2.6, widthUnits: 'pixels' }));
}
if (overlays.fcLines && fcLinesInteractive.length > 0) {
layers.push(new LineLayer<DashSeg>({ id: 'fc-lines-overlay', data: fcLinesInteractive, pickable: false, parameters: overlayParams, getSourcePosition: (d) => d.from, getTargetPosition: (d) => d.to, getColor: (d) => (d.suspicious ? FC_LINE_SUSPICIOUS_DECK_HL : FC_LINE_NORMAL_DECK_HL), getWidth: () => 1.9, widthUnits: 'pixels' }));
}
if (overlays.fleetCircles && fleetCirclesInteractive.length > 0) {
layers.push(new ScatterplotLayer<FleetCircle>({ id: 'fleet-circles-overlay-fill', data: fleetCirclesInteractive, pickable: false, billboard: false, parameters: overlayParams, filled: true, stroked: false, radiusUnits: 'meters', getRadius: (d) => d.radiusNm * 1852, getFillColor: () => FLEET_RANGE_FILL_DECK_HL }));
layers.push(new ScatterplotLayer<FleetCircle>({ id: 'fleet-circles-overlay', data: fleetCirclesInteractive, pickable: false, billboard: false, parameters: overlayParams, filled: false, stroked: true, radiusUnits: 'meters', getRadius: (d) => d.radiusNm * 1852, lineWidthUnits: 'pixels', getLineWidth: () => 1.8, getLineColor: () => FLEET_RANGE_LINE_DECK_HL, getPosition: (d) => d.center }));
}
if (settings.showShips && legacyOverlayTargets.length > 0) {
layers.push(new ScatterplotLayer<AisTarget>({ id: 'legacy-halo-overlay', data: legacyOverlayTargets, pickable: false, billboard: false, parameters: overlayParams, filled: false, stroked: true, radiusUnits: 'pixels', getRadius: (d) => { if (selectedMmsi && d.mmsi === selectedMmsi) return FLAT_LEGACY_HALO_RADIUS_SELECTED; return FLAT_LEGACY_HALO_RADIUS_HIGHLIGHTED; }, lineWidthUnits: 'pixels', getLineWidth: (d) => (selectedMmsi && d.mmsi === selectedMmsi ? 2.5 : 2.2), getLineColor: (d) => { if (selectedMmsi && d.mmsi === selectedMmsi) return HALO_OUTLINE_COLOR_SELECTED; if (shipHighlightSet.has(d.mmsi)) return HALO_OUTLINE_COLOR_HIGHLIGHTED; return HALO_OUTLINE_COLOR; }, getPosition: (d) => [d.lon, d.lat] as [number, number] }));
}
if (settings.showShips && shipOverlayLayerData.filter((t) => legacyHits?.has(t.mmsi)).length > 0) {
const shipOverlayTargetData2 = shipOverlayLayerData.filter((t) => legacyHits?.has(t.mmsi));
layers.push(new IconLayer<AisTarget>({ id: 'ships-overlay-target', data: shipOverlayTargetData2, pickable: false, billboard: false, parameters: overlayParams, iconAtlas: '/assets/ship.svg', iconMapping: SHIP_ICON_MAPPING, getIcon: () => 'ship', getPosition: (d) => [d.lon, d.lat] as [number, number], getAngle: (d) => -getDisplayHeading({ cog: d.cog, heading: d.heading }), sizeUnits: 'pixels', getSize: (d) => { if (selectedMmsi != null && d.mmsi === selectedMmsi) return FLAT_SHIP_ICON_SIZE_SELECTED; if (shipHighlightSet.has(d.mmsi)) return FLAT_SHIP_ICON_SIZE_HIGHLIGHTED; return 0; }, getColor: (d) => { if (!shipHighlightSet.has(d.mmsi) && !(selectedMmsi != null && d.mmsi === selectedMmsi)) return [0, 0, 0, 0]; return getShipColor(d, selectedMmsi, legacyHits?.get(d.mmsi)?.shipCode ?? null, shipHighlightSet); } }));
}
const normalizedLayers = sanitizeDeckLayerList(layers);
const deckProps = {
layers: normalizedLayers,
getTooltip: (info: PickingInfo) => {
if (!info.object) return null;
if (info.layer && info.layer.id === 'density') {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const o: any = info.object;
const n = Array.isArray(o?.points) ? o.points.length : 0;
return { text: `AIS density: ${n}` };
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const obj: any = info.object;
if (typeof obj.mmsi === 'number') {
return getShipTooltipHtml({ mmsi: obj.mmsi, targetByMmsi: shipByMmsi, legacyHits });
}
if (info.layer && info.layer.id === 'pair-lines') {
const aMmsi = toSafeNumber(obj.aMmsi);
const bMmsi = toSafeNumber(obj.bMmsi);
if (aMmsi == null || bMmsi == null) return null;
return getPairLinkTooltipHtml({ warn: !!obj.warn, distanceNm: toSafeNumber(obj.distanceNm), aMmsi, bMmsi, legacyHits, targetByMmsi: shipByMmsi });
}
if (info.layer && info.layer.id === 'fc-lines') {
const fcMmsi = toSafeNumber(obj.fcMmsi);
const otherMmsi = toSafeNumber(obj.otherMmsi);
if (fcMmsi == null || otherMmsi == null) return null;
return getFcLinkTooltipHtml({ suspicious: !!obj.suspicious, distanceNm: toSafeNumber(obj.distanceNm), fcMmsi, otherMmsi, legacyHits, targetByMmsi: shipByMmsi });
}
if (info.layer && info.layer.id === 'pair-range') {
const aMmsi = toSafeNumber(obj.aMmsi);
const bMmsi = toSafeNumber(obj.bMmsi);
if (aMmsi == null || bMmsi == null) return null;
return getRangeTooltipHtml({ warn: !!obj.warn, distanceNm: toSafeNumber(obj.distanceNm), aMmsi, bMmsi, legacyHits });
}
if (info.layer && info.layer.id === 'fleet-circles') {
return getFleetCircleTooltipHtml({ ownerKey: String(obj.ownerKey ?? ''), ownerLabel: String(obj.ownerKey ?? ''), count: Number(obj.count ?? 0) });
}
return null;
},
onClick: (info: PickingInfo) => {
if (!info.object) { onSelectMmsi(null); return; }
if (info.layer && info.layer.id === 'density') return;
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const obj: any = info.object;
if (typeof obj.mmsi === 'number') {
const t = obj as AisTarget;
const sourceEvent = (info as { srcEvent?: { shiftKey?: boolean; ctrlKey?: boolean; metaKey?: boolean } | null }).srcEvent;
if (sourceEvent && hasAuxiliarySelectModifier(sourceEvent)) {
onToggleHighlightMmsi?.(t.mmsi);
return;
}
onSelectMmsi(t.mmsi);
const clickOpts = { center: [t.lon, t.lat] as [number, number], zoom: Math.max(map.getZoom(), 10), duration: 600 };
if (projectionRef.current === 'globe') {
map.flyTo(clickOpts);
} else {
map.easeTo(clickOpts);
}
}
},
};
try {
deckTarget.setProps(deckProps as never);
} catch (e) {
console.error('Failed to apply base mercator deck props. Falling back to empty layer set.', e);
try {
deckTarget.setProps({ ...deckProps, layers: [] as unknown[] } as never);
} catch {
// Ignore secondary failure.
}
}
}, [
ensureMercatorOverlay,
projection,
shipLayerData,
shipByMmsi,
pairRanges,
pairLinks,
fcDashed,
fleetCircles,
legacyTargetsOrdered,
legacyHits,
legacyOverlayTargets,
shipOverlayLayerData,
pairRangesInteractive,
pairLinksInteractive,
fcLinesInteractive,
fleetCirclesInteractive,
overlays.pairRange,
overlays.pairLines,
overlays.fcLines,
overlays.fleetCircles,
settings.showDensity,
settings.showShips,
onDeckSelectOrHighlight,
onSelectMmsi,
onToggleHighlightMmsi,
setDeckHoverPairs,
clearMapFleetHoverState,
setDeckHoverMmsi,
clearDeckHoverMmsi,
toFleetMmsiList,
touchDeckHoverState,
hasAuxiliarySelectModifier,
]);
// Globe Deck overlay
useEffect(() => {
const map = mapRef.current;
if (!map || projection !== 'globe' || projectionBusyRef.current) return;
const deckTarget = globeDeckLayerRef.current;
if (!deckTarget) return;
if (!ENABLE_GLOBE_DECK_OVERLAYS) {
try {
deckTarget.setProps({ layers: [], getTooltip: undefined, onClick: undefined } as never);
} catch {
// ignore
}
return;
}
const overlayParams = GLOBE_OVERLAY_PARAMS;
const globeLayers: unknown[] = [];
if (overlays.pairRange && pairRanges.length > 0) {
globeLayers.push(new ScatterplotLayer<PairRangeCircle>({ id: 'pair-range-globe', data: pairRanges, pickable: true, billboard: false, parameters: overlayParams, filled: false, stroked: true, radiusUnits: 'meters', getRadius: (d) => d.radiusNm * 1852, radiusMinPixels: 10, lineWidthUnits: 'pixels', getLineWidth: (d) => (isHighlightedPair(d.aMmsi, d.bMmsi) ? 2.2 : 1), getLineColor: (d) => { const hl = isHighlightedPair(d.aMmsi, d.bMmsi); if (hl) return d.warn ? PAIR_RANGE_WARN_DECK_HL : PAIR_RANGE_NORMAL_DECK_HL; return d.warn ? PAIR_RANGE_WARN_DECK : PAIR_RANGE_NORMAL_DECK; }, getPosition: (d) => d.center, onHover: (info) => { if (!info.object) { clearDeckHoverPairs(); clearDeckHoverMmsi(); return; } touchDeckHoverState(true); const p = info.object as PairRangeCircle; setDeckHoverPairs([p.aMmsi, p.bMmsi]); setDeckHoverMmsi([p.aMmsi, p.bMmsi]); clearMapFleetHoverState(); } }));
}
if (overlays.pairLines && (pairLinks?.length ?? 0) > 0) {
const links = pairLinks || [];
globeLayers.push(new LineLayer<PairLink>({ id: 'pair-lines-globe', data: links, pickable: true, parameters: overlayParams, getSourcePosition: (d) => d.from, getTargetPosition: (d) => d.to, getColor: (d) => { const hl = isHighlightedPair(d.aMmsi, d.bMmsi); if (hl) return d.warn ? PAIR_LINE_WARN_DECK_HL : PAIR_LINE_NORMAL_DECK_HL; return d.warn ? PAIR_LINE_WARN_DECK : PAIR_LINE_NORMAL_DECK; }, getWidth: (d) => (isHighlightedPair(d.aMmsi, d.bMmsi) ? 2.6 : d.warn ? 2.2 : 1.4), widthUnits: 'pixels', onHover: (info) => { if (!info.object) { clearDeckHoverPairs(); clearDeckHoverMmsi(); return; } touchDeckHoverState(true); const obj = info.object as PairLink; setDeckHoverPairs([obj.aMmsi, obj.bMmsi]); setDeckHoverMmsi([obj.aMmsi, obj.bMmsi]); clearMapFleetHoverState(); } }));
}
if (overlays.fcLines && fcDashed.length > 0) {
globeLayers.push(new LineLayer<DashSeg>({ id: 'fc-lines-globe', data: fcDashed, pickable: true, parameters: overlayParams, getSourcePosition: (d) => d.from, getTargetPosition: (d) => d.to, getColor: (d) => { const ih = [d.fromMmsi, d.toMmsi].some((v) => isHighlightedMmsi(v ?? -1)); if (ih) return d.suspicious ? FC_LINE_SUSPICIOUS_DECK_HL : FC_LINE_NORMAL_DECK_HL; return d.suspicious ? FC_LINE_SUSPICIOUS_DECK : FC_LINE_NORMAL_DECK; }, getWidth: (d) => { const ih = [d.fromMmsi, d.toMmsi].some((v) => isHighlightedMmsi(v ?? -1)); return ih ? 1.9 : 1.3; }, widthUnits: 'pixels', onHover: (info) => { if (!info.object) { clearDeckHoverPairs(); clearDeckHoverMmsi(); return; } touchDeckHoverState(true); const obj = info.object as DashSeg; if (obj.fromMmsi == null || obj.toMmsi == null) { clearDeckHoverPairs(); clearDeckHoverMmsi(); return; } setDeckHoverPairs([obj.fromMmsi, obj.toMmsi]); setDeckHoverMmsi([obj.fromMmsi, obj.toMmsi]); clearMapFleetHoverState(); } }));
}
if (overlays.fleetCircles && (fleetCircles?.length ?? 0) > 0) {
const circles = fleetCircles || [];
globeLayers.push(new ScatterplotLayer<FleetCircle>({ id: 'fleet-circles-globe', data: circles, pickable: true, billboard: false, parameters: overlayParams, filled: false, stroked: true, radiusUnits: 'meters', getRadius: (d) => d.radiusNm * 1852, lineWidthUnits: 'pixels', getLineWidth: (d) => (isHighlightedFleet(d.ownerKey, d.vesselMmsis) ? 1.8 : 1.1), getLineColor: (d) => (isHighlightedFleet(d.ownerKey, d.vesselMmsis) ? FLEET_RANGE_LINE_DECK_HL : FLEET_RANGE_LINE_DECK), getPosition: (d) => d.center, onHover: (info) => { if (!info.object) { clearDeckHoverPairs(); clearDeckHoverMmsi(); clearMapFleetHoverState(); return; } touchDeckHoverState(true); const obj = info.object as FleetCircle; const list = toFleetMmsiList(obj.vesselMmsis); setMapFleetHoverState(obj.ownerKey || null, list); setDeckHoverMmsi(list); clearDeckHoverPairs(); } }));
globeLayers.push(new ScatterplotLayer<FleetCircle>({ id: 'fleet-circles-fill-globe', data: circles, pickable: false, billboard: false, parameters: overlayParams, filled: true, stroked: false, radiusUnits: 'meters', getRadius: (d) => d.radiusNm * 1852, getFillColor: (d) => (isHighlightedFleet(d.ownerKey, d.vesselMmsis) ? FLEET_RANGE_FILL_DECK_HL : FLEET_RANGE_FILL_DECK), getPosition: (d) => d.center }));
}
if (settings.showShips && legacyTargetsOrdered.length > 0) {
globeLayers.push(new ScatterplotLayer<AisTarget>({ id: 'legacy-halo-globe', data: legacyTargetsOrdered, pickable: false, billboard: false, parameters: overlayParams, filled: false, stroked: true, radiusUnits: 'pixels', getRadius: (d) => { if (selectedMmsi && d.mmsi === selectedMmsi) return FLAT_LEGACY_HALO_RADIUS_SELECTED; return FLAT_LEGACY_HALO_RADIUS; }, lineWidthUnits: 'pixels', getLineWidth: (d) => (selectedMmsi && d.mmsi === selectedMmsi ? 2.5 : 2), getLineColor: (d) => { if (selectedMmsi && d.mmsi === selectedMmsi) return HALO_OUTLINE_COLOR_SELECTED; return HALO_OUTLINE_COLOR; }, getPosition: (d) => [d.lon, d.lat] as [number, number] }));
}
const normalizedLayers = sanitizeDeckLayerList(globeLayers);
const globeDeckProps = { layers: normalizedLayers, getTooltip: undefined, onClick: undefined };
try {
deckTarget.setProps(globeDeckProps as never);
} catch (e) {
console.error('Failed to apply globe deck props. Falling back to empty deck layer set.', e);
try {
deckTarget.setProps({ ...globeDeckProps, layers: [] as unknown[] } as never);
} catch {
// Ignore secondary failure.
}
}
}, [
projection,
pairRanges,
pairLinks,
fcDashed,
fleetCircles,
legacyTargetsOrdered,
overlays.pairRange,
overlays.pairLines,
overlays.fcLines,
overlays.fleetCircles,
settings.showShips,
selectedMmsi,
isHighlightedFleet,
isHighlightedPair,
clearDeckHoverPairs,
clearDeckHoverMmsi,
clearMapFleetHoverState,
setDeckHoverPairs,
setDeckHoverMmsi,
setMapFleetHoverState,
toFleetMmsiList,
touchDeckHoverState,
legacyHits,
]);
}

파일 보기

@ -0,0 +1,61 @@
import { useEffect, type MutableRefObject } from 'react';
import type maplibregl from 'maplibre-gl';
import { onMapStyleReady } from '../lib/mapCore';
import type { MapProjectionId } from '../types';
export function useFlyTo(
mapRef: MutableRefObject<maplibregl.Map | null>,
projectionRef: MutableRefObject<MapProjectionId>,
opts: {
selectedMmsi: number | null;
shipData: { mmsi: number; lon: number; lat: number }[];
fleetFocusId: string | number | undefined;
fleetFocusLon: number | undefined;
fleetFocusLat: number | undefined;
fleetFocusZoom: number | undefined;
},
) {
const { selectedMmsi, shipData, fleetFocusId, fleetFocusLon, fleetFocusLat, fleetFocusZoom } = opts;
useEffect(() => {
const map = mapRef.current;
if (!map) return;
if (!selectedMmsi) return;
const t = shipData.find((x) => x.mmsi === selectedMmsi);
if (!t) return;
const flyOpts = { center: [t.lon, t.lat] as [number, number], zoom: Math.max(map.getZoom(), 10), duration: 600 };
if (projectionRef.current === 'globe') {
map.flyTo(flyOpts);
} else {
map.easeTo(flyOpts);
}
}, [selectedMmsi, shipData]);
useEffect(() => {
const map = mapRef.current;
if (!map || fleetFocusLon == null || fleetFocusLat == null || !Number.isFinite(fleetFocusLon) || !Number.isFinite(fleetFocusLat))
return;
const lon = fleetFocusLon;
const lat = fleetFocusLat;
const zoom = fleetFocusZoom ?? 10;
const apply = () => {
const flyOpts = { center: [lon, lat] as [number, number], zoom, duration: 700 };
if (projectionRef.current === 'globe') {
map.flyTo(flyOpts);
} else {
map.easeTo(flyOpts);
}
};
if (map.isStyleLoaded()) {
apply();
return;
}
const stop = onMapStyleReady(map, apply);
return () => {
stop();
};
}, [fleetFocusId, fleetFocusLon, fleetFocusLat, fleetFocusZoom]);
}

파일 보기

@ -0,0 +1,318 @@
import { useCallback, useEffect, useRef, type MutableRefObject } from 'react';
import maplibregl from 'maplibre-gl';
import type { AisTarget } from '../../../entities/aisTarget/model/types';
import type { LegacyVesselInfo } from '../../../entities/legacyVessel/model/types';
import type { MapToggleState } from '../../../features/mapToggles/MapToggles';
import type { Map3DSettings, MapProjectionId } from '../types';
import { toIntMmsi, toSafeNumber } from '../lib/setUtils';
import {
getShipTooltipHtml,
getPairLinkTooltipHtml,
getFcLinkTooltipHtml,
getRangeTooltipHtml,
getFleetCircleTooltipHtml,
} from '../lib/tooltips';
import { getZoneIdFromProps, getZoneDisplayNameFromProps } from '../lib/zoneUtils';
export function useGlobeInteraction(
mapRef: MutableRefObject<maplibregl.Map | null>,
projectionBusyRef: MutableRefObject<boolean>,
opts: {
projection: MapProjectionId;
settings: Map3DSettings;
overlays: MapToggleState;
targets: AisTarget[];
shipData: AisTarget[];
shipByMmsi: Map<number, AisTarget>;
selectedMmsi: number | null;
hoveredZoneId: string | null;
legacyHits: Map<number, LegacyVesselInfo> | null | undefined;
clearDeckHoverPairs: () => void;
clearDeckHoverMmsi: () => void;
clearMapFleetHoverState: () => void;
setDeckHoverPairs: (next: number[]) => void;
setDeckHoverMmsi: (next: number[]) => void;
setMapFleetHoverState: (ownerKey: string | null, vesselMmsis: number[]) => void;
setHoveredZoneId: (updater: (prev: string | null) => string | null) => void;
},
) {
const {
projection, legacyHits, shipByMmsi,
clearDeckHoverPairs, clearDeckHoverMmsi, clearMapFleetHoverState,
setDeckHoverPairs, setDeckHoverMmsi, setMapFleetHoverState, setHoveredZoneId,
} = opts;
const mapTooltipRef = useRef<maplibregl.Popup | null>(null);
const clearGlobeTooltip = useCallback(() => {
if (!mapTooltipRef.current) return;
try {
mapTooltipRef.current.remove();
} catch {
// ignore
}
mapTooltipRef.current = null;
}, []);
// eslint-disable-next-line react-hooks/preserve-manual-memoization
const setGlobeTooltip = useCallback((lngLat: maplibregl.LngLatLike, tooltipHtml: string) => {
const map = mapRef.current;
if (!map || !map.isStyleLoaded()) return;
if (!mapTooltipRef.current) {
mapTooltipRef.current = new maplibregl.Popup({
closeButton: false,
closeOnClick: false,
maxWidth: '360px',
className: 'maplibre-tooltip-popup',
});
}
const container = document.createElement('div');
container.className = 'maplibre-tooltip-popup__content';
container.innerHTML = tooltipHtml;
mapTooltipRef.current.setLngLat(lngLat).setDOMContent(container).addTo(map);
}, []);
const buildGlobeFeatureTooltip = useCallback(
(feature: { properties?: Record<string, unknown> | null; layer?: { id?: string } } | null | undefined) => {
if (!feature) return null;
const props = feature.properties || {};
const layerId = feature.layer?.id;
const maybeMmsi = toIntMmsi(props.mmsi);
if (maybeMmsi != null && maybeMmsi > 0) {
return getShipTooltipHtml({ mmsi: maybeMmsi, targetByMmsi: shipByMmsi, legacyHits });
}
if (layerId === 'pair-lines-ml') {
const warn = props.warn === true;
const aMmsi = toIntMmsi(props.aMmsi);
const bMmsi = toIntMmsi(props.bMmsi);
if (aMmsi == null || bMmsi == null) return null;
return getPairLinkTooltipHtml({
warn, distanceNm: toSafeNumber(props.distanceNm),
aMmsi, bMmsi, legacyHits, targetByMmsi: shipByMmsi,
});
}
if (layerId === 'fc-lines-ml') {
const fcMmsi = toIntMmsi(props.fcMmsi);
const otherMmsi = toIntMmsi(props.otherMmsi);
if (fcMmsi == null || otherMmsi == null) return null;
return getFcLinkTooltipHtml({
suspicious: props.suspicious === true,
distanceNm: toSafeNumber(props.distanceNm),
fcMmsi, otherMmsi, legacyHits, targetByMmsi: shipByMmsi,
});
}
if (layerId === 'pair-range-ml') {
const aMmsi = toIntMmsi(props.aMmsi);
const bMmsi = toIntMmsi(props.bMmsi);
if (aMmsi == null || bMmsi == null) return null;
return getRangeTooltipHtml({
warn: props.warn === true,
distanceNm: toSafeNumber(props.distanceNm),
aMmsi, bMmsi, legacyHits,
});
}
if (layerId === 'fleet-circles-ml') {
return getFleetCircleTooltipHtml({
ownerKey: String(props.ownerKey ?? ''),
ownerLabel: String(props.ownerLabel ?? props.ownerKey ?? ''),
count: Number(props.count ?? 0),
});
}
const zoneLabel = getZoneDisplayNameFromProps(props);
if (zoneLabel) {
return { html: `<div style="font-size: 12px; font-family: system-ui;">${zoneLabel}</div>` };
}
return null;
},
[legacyHits, shipByMmsi],
);
useEffect(() => {
const map = mapRef.current;
if (!map) return;
const clearDeckGlobeHoverState = () => {
clearDeckHoverMmsi();
clearDeckHoverPairs();
setHoveredZoneId((prev) => (prev === null ? prev : null));
clearMapFleetHoverState();
};
const resetGlobeHoverStates = () => {
clearDeckHoverMmsi();
clearDeckHoverPairs();
setHoveredZoneId((prev) => (prev === null ? prev : null));
clearMapFleetHoverState();
};
const normalizeMmsiList = (value: unknown): number[] => {
if (!Array.isArray(value)) return [];
const out: number[] = [];
for (const n of value) {
const m = toIntMmsi(n);
if (m != null) out.push(m);
}
return out;
};
const onMouseMove = (e: maplibregl.MapMouseEvent) => {
if (projection !== 'globe') {
clearGlobeTooltip();
resetGlobeHoverStates();
return;
}
if (projectionBusyRef.current) {
resetGlobeHoverStates();
clearGlobeTooltip();
return;
}
if (!map.isStyleLoaded()) {
clearDeckGlobeHoverState();
clearGlobeTooltip();
return;
}
let candidateLayerIds: string[] = [];
try {
candidateLayerIds = [
'ships-globe', 'ships-globe-halo', 'ships-globe-outline',
'pair-lines-ml', 'fc-lines-ml',
'fleet-circles-ml',
'pair-range-ml',
'zones-fill', 'zones-line', 'zones-label',
].filter((id) => map.getLayer(id));
} catch {
candidateLayerIds = [];
}
if (candidateLayerIds.length === 0) {
resetGlobeHoverStates();
clearGlobeTooltip();
return;
}
let rendered: Array<{ properties?: Record<string, unknown> | null; layer?: { id?: string } }> = [];
try {
rendered = map.queryRenderedFeatures(e.point, { layers: candidateLayerIds }) as unknown as Array<{
properties?: Record<string, unknown> | null;
layer?: { id?: string };
}>;
} catch {
rendered = [];
}
const priority = [
'ships-globe', 'ships-globe-halo', 'ships-globe-outline',
'pair-lines-ml', 'fc-lines-ml', 'pair-range-ml',
'fleet-circles-ml',
'zones-fill', 'zones-line', 'zones-label',
];
const first = priority.map((id) => rendered.find((r) => r.layer?.id === id)).find(Boolean) as
| { properties?: Record<string, unknown> | null; layer?: { id?: string } }
| undefined;
if (!first) {
resetGlobeHoverStates();
clearGlobeTooltip();
return;
}
const layerId = first.layer?.id;
const props = first.properties || {};
const isShipLayer = layerId === 'ships-globe' || layerId === 'ships-globe-halo' || layerId === 'ships-globe-outline';
const isPairLayer = layerId === 'pair-lines-ml' || layerId === 'pair-range-ml';
const isFcLayer = layerId === 'fc-lines-ml';
const isFleetLayer = layerId === 'fleet-circles-ml';
const isZoneLayer = layerId === 'zones-fill' || layerId === 'zones-line' || layerId === 'zones-label';
if (isShipLayer) {
const mmsi = toIntMmsi(props.mmsi);
setDeckHoverMmsi(mmsi == null ? [] : [mmsi]);
clearDeckHoverPairs();
clearMapFleetHoverState();
setHoveredZoneId((prev) => (prev === null ? prev : null));
} else if (isPairLayer) {
const aMmsi = toIntMmsi(props.aMmsi);
const bMmsi = toIntMmsi(props.bMmsi);
setDeckHoverPairs([...(aMmsi == null ? [] : [aMmsi]), ...(bMmsi == null ? [] : [bMmsi])]);
clearDeckHoverMmsi();
clearMapFleetHoverState();
setHoveredZoneId((prev) => (prev === null ? prev : null));
} else if (isFcLayer) {
const from = toIntMmsi(props.fcMmsi);
const to = toIntMmsi(props.otherMmsi);
const fromTo = [from, to].filter((v): v is number => v != null);
setDeckHoverPairs(fromTo);
setDeckHoverMmsi(fromTo);
clearMapFleetHoverState();
setHoveredZoneId((prev) => (prev === null ? prev : null));
} else if (isFleetLayer) {
const ownerKey = String(props.ownerKey ?? '');
const list = normalizeMmsiList(props.vesselMmsis);
setMapFleetHoverState(ownerKey || null, list);
clearDeckHoverMmsi();
clearDeckHoverPairs();
setHoveredZoneId((prev) => (prev === null ? prev : null));
} else if (isZoneLayer) {
clearMapFleetHoverState();
clearDeckHoverMmsi();
clearDeckHoverPairs();
const zoneId = getZoneIdFromProps(props);
setHoveredZoneId(() => zoneId || null);
} else {
resetGlobeHoverStates();
}
const tooltip = buildGlobeFeatureTooltip(first);
if (!tooltip) {
if (!isZoneLayer) {
resetGlobeHoverStates();
}
clearGlobeTooltip();
return;
}
const content = tooltip?.html ?? '';
if (content) {
setGlobeTooltip(e.lngLat, content);
return;
}
clearGlobeTooltip();
};
const onMouseOut = () => {
resetGlobeHoverStates();
clearGlobeTooltip();
};
map.on('mousemove', onMouseMove);
map.on('mouseout', onMouseOut);
return () => {
map.off('mousemove', onMouseMove);
map.off('mouseout', onMouseOut);
clearGlobeTooltip();
};
}, [
projection,
buildGlobeFeatureTooltip,
clearGlobeTooltip,
clearMapFleetHoverState,
clearDeckHoverPairs,
clearDeckHoverMmsi,
setDeckHoverPairs,
setDeckHoverMmsi,
setMapFleetHoverState,
setGlobeTooltip,
]);
}

파일 보기

@ -0,0 +1,524 @@
import { useCallback, useEffect, type MutableRefObject } from 'react';
import type maplibregl from 'maplibre-gl';
import type { GeoJSONSource, GeoJSONSourceSpecification, LayerSpecification } from 'maplibre-gl';
import type { FcLink, FleetCircle, PairLink } from '../../../features/legacyDashboard/model/types';
import type { MapToggleState } from '../../../features/mapToggles/MapToggles';
import type { DashSeg, MapProjectionId, PairRangeCircle } from '../types';
import {
PAIR_LINE_NORMAL_ML, PAIR_LINE_WARN_ML,
PAIR_LINE_NORMAL_ML_HL, PAIR_LINE_WARN_ML_HL,
PAIR_RANGE_NORMAL_ML, PAIR_RANGE_WARN_ML,
PAIR_RANGE_NORMAL_ML_HL, PAIR_RANGE_WARN_ML_HL,
FC_LINE_NORMAL_ML, FC_LINE_SUSPICIOUS_ML,
FC_LINE_NORMAL_ML_HL, FC_LINE_SUSPICIOUS_ML_HL,
FLEET_LINE_ML, FLEET_LINE_ML_HL,
} from '../constants';
import { makeUniqueSorted } from '../lib/setUtils';
import {
makePairLinkFeatureId,
makeFcSegmentFeatureId,
makeFleetCircleFeatureId,
} from '../lib/featureIds';
import {
makeMmsiPairHighlightExpr,
makeMmsiAnyEndpointExpr,
makeFleetOwnerMatchExpr,
makeFleetMemberMatchExpr,
} from '../lib/mlExpressions';
import { kickRepaint, onMapStyleReady } from '../lib/mapCore';
import { circleRingLngLat } from '../lib/geometry';
import { guardedSetVisibility } from '../lib/layerHelpers';
import { dashifyLine } from '../lib/dashifyLine';
export function useGlobeOverlays(
mapRef: MutableRefObject<maplibregl.Map | null>,
projectionBusyRef: MutableRefObject<boolean>,
reorderGlobeFeatureLayers: () => void,
opts: {
overlays: MapToggleState;
pairLinks: PairLink[] | undefined;
fcLinks: FcLink[] | undefined;
fleetCircles: FleetCircle[] | undefined;
projection: MapProjectionId;
mapSyncEpoch: number;
hoveredFleetMmsiList: number[];
hoveredFleetOwnerKeyList: string[];
hoveredPairMmsiList: number[];
},
) {
const {
overlays, pairLinks, fcLinks, fleetCircles, projection, mapSyncEpoch,
hoveredFleetMmsiList, hoveredFleetOwnerKeyList, hoveredPairMmsiList,
} = opts;
// Pair lines
useEffect(() => {
const map = mapRef.current;
if (!map) return;
const srcId = 'pair-lines-ml-src';
const layerId = 'pair-lines-ml';
const remove = () => {
guardedSetVisibility(map, layerId, 'none');
};
const ensure = () => {
if (projectionBusyRef.current) return;
if (!map.isStyleLoaded()) return;
if (projection !== 'globe' || !overlays.pairLines || (pairLinks?.length ?? 0) === 0) {
remove();
return;
}
const fc: GeoJSON.FeatureCollection<GeoJSON.LineString> = {
type: 'FeatureCollection',
features: (pairLinks || []).map((p) => ({
type: 'Feature',
id: makePairLinkFeatureId(p.aMmsi, p.bMmsi),
geometry: { type: 'LineString', coordinates: [p.from, p.to] },
properties: {
type: 'pair',
aMmsi: p.aMmsi,
bMmsi: p.bMmsi,
distanceNm: p.distanceNm,
warn: p.warn,
},
})),
};
try {
const existing = map.getSource(srcId) as GeoJSONSource | undefined;
if (existing) existing.setData(fc);
else map.addSource(srcId, { type: 'geojson', data: fc } as GeoJSONSourceSpecification);
} catch (e) {
console.warn('Pair lines source setup failed:', e);
return;
}
if (!map.getLayer(layerId)) {
try {
map.addLayer(
{
id: layerId,
type: 'line',
source: srcId,
layout: { 'line-cap': 'round', 'line-join': 'round', visibility: 'visible' },
paint: {
'line-color': [
'case',
['==', ['get', 'highlighted'], 1],
['case', ['boolean', ['get', 'warn'], false], PAIR_LINE_WARN_ML_HL, PAIR_LINE_NORMAL_ML_HL],
['boolean', ['get', 'warn'], false],
PAIR_LINE_WARN_ML,
PAIR_LINE_NORMAL_ML,
] as never,
'line-width': [
'case',
['==', ['get', 'highlighted'], 1], 2.8,
['boolean', ['get', 'warn'], false], 2.2,
1.4,
] as never,
'line-opacity': 0.9,
},
} as unknown as LayerSpecification,
undefined,
);
} catch (e) {
console.warn('Pair lines layer add failed:', e);
}
} else {
guardedSetVisibility(map, layerId, 'visible');
}
reorderGlobeFeatureLayers();
kickRepaint(map);
};
const stop = onMapStyleReady(map, ensure);
ensure();
return () => {
stop();
};
}, [projection, overlays.pairLines, pairLinks, mapSyncEpoch, reorderGlobeFeatureLayers]);
// FC lines
useEffect(() => {
const map = mapRef.current;
if (!map) return;
const srcId = 'fc-lines-ml-src';
const layerId = 'fc-lines-ml';
const remove = () => {
guardedSetVisibility(map, layerId, 'none');
};
const ensure = () => {
if (projectionBusyRef.current) return;
if (!map.isStyleLoaded()) return;
if (projection !== 'globe' || !overlays.fcLines) {
remove();
return;
}
const segs: DashSeg[] = [];
for (const l of fcLinks || []) {
segs.push(...dashifyLine(l.from, l.to, l.suspicious, l.distanceNm, l.fcMmsi, l.otherMmsi));
}
if (segs.length === 0) {
remove();
return;
}
const fc: GeoJSON.FeatureCollection<GeoJSON.LineString> = {
type: 'FeatureCollection',
features: segs.map((s, idx) => ({
type: 'Feature',
id: makeFcSegmentFeatureId(s.fromMmsi ?? -1, s.toMmsi ?? -1, idx),
geometry: { type: 'LineString', coordinates: [s.from, s.to] },
properties: {
type: 'fc',
suspicious: s.suspicious,
distanceNm: s.distanceNm,
fcMmsi: s.fromMmsi ?? -1,
otherMmsi: s.toMmsi ?? -1,
},
})),
};
try {
const existing = map.getSource(srcId) as GeoJSONSource | undefined;
if (existing) existing.setData(fc);
else map.addSource(srcId, { type: 'geojson', data: fc } as GeoJSONSourceSpecification);
} catch (e) {
console.warn('FC lines source setup failed:', e);
return;
}
if (!map.getLayer(layerId)) {
try {
map.addLayer(
{
id: layerId,
type: 'line',
source: srcId,
layout: { 'line-cap': 'round', 'line-join': 'round', visibility: 'visible' },
paint: {
'line-color': [
'case',
['==', ['get', 'highlighted'], 1],
['case', ['boolean', ['get', 'suspicious'], false], FC_LINE_SUSPICIOUS_ML_HL, FC_LINE_NORMAL_ML_HL],
['boolean', ['get', 'suspicious'], false],
FC_LINE_SUSPICIOUS_ML,
FC_LINE_NORMAL_ML,
] as never,
'line-width': ['case', ['==', ['get', 'highlighted'], 1], 2.0, 1.3] as never,
'line-opacity': 0.9,
},
} as unknown as LayerSpecification,
undefined,
);
} catch (e) {
console.warn('FC lines layer add failed:', e);
}
} else {
guardedSetVisibility(map, layerId, 'visible');
}
reorderGlobeFeatureLayers();
kickRepaint(map);
};
const stop = onMapStyleReady(map, ensure);
ensure();
return () => {
stop();
};
}, [projection, overlays.fcLines, fcLinks, mapSyncEpoch, reorderGlobeFeatureLayers]);
// Fleet circles
useEffect(() => {
const map = mapRef.current;
if (!map) return;
const srcId = 'fleet-circles-ml-src';
const layerId = 'fleet-circles-ml';
// fill layer 제거됨 — globe tessellation에서 vertex 65535 초과 경고 원인
// 라인만으로 fleet circle 시각화 충분
const remove = () => {
guardedSetVisibility(map, layerId, 'none');
};
const ensure = () => {
if (projectionBusyRef.current) return;
if (!map.isStyleLoaded()) return;
if (projection !== 'globe' || !overlays.fleetCircles || (fleetCircles?.length ?? 0) === 0) {
remove();
return;
}
const fcLine: GeoJSON.FeatureCollection<GeoJSON.LineString> = {
type: 'FeatureCollection',
features: (fleetCircles || []).map((c) => {
const ring = circleRingLngLat(c.center, c.radiusNm * 1852);
return {
type: 'Feature',
id: makeFleetCircleFeatureId(c.ownerKey),
geometry: { type: 'LineString', coordinates: ring },
properties: {
type: 'fleet',
ownerKey: c.ownerKey,
ownerLabel: c.ownerLabel,
count: c.count,
vesselMmsis: c.vesselMmsis,
highlighted: 0,
},
};
}),
};
try {
const existing = map.getSource(srcId) as GeoJSONSource | undefined;
if (existing) existing.setData(fcLine);
else map.addSource(srcId, { type: 'geojson', data: fcLine } as GeoJSONSourceSpecification);
} catch (e) {
console.warn('Fleet circles source setup failed:', e);
return;
}
if (!map.getLayer(layerId)) {
try {
map.addLayer(
{
id: layerId,
type: 'line',
source: srcId,
layout: { 'line-cap': 'round', 'line-join': 'round', visibility: 'visible' },
paint: {
'line-color': ['case', ['==', ['get', 'highlighted'], 1], FLEET_LINE_ML_HL, FLEET_LINE_ML] as never,
'line-width': ['case', ['==', ['get', 'highlighted'], 1], 2, 1.1] as never,
'line-opacity': 0.85,
},
} as unknown as LayerSpecification,
undefined,
);
} catch (e) {
console.warn('Fleet circles layer add failed:', e);
}
} else {
guardedSetVisibility(map, layerId, 'visible');
}
reorderGlobeFeatureLayers();
kickRepaint(map);
};
const stop = onMapStyleReady(map, ensure);
ensure();
return () => {
stop();
};
}, [projection, overlays.fleetCircles, fleetCircles, mapSyncEpoch, reorderGlobeFeatureLayers]);
// Pair range
useEffect(() => {
const map = mapRef.current;
if (!map) return;
const srcId = 'pair-range-ml-src';
const layerId = 'pair-range-ml';
const remove = () => {
guardedSetVisibility(map, layerId, 'none');
};
const ensure = () => {
if (projectionBusyRef.current) return;
if (!map.isStyleLoaded()) return;
if (projection !== 'globe' || !overlays.pairRange) {
remove();
return;
}
const ranges: PairRangeCircle[] = [];
for (const p of pairLinks || []) {
const center: [number, number] = [(p.from[0] + p.to[0]) / 2, (p.from[1] + p.to[1]) / 2];
ranges.push({
center,
radiusNm: Math.max(0.05, p.distanceNm / 2),
warn: p.warn,
aMmsi: p.aMmsi,
bMmsi: p.bMmsi,
distanceNm: p.distanceNm,
});
}
if (ranges.length === 0) {
remove();
return;
}
const fc: GeoJSON.FeatureCollection<GeoJSON.LineString> = {
type: 'FeatureCollection',
features: ranges.map((c) => {
const ring = circleRingLngLat(c.center, c.radiusNm * 1852);
return {
type: 'Feature',
id: makePairLinkFeatureId(c.aMmsi, c.bMmsi),
geometry: { type: 'LineString', coordinates: ring },
properties: {
type: 'pair-range',
warn: c.warn,
aMmsi: c.aMmsi,
bMmsi: c.bMmsi,
distanceNm: c.distanceNm,
highlighted: 0,
},
};
}),
};
try {
const existing = map.getSource(srcId) as GeoJSONSource | undefined;
if (existing) existing.setData(fc);
else map.addSource(srcId, { type: 'geojson', data: fc } as GeoJSONSourceSpecification);
} catch (e) {
console.warn('Pair range source setup failed:', e);
return;
}
if (!map.getLayer(layerId)) {
try {
map.addLayer(
{
id: layerId,
type: 'line',
source: srcId,
layout: { 'line-cap': 'round', 'line-join': 'round', visibility: 'visible' },
paint: {
'line-color': [
'case',
['==', ['get', 'highlighted'], 1],
['case', ['boolean', ['get', 'warn'], false], PAIR_RANGE_WARN_ML_HL, PAIR_RANGE_NORMAL_ML_HL],
['boolean', ['get', 'warn'], false],
PAIR_RANGE_WARN_ML,
PAIR_RANGE_NORMAL_ML,
] as never,
'line-width': ['case', ['==', ['get', 'highlighted'], 1], 1.6, 1.0] as never,
'line-opacity': 0.85,
},
} as unknown as LayerSpecification,
undefined,
);
} catch (e) {
console.warn('Pair range layer add failed:', e);
}
} else {
guardedSetVisibility(map, layerId, 'visible');
}
kickRepaint(map);
};
const stop = onMapStyleReady(map, ensure);
ensure();
return () => {
stop();
};
}, [projection, overlays.pairRange, pairLinks, mapSyncEpoch, reorderGlobeFeatureLayers]);
// Paint state updates for hover highlights
// eslint-disable-next-line react-hooks/preserve-manual-memoization
const updateGlobeOverlayPaintStates = useCallback(() => {
if (projection !== 'globe' || projectionBusyRef.current) return;
const map = mapRef.current;
if (!map || !map.isStyleLoaded()) return;
const fleetAwarePairMmsiList = makeUniqueSorted([...hoveredPairMmsiList, ...hoveredFleetMmsiList]);
const pairHighlightExpr = hoveredPairMmsiList.length >= 2
? makeMmsiPairHighlightExpr('aMmsi', 'bMmsi', hoveredPairMmsiList)
: false;
const fcEndpointHighlightExpr = fleetAwarePairMmsiList.length > 0
? makeMmsiAnyEndpointExpr('fcMmsi', 'otherMmsi', fleetAwarePairMmsiList)
: false;
const fleetOwnerMatchExpr =
hoveredFleetOwnerKeyList.length > 0 ? makeFleetOwnerMatchExpr(hoveredFleetOwnerKeyList) : false;
const fleetMemberExpr =
hoveredFleetMmsiList.length > 0 ? makeFleetMemberMatchExpr(hoveredFleetMmsiList) : false;
const fleetHighlightExpr =
hoveredFleetOwnerKeyList.length > 0 || hoveredFleetMmsiList.length > 0
? (['any', fleetOwnerMatchExpr, fleetMemberExpr] as never)
: false;
try {
if (map.getLayer('pair-lines-ml')) {
map.setPaintProperty(
'pair-lines-ml', 'line-color',
['case', pairHighlightExpr, ['case', ['boolean', ['get', 'warn'], false], PAIR_LINE_WARN_ML_HL, PAIR_LINE_NORMAL_ML_HL], ['boolean', ['get', 'warn'], false], PAIR_LINE_WARN_ML, PAIR_LINE_NORMAL_ML] as never,
);
map.setPaintProperty(
'pair-lines-ml', 'line-width',
['case', pairHighlightExpr, 2.8, ['boolean', ['get', 'warn'], false], 2.2, 1.4] as never,
);
}
} catch {
// ignore
}
try {
if (map.getLayer('fc-lines-ml')) {
map.setPaintProperty(
'fc-lines-ml', 'line-color',
['case', fcEndpointHighlightExpr, ['case', ['boolean', ['get', 'suspicious'], false], FC_LINE_SUSPICIOUS_ML_HL, FC_LINE_NORMAL_ML_HL], ['boolean', ['get', 'suspicious'], false], FC_LINE_SUSPICIOUS_ML, FC_LINE_NORMAL_ML] as never,
);
map.setPaintProperty(
'fc-lines-ml', 'line-width',
['case', fcEndpointHighlightExpr, 2.0, 1.3] as never,
);
}
} catch {
// ignore
}
try {
if (map.getLayer('pair-range-ml')) {
map.setPaintProperty(
'pair-range-ml', 'line-color',
['case', pairHighlightExpr, ['case', ['boolean', ['get', 'warn'], false], PAIR_RANGE_WARN_ML_HL, PAIR_RANGE_NORMAL_ML_HL], ['boolean', ['get', 'warn'], false], PAIR_RANGE_WARN_ML, PAIR_RANGE_NORMAL_ML] as never,
);
map.setPaintProperty(
'pair-range-ml', 'line-width',
['case', pairHighlightExpr, 1.6, 1.0] as never,
);
}
} catch {
// ignore
}
try {
// fleet-circles-ml-fill 제거됨 (vertex 65535 경고 원인)
if (map.getLayer('fleet-circles-ml')) {
map.setPaintProperty('fleet-circles-ml', 'line-color', ['case', fleetHighlightExpr, FLEET_LINE_ML_HL, FLEET_LINE_ML] as never);
map.setPaintProperty('fleet-circles-ml', 'line-width', ['case', fleetHighlightExpr, 2, 1.1] as never);
}
} catch {
// ignore
}
}, [projection, hoveredFleetMmsiList, hoveredFleetOwnerKeyList, hoveredPairMmsiList]);
useEffect(() => {
const map = mapRef.current;
if (!map) return;
const stop = onMapStyleReady(map, updateGlobeOverlayPaintStates);
updateGlobeOverlayPaintStates();
return () => {
stop();
};
}, [mapSyncEpoch, hoveredFleetMmsiList, hoveredFleetOwnerKeyList, hoveredPairMmsiList, projection, updateGlobeOverlayPaintStates]);
}

파일 보기

@ -0,0 +1,890 @@
import { useEffect, useMemo, useRef, type MutableRefObject } from 'react';
import type maplibregl from 'maplibre-gl';
import type { GeoJSONSource, GeoJSONSourceSpecification, LayerSpecification } from 'maplibre-gl';
import type { AisTarget } from '../../../entities/aisTarget/model/types';
import type { LegacyVesselInfo } from '../../../entities/legacyVessel/model/types';
import type { MapToggleState } from '../../../features/mapToggles/MapToggles';
import type { Map3DSettings, MapProjectionId } from '../types';
import {
ANCHORED_SHIP_ICON_ID,
GLOBE_ICON_HEADING_OFFSET_DEG,
GLOBE_OUTLINE_PERMITTED,
GLOBE_OUTLINE_OTHER,
DEG2RAD,
} from '../constants';
import { isFiniteNumber } from '../lib/setUtils';
import { GLOBE_SHIP_CIRCLE_RADIUS_EXPR } from '../lib/mlExpressions';
import { kickRepaint, onMapStyleReady } from '../lib/mapCore';
import {
isAnchoredShip,
getDisplayHeading,
getGlobeBaseShipColor,
} from '../lib/shipUtils';
import {
buildFallbackGlobeAnchoredShipIcon,
ensureFallbackShipImage,
} from '../lib/globeShipIcon';
import { clampNumber } from '../lib/geometry';
import { guardedSetVisibility } from '../lib/layerHelpers';
export function useGlobeShips(
mapRef: MutableRefObject<maplibregl.Map | null>,
projectionBusyRef: MutableRefObject<boolean>,
reorderGlobeFeatureLayers: () => void,
opts: {
projection: MapProjectionId;
settings: Map3DSettings;
shipData: AisTarget[];
shipHighlightSet: Set<number>;
shipHoverOverlaySet: Set<number>;
shipOverlayLayerData: AisTarget[];
shipLayerData: AisTarget[];
shipByMmsi: Map<number, AisTarget>;
mapSyncEpoch: number;
onSelectMmsi: (mmsi: number | null) => void;
onToggleHighlightMmsi?: (mmsi: number) => void;
targets: AisTarget[];
overlays: MapToggleState;
legacyHits: Map<number, LegacyVesselInfo> | null | undefined;
selectedMmsi: number | null;
isBaseHighlightedMmsi: (mmsi: number) => boolean;
hasAuxiliarySelectModifier: (ev?: { shiftKey?: boolean; ctrlKey?: boolean; metaKey?: boolean } | null) => boolean;
onGlobeShipsReady?: (ready: boolean) => void;
},
) {
const {
projection, settings, shipData, shipHighlightSet, shipHoverOverlaySet,
shipLayerData, mapSyncEpoch, onSelectMmsi, onToggleHighlightMmsi, targets,
overlays, legacyHits, selectedMmsi, isBaseHighlightedMmsi, hasAuxiliarySelectModifier,
onGlobeShipsReady,
} = opts;
const globeShipsEpochRef = useRef(-1);
const globeHoverShipSignatureRef = useRef('');
// Globe GeoJSON을 projection과 무관하게 항상 사전 계산
// Globe 전환 시 즉시 사용 가능하도록 useMemo로 캐싱
const globeShipGeoJson = useMemo((): GeoJSON.FeatureCollection<GeoJSON.Point> => {
return {
type: 'FeatureCollection',
features: shipData.map((t) => {
const legacy = legacyHits?.get(t.mmsi) ?? null;
const labelName = legacy?.shipNameCn || legacy?.shipNameRoman || t.name || '';
const heading = getDisplayHeading({
cog: t.cog,
heading: t.heading,
offset: GLOBE_ICON_HEADING_OFFSET_DEG,
});
const isAnchored = isAnchoredShip({ sog: t.sog, cog: t.cog, heading: t.heading });
const shipHeading = isAnchored ? 0 : heading;
const hull = clampNumber(
(isFiniteNumber(t.length) ? t.length : 0) + (isFiniteNumber(t.width) ? t.width : 0) * 3,
50, 420,
);
const sizeScale = clampNumber(0.85 + (hull - 50) / 420, 0.82, 1.85);
const selected = t.mmsi === selectedMmsi;
const highlighted = isBaseHighlightedMmsi(t.mmsi);
const selectedScale = selected ? 1.08 : 1;
const highlightScale = highlighted ? 1.06 : 1;
const iconScale = selected ? selectedScale : highlightScale;
const iconSize3 = clampNumber(0.35 * sizeScale * selectedScale, 0.25, 1.3);
const iconSize7 = clampNumber(0.45 * sizeScale * selectedScale, 0.3, 1.45);
const iconSize10 = clampNumber(0.58 * sizeScale * selectedScale, 0.35, 1.8);
const iconSize14 = clampNumber(0.85 * sizeScale * selectedScale, 0.45, 2.6);
const iconSize18 = clampNumber(2.5 * sizeScale * selectedScale, 1.0, 6.0);
return {
type: 'Feature' as const,
...(isFiniteNumber(t.mmsi) ? { id: Math.trunc(t.mmsi) } : {}),
geometry: { type: 'Point' as const, coordinates: [t.lon, t.lat] },
properties: {
mmsi: t.mmsi,
name: t.name || '',
labelName,
cog: shipHeading,
heading: shipHeading,
sog: isFiniteNumber(t.sog) ? t.sog : 0,
isAnchored: isAnchored ? 1 : 0,
shipColor: getGlobeBaseShipColor({
legacy: legacy?.shipCode || null,
sog: isFiniteNumber(t.sog) ? t.sog : null,
}),
iconSize3: iconSize3 * iconScale,
iconSize7: iconSize7 * iconScale,
iconSize10: iconSize10 * iconScale,
iconSize14: iconSize14 * iconScale,
iconSize18: iconSize18 * iconScale,
sizeScale,
selected: selected ? 1 : 0,
highlighted: highlighted ? 1 : 0,
permitted: legacy ? 1 : 0,
code: legacy?.shipCode || '',
},
};
}),
};
}, [shipData, legacyHits, selectedMmsi, isBaseHighlightedMmsi]);
// Ship name labels in mercator
useEffect(() => {
const map = mapRef.current;
if (!map) return;
const srcId = 'ship-labels-src';
const layerId = 'ship-labels';
const remove = () => {
try {
if (map.getLayer(layerId)) map.removeLayer(layerId);
} catch {
// ignore
}
try {
if (map.getSource(srcId)) map.removeSource(srcId);
} catch {
// ignore
}
};
const ensure = () => {
if (projectionBusyRef.current) return;
if (!map.isStyleLoaded()) return;
if (projection !== 'mercator' || !settings.showShips) {
remove();
return;
}
const visibility = overlays.shipLabels ? 'visible' : 'none';
const features: GeoJSON.Feature<GeoJSON.Point>[] = [];
for (const t of shipData) {
const legacy = legacyHits?.get(t.mmsi) ?? null;
const isTarget = !!legacy;
const isSelected = selectedMmsi != null && t.mmsi === selectedMmsi;
const isPinnedHighlight = shipHighlightSet.has(t.mmsi);
if (!isTarget && !isSelected && !isPinnedHighlight) continue;
const labelName = (legacy?.shipNameCn || legacy?.shipNameRoman || t.name || '').trim();
if (!labelName) continue;
features.push({
type: 'Feature',
id: `ship-label-${t.mmsi}`,
geometry: { type: 'Point', coordinates: [t.lon, t.lat] },
properties: {
mmsi: t.mmsi,
labelName,
selected: isSelected ? 1 : 0,
highlighted: isPinnedHighlight ? 1 : 0,
permitted: isTarget ? 1 : 0,
},
});
}
const fc: GeoJSON.FeatureCollection<GeoJSON.Point> = { type: 'FeatureCollection', features };
try {
const existing = map.getSource(srcId) as GeoJSONSource | undefined;
if (existing) existing.setData(fc);
else map.addSource(srcId, { type: 'geojson', data: fc } as GeoJSONSourceSpecification);
} catch (e) {
console.warn('Ship label source setup failed:', e);
return;
}
const filter = ['!=', ['to-string', ['coalesce', ['get', 'labelName'], '']], ''] as unknown as unknown[];
if (!map.getLayer(layerId)) {
try {
map.addLayer(
{
id: layerId,
type: 'symbol',
source: srcId,
minzoom: 7,
filter: filter as never,
layout: {
visibility,
'symbol-placement': 'point',
'text-field': ['get', 'labelName'] as never,
'text-font': ['Noto Sans Regular', 'Open Sans Regular'],
'text-size': ['interpolate', ['linear'], ['zoom'], 7, 10, 10, 11, 12, 12, 14, 13] as never,
'text-anchor': 'top',
'text-offset': [0, 1.1],
'text-padding': 2,
'text-allow-overlap': false,
'text-ignore-placement': false,
},
paint: {
'text-color': [
'case',
['==', ['get', 'selected'], 1],
'rgba(14,234,255,0.95)',
['==', ['get', 'highlighted'], 1],
'rgba(245,158,11,0.95)',
'rgba(226,232,240,0.92)',
] as never,
'text-halo-color': 'rgba(2,6,23,0.85)',
'text-halo-width': 1.2,
'text-halo-blur': 0.8,
},
} as unknown as LayerSpecification,
undefined,
);
} catch (e) {
console.warn('Ship label layer add failed:', e);
}
} else {
try {
map.setLayoutProperty(layerId, 'visibility', visibility);
} catch {
// ignore
}
}
kickRepaint(map);
};
const stop = onMapStyleReady(map, ensure);
return () => {
stop();
};
}, [
projection,
settings.showShips,
overlays.shipLabels,
shipData,
legacyHits,
selectedMmsi,
shipHighlightSet,
mapSyncEpoch,
]);
// Ships in globe mode
useEffect(() => {
const map = mapRef.current;
if (!map) return;
const imgId = 'ship-globe-icon';
const anchoredImgId = ANCHORED_SHIP_ICON_ID;
const srcId = 'ships-globe-src';
const haloId = 'ships-globe-halo';
const outlineId = 'ships-globe-outline';
const symbolId = 'ships-globe';
const labelId = 'ships-globe-label';
// 레이어를 제거하지 않고 visibility만 'none'으로 설정
// guardedSetVisibility로 현재 값과 동일하면 호출 생략 (style._changed 방지)
const hide = () => {
for (const id of [labelId, symbolId, outlineId, haloId]) {
guardedSetVisibility(map, id, 'none');
}
};
const ensureImage = () => {
ensureFallbackShipImage(map, imgId);
ensureFallbackShipImage(map, anchoredImgId, buildFallbackGlobeAnchoredShipIcon);
if (map.hasImage(imgId) && map.hasImage(anchoredImgId)) return;
kickRepaint(map);
};
const ensure = () => {
if (!settings.showShips) {
hide();
onGlobeShipsReady?.(false);
return;
}
// 빠른 visibility 토글 — projectionBusy 중에도 실행
// guardedSetVisibility로 값이 실제로 바뀔 때만 setLayoutProperty 호출
// → style._changed 방지 → 불필요한 symbol placement 재계산 방지 → 라벨 사라짐 방지
const visibility: 'visible' | 'none' = projection === 'globe' ? 'visible' : 'none';
const labelVisibility: 'visible' | 'none' = projection === 'globe' && overlays.shipLabels ? 'visible' : 'none';
if (map.getLayer(symbolId)) {
const changed = map.getLayoutProperty(symbolId, 'visibility') !== visibility;
if (changed) {
for (const id of [haloId, outlineId, symbolId]) {
guardedSetVisibility(map, id, visibility);
}
if (projection === 'globe') kickRepaint(map);
}
guardedSetVisibility(map, labelId, labelVisibility);
}
// 데이터 업데이트는 projectionBusy 중에는 차단
if (projectionBusyRef.current) {
// 레이어가 이미 존재하면 ready 상태 유지
if (map.getLayer(symbolId)) onGlobeShipsReady?.(true);
return;
}
if (!map.isStyleLoaded()) return;
if (globeShipsEpochRef.current !== mapSyncEpoch) {
globeShipsEpochRef.current = mapSyncEpoch;
}
try {
ensureImage();
} catch (e) {
console.warn('Ship icon image setup failed:', e);
}
// 사전 계산된 GeoJSON 사용 (useMemo에서 projection과 무관하게 항상 준비됨)
const geojson = globeShipGeoJson;
try {
const existing = map.getSource(srcId) as GeoJSONSource | undefined;
if (existing) existing.setData(geojson);
else map.addSource(srcId, { type: 'geojson', data: geojson } as GeoJSONSourceSpecification);
} catch (e) {
console.warn('Ship source setup failed:', e);
return;
}
const before = undefined;
if (!map.getLayer(haloId)) {
try {
map.addLayer(
{
id: haloId,
type: 'circle',
source: srcId,
layout: {
visibility,
'circle-sort-key': [
'case',
['all', ['==', ['get', 'selected'], 1], ['==', ['get', 'permitted'], 1]], 120,
['all', ['==', ['get', 'highlighted'], 1], ['==', ['get', 'permitted'], 1]], 115,
['==', ['get', 'permitted'], 1], 110,
['==', ['get', 'selected'], 1], 60,
['==', ['get', 'highlighted'], 1], 55,
20,
] as never,
},
paint: {
'circle-radius': GLOBE_SHIP_CIRCLE_RADIUS_EXPR,
'circle-color': ['coalesce', ['get', 'shipColor'], '#64748b'] as never,
'circle-opacity': [
'case',
['==', ['get', 'selected'], 1], 0.38,
['==', ['get', 'highlighted'], 1], 0.34,
0.16,
] as never,
},
} as unknown as LayerSpecification,
before,
);
} catch (e) {
console.warn('Ship halo layer add failed:', e);
}
}
// halo: data-driven expressions are static — visibility handled by fast toggle above
if (!map.getLayer(outlineId)) {
try {
map.addLayer(
{
id: outlineId,
type: 'circle',
source: srcId,
paint: {
'circle-radius': GLOBE_SHIP_CIRCLE_RADIUS_EXPR,
'circle-color': 'rgba(0,0,0,0)',
'circle-stroke-color': [
'case',
['==', ['get', 'selected'], 1], 'rgba(14,234,255,0.95)',
['==', ['get', 'highlighted'], 1], 'rgba(245,158,11,0.95)',
['==', ['get', 'permitted'], 1], GLOBE_OUTLINE_PERMITTED,
GLOBE_OUTLINE_OTHER,
] as never,
'circle-stroke-width': [
'case',
['==', ['get', 'selected'], 1], 3.4,
['==', ['get', 'highlighted'], 1], 2.7,
['==', ['get', 'permitted'], 1], 1.8,
0.7,
] as never,
'circle-stroke-opacity': 0.85,
},
layout: {
visibility,
'circle-sort-key': [
'case',
['all', ['==', ['get', 'selected'], 1], ['==', ['get', 'permitted'], 1]], 130,
['all', ['==', ['get', 'highlighted'], 1], ['==', ['get', 'permitted'], 1]], 125,
['==', ['get', 'permitted'], 1], 120,
['==', ['get', 'selected'], 1], 70,
['==', ['get', 'highlighted'], 1], 65,
30,
] as never,
},
} as unknown as LayerSpecification,
before,
);
} catch (e) {
console.warn('Ship outline layer add failed:', e);
}
}
// outline: data-driven expressions are static — visibility handled by fast toggle
if (!map.getLayer(symbolId)) {
try {
map.addLayer(
{
id: symbolId,
type: 'symbol',
source: srcId,
layout: {
visibility,
'symbol-sort-key': [
'case',
['all', ['==', ['get', 'selected'], 1], ['==', ['get', 'permitted'], 1]], 140,
['all', ['==', ['get', 'highlighted'], 1], ['==', ['get', 'permitted'], 1]], 135,
['==', ['get', 'permitted'], 1], 130,
['==', ['get', 'selected'], 1], 80,
['==', ['get', 'highlighted'], 1], 75,
45,
] as never,
'icon-image': [
'case',
['==', ['to-number', ['get', 'isAnchored'], 0], 1],
anchoredImgId,
imgId,
] as never,
'icon-size': [
'interpolate', ['linear'], ['zoom'],
3, ['to-number', ['get', 'iconSize3'], 0.35],
7, ['to-number', ['get', 'iconSize7'], 0.45],
10, ['to-number', ['get', 'iconSize10'], 0.58],
14, ['to-number', ['get', 'iconSize14'], 0.85],
18, ['to-number', ['get', 'iconSize18'], 2.5],
] as unknown as number[],
'icon-allow-overlap': true,
'icon-ignore-placement': true,
'icon-anchor': 'center',
'icon-rotate': [
'case',
['==', ['to-number', ['get', 'isAnchored'], 0], 1], 0,
['to-number', ['get', 'heading'], 0],
] as never,
'icon-rotation-alignment': 'map',
'icon-pitch-alignment': 'map',
},
paint: {
'icon-color': ['coalesce', ['get', 'shipColor'], '#64748b'] as never,
'icon-opacity': [
'case',
['==', ['get', 'permitted'], 1], 1,
['==', ['get', 'selected'], 1], 0.86,
['==', ['get', 'highlighted'], 1], 0.82,
0.66,
] as never,
},
} as unknown as LayerSpecification,
before,
);
} catch (e) {
console.warn('Ship symbol layer add failed:', e);
}
}
// symbol: data-driven expressions are static — visibility handled by fast toggle
const labelFilter = [
'all',
['!=', ['to-string', ['coalesce', ['get', 'labelName'], '']], ''],
[
'any',
['==', ['get', 'permitted'], 1],
['==', ['get', 'selected'], 1],
['==', ['get', 'highlighted'], 1],
],
] as unknown as unknown[];
if (!map.getLayer(labelId)) {
try {
map.addLayer(
{
id: labelId,
type: 'symbol',
source: srcId,
minzoom: 7,
filter: labelFilter as never,
layout: {
visibility: labelVisibility,
'symbol-placement': 'point',
'text-field': ['get', 'labelName'] as never,
'text-font': ['Noto Sans Regular', 'Open Sans Regular'],
'text-size': ['interpolate', ['linear'], ['zoom'], 7, 10, 10, 11, 12, 12, 14, 13] as never,
'text-anchor': 'top',
'text-offset': [0, 1.1],
'text-padding': 2,
'text-allow-overlap': false,
'text-ignore-placement': false,
},
paint: {
'text-color': [
'case',
['==', ['get', 'selected'], 1], 'rgba(14,234,255,0.95)',
['==', ['get', 'highlighted'], 1], 'rgba(245,158,11,0.95)',
'rgba(226,232,240,0.92)',
] as never,
'text-halo-color': 'rgba(2,6,23,0.85)',
'text-halo-width': 1.2,
'text-halo-blur': 0.8,
},
} as unknown as LayerSpecification,
undefined,
);
} catch (e) {
console.warn('Ship label layer add failed:', e);
}
}
// label: filter/text-field are static — visibility handled by fast toggle
// 레이어가 준비되었음을 알림 (projection과 무관 — 토글 버튼 활성화용)
onGlobeShipsReady?.(true);
if (projection === 'globe') {
reorderGlobeFeatureLayers();
}
kickRepaint(map);
};
const stop = onMapStyleReady(map, ensure);
return () => {
stop();
};
}, [
projection,
settings.showShips,
overlays.shipLabels,
globeShipGeoJson,
selectedMmsi,
isBaseHighlightedMmsi,
mapSyncEpoch,
reorderGlobeFeatureLayers,
onGlobeShipsReady,
]);
// Globe hover overlay ships
useEffect(() => {
const map = mapRef.current;
if (!map) return;
const imgId = 'ship-globe-icon';
const srcId = 'ships-globe-hover-src';
const haloId = 'ships-globe-hover-halo';
const outlineId = 'ships-globe-hover-outline';
const symbolId = 'ships-globe-hover';
const hideHover = () => {
for (const id of [symbolId, outlineId, haloId]) {
guardedSetVisibility(map, id, 'none');
}
};
const ensure = () => {
if (projectionBusyRef.current) return;
if (!map.isStyleLoaded()) return;
if (projection !== 'globe' || !settings.showShips || shipHoverOverlaySet.size === 0) {
hideHover();
return;
}
if (globeShipsEpochRef.current !== mapSyncEpoch) {
globeShipsEpochRef.current = mapSyncEpoch;
}
ensureFallbackShipImage(map, imgId);
if (!map.hasImage(imgId)) {
return;
}
const hovered = shipLayerData.filter((t) => shipHoverOverlaySet.has(t.mmsi) && !!legacyHits?.has(t.mmsi));
if (hovered.length === 0) {
hideHover();
return;
}
const hoverSignature = hovered
.map((t) => `${t.mmsi}:${t.lon.toFixed(6)}:${t.lat.toFixed(6)}:${t.heading ?? 0}`)
.join('|');
const hasHoverSource = map.getSource(srcId) != null;
const hasHoverLayers = [symbolId, outlineId, haloId].every((id) => map.getLayer(id));
if (hoverSignature === globeHoverShipSignatureRef.current && hasHoverSource && hasHoverLayers) {
return;
}
globeHoverShipSignatureRef.current = hoverSignature;
const needReorder = !hasHoverSource || !hasHoverLayers;
const hoverGeojson: GeoJSON.FeatureCollection<GeoJSON.Point> = {
type: 'FeatureCollection',
features: hovered.map((t) => {
const legacy = legacyHits?.get(t.mmsi) ?? null;
const heading = getDisplayHeading({
cog: t.cog,
heading: t.heading,
offset: GLOBE_ICON_HEADING_OFFSET_DEG,
});
const hull = clampNumber(
(isFiniteNumber(t.length) ? t.length : 0) + (isFiniteNumber(t.width) ? t.width : 0) * 3,
50,
420,
);
const sizeScale = clampNumber(0.85 + (hull - 50) / 420, 0.82, 1.85);
const selected = t.mmsi === selectedMmsi;
const scale = selected ? 1.16 : 1.1;
return {
type: 'Feature',
...(isFiniteNumber(t.mmsi) ? { id: Math.trunc(t.mmsi) } : {}),
geometry: { type: 'Point', coordinates: [t.lon, t.lat] },
properties: {
mmsi: t.mmsi,
name: t.name || '',
cog: heading,
heading,
sog: isFiniteNumber(t.sog) ? t.sog : 0,
shipColor: getGlobeBaseShipColor({
legacy: legacy?.shipCode || null,
sog: isFiniteNumber(t.sog) ? t.sog : null,
}),
iconSize3: clampNumber(0.35 * sizeScale * scale, 0.25, 1.45),
iconSize7: clampNumber(0.45 * sizeScale * scale, 0.3, 1.7),
iconSize10: clampNumber(0.58 * sizeScale * scale, 0.35, 2.1),
iconSize14: clampNumber(0.85 * sizeScale * scale, 0.45, 3.0),
iconSize18: clampNumber(2.5 * sizeScale * scale, 1.0, 7.0),
selected: selected ? 1 : 0,
permitted: legacy ? 1 : 0,
},
};
}),
};
try {
const existing = map.getSource(srcId) as GeoJSONSource | undefined;
if (existing) existing.setData(hoverGeojson);
else map.addSource(srcId, { type: 'geojson', data: hoverGeojson } as GeoJSONSourceSpecification);
} catch (e) {
console.warn('Ship hover source setup failed:', e);
return;
}
const before = undefined;
if (!map.getLayer(haloId)) {
try {
map.addLayer(
{
id: haloId,
type: 'circle',
source: srcId,
layout: {
visibility: 'visible',
'circle-sort-key': [
'case',
['==', ['get', 'selected'], 1], 120,
['==', ['get', 'permitted'], 1], 115,
110,
] as never,
},
paint: {
'circle-radius': GLOBE_SHIP_CIRCLE_RADIUS_EXPR,
'circle-color': [
'case',
['==', ['get', 'selected'], 1], 'rgba(14,234,255,1)',
'rgba(245,158,11,1)',
] as never,
'circle-opacity': 0.42,
},
} as unknown as LayerSpecification,
before,
);
} catch (e) {
console.warn('Ship hover halo layer add failed:', e);
}
} else {
map.setLayoutProperty(haloId, 'visibility', 'visible');
}
if (!map.getLayer(outlineId)) {
try {
map.addLayer(
{
id: outlineId,
type: 'circle',
source: srcId,
paint: {
'circle-radius': GLOBE_SHIP_CIRCLE_RADIUS_EXPR,
'circle-color': 'rgba(0,0,0,0)',
'circle-stroke-color': [
'case',
['==', ['get', 'selected'], 1], 'rgba(14,234,255,0.95)',
'rgba(245,158,11,0.95)',
] as never,
'circle-stroke-width': [
'case',
['==', ['get', 'selected'], 1], 3.8,
2.2,
] as never,
'circle-stroke-opacity': 0.9,
},
layout: {
visibility: 'visible',
'circle-sort-key': [
'case',
['==', ['get', 'selected'], 1], 121,
['==', ['get', 'permitted'], 1], 116,
111,
] as never,
},
} as unknown as LayerSpecification,
before,
);
} catch (e) {
console.warn('Ship hover outline layer add failed:', e);
}
} else {
map.setLayoutProperty(outlineId, 'visibility', 'visible');
}
if (!map.getLayer(symbolId)) {
try {
map.addLayer(
{
id: symbolId,
type: 'symbol',
source: srcId,
layout: {
visibility: 'visible',
'symbol-sort-key': [
'case',
['==', ['get', 'selected'], 1], 122,
['==', ['get', 'permitted'], 1], 117,
112,
] as never,
'icon-image': imgId,
'icon-size': [
'interpolate', ['linear'], ['zoom'],
3, ['to-number', ['get', 'iconSize3'], 0.35],
7, ['to-number', ['get', 'iconSize7'], 0.45],
10, ['to-number', ['get', 'iconSize10'], 0.58],
14, ['to-number', ['get', 'iconSize14'], 0.85],
18, ['to-number', ['get', 'iconSize18'], 2.5],
] as unknown as number[],
'icon-allow-overlap': true,
'icon-ignore-placement': true,
'icon-anchor': 'center',
'icon-rotate': ['to-number', ['get', 'heading'], 0],
'icon-rotation-alignment': 'map',
'icon-pitch-alignment': 'map',
},
paint: {
'icon-color': ['coalesce', ['get', 'shipColor'], '#64748b'] as never,
'icon-opacity': 1,
},
} as unknown as LayerSpecification,
before,
);
} catch (e) {
console.warn('Ship hover symbol layer add failed:', e);
}
} else {
map.setLayoutProperty(symbolId, 'visibility', 'visible');
}
if (needReorder) {
reorderGlobeFeatureLayers();
}
kickRepaint(map);
};
const stop = onMapStyleReady(map, ensure);
return () => {
stop();
};
}, [
projection,
settings.showShips,
shipLayerData,
legacyHits,
shipHoverOverlaySet,
selectedMmsi,
mapSyncEpoch,
reorderGlobeFeatureLayers,
]);
// Globe ship click selection
useEffect(() => {
const map = mapRef.current;
if (!map) return;
if (projection !== 'globe' || !settings.showShips) return;
const symbolId = 'ships-globe';
const haloId = 'ships-globe-halo';
const outlineId = 'ships-globe-outline';
const clickedRadiusDeg2 = Math.pow(0.08, 2);
const onClick = (e: maplibregl.MapMouseEvent) => {
try {
const layerIds = [symbolId, haloId, outlineId].filter((id) => map.getLayer(id));
let feats: unknown[] = [];
if (layerIds.length > 0) {
try {
feats = map.queryRenderedFeatures(e.point, { layers: layerIds }) as unknown[];
} catch {
feats = [];
}
}
const f = feats?.[0];
const props = ((f as { properties?: Record<string, unknown> } | undefined)?.properties || {}) as Record<
string,
unknown
>;
const mmsi = Number(props.mmsi);
if (Number.isFinite(mmsi)) {
if (hasAuxiliarySelectModifier(e as unknown as { shiftKey?: boolean; ctrlKey?: boolean; metaKey?: boolean })) {
onToggleHighlightMmsi?.(mmsi);
return;
}
onSelectMmsi(mmsi);
return;
}
const clicked = { lat: e.lngLat.lat, lon: e.lngLat.lng };
const cosLat = Math.cos(clicked.lat * DEG2RAD);
let bestMmsi: number | null = null;
let bestD2 = Number.POSITIVE_INFINITY;
for (const t of targets) {
if (!isFiniteNumber(t.lat) || !isFiniteNumber(t.lon)) continue;
const dLon = (clicked.lon - t.lon) * cosLat;
const dLat = clicked.lat - t.lat;
const d2 = dLon * dLon + dLat * dLat;
if (d2 <= clickedRadiusDeg2 && d2 < bestD2) {
bestD2 = d2;
bestMmsi = t.mmsi;
}
}
if (bestMmsi != null) {
if (hasAuxiliarySelectModifier(e as unknown as { shiftKey?: boolean; ctrlKey?: boolean; metaKey?: boolean })) {
onToggleHighlightMmsi?.(bestMmsi);
return;
}
onSelectMmsi(bestMmsi);
return;
}
} catch {
// ignore
}
onSelectMmsi(null);
};
map.on('click', onClick);
return () => {
try {
map.off('click', onClick);
} catch {
// ignore
}
};
}, [projection, settings.showShips, onSelectMmsi, onToggleHighlightMmsi, mapSyncEpoch, targets]);
}

파일 보기

@ -0,0 +1,66 @@
import { useMemo, useState } from 'react';
import { toNumberSet } from '../lib/setUtils';
export interface HoverStateInput {
hoveredMmsiSet: number[];
hoveredFleetMmsiSet: number[];
hoveredPairMmsiSet: number[];
hoveredFleetOwnerKey: string | null;
highlightedMmsiSet: number[];
}
export function useHoverState(input: HoverStateInput) {
const {
hoveredMmsiSet,
hoveredFleetMmsiSet,
hoveredPairMmsiSet,
hoveredFleetOwnerKey,
highlightedMmsiSet,
} = input;
// Internal deck hover states
const [hoveredDeckMmsiSet, setHoveredDeckMmsiSet] = useState<number[]>([]);
const [hoveredDeckPairMmsiSet, setHoveredDeckPairMmsiSet] = useState<number[]>([]);
const [hoveredDeckFleetOwnerKey, setHoveredDeckFleetOwnerKey] = useState<string | null>(null);
const [hoveredDeckFleetMmsiSet, setHoveredDeckFleetMmsiSet] = useState<number[]>([]);
const [hoveredZoneId, setHoveredZoneId] = useState<string | null>(null);
// Derived sets
const hoveredMmsiSetRef = useMemo(() => toNumberSet(hoveredMmsiSet), [hoveredMmsiSet]);
const hoveredFleetMmsiSetRef = useMemo(() => toNumberSet(hoveredFleetMmsiSet), [hoveredFleetMmsiSet]);
const hoveredPairMmsiSetRef = useMemo(() => toNumberSet(hoveredPairMmsiSet), [hoveredPairMmsiSet]);
const externalHighlightedSetRef = useMemo(() => toNumberSet(highlightedMmsiSet), [highlightedMmsiSet]);
const hoveredDeckMmsiSetRef = useMemo(() => toNumberSet(hoveredDeckMmsiSet), [hoveredDeckMmsiSet]);
const hoveredDeckPairMmsiSetRef = useMemo(() => toNumberSet(hoveredDeckPairMmsiSet), [hoveredDeckPairMmsiSet]);
const hoveredDeckFleetMmsiSetRef = useMemo(() => toNumberSet(hoveredDeckFleetMmsiSet), [hoveredDeckFleetMmsiSet]);
const hoveredFleetOwnerKeys = useMemo(() => {
const keys = new Set<string>();
if (hoveredFleetOwnerKey) keys.add(hoveredFleetOwnerKey);
if (hoveredDeckFleetOwnerKey) keys.add(hoveredDeckFleetOwnerKey);
return keys;
}, [hoveredFleetOwnerKey, hoveredDeckFleetOwnerKey]);
return {
// Internal states + setters
hoveredDeckMmsiSet,
setHoveredDeckMmsiSet,
hoveredDeckPairMmsiSet,
setHoveredDeckPairMmsiSet,
hoveredDeckFleetOwnerKey,
setHoveredDeckFleetOwnerKey,
hoveredDeckFleetMmsiSet,
setHoveredDeckFleetMmsiSet,
hoveredZoneId,
setHoveredZoneId,
// Derived sets
hoveredMmsiSetRef,
hoveredFleetMmsiSetRef,
hoveredPairMmsiSetRef,
externalHighlightedSetRef,
hoveredDeckMmsiSetRef,
hoveredDeckPairMmsiSetRef,
hoveredDeckFleetMmsiSetRef,
hoveredFleetOwnerKeys,
};
}

파일 보기

@ -0,0 +1,287 @@
import { useCallback, useEffect, useRef, type MutableRefObject, type Dispatch, type SetStateAction } from 'react';
import maplibregl, { type StyleSpecification } from 'maplibre-gl';
import { MapboxOverlay } from '@deck.gl/mapbox';
import { MaplibreDeckCustomLayer } from '../MaplibreDeckCustomLayer';
import type { BaseMapId, MapProjectionId, MapViewState } from '../types';
import { DECK_VIEW_ID, ANCHORED_SHIP_ICON_ID } from '../constants';
import { kickRepaint, onMapStyleReady } from '../lib/mapCore';
import { ensureSeamarkOverlay } from '../layers/seamark';
import { resolveMapStyle } from '../layers/bathymetry';
export function useMapInit(
containerRef: MutableRefObject<HTMLDivElement | null>,
mapRef: MutableRefObject<maplibregl.Map | null>,
overlayRef: MutableRefObject<MapboxOverlay | null>,
overlayInteractionRef: MutableRefObject<MapboxOverlay | null>,
globeDeckLayerRef: MutableRefObject<MaplibreDeckCustomLayer | null>,
baseMapRef: MutableRefObject<BaseMapId>,
projectionRef: MutableRefObject<MapProjectionId>,
opts: {
baseMap: BaseMapId;
projection: MapProjectionId;
showSeamark: boolean;
onViewBboxChange?: (bbox: [number, number, number, number]) => void;
setMapSyncEpoch: Dispatch<SetStateAction<number>>;
initialView?: MapViewState | null;
onViewStateChange?: (view: MapViewState) => void;
},
) {
const { onViewBboxChange, setMapSyncEpoch, showSeamark } = opts;
const showSeamarkRef = useRef(showSeamark);
const onViewStateChangeRef = useRef(opts.onViewStateChange);
useEffect(() => { onViewStateChangeRef.current = opts.onViewStateChange; }, [opts.onViewStateChange]);
useEffect(() => {
showSeamarkRef.current = showSeamark;
}, [showSeamark]);
const ensureMercatorOverlay = useCallback(() => {
const map = mapRef.current;
if (!map) return null;
if (overlayRef.current) return overlayRef.current;
try {
const next = new MapboxOverlay({ interleaved: true, layers: [] } as unknown as never);
map.addControl(next);
overlayRef.current = next;
return next;
} catch (e) {
console.warn('Deck overlay create failed:', e);
return null;
}
}, []);
const pulseMapSync = useCallback(() => {
setMapSyncEpoch((prev) => prev + 1);
requestAnimationFrame(() => {
kickRepaint(mapRef.current);
setMapSyncEpoch((prev) => prev + 1);
});
}, [setMapSyncEpoch]);
useEffect(() => {
if (!containerRef.current || mapRef.current) return;
let map: maplibregl.Map | null = null;
let cancelled = false;
let viewSaveTimer: ReturnType<typeof setInterval> | null = null;
const controller = new AbortController();
(async () => {
let style: string | StyleSpecification = '/map/styles/osm-seamark.json';
try {
style = await resolveMapStyle(baseMapRef.current, controller.signal);
} catch (e) {
console.warn('Map style init failed, falling back to local raster style:', e);
style = '/map/styles/osm-seamark.json';
}
if (cancelled || !containerRef.current) return;
const iv = opts.initialView;
map = new maplibregl.Map({
container: containerRef.current,
style,
center: iv?.center ?? [126.5, 34.2],
zoom: iv?.zoom ?? 7,
pitch: iv?.pitch ?? 45,
bearing: iv?.bearing ?? 0,
maxPitch: 85,
dragRotate: true,
pitchWithRotate: true,
touchPitch: true,
scrollZoom: { around: 'center' },
});
map.addControl(new maplibregl.NavigationControl({ showZoom: true, showCompass: true }), 'top-left');
map.addControl(new maplibregl.ScaleControl({ maxWidth: 120, unit: 'metric' }), 'bottom-left');
// MapLibre 내부 placement TypeError 방어 + globe easing 경고 억제
// symbol layer 추가/제거와 render cycle 간 타이밍 이슈로 발생하는 에러 억제
// globe projection에서 scrollZoom이 easeTo(around)를 호출하면 경고 발생 → 구조적 한계로 억제
{
const origRender = (map as unknown as { _render: (arg?: number) => void })._render;
const origWarn = console.warn;
(map as unknown as { _render: (arg?: number) => void })._render = function (arg?: number) {
// globe 모드에서 scrollZoom의 easeTo around 경고 억제
// eslint-disable-next-line no-console
console.warn = function (...args: unknown[]) {
if (typeof args[0] === 'string') {
const msg = args[0] as string;
if (msg.includes('Easing around a point')) return;
// vertex 경고는 디버그용으로 1회만 출력 후 억제
if (msg.includes('Max vertices per segment')) {
origWarn.apply(console, args as [unknown, ...unknown[]]);
return;
}
}
origWarn.apply(console, args as [unknown, ...unknown[]]);
};
try {
origRender.call(this, arg);
} catch (e) {
if (e instanceof TypeError && (e.message?.includes("reading 'get'") || e.message?.includes('placement'))) {
return;
}
throw e;
} finally {
// eslint-disable-next-line no-console
console.warn = origWarn;
}
};
}
// Globe 모드 전환 시 지연을 제거하기 위해 ship.svg를 미리 로드
{
const SHIP_IMG_ID = 'ship-globe-icon';
const localMap = map;
void localMap
.loadImage('/assets/ship.svg')
.then((response) => {
if (cancelled || !localMap) return;
const img = (response as { data?: HTMLImageElement | ImageBitmap } | undefined)?.data;
if (!img) return;
try {
if (!localMap.hasImage(SHIP_IMG_ID)) localMap.addImage(SHIP_IMG_ID, img, { pixelRatio: 2, sdf: true });
if (!localMap.hasImage(ANCHORED_SHIP_ICON_ID)) localMap.addImage(ANCHORED_SHIP_ICON_ID, img, { pixelRatio: 2, sdf: true });
} catch {
// ignore — fallback canvas icon이 useGlobeShips에서 사용됨
}
})
.catch(() => {
// ignore — useGlobeShips에서 fallback 처리
});
}
mapRef.current = map;
// 양쪽 overlay를 모두 초기화 — projection 전환 시 재생성 비용 제거
ensureMercatorOverlay();
globeDeckLayerRef.current = new MaplibreDeckCustomLayer({
id: 'deck-globe',
viewId: DECK_VIEW_ID,
deckProps: { layers: [] },
});
function applyProjection() {
if (!map) return;
const next = projectionRef.current;
if (next === 'mercator') return;
try {
map.setProjection({ type: next });
map.setRenderWorldCopies(next !== 'globe');
} catch (e) {
console.warn('Projection apply failed:', e);
}
}
onMapStyleReady(map, () => {
applyProjection();
// deck-globe를 항상 추가 (projection과 무관)
const deckLayer = globeDeckLayerRef.current;
if (deckLayer && !map!.getLayer(deckLayer.id)) {
try {
map!.addLayer(deckLayer);
} catch {
// ignore
}
}
if (!showSeamarkRef.current) return;
try {
ensureSeamarkOverlay(map!, 'bathymetry-lines-coarse');
} catch {
// ignore
}
});
const emitBbox = () => {
const cb = onViewBboxChange;
if (!cb || !map) return;
const b = map.getBounds();
cb([b.getWest(), b.getSouth(), b.getEast(), b.getNorth()]);
};
map.on('load', emitBbox);
map.on('moveend', emitBbox);
// 60초 인터벌로 뷰 상태 저장 (mercator일 때만)
viewSaveTimer = setInterval(() => {
const cb = onViewStateChangeRef.current;
if (!cb || !map || projectionRef.current !== 'mercator') return;
const c = map.getCenter();
cb({ center: [c.lng, c.lat], zoom: map.getZoom(), bearing: map.getBearing(), pitch: map.getPitch() });
}, 60_000);
map.once('load', () => {
// Globe 배경(타일 밖)을 심해 색상과 맞춰 타일 경계 seam을 비가시화
try {
map!.setSky({
'sky-color': '#010610',
'horizon-color': '#010610',
'fog-color': '#010610',
'fog-ground-blend': 1,
'sky-horizon-blend': 0,
'atmosphere-blend': 0,
});
} catch {
// ignore
}
// 캔버스 배경도 심해색으로 통일
try {
map!.getCanvas().style.background = '#010610';
} catch {
// ignore
}
if (showSeamarkRef.current) {
try {
ensureSeamarkOverlay(map!, 'bathymetry-lines-coarse');
} catch {
// ignore
}
try {
const opacity = showSeamarkRef.current ? 0.85 : 0;
map!.setPaintProperty('seamark', 'raster-opacity', opacity);
} catch {
// ignore
}
}
// 종속 hook들(useMapStyleSettings 등)이 저장된 설정을 적용하도록 트리거
setMapSyncEpoch((prev) => prev + 1);
});
})();
return () => {
cancelled = true;
controller.abort();
if (viewSaveTimer) clearInterval(viewSaveTimer);
// 최종 뷰 상태 저장 (mercator일 때만 — globe 위치는 영속화하지 않음)
const cb = onViewStateChangeRef.current;
if (cb && map && projectionRef.current === 'mercator') {
const c = map.getCenter();
cb({ center: [c.lng, c.lat], zoom: map.getZoom(), bearing: map.getBearing(), pitch: map.getPitch() });
}
try {
globeDeckLayerRef.current?.requestFinalize();
} catch {
// ignore
}
if (map) {
map.remove();
map = null;
}
if (overlayRef.current) {
overlayRef.current.finalize();
overlayRef.current = null;
}
if (overlayInteractionRef.current) {
overlayInteractionRef.current.finalize();
overlayInteractionRef.current = null;
}
globeDeckLayerRef.current = null;
mapRef.current = null;
};
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
return { ensureMercatorOverlay, pulseMapSync };
}

파일 보기

@ -0,0 +1,181 @@
import { useEffect, useRef, type MutableRefObject } from 'react';
import maplibregl from 'maplibre-gl';
import type { MapStyleSettings, MapLabelLanguage, DepthColorStop, DepthFontSize } from '../../../features/mapSettings/types';
import type { BaseMapId } from '../types';
import { kickRepaint, onMapStyleReady } from '../lib/mapCore';
/* ── Depth font size presets ──────────────────────────────────────── */
const DEPTH_FONT_SIZE_MAP: Record<DepthFontSize, unknown[]> = {
small: ['interpolate', ['linear'], ['zoom'], 7, 8, 9, 9, 11, 11, 13, 13],
medium: ['interpolate', ['linear'], ['zoom'], 7, 10, 9, 12, 11, 14, 13, 16],
large: ['interpolate', ['linear'], ['zoom'], 7, 12, 9, 15, 11, 18, 13, 20],
};
/* ── Helpers ──────────────────────────────────────────────────────── */
function darkenHex(hex: string, factor = 0.85): string {
const r = parseInt(hex.slice(1, 3), 16);
const g = parseInt(hex.slice(3, 5), 16);
const b = parseInt(hex.slice(5, 7), 16);
return `#${[r, g, b].map((c) => Math.round(c * factor).toString(16).padStart(2, '0')).join('')}`;
}
function lightenHex(hex: string, factor = 1.3): string {
const r = parseInt(hex.slice(1, 3), 16);
const g = parseInt(hex.slice(3, 5), 16);
const b = parseInt(hex.slice(5, 7), 16);
return `#${[r, g, b].map((c) => Math.min(255, Math.round(c * factor)).toString(16).padStart(2, '0')).join('')}`;
}
/* ── Apply functions ──────────────────────────────────────────────── */
function applyLabelLanguage(map: maplibregl.Map, lang: MapLabelLanguage) {
const style = map.getStyle();
if (!style?.layers) return;
for (const layer of style.layers) {
if (layer.type !== 'symbol') continue;
const layout = (layer as { layout?: Record<string, unknown> }).layout;
if (!layout?.['text-field']) continue;
if (layer.id.startsWith('bathymetry-labels')) continue;
const textField =
lang === 'local'
? ['get', 'name']
: ['coalesce', ['get', `name:${lang}`], ['get', 'name']];
try {
map.setLayoutProperty(layer.id, 'text-field', textField);
} catch {
// ignore
}
}
}
function applyLandColor(map: maplibregl.Map, color: string) {
const style = map.getStyle();
if (!style?.layers) return;
const waterRegex = /(water|sea|ocean|river|lake|coast|bay)/i;
const darkVariant = darkenHex(color, 0.8);
for (const layer of style.layers) {
const id = layer.id;
if (id.startsWith('bathymetry-')) continue;
if (id.startsWith('subcables-')) continue;
if (id.startsWith('zones-')) continue;
if (id.startsWith('ships-')) continue;
if (id.startsWith('pair-')) continue;
if (id.startsWith('fc-')) continue;
if (id.startsWith('fleet-')) continue;
if (id.startsWith('predict-')) continue;
if (id === 'deck-globe') continue;
const sourceLayer = String((layer as Record<string, unknown>)['source-layer'] ?? '');
const isWater = waterRegex.test(id) || waterRegex.test(sourceLayer);
if (isWater) continue;
try {
if (layer.type === 'background') {
map.setPaintProperty(id, 'background-color', color);
} else if (layer.type === 'fill') {
map.setPaintProperty(id, 'fill-color', darkVariant);
}
} catch {
// ignore
}
}
}
function applyWaterBaseColor(map: maplibregl.Map, fillColor: string) {
const style = map.getStyle();
if (!style?.layers) return;
const waterRegex = /(water|sea|ocean|river|lake|coast|bay)/i;
const lineColor = darkenHex(fillColor, 0.85);
for (const layer of style.layers) {
const id = layer.id;
if (id.startsWith('bathymetry-')) continue;
const sourceLayer = String((layer as Record<string, unknown>)['source-layer'] ?? '');
if (!waterRegex.test(id) && !waterRegex.test(sourceLayer)) continue;
try {
if (layer.type === 'fill') {
map.setPaintProperty(id, 'fill-color', fillColor);
} else if (layer.type === 'line') {
map.setPaintProperty(id, 'line-color', lineColor);
}
} catch {
// ignore
}
}
}
function applyDepthGradient(map: maplibregl.Map, stops: DepthColorStop[]) {
const depth = ['to-number', ['get', 'depth']];
const sorted = [...stops].sort((a, b) => a.depth - b.depth);
if (sorted.length === 0) return;
const expr: unknown[] = ['interpolate', ['linear'], depth];
for (const s of sorted) {
expr.push(s.depth, s.color);
}
// 0m까지 확장 (최천층 stop이 0보다 깊으면)
const shallowest = sorted[sorted.length - 1];
if (shallowest.depth < 0) {
expr.push(0, lightenHex(shallowest.color, 1.8));
}
if (!map.getLayer('bathymetry-fill')) return;
try {
map.setPaintProperty('bathymetry-fill', 'fill-color', expr as never);
} catch {
// ignore
}
}
function applyDepthFontSize(map: maplibregl.Map, size: DepthFontSize) {
const expr = DEPTH_FONT_SIZE_MAP[size];
for (const layerId of ['bathymetry-labels', 'bathymetry-labels-coarse', 'bathymetry-landforms']) {
if (!map.getLayer(layerId)) continue;
try {
map.setLayoutProperty(layerId, 'text-size', expr);
} catch {
// ignore
}
}
}
function applyDepthFontColor(map: maplibregl.Map, color: string) {
for (const layerId of ['bathymetry-labels', 'bathymetry-labels-coarse', 'bathymetry-landforms']) {
if (!map.getLayer(layerId)) continue;
try {
map.setPaintProperty(layerId, 'text-color', color);
} catch {
// ignore
}
}
}
/* ── Hook ──────────────────────────────────────────────────────────── */
export function useMapStyleSettings(
mapRef: MutableRefObject<maplibregl.Map | null>,
settings: MapStyleSettings | undefined,
opts: { baseMap: BaseMapId; mapSyncEpoch: number },
) {
const settingsRef = useRef(settings);
useEffect(() => {
settingsRef.current = settings;
});
const { baseMap, mapSyncEpoch } = opts;
useEffect(() => {
const map = mapRef.current;
const s = settingsRef.current;
if (!map || !s) return;
const stop = onMapStyleReady(map, () => {
applyLabelLanguage(map, s.labelLanguage);
applyLandColor(map, s.landColor);
applyWaterBaseColor(map, s.waterBaseColor);
if (baseMap === 'enhanced') {
applyDepthGradient(map, s.depthStops);
applyDepthFontSize(map, s.depthFontSize);
applyDepthFontColor(map, s.depthFontColor);
}
kickRepaint(map);
});
return () => stop();
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [settings, baseMap, mapSyncEpoch]);
}

파일 보기

@ -0,0 +1,169 @@
/**
* useNativeMapLayers Mercator/Globe MapLibre hook
*
* :
* - projectionBusy / isStyleLoaded
* - GeoJSON source /
* - Layer (ensureLayer)
* - Visibility
* - Globe (reorderGlobeFeatureLayers)
* - kickRepaint
* - Unmount cleanupLayers
*
* ,
* useEffect에서 .
*/
import { useEffect, useRef, type MutableRefObject } from 'react';
import maplibregl, { type GeoJSONSourceSpecification, type LayerSpecification } from 'maplibre-gl';
import { ensureGeoJsonSource, ensureLayer, setLayerVisibility, cleanupLayers } from '../lib/layerHelpers';
import { kickRepaint, onMapStyleReady } from '../lib/mapCore';
/* ── Public types ──────────────────────────────────────────────────── */
export interface NativeSourceConfig {
id: string;
data: GeoJSON.GeoJSON | null;
/** GeoJSON source 옵션 (tolerance, buffer 등) */
options?: Partial<Omit<GeoJSONSourceSpecification, 'type' | 'data'>>;
}
export interface NativeLayerSpec {
id: string;
type: 'line' | 'fill' | 'circle' | 'symbol';
sourceId: string;
paint: Record<string, unknown>;
layout?: Record<string, unknown>;
filter?: unknown[];
minzoom?: number;
maxzoom?: number;
}
export interface NativeMapLayersConfig {
/** GeoJSON 데이터 소스 (다중 지원) */
sources: NativeSourceConfig[];
/** 레이어 스펙 배열 (생성 순서대로) */
layers: NativeLayerSpec[];
/** 전체 레이어 on/off */
visible: boolean;
/**
* ID.
* .
*/
beforeLayer?: string | string[];
/**
* () .
* .
*/
onAfterSetup?: (map: maplibregl.Map) => void;
}
/* ── Hook ──────────────────────────────────────────────────────────── */
/**
* @param mapRef - Map ref
* @param projectionBusyRef - ref
* @param reorderGlobeFeatureLayers - Globe
* @param config - //visibility
* @param deps - .
* (subcableGeo, overlays.subcables, projection, mapSyncEpoch )
*/
export function useNativeMapLayers(
mapRef: MutableRefObject<maplibregl.Map | null>,
projectionBusyRef: MutableRefObject<boolean>,
reorderGlobeFeatureLayers: () => void,
config: NativeMapLayersConfig,
deps: readonly unknown[],
) {
// 최신 config를 항상 읽기 위한 ref (deps에 config 객체를 넣지 않기 위함)
const configRef = useRef(config);
useEffect(() => {
configRef.current = config;
});
/* ── 레이어 생성/데이터 업데이트 ─────────────────────────────────── */
useEffect(() => {
const map = mapRef.current;
if (!map) return;
const ensure = () => {
const cfg = configRef.current;
if (projectionBusyRef.current) return;
// 1. Visibility 토글
for (const spec of cfg.layers) {
setLayerVisibility(map, spec.id, cfg.visible);
}
// 2. 데이터가 있는 source가 하나도 없으면 종료
const hasData = cfg.sources.some((s) => s.data != null);
if (!hasData) return;
if (!map.isStyleLoaded()) return;
try {
// 3. Source 생성/업데이트
for (const src of cfg.sources) {
if (src.data) {
ensureGeoJsonSource(map, src.id, src.data, src.options);
}
}
// 4. Before layer 해석
let before: string | undefined;
if (cfg.beforeLayer) {
const candidates = Array.isArray(cfg.beforeLayer) ? cfg.beforeLayer : [cfg.beforeLayer];
for (const candidate of candidates) {
if (map.getLayer(candidate)) {
before = candidate;
break;
}
}
}
// 5. Layer 생성
const vis = cfg.visible ? 'visible' : 'none';
for (const spec of cfg.layers) {
const layerDef: Record<string, unknown> = {
id: spec.id,
type: spec.type,
source: spec.sourceId,
paint: spec.paint,
layout: { ...spec.layout, visibility: vis },
};
if (spec.filter) layerDef.filter = spec.filter;
if (spec.minzoom != null) layerDef.minzoom = spec.minzoom;
if (spec.maxzoom != null) layerDef.maxzoom = spec.maxzoom;
ensureLayer(map, layerDef as unknown as LayerSpecification, { before });
}
// 6. Post-setup callback
if (cfg.onAfterSetup) {
cfg.onAfterSetup(map);
}
} catch (e) {
console.warn('Native map layers setup failed:', e);
} finally {
reorderGlobeFeatureLayers();
kickRepaint(map);
}
};
const stop = onMapStyleReady(map, ensure);
return () => {
stop();
};
// eslint-disable-next-line react-hooks/exhaustive-deps
}, deps);
/* ── Unmount cleanup ─────────────────────────────────────────────── */
useEffect(() => {
const mapInstance = mapRef.current;
return () => {
if (!mapInstance) return;
const cfg = configRef.current;
const layerIds = [...cfg.layers].reverse().map((l) => l.id);
const sourceIds = [...cfg.sources].reverse().map((s) => s.id);
cleanupLayers(mapInstance, layerIds, sourceIds);
};
}, []);
}

파일 보기

@ -0,0 +1,210 @@
import { useEffect, type MutableRefObject } from 'react';
import type maplibregl from 'maplibre-gl';
import type { GeoJSONSource, GeoJSONSourceSpecification, LayerSpecification } from 'maplibre-gl';
import type { AisTarget } from '../../../entities/aisTarget/model/types';
import type { LegacyVesselInfo } from '../../../entities/legacyVessel/model/types';
import type { MapToggleState } from '../../../features/mapToggles/MapToggles';
import type { Map3DSettings, MapProjectionId } from '../types';
import { LEGACY_CODE_COLORS_RGB, OTHER_AIS_SPEED_RGB, rgba as rgbaCss } from '../../../shared/lib/map/palette';
import { kickRepaint, onMapStyleReady } from '../lib/mapCore';
import { destinationPointLngLat } from '../lib/geometry';
import { isFiniteNumber } from '../lib/setUtils';
import { toValidBearingDeg, lightenColor } from '../lib/shipUtils';
export function usePredictionVectors(
mapRef: MutableRefObject<maplibregl.Map | null>,
projectionBusyRef: MutableRefObject<boolean>,
reorderGlobeFeatureLayers: () => void,
opts: {
overlays: MapToggleState;
settings: Map3DSettings;
shipData: AisTarget[];
legacyHits: Map<number, LegacyVesselInfo> | null | undefined;
selectedMmsi: number | null;
externalHighlightedSetRef: Set<number>;
projection: MapProjectionId;
baseMap: string;
mapSyncEpoch: number;
},
) {
const { overlays, settings, shipData, legacyHits, selectedMmsi, externalHighlightedSetRef, projection, baseMap, mapSyncEpoch } = opts;
useEffect(() => {
const map = mapRef.current;
if (!map) return;
const srcId = 'predict-vectors-src';
const outlineId = 'predict-vectors-outline';
const lineId = 'predict-vectors';
const hlOutlineId = 'predict-vectors-hl-outline';
const hlId = 'predict-vectors-hl';
const ensure = () => {
if (projectionBusyRef.current) return;
if (!map.isStyleLoaded()) return;
const visibility = overlays.predictVectors ? 'visible' : 'none';
const horizonMinutes = 15;
const horizonSeconds = horizonMinutes * 60;
const metersPerSecondPerKnot = 0.514444;
const features: GeoJSON.Feature<GeoJSON.LineString>[] = [];
if (overlays.predictVectors && settings.showShips && shipData.length > 0) {
for (const t of shipData) {
const legacy = legacyHits?.get(t.mmsi) ?? null;
const isTarget = !!legacy;
const isSelected = selectedMmsi != null && t.mmsi === selectedMmsi;
const isPinnedHighlight = externalHighlightedSetRef.has(t.mmsi);
if (!isTarget && !isSelected && !isPinnedHighlight) continue;
const sog = isFiniteNumber(t.sog) ? t.sog : null;
const bearing = toValidBearingDeg(t.cog) ?? toValidBearingDeg(t.heading);
if (sog == null || bearing == null) continue;
if (sog < 0.2) continue;
const distM = sog * metersPerSecondPerKnot * horizonSeconds;
if (!Number.isFinite(distM) || distM <= 0) continue;
const to = destinationPointLngLat([t.lon, t.lat], bearing, distM);
const baseRgb = isTarget
? LEGACY_CODE_COLORS_RGB[legacy?.shipCode ?? ''] ?? OTHER_AIS_SPEED_RGB.moving
: OTHER_AIS_SPEED_RGB.moving;
const rgb = lightenColor(baseRgb, isTarget ? 0.55 : 0.62);
const alpha = isTarget ? 0.72 : 0.52;
const alphaHl = isTarget ? 0.92 : 0.84;
const hl = isSelected || isPinnedHighlight ? 1 : 0;
features.push({
type: 'Feature',
id: `pred-${t.mmsi}`,
geometry: { type: 'LineString', coordinates: [[t.lon, t.lat], to] },
properties: {
mmsi: t.mmsi,
minutes: horizonMinutes,
sog,
cog: bearing,
target: isTarget ? 1 : 0,
hl,
color: rgbaCss(rgb, alpha),
colorHl: rgbaCss(rgb, alphaHl),
},
});
}
}
const fc: GeoJSON.FeatureCollection<GeoJSON.LineString> = { type: 'FeatureCollection', features };
try {
const existing = map.getSource(srcId) as GeoJSONSource | undefined;
if (existing) existing.setData(fc);
else map.addSource(srcId, { type: 'geojson', data: fc } as GeoJSONSourceSpecification);
} catch (e) {
console.warn('Prediction vector source setup failed:', e);
return;
}
const ensureLayer = (id: string, paint: LayerSpecification['paint'], filter: unknown[]) => {
if (!map.getLayer(id)) {
try {
map.addLayer(
{
id,
type: 'line',
source: srcId,
filter: filter as never,
layout: {
visibility,
'line-cap': 'round',
'line-join': 'round',
},
paint,
} as unknown as LayerSpecification,
undefined,
);
} catch (e) {
console.warn('Prediction vector layer add failed:', e);
}
} else {
try {
map.setLayoutProperty(id, 'visibility', visibility);
map.setFilter(id, filter as never);
if (paint && typeof paint === 'object') {
for (const [key, value] of Object.entries(paint)) {
map.setPaintProperty(id, key as never, value as never);
}
}
} catch {
// ignore
}
}
};
const baseFilter = ['==', ['to-number', ['get', 'hl'], 0], 0] as unknown as unknown[];
const hlFilter = ['==', ['to-number', ['get', 'hl'], 0], 1] as unknown as unknown[];
ensureLayer(
outlineId,
{
'line-color': 'rgba(2,6,23,0.86)',
'line-width': 4.8,
'line-opacity': 1,
'line-blur': 0.2,
'line-dasharray': [1.2, 1.8] as never,
} as never,
baseFilter,
);
ensureLayer(
lineId,
{
'line-color': ['coalesce', ['get', 'color'], 'rgba(226,232,240,0.62)'] as never,
'line-width': 2.4,
'line-opacity': 1,
'line-dasharray': [1.2, 1.8] as never,
} as never,
baseFilter,
);
ensureLayer(
hlOutlineId,
{
'line-color': 'rgba(2,6,23,0.92)',
'line-width': 6.4,
'line-opacity': 1,
'line-blur': 0.25,
'line-dasharray': [1.2, 1.8] as never,
} as never,
hlFilter,
);
ensureLayer(
hlId,
{
'line-color': ['coalesce', ['get', 'colorHl'], ['get', 'color'], 'rgba(241,245,249,0.92)'] as never,
'line-width': 3.6,
'line-opacity': 1,
'line-dasharray': [1.2, 1.8] as never,
} as never,
hlFilter,
);
reorderGlobeFeatureLayers();
kickRepaint(map);
};
const stop = onMapStyleReady(map, ensure);
return () => {
stop();
};
}, [
overlays.predictVectors,
settings.showShips,
shipData,
legacyHits,
selectedMmsi,
externalHighlightedSetRef,
projection,
baseMap,
mapSyncEpoch,
reorderGlobeFeatureLayers,
]);
}

파일 보기

@ -0,0 +1,290 @@
import { useCallback, useEffect, useRef, type MutableRefObject } from 'react';
import type maplibregl from 'maplibre-gl';
import { MapboxOverlay } from '@deck.gl/mapbox';
import { MaplibreDeckCustomLayer } from '../MaplibreDeckCustomLayer';
import type { MapProjectionId } from '../types';
import { kickRepaint, onMapStyleReady, extractProjectionType } from '../lib/mapCore';
export function useProjectionToggle(
mapRef: MutableRefObject<maplibregl.Map | null>,
overlayRef: MutableRefObject<MapboxOverlay | null>,
overlayInteractionRef: MutableRefObject<MapboxOverlay | null>,
globeDeckLayerRef: MutableRefObject<MaplibreDeckCustomLayer | null>,
projectionBusyRef: MutableRefObject<boolean>,
opts: {
projection: MapProjectionId;
ensureMercatorOverlay: () => MapboxOverlay | null;
onProjectionLoadingChange?: (loading: boolean) => void;
pulseMapSync: () => void;
setMapSyncEpoch: (updater: (prev: number) => number) => void;
},
): () => void {
const { projection, ensureMercatorOverlay, onProjectionLoadingChange, pulseMapSync, setMapSyncEpoch } = opts;
const projectionBusyTokenRef = useRef(0);
const projectionBusyTimerRef = useRef<ReturnType<typeof window.setTimeout> | null>(null);
const projectionPrevRef = useRef<MapProjectionId>(projection);
const projectionRef = useRef<MapProjectionId>(projection);
useEffect(() => {
projectionRef.current = projection;
}, [projection]);
const clearProjectionBusyTimer = useCallback(() => {
if (projectionBusyTimerRef.current == null) return;
clearTimeout(projectionBusyTimerRef.current);
projectionBusyTimerRef.current = null;
}, []);
// eslint-disable-next-line react-hooks/preserve-manual-memoization
const endProjectionLoading = useCallback(() => {
if (!projectionBusyRef.current) return;
projectionBusyRef.current = false;
clearProjectionBusyTimer();
if (onProjectionLoadingChange) {
onProjectionLoadingChange(false);
}
setMapSyncEpoch((prev) => prev + 1);
kickRepaint(mapRef.current);
}, [clearProjectionBusyTimer, onProjectionLoadingChange, setMapSyncEpoch]);
const setProjectionLoading = useCallback(
// eslint-disable-next-line react-hooks/preserve-manual-memoization
(loading: boolean) => {
if (projectionBusyRef.current === loading) return;
if (!loading) {
endProjectionLoading();
return;
}
clearProjectionBusyTimer();
projectionBusyRef.current = true;
const token = ++projectionBusyTokenRef.current;
if (onProjectionLoadingChange) {
onProjectionLoadingChange(true);
}
projectionBusyTimerRef.current = setTimeout(() => {
if (!projectionBusyRef.current || projectionBusyTokenRef.current !== token) return;
console.debug('Projection loading fallback timeout reached.');
endProjectionLoading();
}, 2000);
},
[clearProjectionBusyTimer, endProjectionLoading, onProjectionLoadingChange],
);
useEffect(() => {
return () => {
clearProjectionBusyTimer();
endProjectionLoading();
};
}, [clearProjectionBusyTimer, endProjectionLoading]);
// eslint-disable-next-line react-hooks/preserve-manual-memoization
const reorderGlobeFeatureLayers = useCallback(() => {
const map = mapRef.current;
if (!map || projectionRef.current !== 'globe') return;
if (projectionBusyRef.current) return;
if (!map.isStyleLoaded()) return;
const ordering = [
'subcables-hitarea',
'subcables-casing',
'subcables-line',
'subcables-glow',
'subcables-points',
'subcables-label',
'zones-fill',
'zones-line',
'zones-label',
'predict-vectors-outline',
'predict-vectors',
'predict-vectors-hl-outline',
'predict-vectors-hl',
'ships-globe-halo',
'ships-globe-outline',
'ships-globe',
'ships-globe-label',
'ships-globe-hover-halo',
'ships-globe-hover-outline',
'ships-globe-hover',
'pair-lines-ml',
'fc-lines-ml',
'pair-range-ml',
'fleet-circles-ml',
];
for (const layerId of ordering) {
try {
if (map.getLayer(layerId)) map.moveLayer(layerId);
} catch {
// ignore
}
}
kickRepaint(map);
}, []);
// Projection toggle (mercator <-> globe)
useEffect(() => {
const map = mapRef.current;
if (!map) return;
let cancelled = false;
let retries = 0;
const maxRetries = 18;
const isTransition = projectionPrevRef.current !== projection;
projectionPrevRef.current = projection;
let settleScheduled = false;
let settleCleanup: (() => void) | null = null;
const startProjectionSettle = () => {
if (!isTransition || settleScheduled) return;
settleScheduled = true;
const finalize = () => {
if (!cancelled && isTransition) setProjectionLoading(false);
};
const finalizeSoon = () => {
if (cancelled || !isTransition || projectionBusyRef.current === false) return;
if (!map.isStyleLoaded()) {
requestAnimationFrame(finalizeSoon);
return;
}
requestAnimationFrame(finalize);
};
const onIdle = () => finalizeSoon();
try {
map.on('idle', onIdle);
const styleReadyCleanup = onMapStyleReady(map, finalizeSoon);
settleCleanup = () => {
map.off('idle', onIdle);
styleReadyCleanup();
};
} catch {
requestAnimationFrame(finalize);
settleCleanup = null;
}
finalizeSoon();
};
if (isTransition) setProjectionLoading(true);
// 파괴하지 않고 레이어만 비움 — 양쪽 파이프라인 항상 유지
const quietMercatorOverlays = () => {
try { overlayRef.current?.setProps({ layers: [] } as never); } catch { /* ignore */ }
try { overlayInteractionRef.current?.setProps({ layers: [] } as never); } catch { /* ignore */ }
};
const quietGlobeDeckLayer = () => {
try { globeDeckLayerRef.current?.setProps({ layers: [] } as never); } catch { /* ignore */ }
};
const syncProjectionAndDeck = () => {
if (cancelled) return;
if (!isTransition) {
return;
}
if (!map.isStyleLoaded()) {
if (!cancelled && retries < maxRetries) {
retries += 1;
window.requestAnimationFrame(() => syncProjectionAndDeck());
}
return;
}
const next = projection;
const currentProjection = extractProjectionType(map);
const shouldSwitchProjection = currentProjection !== next;
if (projection === 'globe') {
quietMercatorOverlays();
} else {
quietGlobeDeckLayer();
}
try {
if (shouldSwitchProjection) {
map.setProjection({ type: next });
}
map.setRenderWorldCopies(next !== 'globe');
// Globe에서는 easeTo around 미지원 → scrollZoom 동작 전환
try {
map.scrollZoom.disable();
if (next === 'globe') {
map.scrollZoom.enable();
} else {
map.scrollZoom.enable({ around: 'center' });
}
} catch { /* ignore */ }
if (shouldSwitchProjection && currentProjection !== next && !cancelled && retries < maxRetries) {
retries += 1;
window.requestAnimationFrame(() => syncProjectionAndDeck());
return;
}
} catch (e) {
if (!cancelled && retries < maxRetries) {
retries += 1;
window.requestAnimationFrame(() => syncProjectionAndDeck());
return;
}
if (isTransition) setProjectionLoading(false);
console.warn('Projection switch failed:', e);
}
// 양쪽 overlay가 항상 존재하므로 재생성 불필요
// deck-globe가 map에서 빠져있을 경우에만 재추가
if (projection === 'globe') {
const layer = globeDeckLayerRef.current;
const layerId = layer?.id;
if (layer && layerId && map.isStyleLoaded() && !map.getLayer(layerId)) {
try {
map.addLayer(layer);
} catch {
// ignore
}
}
} else {
ensureMercatorOverlay();
}
reorderGlobeFeatureLayers();
kickRepaint(map);
try {
map.resize();
} catch {
// ignore
}
if (isTransition) {
startProjectionSettle();
}
pulseMapSync();
};
if (!isTransition) return;
if (map.isStyleLoaded()) syncProjectionAndDeck();
else {
const stop = onMapStyleReady(map, syncProjectionAndDeck);
return () => {
cancelled = true;
if (settleCleanup) settleCleanup();
stop();
if (isTransition) setProjectionLoading(false);
};
}
return () => {
cancelled = true;
if (settleCleanup) settleCleanup();
if (isTransition) setProjectionLoading(false);
};
}, [projection, ensureMercatorOverlay, reorderGlobeFeatureLayers, setProjectionLoading]);
return reorderGlobeFeatureLayers;
}

파일 보기

@ -0,0 +1,291 @@
import { useEffect, useMemo, useRef, type MutableRefObject } from 'react';
import maplibregl from 'maplibre-gl';
import type { SubcableGeoJson } from '../../../entities/subcable/model/types';
import type { MapToggleState } from '../../../features/mapToggles/MapToggles';
import type { MapProjectionId } from '../types';
import { kickRepaint } from '../lib/mapCore';
import { useNativeMapLayers, type NativeLayerSpec } from './useNativeMapLayers';
/* ── Layer / Source IDs ─────────────────────────────────────────────── */
const SRC_ID = 'subcables-src';
const POINTS_SRC_ID = 'subcables-pts-src';
const HITAREA_ID = 'subcables-hitarea';
const CASING_ID = 'subcables-casing';
const LINE_ID = 'subcables-line';
const GLOW_ID = 'subcables-glow';
const POINTS_ID = 'subcables-points';
const LABEL_ID = 'subcables-label';
/* ── Paint defaults (used for layer creation + hover reset) ──────── */
const LINE_OPACITY_DEFAULT = ['interpolate', ['linear'], ['zoom'], 2, 0.7, 6, 0.82, 10, 0.92];
const LINE_WIDTH_DEFAULT = ['interpolate', ['linear'], ['zoom'], 2, 1.6, 6, 2.5, 10, 4.0];
const CASING_OPACITY_DEFAULT = ['interpolate', ['linear'], ['zoom'], 2, 0.3, 5, 0.5, 8, 0.65];
const CASING_WIDTH_DEFAULT = ['interpolate', ['linear'], ['zoom'], 2, 2.4, 6, 3.6, 10, 5.5];
const POINTS_OPACITY_DEFAULT = ['interpolate', ['linear'], ['zoom'], 2, 0.5, 5, 0.7, 8, 0.85];
const POINTS_RADIUS_DEFAULT = ['interpolate', ['linear'], ['zoom'], 2, 1.5, 6, 2.5, 10, 4];
/* ── Layer specifications ────────────────────────────────────────── */
const LAYER_SPECS: NativeLayerSpec[] = [
{
id: HITAREA_ID,
type: 'line',
sourceId: SRC_ID,
paint: { 'line-color': 'rgba(0,0,0,0)', 'line-width': 14, 'line-opacity': 0 },
layout: { 'line-cap': 'round', 'line-join': 'round' },
minzoom: 3,
},
{
id: CASING_ID,
type: 'line',
sourceId: SRC_ID,
paint: {
'line-color': 'rgba(0,0,0,0.55)',
'line-width': CASING_WIDTH_DEFAULT,
'line-opacity': CASING_OPACITY_DEFAULT,
},
layout: { 'line-cap': 'round', 'line-join': 'round' },
minzoom: 3,
},
{
id: LINE_ID,
type: 'line',
sourceId: SRC_ID,
paint: {
'line-color': ['get', 'color'],
'line-opacity': LINE_OPACITY_DEFAULT,
'line-width': LINE_WIDTH_DEFAULT,
},
layout: { 'line-cap': 'round', 'line-join': 'round' },
},
{
id: GLOW_ID,
type: 'line',
sourceId: SRC_ID,
paint: {
'line-color': ['get', 'color'],
'line-opacity': 0,
'line-width': ['interpolate', ['linear'], ['zoom'], 2, 5, 6, 8, 10, 12],
'line-blur': ['interpolate', ['linear'], ['zoom'], 2, 3, 6, 5, 10, 7],
},
filter: ['==', ['get', 'id'], ''],
layout: { 'line-cap': 'round', 'line-join': 'round' },
minzoom: 3,
},
{
id: POINTS_ID,
type: 'circle',
sourceId: POINTS_SRC_ID,
paint: {
'circle-radius': POINTS_RADIUS_DEFAULT,
'circle-color': ['get', 'color'],
'circle-opacity': POINTS_OPACITY_DEFAULT,
'circle-stroke-color': 'rgba(0,0,0,0.5)',
'circle-stroke-width': 0.5,
},
minzoom: 3,
},
{
id: LABEL_ID,
type: 'symbol',
sourceId: SRC_ID,
paint: {
'text-color': 'rgba(220,232,245,0.82)',
'text-halo-color': 'rgba(2,6,23,0.9)',
'text-halo-width': 1.2,
'text-halo-blur': 0.5,
'text-opacity': ['interpolate', ['linear'], ['zoom'], 4, 0, 5, 0.7, 8, 0.88],
},
layout: {
'symbol-placement': 'line',
'text-field': ['get', 'name'],
'text-size': ['interpolate', ['linear'], ['zoom'], 4, 9, 8, 11, 12, 13],
'text-font': ['Noto Sans Regular', 'Open Sans Regular'],
'text-allow-overlap': false,
'text-padding': 8,
'text-rotation-alignment': 'map',
},
minzoom: 4,
},
];
export function useSubcablesLayer(
mapRef: MutableRefObject<maplibregl.Map | null>,
projectionBusyRef: MutableRefObject<boolean>,
reorderGlobeFeatureLayers: () => void,
opts: {
subcableGeo: SubcableGeoJson | null;
overlays: MapToggleState;
projection: MapProjectionId;
mapSyncEpoch: number;
hoveredCableId: string | null;
onHoverCable: (cableId: string | null) => void;
onClickCable: (cableId: string | null) => void;
},
) {
const { subcableGeo, overlays, projection, mapSyncEpoch, hoveredCableId, onHoverCable, onClickCable } = opts;
const onHoverRef = useRef(onHoverCable);
const onClickRef = useRef(onClickCable);
const hoveredCableIdRef = useRef(hoveredCableId);
useEffect(() => {
onHoverRef.current = onHoverCable;
onClickRef.current = onClickCable;
hoveredCableIdRef.current = hoveredCableId;
});
/* ── Derived point features ──────────────────────────────────────── */
const pointsGeoJson = useMemo<GeoJSON.FeatureCollection>(() => {
if (!subcableGeo) return { type: 'FeatureCollection', features: [] };
const features: GeoJSON.Feature<GeoJSON.Point>[] = [];
for (const f of subcableGeo.features) {
const coords = f.properties.coordinates;
if (!coords || coords.length < 2) continue;
features.push({
type: 'Feature',
properties: { id: f.properties.id, color: f.properties.color },
geometry: { type: 'Point', coordinates: coords },
});
}
return { type: 'FeatureCollection', features };
}, [subcableGeo]);
/* ================================================================
* Effect 1: Layer creation & data update (via useNativeMapLayers)
* ================================================================ */
useNativeMapLayers(
mapRef,
projectionBusyRef,
reorderGlobeFeatureLayers,
{
sources: [
{ id: SRC_ID, data: subcableGeo, options: { tolerance: 1, buffer: 64 } },
{ id: POINTS_SRC_ID, data: pointsGeoJson },
],
layers: LAYER_SPECS,
visible: overlays.subcables,
beforeLayer: ['zones-fill', 'deck-globe'],
onAfterSetup: (map) => applyHoverHighlight(map, hoveredCableIdRef.current),
},
[subcableGeo, pointsGeoJson, overlays.subcables, projection, mapSyncEpoch, reorderGlobeFeatureLayers],
);
/* ================================================================
* Effect 2: Hover highlight (paint-only, no layer creation)
* ================================================================ */
useEffect(() => {
const map = mapRef.current;
if (!map || !map.isStyleLoaded()) return;
if (projectionBusyRef.current) return;
if (!map.getLayer(LINE_ID)) return;
applyHoverHighlight(map, hoveredCableId);
kickRepaint(map);
}, [hoveredCableId]);
/* ================================================================
* Effect 3: Mouse events (bind to hit-area for easy hovering)
* ================================================================ */
useEffect(() => {
const map = mapRef.current;
if (!map) return;
if (!overlays.subcables) return;
let cancelled = false;
let retryTimer: ReturnType<typeof setTimeout> | null = null;
const onMouseMove = (e: maplibregl.MapMouseEvent & { features?: maplibregl.MapGeoJSONFeature[] }) => {
const cableId = e.features?.[0]?.properties?.id;
if (typeof cableId === 'string' && cableId) {
map.getCanvas().style.cursor = 'pointer';
onHoverRef.current(cableId);
}
};
const onMouseLeave = () => {
map.getCanvas().style.cursor = '';
onHoverRef.current(null);
};
const onClick = (e: maplibregl.MapMouseEvent & { features?: maplibregl.MapGeoJSONFeature[] }) => {
const cableId = e.features?.[0]?.properties?.id;
if (typeof cableId === 'string' && cableId) {
onClickRef.current(cableId);
}
};
const bindEvents = () => {
if (cancelled) return;
const targetLayer = map.getLayer(HITAREA_ID) ? HITAREA_ID : map.getLayer(LINE_ID) ? LINE_ID : null;
if (!targetLayer) {
retryTimer = setTimeout(bindEvents, 200);
return;
}
map.on('mousemove', targetLayer, onMouseMove);
map.on('mouseleave', targetLayer, onMouseLeave);
map.on('click', targetLayer, onClick);
};
if (map.isStyleLoaded()) {
bindEvents();
} else {
map.once('idle', bindEvents);
}
return () => {
cancelled = true;
if (retryTimer) clearTimeout(retryTimer);
try {
map.off('mousemove', HITAREA_ID, onMouseMove);
map.off('mouseleave', HITAREA_ID, onMouseLeave);
map.off('click', HITAREA_ID, onClick);
map.off('mousemove', LINE_ID, onMouseMove);
map.off('mouseleave', LINE_ID, onMouseLeave);
map.off('click', LINE_ID, onClick);
} catch {
// ignore
}
};
}, [overlays.subcables, mapSyncEpoch]);
}
/* ── Hover highlight helper (paint-only mutations) ────────────────── */
function applyHoverHighlight(map: maplibregl.Map, hoveredId: string | null) {
if (hoveredId) {
const matchExpr = ['==', ['get', 'id'], hoveredId];
if (map.getLayer(LINE_ID)) {
map.setPaintProperty(LINE_ID, 'line-opacity', ['case', matchExpr, 1.0, 0.2] as never);
map.setPaintProperty(LINE_ID, 'line-width', ['case', matchExpr, 4.5, 1.2] as never);
}
if (map.getLayer(CASING_ID)) {
map.setPaintProperty(CASING_ID, 'line-opacity', ['case', matchExpr, 0.7, 0.12] as never);
map.setPaintProperty(CASING_ID, 'line-width', ['case', matchExpr, 6.5, 2.0] as never);
}
if (map.getLayer(GLOW_ID)) {
map.setFilter(GLOW_ID, matchExpr as never);
map.setPaintProperty(GLOW_ID, 'line-opacity', 0.35);
}
if (map.getLayer(POINTS_ID)) {
map.setPaintProperty(POINTS_ID, 'circle-opacity', ['case', matchExpr, 1.0, 0.15] as never);
map.setPaintProperty(POINTS_ID, 'circle-radius', ['case', matchExpr, 4, 1.5] as never);
}
} else {
if (map.getLayer(LINE_ID)) {
map.setPaintProperty(LINE_ID, 'line-opacity', LINE_OPACITY_DEFAULT as never);
map.setPaintProperty(LINE_ID, 'line-width', LINE_WIDTH_DEFAULT as never);
}
if (map.getLayer(CASING_ID)) {
map.setPaintProperty(CASING_ID, 'line-opacity', CASING_OPACITY_DEFAULT as never);
map.setPaintProperty(CASING_ID, 'line-width', CASING_WIDTH_DEFAULT as never);
}
if (map.getLayer(GLOW_ID)) {
map.setFilter(GLOW_ID, ['==', ['get', 'id'], ''] as never);
map.setPaintProperty(GLOW_ID, 'line-opacity', 0);
}
if (map.getLayer(POINTS_ID)) {
map.setPaintProperty(POINTS_ID, 'circle-opacity', POINTS_OPACITY_DEFAULT as never);
map.setPaintProperty(POINTS_ID, 'circle-radius', POINTS_RADIUS_DEFAULT as never);
}
}
}

파일 보기

@ -0,0 +1,262 @@
import { useEffect, useMemo, type MutableRefObject } from 'react';
import maplibregl, {
type GeoJSONSource,
type GeoJSONSourceSpecification,
type LayerSpecification,
} from 'maplibre-gl';
import type { ZoneId } from '../../../entities/zone/model/meta';
import { ZONE_META } from '../../../entities/zone/model/meta';
import type { ZonesGeoJson } from '../../../entities/zone/api/useZones';
import type { MapToggleState } from '../../../features/mapToggles/MapToggles';
import type { BaseMapId, MapProjectionId } from '../types';
import { kickRepaint, onMapStyleReady } from '../lib/mapCore';
import { guardedSetVisibility } from '../lib/layerHelpers';
/** Globe tessellation vertex 65535 .
* ( 2100+ vertex) globe에서 70,000+
* ring당 maxPts개로 . centroid에는 . */
function simplifyZonesForGlobe(zones: ZonesGeoJson): ZonesGeoJson {
const MAX_PTS = 60;
const subsample = (ring: GeoJSON.Position[]): GeoJSON.Position[] => {
if (ring.length <= MAX_PTS) return ring;
const step = Math.ceil(ring.length / MAX_PTS);
const out: GeoJSON.Position[] = [ring[0]];
for (let i = step; i < ring.length - 1; i += step) out.push(ring[i]);
out.push(ring[0]); // close ring
return out;
};
return {
...zones,
features: zones.features.map((f) => ({
...f,
geometry: {
...f.geometry,
coordinates: f.geometry.coordinates.map((polygon) =>
polygon.map((ring) => subsample(ring)),
),
},
})),
};
}
export function useZonesLayer(
mapRef: MutableRefObject<maplibregl.Map | null>,
projectionBusyRef: MutableRefObject<boolean>,
reorderGlobeFeatureLayers: () => void,
opts: {
zones: ZonesGeoJson | null;
overlays: MapToggleState;
projection: MapProjectionId;
baseMap: BaseMapId;
hoveredZoneId: string | null;
mapSyncEpoch: number;
},
) {
const { zones, overlays, projection, baseMap, hoveredZoneId, mapSyncEpoch } = opts;
// globe용 간소화 데이터를 미리 캐싱 — ensure() 내 매번 재계산 방지
const simplifiedZones = useMemo(
() => (zones ? simplifyZonesForGlobe(zones) : null),
[zones],
);
useEffect(() => {
const map = mapRef.current;
if (!map) return;
const srcId = 'zones-src';
const fillId = 'zones-fill';
const lineId = 'zones-line';
const labelId = 'zones-label';
const zoneColorExpr: unknown[] = ['match', ['get', 'zoneId']];
for (const k of Object.keys(ZONE_META) as ZoneId[]) {
zoneColorExpr.push(k, ZONE_META[k].color);
}
zoneColorExpr.push('#3B82F6');
const zoneLabelExpr: unknown[] = ['match', ['to-string', ['coalesce', ['get', 'zoneId'], '']]];
for (const k of Object.keys(ZONE_META) as ZoneId[]) {
zoneLabelExpr.push(k, ZONE_META[k].name);
}
zoneLabelExpr.push(['coalesce', ['get', 'zoneName'], ['get', 'zoneLabel'], ['get', 'NAME'], '수역']);
const ensure = () => {
// 소스 데이터 간소화 — projectionBusy 중에도 실행해야 함
// globe 전환 시 projectionBusy 가드 뒤에서만 실행하면 MapLibre가
// 원본(2100+ vertex) 데이터로 globe tessellation → 73,000+ vertex → 노란 막대
const sourceData = projection === 'globe' ? simplifiedZones : zones;
if (sourceData) {
try {
const existing = map.getSource(srcId) as GeoJSONSource | undefined;
if (existing) existing.setData(sourceData);
} catch { /* ignore — source may not exist yet */ }
}
const visibility: 'visible' | 'none' = overlays.zones ? 'visible' : 'none';
guardedSetVisibility(map, fillId, visibility);
guardedSetVisibility(map, lineId, visibility);
guardedSetVisibility(map, labelId, visibility);
if (projectionBusyRef.current) return;
if (!zones) return;
if (!map.isStyleLoaded()) return;
try {
// 소스가 아직 없으면 생성 (setData는 위에서 이미 처리됨)
if (!map.getSource(srcId)) {
const data = projection === 'globe' ? simplifiedZones ?? zones : zones;
map.addSource(srcId, { type: 'geojson', data: data! } as GeoJSONSourceSpecification);
}
const style = map.getStyle();
const styleLayers = style && Array.isArray(style.layers) ? style.layers : [];
const firstSymbol = styleLayers.find((l) => (l as { type?: string } | undefined)?.type === 'symbol') as
| { id?: string }
| undefined;
const before = map.getLayer('deck-globe')
? 'deck-globe'
: map.getLayer('ships')
? 'ships'
: map.getLayer('seamark')
? 'seamark'
: firstSymbol?.id;
const zoneMatchExpr =
hoveredZoneId !== null
? (['==', ['to-string', ['coalesce', ['get', 'zoneId'], '']], hoveredZoneId] as unknown[])
: false;
const zoneLineWidthExpr = hoveredZoneId
? ([
'interpolate',
['linear'],
['zoom'],
4,
['case', zoneMatchExpr, 1.6, 0.8],
10,
['case', zoneMatchExpr, 2.0, 1.4],
14,
['case', zoneMatchExpr, 2.8, 2.1],
] as unknown as never)
: (['interpolate', ['linear'], ['zoom'], 4, 0.8, 10, 1.4, 14, 2.1] as never);
if (map.getLayer(fillId)) {
try {
map.setPaintProperty(
fillId,
'fill-opacity',
hoveredZoneId ? (['case', zoneMatchExpr, 0.24, 0.1] as unknown as number) : 0.12,
);
} catch {
// ignore
}
}
if (map.getLayer(lineId)) {
try {
map.setPaintProperty(
lineId,
'line-color',
hoveredZoneId
? (['case', zoneMatchExpr, 'rgba(125,211,252,0.98)', zoneColorExpr as never] as never)
: (zoneColorExpr as never),
);
} catch {
// ignore
}
try {
map.setPaintProperty(lineId, 'line-opacity', hoveredZoneId ? (['case', zoneMatchExpr, 1, 0.85] as never) : 0.85);
} catch {
// ignore
}
try {
map.setPaintProperty(lineId, 'line-width', zoneLineWidthExpr);
} catch {
// ignore
}
}
if (!map.getLayer(fillId)) {
map.addLayer(
{
id: fillId,
type: 'fill',
source: srcId,
paint: {
'fill-color': zoneColorExpr as never,
'fill-opacity': hoveredZoneId
? ([
'case',
zoneMatchExpr,
0.24,
0.1,
] as unknown as number)
: 0.12,
},
layout: { visibility },
} as unknown as LayerSpecification,
before,
);
}
if (!map.getLayer(lineId)) {
map.addLayer(
{
id: lineId,
type: 'line',
source: srcId,
paint: {
'line-color': hoveredZoneId
? (['case', zoneMatchExpr, 'rgba(125,211,252,0.98)', zoneColorExpr as never] as never)
: (zoneColorExpr as never),
'line-opacity': hoveredZoneId
? (['case', zoneMatchExpr, 1, 0.85] as never)
: 0.85,
'line-width': zoneLineWidthExpr,
},
layout: { visibility },
} as unknown as LayerSpecification,
before,
);
}
if (!map.getLayer(labelId)) {
map.addLayer(
{
id: labelId,
type: 'symbol',
source: srcId,
layout: {
visibility,
'symbol-placement': 'point',
'text-field': zoneLabelExpr as never,
'text-size': 11,
'text-font': ['Noto Sans Regular', 'Open Sans Regular'],
'text-anchor': 'top',
'text-offset': [0, 0.35],
'text-allow-overlap': false,
'text-ignore-placement': false,
},
paint: {
'text-color': '#dbeafe',
'text-halo-color': 'rgba(2,6,23,0.85)',
'text-halo-width': 1.2,
'text-halo-blur': 0.8,
},
} as unknown as LayerSpecification,
undefined,
);
}
} catch (e) {
console.warn('Zones layer setup failed:', e);
} finally {
reorderGlobeFeatureLayers();
kickRepaint(map);
}
};
const stop = onMapStyleReady(map, ensure);
return () => {
stop();
};
}, [zones, simplifiedZones, overlays.zones, projection, baseMap, hoveredZoneId, mapSyncEpoch, reorderGlobeFeatureLayers]);
}

파일 보기

@ -0,0 +1,397 @@
import maplibregl, {
type LayerSpecification,
type StyleSpecification,
type VectorSourceSpecification,
} from 'maplibre-gl';
import type { BaseMapId, BathyZoomRange, MapProjectionId } from '../types';
import { getLayerId, getMapTilerKey } from '../lib/mapCore';
export const SHALLOW_WATER_FILL_DEFAULT = '#14606e';
export const SHALLOW_WATER_LINE_DEFAULT = '#114f5c';
const BATHY_ZOOM_RANGES: BathyZoomRange[] = [
{ id: 'bathymetry-fill', mercator: [3, 24], globe: [3, 24] },
{ id: 'bathymetry-borders-major', mercator: [3, 7], globe: [3, 7] },
{ id: 'bathymetry-borders', mercator: [7, 24], globe: [7, 24] },
{ id: 'bathymetry-lines-coarse', mercator: [5, 7], globe: [5, 7] },
{ id: 'bathymetry-lines-major', mercator: [7, 9], globe: [7, 9] },
{ id: 'bathymetry-lines-detail', mercator: [9, 24], globe: [9, 24] },
{ id: 'bathymetry-labels-coarse', mercator: [6, 9], globe: [6, 9] },
{ id: 'bathymetry-labels', mercator: [9, 24], globe: [9, 24] },
];
/**
* LOD vertex가 minzoom을
* , .
* .
*/
function applyLandLayerLOD(style: StyleSpecification): void {
if (!style.layers || !Array.isArray(style.layers)) return;
// source-layer → 렌더링을 시작할 최소 줌 레벨
// globe 모드 줌아웃 시 vertex 65535 초과로 GPU 렌더링 아티팩트(노란 막대) 방지
const LOD_MINZOOM: Record<string, number> = {
'landcover': 9,
'globallandcover': 9,
'landuse': 11,
'boundary': 5,
'transportation': 8,
'transportation_name': 10,
'building': 14,
'housenumber': 16,
'aeroway': 11,
'park': 10,
'mountain_peak': 11,
};
for (const layer of style.layers as unknown as LayerSpecification[]) {
const spec = layer as Record<string, unknown>;
const sourceLayer = spec['source-layer'] as string | undefined;
if (!sourceLayer) continue;
const lodMin = LOD_MINZOOM[sourceLayer];
if (lodMin === undefined) continue;
// 기존 minzoom보다 높을 때만 덮어씀
const current = (spec.minzoom as number) ?? 0;
if (lodMin > current) {
spec.minzoom = lodMin;
}
}
}
export function injectOceanBathymetryLayers(style: StyleSpecification, maptilerKey: string) {
const oceanSourceId = 'maptiler-ocean';
if (!style.sources) style.sources = {} as StyleSpecification['sources'];
if (!style.layers) style.layers = [];
if (!style.sources[oceanSourceId]) {
style.sources[oceanSourceId] = {
type: 'vector',
url: `https://api.maptiler.com/tiles/ocean/tiles.json?key=${encodeURIComponent(maptilerKey)}`,
} satisfies VectorSourceSpecification as unknown as StyleSpecification['sources'][string];
}
const depth = ['to-number', ['get', 'depth']] as unknown as number[];
const depthLabel = ['concat', ['to-string', ['*', depth, -1]], 'm'] as unknown as string[];
// 수심 색상: 전체 범위 (-8000m ~ 0m)
const bathyFillColor = [
'interpolate',
['linear'],
depth,
-8000,
'#010610',
-4000,
'#030c1c',
-2000,
'#041022',
-1000,
'#051529',
-500,
'#061a30',
-200,
'#071f36',
-100,
'#08263d',
-50,
'#0e3d5e',
-20,
'#145578',
-10,
'#1a6e8e',
0,
'#2097a6',
] as const;
// --- Depth tiers for zoom-based LOD ---
// 줌 기반 LOD로 vertex 제어 — 줌아웃에선 주요 등심선만, 줌인에서 점진적 디테일
const DEPTHS_COARSE = [-1000, -2000];
const DEPTHS_MEDIUM = [-100, -500, -1000, -2000, -4000];
const DEPTHS_DETAIL = [-50, -100, -200, -500, -1000, -2000, -4000, -8000];
const depthIn = (depths: number[]) =>
['in', depth, ['literal', depths]] as unknown[];
// === Fill (contour polygons) — 단일 레이어, 전체 depth ===
const bathyFill: LayerSpecification = {
id: 'bathymetry-fill',
type: 'fill',
source: oceanSourceId,
'source-layer': 'contour',
minzoom: 3,
maxzoom: 24,
paint: {
'fill-color': bathyFillColor,
'fill-opacity': ['interpolate', ['linear'], ['zoom'], 0, 0.9, 5, 0.88, 8, 0.84, 10, 0.78],
},
} as unknown as LayerSpecification;
// === Borders (contour polygon edges) — 2-tier LOD ===
// z3-z7: 1000m, 2000m 경계만
const bathyBordersMajor: LayerSpecification = {
id: 'bathymetry-borders-major',
type: 'line',
source: oceanSourceId,
'source-layer': 'contour',
minzoom: 3,
maxzoom: 7,
filter: depthIn(DEPTHS_COARSE) as unknown as unknown[],
paint: {
'line-color': 'rgba(255,255,255,0.14)',
'line-opacity': ['interpolate', ['linear'], ['zoom'], 3, 0.10, 6, 0.16],
'line-blur': ['interpolate', ['linear'], ['zoom'], 3, 0.5, 6, 0.35],
'line-width': ['interpolate', ['linear'], ['zoom'], 3, 0.25, 6, 0.4],
},
} as unknown as LayerSpecification;
// z7+: 전체 등심선 경계
const bathyBorders: LayerSpecification = {
id: 'bathymetry-borders',
type: 'line',
source: oceanSourceId,
'source-layer': 'contour',
minzoom: 7,
maxzoom: 24,
paint: {
'line-color': 'rgba(255,255,255,0.06)',
'line-opacity': ['interpolate', ['linear'], ['zoom'], 7, 0.18, 12, 0.22],
'line-blur': ['interpolate', ['linear'], ['zoom'], 7, 0.3, 10, 0.2],
'line-width': ['interpolate', ['linear'], ['zoom'], 7, 0.35, 12, 0.6],
},
} as unknown as LayerSpecification;
// === Contour lines (contour_line) — 3-tier LOD ===
// z5-z7: 1000m, 2000m만
const bathyLinesCoarse: LayerSpecification = {
id: 'bathymetry-lines-coarse',
type: 'line',
source: oceanSourceId,
'source-layer': 'contour_line',
minzoom: 5,
maxzoom: 7,
filter: depthIn(DEPTHS_COARSE) as unknown as unknown[],
paint: {
'line-color': 'rgba(255,255,255,0.12)',
'line-opacity': ['interpolate', ['linear'], ['zoom'], 5, 0.15, 7, 0.22],
'line-blur': 0.5,
'line-width': ['interpolate', ['linear'], ['zoom'], 5, 0.4, 7, 0.6],
},
} as unknown as LayerSpecification;
// z7-z9: 100, 500, 1000, 2000, 4000m
const bathyLinesMajor: LayerSpecification = {
id: 'bathymetry-lines-major',
type: 'line',
source: oceanSourceId,
'source-layer': 'contour_line',
minzoom: 7,
maxzoom: 9,
filter: depthIn(DEPTHS_MEDIUM) as unknown as unknown[],
paint: {
'line-color': 'rgba(255,255,255,0.16)',
'line-opacity': ['interpolate', ['linear'], ['zoom'], 7, 0.22, 9, 0.28],
'line-blur': ['interpolate', ['linear'], ['zoom'], 7, 0.4, 9, 0.2],
'line-width': ['interpolate', ['linear'], ['zoom'], 7, 0.6, 9, 0.95],
},
} as unknown as LayerSpecification;
// z9+: 50~8000m (풀 디테일)
const bathyLinesDetail: LayerSpecification = {
id: 'bathymetry-lines-detail',
type: 'line',
source: oceanSourceId,
'source-layer': 'contour_line',
minzoom: 9,
maxzoom: 24,
filter: depthIn(DEPTHS_DETAIL) as unknown as unknown[],
paint: {
'line-color': 'rgba(255,255,255,0.16)',
'line-opacity': ['interpolate', ['linear'], ['zoom'], 9, 0.28, 12, 0.34],
'line-blur': ['interpolate', ['linear'], ['zoom'], 9, 0.2, 11, 0.15],
'line-width': ['interpolate', ['linear'], ['zoom'], 9, 0.95, 12, 1.3],
},
} as unknown as LayerSpecification;
// === Labels — 2-tier LOD ===
// z6-z9: 1000m, 2000m 라벨만
const bathyLabelsCoarse: LayerSpecification = {
id: 'bathymetry-labels-coarse',
type: 'symbol',
source: oceanSourceId,
'source-layer': 'contour_line',
minzoom: 6,
maxzoom: 9,
filter: depthIn(DEPTHS_COARSE) as unknown as unknown[],
layout: {
'symbol-placement': 'line',
'text-field': depthLabel,
'text-font': ['Noto Sans Regular', 'Open Sans Regular'],
'text-size': ['interpolate', ['linear'], ['zoom'], 6, 10, 9, 12],
'text-allow-overlap': false,
'text-padding': 4,
'text-rotation-alignment': 'map',
},
paint: {
'text-color': 'rgba(226,232,240,0.78)',
'text-halo-color': 'rgba(2,6,23,0.88)',
'text-halo-width': 1.2,
'text-halo-blur': 0.5,
},
} as unknown as LayerSpecification;
// z9+: 100~4000m 라벨
const bathyLabels: LayerSpecification = {
id: 'bathymetry-labels',
type: 'symbol',
source: oceanSourceId,
'source-layer': 'contour_line',
minzoom: 9,
filter: depthIn(DEPTHS_MEDIUM) as unknown as unknown[],
layout: {
'symbol-placement': 'line',
'text-field': depthLabel,
'text-font': ['Noto Sans Regular', 'Open Sans Regular'],
'text-size': ['interpolate', ['linear'], ['zoom'], 9, 12, 11, 14, 13, 16],
'text-allow-overlap': false,
'text-padding': 4,
'text-rotation-alignment': 'map',
},
paint: {
'text-color': 'rgba(226,232,240,0.78)',
'text-halo-color': 'rgba(2,6,23,0.88)',
'text-halo-width': 1.2,
'text-halo-blur': 0.5,
},
} as unknown as LayerSpecification;
const landformLabels: LayerSpecification = {
id: 'bathymetry-landforms',
type: 'symbol',
source: oceanSourceId,
'source-layer': 'landform',
minzoom: 6,
filter: ['has', 'name'] as unknown as unknown[],
layout: {
'text-field': ['get', 'name'] as unknown as unknown[],
'text-font': ['Noto Sans Italic', 'Noto Sans Regular', 'Open Sans Italic', 'Open Sans Regular'],
'text-size': ['interpolate', ['linear'], ['zoom'], 6, 10, 8, 12, 10, 13, 12, 14],
'text-allow-overlap': false,
'text-anchor': 'center',
'text-offset': [0, 0.0],
},
paint: {
'text-color': 'rgba(148,163,184,0.75)',
'text-halo-color': 'rgba(2,6,23,0.88)',
'text-halo-width': 1.2,
'text-halo-blur': 0.6,
},
} as unknown as LayerSpecification;
const layers = Array.isArray(style.layers) ? (style.layers as unknown as LayerSpecification[]) : [];
if (!Array.isArray(style.layers)) {
style.layers = layers as unknown as StyleSpecification['layers'];
}
// Brighten base-map water fills so shallow coasts, rivers & lakes blend naturally
// with the bathymetry gradient instead of appearing as near-black voids.
const waterRegex = /(water|sea|ocean|river|lake|coast|bay)/i;
const SHALLOW_WATER_FILL = SHALLOW_WATER_FILL_DEFAULT;
const SHALLOW_WATER_LINE = SHALLOW_WATER_LINE_DEFAULT;
for (const layer of layers) {
const id = getLayerId(layer);
if (!id) continue;
const spec = layer as Record<string, unknown>;
const sourceLayer = String(spec['source-layer'] ?? '').toLowerCase();
const layerType = String(spec.type ?? '');
const isWater = waterRegex.test(id) || waterRegex.test(sourceLayer);
if (!isWater) continue;
const paint = (spec.paint ?? {}) as Record<string, unknown>;
if (layerType === 'fill') {
paint['fill-color'] = SHALLOW_WATER_FILL;
spec.paint = paint;
} else if (layerType === 'line') {
paint['line-color'] = SHALLOW_WATER_LINE;
spec.paint = paint;
}
}
const symbolIndex = layers.findIndex((l) => (l as { type?: unknown } | null)?.type === 'symbol');
const insertAt = symbolIndex >= 0 ? symbolIndex : layers.length;
const existingIds = new Set<string>();
for (const layer of layers) {
const id = getLayerId(layer);
if (id) existingIds.add(id);
}
const toInsert = [
bathyFill,
bathyBordersMajor,
bathyBorders,
bathyLinesCoarse,
bathyLinesMajor,
bathyLinesDetail,
bathyLabelsCoarse,
bathyLabels,
landformLabels,
].filter((l) => !existingIds.has(l.id));
if (toInsert.length > 0) layers.splice(insertAt, 0, ...toInsert);
}
export function applyBathymetryZoomProfile(map: maplibregl.Map, baseMap: BaseMapId, projection: MapProjectionId) {
if (!map || !map.isStyleLoaded()) return;
if (baseMap !== 'enhanced') return;
const isGlobe = projection === 'globe';
for (const range of BATHY_ZOOM_RANGES) {
if (!map.getLayer(range.id)) continue;
const [minzoom, maxzoom] = isGlobe ? range.globe : range.mercator;
try {
map.setLayoutProperty(range.id, 'visibility', 'visible');
} catch {
// ignore
}
try {
map.setLayerZoomRange(range.id, minzoom, maxzoom);
} catch {
// ignore
}
}
}
function applyKoreanLabels(style: StyleSpecification) {
if (!style.layers) return;
const koTextField = ['coalesce', ['get', 'name:ko'], ['get', 'name']];
for (const layer of style.layers as unknown as LayerSpecification[]) {
if ((layer as { type?: string }).type !== 'symbol') continue;
const layout = (layer as Record<string, unknown>).layout as
| Record<string, unknown>
| undefined;
if (!layout?.['text-field']) continue;
layout['text-field'] = koTextField;
}
}
export async function resolveInitialMapStyle(signal: AbortSignal): Promise<string | StyleSpecification> {
const key = getMapTilerKey();
if (!key) return '/map/styles/osm-seamark.json';
const baseMapId = (import.meta.env.VITE_MAPTILER_BASE_MAP_ID || 'dataviz-dark').trim();
const styleUrl = `https://api.maptiler.com/maps/${encodeURIComponent(baseMapId)}/style.json?key=${encodeURIComponent(key)}`;
const res = await fetch(styleUrl, { signal, headers: { accept: 'application/json' } });
if (!res.ok) throw new Error(`MapTiler style fetch failed: ${res.status} ${res.statusText}`);
const json = (await res.json()) as StyleSpecification;
applyLandLayerLOD(json);
applyKoreanLabels(json);
injectOceanBathymetryLayers(json, key);
return json;
}
export async function resolveMapStyle(baseMap: BaseMapId, signal: AbortSignal): Promise<string | StyleSpecification> {
// 레거시 베이스맵 비활성 — 향후 위성/라이트 테마 등 추가 시 재활용
// if (baseMap === 'legacy') return '/map/styles/carto-dark.json';
void baseMap;
return resolveInitialMapStyle(signal);
}

파일 보기

@ -0,0 +1,27 @@
import maplibregl, { type LayerSpecification } from 'maplibre-gl';
export function ensureSeamarkOverlay(map: maplibregl.Map, beforeLayerId?: string) {
const srcId = 'seamark';
const layerId = 'seamark';
if (!map.getSource(srcId)) {
map.addSource(srcId, {
type: 'raster',
tiles: ['https://tiles.openseamap.org/seamark/{z}/{x}/{y}.png'],
tileSize: 256,
attribution: '© OpenSeaMap contributors',
});
}
if (!map.getLayer(layerId)) {
const layer: LayerSpecification = {
id: layerId,
type: 'raster',
source: srcId,
paint: { 'raster-opacity': 0.85 },
} as unknown as LayerSpecification;
const before = beforeLayerId && map.getLayer(beforeLayerId) ? beforeLayerId : undefined;
map.addLayer(layer, before);
}
}

파일 보기

@ -0,0 +1,31 @@
import type { DashSeg } from '../types';
export function dashifyLine(
from: [number, number],
to: [number, number],
suspicious: boolean,
distanceNm?: number,
fromMmsi?: number,
toMmsi?: number,
): DashSeg[] {
const segs: DashSeg[] = [];
const steps = 14;
for (let i = 0; i < steps; i++) {
if (i % 2 === 1) continue;
const a0 = i / steps;
const a1 = (i + 1) / steps;
const lon0 = from[0] + (to[0] - from[0]) * a0;
const lat0 = from[1] + (to[1] - from[1]) * a0;
const lon1 = from[0] + (to[0] - from[0]) * a1;
const lat1 = from[1] + (to[1] - from[1]) * a1;
segs.push({
from: [lon0, lat0],
to: [lon1, lat1],
suspicious,
distanceNm,
fromMmsi,
toMmsi,
});
}
return segs;
}

파일 보기

@ -0,0 +1,19 @@
export function makeOrderedPairKey(a: number, b: number) {
const left = Math.trunc(Math.min(a, b));
const right = Math.trunc(Math.max(a, b));
return `${left}-${right}`;
}
export function makePairLinkFeatureId(a: number, b: number, suffix?: string) {
const pair = makeOrderedPairKey(a, b);
return suffix ? `pair-${pair}-${suffix}` : `pair-${pair}`;
}
export function makeFcSegmentFeatureId(a: number, b: number, segmentIndex: number) {
const pair = makeOrderedPairKey(a, b);
return `fc-${pair}-${segmentIndex}`;
}
export function makeFleetCircleFeatureId(ownerKey: string) {
return `fleet-${ownerKey}`;
}

파일 보기

@ -0,0 +1,61 @@
import { DEG2RAD, RAD2DEG, EARTH_RADIUS_M } from '../constants';
export const clampNumber = (value: number, minValue: number, maxValue: number) =>
Math.max(minValue, Math.min(maxValue, value));
export function wrapLonDeg(lon: number) {
const v = ((lon + 180) % 360 + 360) % 360;
return v - 180;
}
export function destinationPointLngLat(
from: [number, number],
bearingDeg: number,
distanceMeters: number,
): [number, number] {
const [lonDeg, latDeg] = from;
const lat1 = latDeg * DEG2RAD;
const lon1 = lonDeg * DEG2RAD;
const brng = bearingDeg * DEG2RAD;
const dr = Math.max(0, distanceMeters) / EARTH_RADIUS_M;
if (!Number.isFinite(dr) || dr === 0) return [lonDeg, latDeg];
const sinLat1 = Math.sin(lat1);
const cosLat1 = Math.cos(lat1);
const sinDr = Math.sin(dr);
const cosDr = Math.cos(dr);
const lat2 = Math.asin(sinLat1 * cosDr + cosLat1 * sinDr * Math.cos(brng));
const lon2 =
lon1 +
Math.atan2(
Math.sin(brng) * sinDr * cosLat1,
cosDr - sinLat1 * Math.sin(lat2),
);
const outLon = wrapLonDeg(lon2 * RAD2DEG);
const outLat = clampNumber(lat2 * RAD2DEG, -85.0, 85.0);
return [outLon, outLat];
}
export function circleRingLngLat(center: [number, number], radiusMeters: number, steps = 36): [number, number][] {
// 반경이 지구 둘레의 1/4 (≈10,000km)을 넘으면 클램핑
const r = clampNumber(radiusMeters, 0, EARTH_RADIUS_M * Math.PI * 0.5);
const ring: [number, number][] = [];
for (let i = 0; i <= steps; i++) {
const a = (i / steps) * Math.PI * 2;
const pt = destinationPointLngLat(center, a * RAD2DEG, r);
ring.push(pt);
}
// 고리 닫기 보정
if (ring.length > 1) {
ring[ring.length - 1] = ring[0];
}
return ring;
}
export function normalizeAngleDeg(value: number, offset = 0): number {
const v = value + offset;
return ((v % 360) + 360) % 360;
}

파일 보기

@ -0,0 +1,76 @@
import maplibregl from 'maplibre-gl';
export function buildFallbackGlobeShipIcon() {
const size = 96;
const canvas = document.createElement('canvas');
canvas.width = size;
canvas.height = size;
const ctx = canvas.getContext('2d');
if (!ctx) return null;
ctx.clearRect(0, 0, size, size);
ctx.fillStyle = 'rgba(255,255,255,1)';
ctx.beginPath();
ctx.moveTo(size / 2, 6);
ctx.lineTo(size / 2 - 14, 24);
ctx.lineTo(size / 2 - 18, 58);
ctx.lineTo(size / 2 - 10, 88);
ctx.lineTo(size / 2 + 10, 88);
ctx.lineTo(size / 2 + 18, 58);
ctx.lineTo(size / 2 + 14, 24);
ctx.closePath();
ctx.fill();
ctx.fillRect(size / 2 - 8, 34, 16, 18);
return ctx.getImageData(0, 0, size, size);
}
export function buildFallbackGlobeAnchoredShipIcon() {
const baseImage = buildFallbackGlobeShipIcon();
if (!baseImage) return null;
const size = baseImage.width;
const canvas = document.createElement('canvas');
canvas.width = size;
canvas.height = size;
const ctx = canvas.getContext('2d');
if (!ctx) return null;
ctx.putImageData(baseImage, 0, 0);
ctx.strokeStyle = 'rgba(248,250,252,1)';
ctx.lineWidth = 5;
ctx.lineCap = 'round';
ctx.beginPath();
const cx = size / 2;
ctx.moveTo(cx - 18, 76);
ctx.lineTo(cx + 18, 76);
ctx.moveTo(cx, 66);
ctx.lineTo(cx, 82);
ctx.moveTo(cx, 82);
ctx.arc(cx, 82, 7, 0, Math.PI * 2);
ctx.moveTo(cx, 82);
ctx.lineTo(cx, 88);
ctx.moveTo(cx - 9, 88);
ctx.lineTo(cx + 9, 88);
ctx.stroke();
return ctx.getImageData(0, 0, size, size);
}
export function ensureFallbackShipImage(
map: maplibregl.Map,
imageId: string,
fallbackBuilder: () => ImageData | null = buildFallbackGlobeShipIcon,
) {
if (!map || map.hasImage(imageId)) return;
const image = fallbackBuilder();
if (!image) return;
try {
map.addImage(imageId, image, { pixelRatio: 2, sdf: true });
} catch {
// ignore
}
}

파일 보기

@ -0,0 +1,134 @@
import maplibregl, {
type GeoJSONSourceSpecification,
type LayerSpecification,
} from 'maplibre-gl';
export function removeLayerIfExists(map: maplibregl.Map, layerId: string | null | undefined) {
if (!layerId) return;
try {
if (map.getLayer(layerId)) {
map.removeLayer(layerId);
}
} catch {
// ignore
}
}
export function removeSourceIfExists(map: maplibregl.Map, sourceId: string) {
try {
if (map.getSource(sourceId)) {
map.removeSource(sourceId);
}
} catch {
// ignore
}
}
// Ship 레이어/소스는 useGlobeShips에서 visibility 토글로 관리 (재생성 비용 회피)
const GLOBE_NATIVE_LAYER_IDS = [
'pair-lines-ml',
'fc-lines-ml',
'fleet-circles-ml',
'pair-range-ml',
'subcables-hitarea',
'subcables-casing',
'subcables-line',
'subcables-glow',
'subcables-points',
'subcables-label',
'deck-globe',
];
const GLOBE_NATIVE_SOURCE_IDS = [
'pair-lines-ml-src',
'fc-lines-ml-src',
'fleet-circles-ml-src',
'pair-range-ml-src',
'subcables-src',
'subcables-pts-src',
];
export function clearGlobeNativeLayers(map: maplibregl.Map) {
for (const id of GLOBE_NATIVE_LAYER_IDS) {
removeLayerIfExists(map, id);
}
for (const id of GLOBE_NATIVE_SOURCE_IDS) {
removeSourceIfExists(map, id);
}
}
export function ensureGeoJsonSource(
map: maplibregl.Map,
sourceId: string,
data: GeoJSON.GeoJSON,
options?: Partial<Omit<GeoJSONSourceSpecification, 'type' | 'data'>>,
) {
const existing = map.getSource(sourceId);
if (existing) {
(existing as maplibregl.GeoJSONSource).setData(data);
} else {
map.addSource(sourceId, {
type: 'geojson',
data,
...options,
} satisfies GeoJSONSourceSpecification);
}
}
export function ensureLayer(
map: maplibregl.Map,
spec: LayerSpecification,
options?: { before?: string },
) {
if (map.getLayer(spec.id)) return;
const before = options?.before && map.getLayer(options.before) ? options.before : undefined;
map.addLayer(spec, before);
}
export function setLayerVisibility(map: maplibregl.Map, layerId: string, visible: boolean) {
if (!map.getLayer(layerId)) return;
try {
map.setLayoutProperty(layerId, 'visibility', visible ? 'visible' : 'none');
} catch {
// ignore
}
}
/**
* setLayoutProperty('visibility') wrapper .
* MapLibre는 setLayoutProperty style._changed = true를
* symbol layer의 placement를 . text-allow-overlap:false
* , .
*/
export function guardedSetVisibility(map: maplibregl.Map, layerId: string, target: 'visible' | 'none') {
if (!map.getLayer(layerId)) return;
try {
if (map.getLayoutProperty(layerId, 'visibility') === target) return;
map.setLayoutProperty(layerId, 'visibility', target);
} catch {
// ignore
}
}
export function cleanupLayers(
map: maplibregl.Map,
layerIds: string[],
sourceIds: string[],
) {
requestAnimationFrame(() => {
for (const id of layerIds) {
try {
if (map.getLayer(id)) map.removeLayer(id);
} catch {
// ignore
}
}
for (const id of sourceIds) {
try {
if (map.getSource(id)) map.removeSource(id);
} catch {
// ignore
}
}
});
}

파일 보기

@ -0,0 +1,124 @@
import maplibregl from 'maplibre-gl';
import type { MapProjectionId } from '../types';
export function kickRepaint(map: maplibregl.Map | null) {
if (!map) return;
try {
if (map.isStyleLoaded()) map.triggerRepaint();
} catch {
// ignore
}
try {
requestAnimationFrame(() => {
try {
if (map.isStyleLoaded()) map.triggerRepaint();
} catch {
// ignore
}
});
requestAnimationFrame(() => {
try {
if (map.isStyleLoaded()) map.triggerRepaint();
} catch {
// ignore
}
});
} catch {
// ignore (e.g., non-browser env)
}
}
export function onMapStyleReady(map: maplibregl.Map | null, callback: () => void) {
if (!map) {
return () => {
// noop
};
}
if (map.isStyleLoaded()) {
callback();
return () => {
// noop
};
}
let fired = false;
const runOnce = () => {
if (!map || fired || !map.isStyleLoaded()) return;
fired = true;
callback();
try {
map.off('style.load', runOnce);
map.off('styledata', runOnce);
map.off('idle', runOnce);
} catch {
// ignore
}
};
map.on('style.load', runOnce);
map.on('styledata', runOnce);
map.on('idle', runOnce);
return () => {
if (fired) return;
fired = true;
try {
if (!map) return;
map.off('style.load', runOnce);
map.off('styledata', runOnce);
map.off('idle', runOnce);
} catch {
// ignore
}
};
}
export function extractProjectionType(map: maplibregl.Map): MapProjectionId | undefined {
const projection = map.getProjection?.();
if (!projection || typeof projection !== 'object') return undefined;
const rawType = (projection as { type?: unknown; name?: unknown }).type ?? (projection as { type?: unknown; name?: unknown }).name;
if (rawType === 'globe') return 'globe';
if (rawType === 'mercator') return 'mercator';
return undefined;
}
export function getMapTilerKey(): string | null {
const k = import.meta.env.VITE_MAPTILER_KEY;
if (typeof k !== 'string') return null;
const v = k.trim();
return v ? v : null;
}
export function getLayerId(value: unknown): string | null {
if (!value || typeof value !== 'object') return null;
const candidate = (value as { id?: unknown }).id;
return typeof candidate === 'string' ? candidate : null;
}
export function sanitizeDeckLayerList(value: unknown): unknown[] {
if (!Array.isArray(value)) return [];
const seen = new Set<string>();
const out: unknown[] = [];
let dropped = 0;
for (const layer of value) {
const layerId = getLayerId(layer);
if (!layerId) {
dropped += 1;
continue;
}
if (seen.has(layerId)) {
dropped += 1;
continue;
}
seen.add(layerId);
out.push(layer);
}
if (dropped > 0 && import.meta.env.DEV) {
console.warn(`Sanitized deck layer list: dropped ${dropped} invalid/duplicate entries`);
}
return out;
}

파일 보기

@ -0,0 +1,68 @@
export function makeMmsiPairHighlightExpr(aField: string, bField: string, hoveredMmsiList: number[]) {
if (!Array.isArray(hoveredMmsiList) || hoveredMmsiList.length < 2) {
return false;
}
const inA = ['in', ['to-number', ['get', aField]], ['literal', hoveredMmsiList]] as unknown[];
const inB = ['in', ['to-number', ['get', bField]], ['literal', hoveredMmsiList]] as unknown[];
return ['all', inA, inB] as unknown[];
}
export function makeMmsiAnyEndpointExpr(aField: string, bField: string, hoveredMmsiList: number[]) {
if (!Array.isArray(hoveredMmsiList) || hoveredMmsiList.length === 0) {
return false;
}
const literal = ['literal', hoveredMmsiList] as unknown[];
return [
'any',
['in', ['to-number', ['get', aField]], literal],
['in', ['to-number', ['get', bField]], literal],
] as unknown[];
}
export function makeFleetOwnerMatchExpr(hoveredOwnerKeys: string[]) {
if (!Array.isArray(hoveredOwnerKeys) || hoveredOwnerKeys.length === 0) {
return false;
}
const expr = ['match', ['to-string', ['coalesce', ['get', 'ownerKey'], '']]] as unknown[];
for (const ownerKey of hoveredOwnerKeys) {
expr.push(String(ownerKey), true);
}
expr.push(false);
return expr;
}
export function makeFleetMemberMatchExpr(hoveredFleetMmsiList: number[]) {
if (!Array.isArray(hoveredFleetMmsiList) || hoveredFleetMmsiList.length === 0) {
return false;
}
const clauses = hoveredFleetMmsiList.map((mmsi) =>
['in', mmsi, ['coalesce', ['get', 'vesselMmsis'], ['literal', []]]] as unknown[],
);
return ['any', ...clauses] as unknown[];
}
export function makeGlobeCircleRadiusExpr() {
const base3 = 4;
const base7 = 6;
const base10 = 8;
const base14 = 12;
const base18 = 32;
return [
'interpolate',
['linear'],
['zoom'],
3,
['case', ['==', ['get', 'selected'], 1], 4.6, ['==', ['get', 'highlighted'], 1], 4.2, base3],
7,
['case', ['==', ['get', 'selected'], 1], 6.8, ['==', ['get', 'highlighted'], 1], 6.2, base7],
10,
['case', ['==', ['get', 'selected'], 1], 9.0, ['==', ['get', 'highlighted'], 1], 8.2, base10],
14,
['case', ['==', ['get', 'selected'], 1], 13.5, ['==', ['get', 'highlighted'], 1], 12.6, base14],
18,
['case', ['==', ['get', 'selected'], 1], 36, ['==', ['get', 'highlighted'], 1], 34, base18],
];
}
export const GLOBE_SHIP_CIRCLE_RADIUS_EXPR = makeGlobeCircleRadiusExpr() as never;

파일 보기

@ -0,0 +1,79 @@
export function toNumberSet(values: number[] | undefined | null) {
const out = new Set<number>();
if (!values) return out;
for (const value of values) {
if (Number.isFinite(value)) {
out.add(value);
}
}
return out;
}
export function mergeNumberSets(...sets: Set<number>[]) {
const out = new Set<number>();
for (const s of sets) {
for (const v of s) {
out.add(v);
}
}
return out;
}
export function makeSetSignature(values: Set<number>) {
return Array.from(values).sort((a, b) => a - b).join(',');
}
export function toSafeNumber(value: unknown): number | null {
if (typeof value === 'number' && Number.isFinite(value)) return value;
return null;
}
export function toIntMmsi(value: unknown): number | null {
const n = toSafeNumber(value);
if (n == null) return null;
return Math.trunc(n);
}
export function isFiniteNumber(x: unknown): x is number {
return typeof x === 'number' && Number.isFinite(x);
}
export const toNumberArray = (values: unknown): number[] => {
if (values == null) return [];
if (Array.isArray(values)) {
return values as unknown as number[];
}
if (typeof values === 'number' && Number.isFinite(values)) {
return [values];
}
if (typeof values === 'string') {
const value = toSafeNumber(Number(values));
return value == null ? [] : [value];
}
if (typeof values === 'object') {
if (typeof (values as { [Symbol.iterator]?: unknown })?.[Symbol.iterator] === 'function') {
try {
return Array.from(values as Iterable<unknown>) as number[];
} catch {
return [];
}
}
}
return [];
};
export const makeUniqueSorted = (values: unknown) => {
const maybeArray = toNumberArray(values);
const normalized = Array.isArray(maybeArray) ? maybeArray : [];
const unique = Array.from(new Set(normalized.filter((value) => Number.isFinite(value))));
unique.sort((a, b) => a - b);
return unique;
};
export const equalNumberArrays = (a: number[], b: number[]) => {
if (a.length !== b.length) return false;
for (let i = 0; i < a.length; i += 1) {
if (a[i] !== b[i]) return false;
}
return true;
};

파일 보기

@ -0,0 +1,117 @@
import type { AisTarget } from '../../../entities/aisTarget/model/types';
import type { LegacyVesselInfo } from '../../../entities/legacyVessel/model/types';
import { rgbToHex } from '../../../shared/lib/map/palette';
import {
ANCHOR_SPEED_THRESHOLD_KN,
LEGACY_CODE_COLORS,
MAP_SELECTED_SHIP_RGB,
MAP_HIGHLIGHT_SHIP_RGB,
MAP_DEFAULT_SHIP_RGB,
} from '../constants';
import { isFiniteNumber } from './setUtils';
import { normalizeAngleDeg } from './geometry';
export function toValidBearingDeg(value: unknown): number | null {
if (typeof value !== 'number' || !Number.isFinite(value)) return null;
if (value === 511) return null;
if (value < 0) return null;
if (value >= 360) return null;
return value;
}
export function isAnchoredShip({
sog,
cog,
heading,
}: {
sog: number | null | undefined;
cog: number | null | undefined;
heading: number | null | undefined;
}): boolean {
if (!isFiniteNumber(sog)) return true;
if (sog <= ANCHOR_SPEED_THRESHOLD_KN) return true;
return toValidBearingDeg(cog) == null && toValidBearingDeg(heading) == null;
}
export function getDisplayHeading({
cog,
heading,
offset = 0,
}: {
cog: number | null | undefined;
heading: number | null | undefined;
offset?: number;
}) {
const raw = toValidBearingDeg(cog) ?? toValidBearingDeg(heading) ?? 0;
return normalizeAngleDeg(raw, offset);
}
export function lightenColor(rgb: [number, number, number], ratio = 0.32) {
const out = rgb.map((v) => Math.round(v + (255 - v) * ratio) as number) as [number, number, number];
return out;
}
export function getGlobeBaseShipColor({
legacy,
sog,
}: {
legacy: string | null;
sog: number | null;
}) {
if (legacy) {
const rgb = LEGACY_CODE_COLORS[legacy];
if (rgb) return rgbToHex(lightenColor(rgb, 0.38));
}
if (!isFiniteNumber(sog)) return 'rgba(100,116,139,0.55)';
if (sog >= 10) return 'rgba(148,163,184,0.78)';
if (sog >= 1) return 'rgba(100,116,139,0.74)';
return 'rgba(71,85,105,0.68)';
}
export function getShipColor(
t: AisTarget,
selectedMmsi: number | null,
legacyShipCode: string | null,
highlightedMmsis: Set<number>,
): [number, number, number, number] {
if (selectedMmsi && t.mmsi === selectedMmsi) {
return [MAP_SELECTED_SHIP_RGB[0], MAP_SELECTED_SHIP_RGB[1], MAP_SELECTED_SHIP_RGB[2], 255];
}
if (highlightedMmsis.has(t.mmsi)) {
return [MAP_HIGHLIGHT_SHIP_RGB[0], MAP_HIGHLIGHT_SHIP_RGB[1], MAP_HIGHLIGHT_SHIP_RGB[2], 235];
}
if (legacyShipCode) {
const rgb = LEGACY_CODE_COLORS[legacyShipCode];
if (rgb) return [rgb[0], rgb[1], rgb[2], 235];
return [245, 158, 11, 235];
}
if (!isFiniteNumber(t.sog)) return [MAP_DEFAULT_SHIP_RGB[0], MAP_DEFAULT_SHIP_RGB[1], MAP_DEFAULT_SHIP_RGB[2], 130];
if (t.sog >= 10) return [148, 163, 184, 185];
if (t.sog >= 1) return [MAP_DEFAULT_SHIP_RGB[0], MAP_DEFAULT_SHIP_RGB[1], MAP_DEFAULT_SHIP_RGB[2], 175];
return [71, 85, 105, 165];
}
export function buildGlobeShipFeature(
t: AisTarget,
legacy: LegacyVesselInfo | undefined,
selectedMmsi: number | null,
highlightedMmsis: Set<number>,
offset: number,
) {
const isSelected = selectedMmsi != null && t.mmsi === selectedMmsi ? 1 : 0;
const isHighlighted = highlightedMmsis.has(t.mmsi) ? 1 : 0;
const anchored = isAnchoredShip(t);
return {
mmsi: t.mmsi,
heading: getDisplayHeading({ cog: t.cog, heading: t.heading, offset }),
anchored,
color: getGlobeBaseShipColor({ legacy: legacy?.shipCode ?? null, sog: t.sog ?? null }),
selected: isSelected,
highlighted: isHighlighted,
permitted: legacy ? 1 : 0,
labelName: (t.name || '').trim() || legacy?.shipNameCn || legacy?.shipNameRoman || '',
legacyTag: legacy ? `${legacy.permitNo} (${legacy.shipCode})` : '',
};
}

파일 보기

@ -0,0 +1,170 @@
import type { AisTarget } from '../../../entities/aisTarget/model/types';
import type { LegacyVesselInfo } from '../../../entities/legacyVessel/model/types';
import { fmtIsoFull } from '../../../shared/lib/datetime';
import { isFiniteNumber, toSafeNumber } from './setUtils';
export function formatNm(value: number | null | undefined) {
if (!isFiniteNumber(value)) return '-';
return `${value.toFixed(2)} NM`;
}
export function getLegacyTag(legacyHits: Map<number, LegacyVesselInfo> | null | undefined, mmsi: number) {
const legacy = legacyHits?.get(mmsi);
if (!legacy) return null;
return `${legacy.permitNo} (${legacy.shipCode})`;
}
export function getTargetName(
mmsi: number,
targetByMmsi: Map<number, AisTarget>,
legacyHits: Map<number, LegacyVesselInfo> | null | undefined,
) {
const legacy = legacyHits?.get(mmsi);
const target = targetByMmsi.get(mmsi);
return (
(target?.name || '').trim() || legacy?.shipNameCn || legacy?.shipNameRoman || `MMSI ${mmsi}`
);
}
export function getShipTooltipHtml({
mmsi,
targetByMmsi,
legacyHits,
}: {
mmsi: number;
targetByMmsi: Map<number, AisTarget>;
legacyHits: Map<number, LegacyVesselInfo> | null | undefined;
}) {
const legacy = legacyHits?.get(mmsi);
const t = targetByMmsi.get(mmsi);
const name = getTargetName(mmsi, targetByMmsi, legacyHits);
const sog = isFiniteNumber(t?.sog) ? t.sog : null;
const cog = isFiniteNumber(t?.cog) ? t.cog : null;
const msg = t?.messageTimestamp ?? null;
const vesselType = t?.vesselType || '';
const legacyHtml = legacy
? `<div style="margin-top: 6px; padding-top: 6px; border-top: 1px solid rgba(255,255,255,.08)">
<div><b>CN Permit</b> · <b>${legacy.shipCode}</b> · ${legacy.permitNo}</div>
<div>유효범위: ${legacy.workSeaArea || '-'}</div>
</div>`
: '';
return {
html: `<div style="font-family: system-ui; font-size: 12px; white-space: nowrap;">
<div style="font-weight: 700; margin-bottom: 4px;">${name}</div>
<div>MMSI: <b>${mmsi}</b>${vesselType ? ` · ${vesselType}` : ''}</div>
<div>SOG: <b>${sog ?? '?'}</b> kt · COG: <b>${cog ?? '?'}</b>°</div>
${msg ? `<div style="opacity:.7; font-size: 11px; margin-top: 4px;">${fmtIsoFull(msg)}</div>` : ''}
${legacyHtml}
</div>`,
};
}
export function getPairLinkTooltipHtml({
warn,
distanceNm,
aMmsi,
bMmsi,
legacyHits,
targetByMmsi,
}: {
warn: boolean;
distanceNm: number | null | undefined;
aMmsi: number;
bMmsi: number;
legacyHits: Map<number, LegacyVesselInfo> | null | undefined;
targetByMmsi: Map<number, AisTarget>;
}) {
const d = formatNm(distanceNm);
const a = getTargetName(aMmsi, targetByMmsi, legacyHits);
const b = getTargetName(bMmsi, targetByMmsi, legacyHits);
const aTag = getLegacyTag(legacyHits, aMmsi);
const bTag = getLegacyTag(legacyHits, bMmsi);
return {
html: `<div style="font-family: system-ui; font-size: 12px;">
<div style="font-weight: 700; margin-bottom: 4px;"> </div>
<div>${aTag ?? `MMSI ${aMmsi}`}</div>
<div style="opacity:.85;"> ${bTag ?? `MMSI ${bMmsi}`}</div>
<div style="margin-top: 4px;">: <b>${d}</b> · : <b>${warn ? '주의' : '정상'}</b></div>
<div style="opacity:.6; margin-top: 3px;">${a} / ${b}</div>
</div>`,
};
}
export function getFcLinkTooltipHtml({
suspicious,
distanceNm,
fcMmsi,
otherMmsi,
legacyHits,
targetByMmsi,
}: {
suspicious: boolean;
distanceNm: number | null | undefined;
fcMmsi: number;
otherMmsi: number;
legacyHits: Map<number, LegacyVesselInfo> | null | undefined;
targetByMmsi: Map<number, AisTarget>;
}) {
const d = formatNm(distanceNm);
const a = getTargetName(fcMmsi, targetByMmsi, legacyHits);
const b = getTargetName(otherMmsi, targetByMmsi, legacyHits);
const aTag = getLegacyTag(legacyHits, fcMmsi);
const bTag = getLegacyTag(legacyHits, otherMmsi);
return {
html: `<div style="font-family: system-ui; font-size: 12px;">
<div style="font-weight: 700; margin-bottom: 4px;"> </div>
<div>${aTag ?? `MMSI ${fcMmsi}`}</div>
<div style="opacity:.85;"> ${bTag ?? `MMSI ${otherMmsi}`}</div>
<div style="margin-top: 4px;">: <b>${d}</b> · : <b>${suspicious ? '의심' : '일반'}</b></div>
<div style="opacity:.6; margin-top: 3px;">${a} / ${b}</div>
</div>`,
};
}
export function getRangeTooltipHtml({
warn,
distanceNm,
aMmsi,
bMmsi,
legacyHits,
}: {
warn: boolean;
distanceNm: number | null | undefined;
aMmsi: number;
bMmsi: number;
legacyHits: Map<number, LegacyVesselInfo> | null | undefined;
}) {
const d = formatNm(distanceNm);
const aTag = getLegacyTag(legacyHits, aMmsi);
const bTag = getLegacyTag(legacyHits, bMmsi);
const radiusNm = toSafeNumber(distanceNm);
return {
html: `<div style="font-family: system-ui; font-size: 12px;">
<div style="font-weight: 700; margin-bottom: 4px;"> </div>
<div>${aTag ?? `MMSI ${aMmsi}`}</div>
<div style="opacity:.85;"> ${bTag ?? `MMSI ${bMmsi}`}</div>
<div style="margin-top: 4px;">: <b>${d}</b> · : <b>${formatNm(radiusNm == null ? null : radiusNm / 2)}</b> · : <b>${warn ? '주의' : '정상'}</b></div>
</div>`,
};
}
export function getFleetCircleTooltipHtml({
ownerKey,
ownerLabel,
count,
}: {
ownerKey: string;
ownerLabel?: string;
count: number;
}) {
const displayOwner = ownerLabel && ownerLabel.trim() ? ownerLabel : ownerKey;
return {
html: `<div style="font-family: system-ui; font-size: 12px;">
<div style="font-weight: 700; margin-bottom: 4px;"> </div>
<div>소유주: ${displayOwner || '-'}</div>
<div> : <b>${count}</b></div>
</div>`,
};
}

파일 보기

@ -0,0 +1,40 @@
import type { ZoneId } from '../../../entities/zone/model/meta';
import { ZONE_META } from '../../../entities/zone/model/meta';
function toTextValue(value: unknown): string {
if (value == null) return '';
return String(value).trim();
}
export function getZoneIdFromProps(props: Record<string, unknown> | null | undefined): string {
const safeProps = props || {};
const candidates = [
'zoneId',
'zone_id',
'zoneIdNo',
'zoneKey',
'zoneCode',
'ZONE_ID',
'ZONECODE',
'id',
];
for (const key of candidates) {
const value = toTextValue(safeProps[key]);
if (value) return value;
}
return '';
}
export function getZoneDisplayNameFromProps(props: Record<string, unknown> | null | undefined): string {
const safeProps = props || {};
const nameCandidates = ['zoneName', 'zoneLabel', 'NAME', 'name', 'ZONE_NM', 'label'];
for (const key of nameCandidates) {
const name = toTextValue(safeProps[key]);
if (name) return name;
}
const zoneId = getZoneIdFromProps(safeProps);
if (!zoneId) return '수역';
return ZONE_META[(zoneId as ZoneId)]?.name || `수역 ${zoneId}`;
}

파일 보기

@ -0,0 +1,89 @@
import type { AisTarget } from '../../entities/aisTarget/model/types';
import type { LegacyVesselInfo } from '../../entities/legacyVessel/model/types';
import type { SubcableGeoJson } from '../../entities/subcable/model/types';
import type { ZonesGeoJson } from '../../entities/zone/api/useZones';
import type { MapToggleState } from '../../features/mapToggles/MapToggles';
import type { FcLink, FleetCircle, PairLink } from '../../features/legacyDashboard/model/types';
import type { MapStyleSettings } from '../../features/mapSettings/types';
export type Map3DSettings = {
showSeamark: boolean;
showShips: boolean;
showDensity: boolean;
};
export type BaseMapId = 'enhanced' | 'legacy';
export type MapProjectionId = 'mercator' | 'globe';
export interface MapViewState {
center: [number, number]; // [lon, lat]
zoom: number;
bearing: number;
pitch: number;
}
export interface Map3DProps {
targets: AisTarget[];
zones: ZonesGeoJson | null;
selectedMmsi: number | null;
hoveredMmsiSet?: number[];
hoveredFleetMmsiSet?: number[];
hoveredPairMmsiSet?: number[];
hoveredFleetOwnerKey?: string | null;
highlightedMmsiSet?: number[];
settings: Map3DSettings;
baseMap: BaseMapId;
projection: MapProjectionId;
overlays: MapToggleState;
onSelectMmsi: (mmsi: number | null) => void;
onToggleHighlightMmsi?: (mmsi: number) => void;
onViewBboxChange?: (bbox: [number, number, number, number]) => void;
legacyHits?: Map<number, LegacyVesselInfo> | null;
pairLinks?: PairLink[];
fcLinks?: FcLink[];
fleetCircles?: FleetCircle[];
onProjectionLoadingChange?: (loading: boolean) => void;
fleetFocus?: {
id: string | number;
center: [number, number];
zoom?: number;
};
onHoverFleet?: (ownerKey: string | null, fleetMmsiSet: number[]) => void;
onClearFleetHover?: () => void;
onHoverMmsi?: (mmsiList: number[]) => void;
onClearMmsiHover?: () => void;
onHoverPair?: (mmsiList: number[]) => void;
onClearPairHover?: () => void;
subcableGeo?: SubcableGeoJson | null;
hoveredCableId?: string | null;
onHoverCable?: (cableId: string | null) => void;
onClickCable?: (cableId: string | null) => void;
mapStyleSettings?: MapStyleSettings;
initialView?: MapViewState | null;
onViewStateChange?: (view: MapViewState) => void;
onGlobeShipsReady?: (ready: boolean) => void;
}
export type DashSeg = {
from: [number, number];
to: [number, number];
suspicious: boolean;
distanceNm?: number;
fromMmsi?: number;
toMmsi?: number;
};
export type PairRangeCircle = {
center: [number, number]; // [lon, lat]
radiusNm: number;
warn: boolean;
aMmsi: number;
bMmsi: number;
distanceNm: number;
};
export type BathyZoomRange = {
id: string;
mercator: [number, number];
globe: [number, number];
};

파일 보기

@ -0,0 +1,107 @@
import type { SubcableDetail } from '../../entities/subcable/model/types';
interface Props {
detail: SubcableDetail;
color?: string;
onClose: () => void;
}
export function SubcableInfoPanel({ detail, color, onClose }: Props) {
const landingCount = detail.landing_points.length;
const countries = [...new Set(detail.landing_points.map((lp) => lp.country).filter(Boolean))];
return (
<div className="map-info" style={{ maxWidth: 340 }}>
<button className="close-btn" onClick={onClose} aria-label="close">
</button>
<div style={{ marginBottom: 8 }}>
<div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
{color && (
<div
style={{
width: 12,
height: 12,
borderRadius: 3,
backgroundColor: color,
flexShrink: 0,
}}
/>
)}
<div style={{ fontSize: 16, fontWeight: 900, color: 'var(--accent)' }}>{detail.name}</div>
</div>
<div style={{ fontSize: 10, color: 'var(--muted)', marginTop: 2 }}>
Submarine Cable{detail.is_planned ? ' (Planned)' : ''}
</div>
</div>
<div className="ir">
<span className="il"></span>
<span className="iv">{detail.length || '-'}</span>
</div>
<div className="ir">
<span className="il"></span>
<span className="iv">{detail.rfs || '-'}</span>
</div>
{detail.owners && (
<div className="ir" style={{ alignItems: 'flex-start' }}>
<span className="il"></span>
<span className="iv" style={{ wordBreak: 'break-word' }}>
{detail.owners}
</span>
</div>
)}
{detail.suppliers && (
<div className="ir">
<span className="il"></span>
<span className="iv">{detail.suppliers}</span>
</div>
)}
{landingCount > 0 && (
<div style={{ marginTop: 8 }}>
<div style={{ fontSize: 10, fontWeight: 700, color: 'var(--muted)', marginBottom: 4 }}>
Landing Points ({landingCount}) · {countries.length} countries
</div>
<div
style={{
maxHeight: 140,
overflowY: 'auto',
fontSize: 10,
lineHeight: 1.6,
color: 'var(--text)',
}}
>
{detail.landing_points.map((lp) => (
<div key={lp.id}>
<span style={{ color: 'var(--muted)' }}>{lp.country}</span>{' '}
<b>{lp.name}</b>
{lp.is_tbd && <span style={{ color: '#F59E0B', marginLeft: 4 }}>TBD</span>}
</div>
))}
</div>
</div>
)}
{detail.notes && (
<div style={{ marginTop: 8, fontSize: 10, color: 'var(--muted)', fontStyle: 'italic' }}>
{detail.notes}
</div>
)}
{detail.url && (
<div style={{ marginTop: 8 }}>
<a
href={detail.url}
target="_blank"
rel="noopener noreferrer"
style={{ fontSize: 10, color: 'var(--accent)' }}
>
Official website
</a>
</div>
)}
</div>
);
}

파일 보기

@ -9,9 +9,11 @@ type Props = {
clock: string;
adminMode?: boolean;
onLogoClick?: () => void;
userName?: string;
onLogout?: () => void;
};
export function Topbar({ total, fishing, transit, pairLinks, alarms, pollingStatus, lastFetchMinutes, clock, adminMode, onLogoClick }: Props) {
export function Topbar({ total, fishing, transit, pairLinks, alarms, pollingStatus, lastFetchMinutes, clock, adminMode, onLogoClick, userName, onLogout }: Props) {
const statusColor =
pollingStatus === "ready" ? "#22C55E" : pollingStatus === "loading" ? "#F59E0B" : pollingStatus === "error" ? "#EF4444" : "var(--muted)";
return (
@ -47,6 +49,16 @@ export function Topbar({ total, fishing, transit, pairLinks, alarms, pollingStat
</div>
</div>
<div className="time">{clock}</div>
{userName && (
<div className="topbar-user">
<span className="topbar-user__name">{userName}</span>
{onLogout && (
<button className="topbar-user__logout" onClick={onLogout}>
</button>
)}
</div>
)}
</div>
);
}

37
package-lock.json generated
파일 보기

@ -33,9 +33,11 @@
"@deck.gl/core": "^9.2.7",
"@deck.gl/layers": "^9.2.7",
"@deck.gl/mapbox": "^9.2.7",
"@react-oauth/google": "^0.13.4",
"maplibre-gl": "^5.18.0",
"react": "^19.2.0",
"react-dom": "^19.2.0"
"react-dom": "^19.2.0",
"react-router": "^7.13.0"
},
"devDependencies": {
"@eslint/js": "^9.39.1",
@ -1575,6 +1577,16 @@
"integrity": "sha512-EI413MkWKBDVNIfLdqbeNSJTs7ToBz/KVGkwi3D+dQrSIkRI2IYbWGAU3xX+D6+CI4ls8ehxMhNpUVMaZggDvQ==",
"license": "MIT"
},
"node_modules/@react-oauth/google": {
"version": "0.13.4",
"resolved": "https://registry.npmjs.org/@react-oauth/google/-/google-0.13.4.tgz",
"integrity": "sha512-hGKyNEH+/PK8M0sFEuo3MAEk0txtHpgs94tDQit+s2LXg7b6z53NtzHfqDvoB2X8O6lGB+FRg80hY//X6hfD+w==",
"license": "MIT",
"peerDependencies": {
"react": ">=16.8.0",
"react-dom": ">=16.8.0"
}
},
"node_modules/@rolldown/pluginutils": {
"version": "1.0.0-rc.3",
"resolved": "https://registry.npmjs.org/@rolldown/pluginutils/-/pluginutils-1.0.0-rc.3.tgz",
@ -4030,6 +4042,7 @@
"resolved": "https://registry.npmjs.org/react-dom/-/react-dom-19.2.4.tgz",
"integrity": "sha512-AXJdLo8kgMbimY95O2aKQqsz2iWi9jMgKJhRBAxECE4IFxfcazB2LmzloIoibJI3C12IlY20+KFaLv+71bUJeQ==",
"license": "MIT",
"peer": true,
"dependencies": {
"scheduler": "^0.27.0"
},
@ -4047,6 +4060,28 @@
"node": ">=0.10.0"
}
},
"node_modules/react-router": {
"version": "7.13.0",
"resolved": "https://registry.npmjs.org/react-router/-/react-router-7.13.0.tgz",
"integrity": "sha512-PZgus8ETambRT17BUm/LL8lX3Of+oiLaPuVTRH3l1eLvSPpKO3AvhAEb5N7ihAFZQrYDqkvvWfFh9p0z9VsjLw==",
"license": "MIT",
"dependencies": {
"cookie": "^1.0.1",
"set-cookie-parser": "^2.6.0"
},
"engines": {
"node": ">=20.0.0"
},
"peerDependencies": {
"react": ">=18",
"react-dom": ">=18"
},
"peerDependenciesMeta": {
"react-dom": {
"optional": true
}
}
},
"node_modules/real-require": {
"version": "0.2.0",
"resolved": "https://registry.npmjs.org/real-require/-/real-require-0.2.0.tgz",

파일 보기

@ -10,7 +10,8 @@
"build:web": "npm -w @wing/web run build",
"build:api": "npm -w @wing/api run build",
"lint": "npm -w @wing/web run lint",
"prepare:data": "node scripts/prepare-zones.mjs && node scripts/prepare-legacy.mjs"
"prepare:data": "node scripts/prepare-zones.mjs && node scripts/prepare-legacy.mjs",
"prepare:subcables": "node scripts/prepare-subcables.mjs"
},
"devDependencies": {
"xlsx": "^0.18.5"

파일 보기

@ -0,0 +1,176 @@
import fs from "node:fs/promises";
import path from "node:path";
import { fileURLToPath } from "node:url";
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const OUT_DIR = path.resolve(__dirname, "..", "apps", "web", "public", "data", "subcables");
const GEO_URL = "https://www.submarinecablemap.com/api/v3/cable/cable-geo.json";
const DETAILS_URL_BASE = "https://www.submarinecablemap.com/api/v3/cable/";
const CONCURRENCY = Math.max(1, Math.min(24, Number(process.env.CONCURRENCY || 12)));
const TIMEOUT_MS = Math.max(5_000, Math.min(60_000, Number(process.env.TIMEOUT_MS || 20_000)));
function sleep(ms) {
return new Promise((resolve) => setTimeout(resolve, ms));
}
async function fetchText(url, { timeoutMs = TIMEOUT_MS } = {}) {
const controller = new AbortController();
const timeout = setTimeout(() => controller.abort(), timeoutMs);
try {
const res = await fetch(url, {
signal: controller.signal,
headers: {
accept: "application/json",
},
});
const text = await res.text();
const contentType = res.headers.get("content-type") || "";
if (!res.ok) {
throw new Error(`HTTP ${res.status} (${res.statusText})`);
}
return { text, contentType };
} finally {
clearTimeout(timeout);
}
}
async function fetchJson(url) {
const { text, contentType } = await fetchText(url);
if (!contentType.toLowerCase().includes("application/json")) {
const snippet = text.slice(0, 200).replace(/\s+/g, " ").trim();
throw new Error(`Unexpected content-type (${contentType || "unknown"}): ${snippet || "<empty>"}`);
}
try {
return JSON.parse(text);
} catch (e) {
throw new Error(`Invalid JSON: ${e instanceof Error ? e.message : String(e)}`);
}
}
async function fetchJsonWithRetry(url, attempts = 2) {
let lastErr = null;
for (let i = 0; i < attempts; i += 1) {
try {
return await fetchJson(url);
} catch (e) {
lastErr = e;
if (i < attempts - 1) {
await sleep(250 * (i + 1));
}
}
}
throw lastErr;
}
function pickCableDetails(raw) {
const obj = raw && typeof raw === "object" ? raw : {};
const landingPoints = Array.isArray(obj.landing_points) ? obj.landing_points : [];
return {
id: String(obj.id || ""),
name: String(obj.name || ""),
length: obj.length == null ? null : String(obj.length),
rfs: obj.rfs == null ? null : String(obj.rfs),
rfs_year: typeof obj.rfs_year === "number" ? obj.rfs_year : null,
is_planned: Boolean(obj.is_planned),
owners: obj.owners == null ? null : String(obj.owners),
suppliers: obj.suppliers == null ? null : String(obj.suppliers),
landing_points: landingPoints.map((lp) => {
const p = lp && typeof lp === "object" ? lp : {};
return {
id: String(p.id || ""),
name: String(p.name || ""),
country: String(p.country || ""),
is_tbd: p.is_tbd === true,
};
}),
notes: obj.notes == null ? null : String(obj.notes),
url: obj.url == null ? null : String(obj.url),
};
}
async function main() {
await fs.mkdir(OUT_DIR, { recursive: true });
console.log(`[subcables] fetching geojson: ${GEO_URL}`);
const geo = await fetchJsonWithRetry(GEO_URL, 3);
const geoPath = path.join(OUT_DIR, "cable-geo.json");
await fs.writeFile(geoPath, JSON.stringify(geo));
const features = Array.isArray(geo?.features) ? geo.features : [];
const ids = Array.from(
new Set(
features
.map((f) => f?.properties?.id)
.filter((v) => typeof v === "string" && v.trim().length > 0)
.map((v) => v.trim()),
),
).sort();
console.log(`[subcables] cables: ${ids.length} (concurrency=${CONCURRENCY}, timeoutMs=${TIMEOUT_MS})`);
const byId = {};
const failures = [];
let cursor = 0;
let completed = 0;
const startedAt = Date.now();
const worker = async () => {
for (;;) {
const idx = cursor;
cursor += 1;
if (idx >= ids.length) return;
const id = ids[idx];
const url = new URL(`${id}.json`, DETAILS_URL_BASE).toString();
try {
const raw = await fetchJsonWithRetry(url, 2);
const picked = pickCableDetails(raw);
if (!picked.id) {
throw new Error("Missing id in details response");
}
byId[id] = picked;
} catch (e) {
failures.push({ id, error: e instanceof Error ? e.message : String(e) });
} finally {
completed += 1;
if (completed % 25 === 0 || completed === ids.length) {
const sec = Math.max(1, Math.round((Date.now() - startedAt) / 1000));
const rate = (completed / sec).toFixed(1);
console.log(`[subcables] ${completed}/${ids.length} (${rate}/s)`);
}
}
}
};
await Promise.all(Array.from({ length: CONCURRENCY }, () => worker()));
const detailsOut = {
version: 1,
generated_at: new Date().toISOString(),
by_id: byId,
};
const detailsPath = path.join(OUT_DIR, "cable-details.min.json");
await fs.writeFile(detailsPath, JSON.stringify(detailsOut));
if (failures.length > 0) {
console.error(`[subcables] failures: ${failures.length}`);
for (const f of failures.slice(0, 30)) {
console.error(`- ${f.id}: ${f.error}`);
}
if (failures.length > 30) {
console.error(`- ... +${failures.length - 30} more`);
}
process.exitCode = 1;
}
console.log(`[subcables] wrote: ${geoPath}`);
console.log(`[subcables] wrote: ${detailsPath}`);
}
main().catch((e) => {
console.error(`[subcables] fatal: ${e instanceof Error ? e.stack || e.message : String(e)}`);
process.exitCode = 1;
});