@file-viewer/renderer-geo 2.1.11 → 2.1.13

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.en.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # @file-viewer/renderer-geo
2
2
 
3
- Standalone geospatial renderer package for Flyfish File Viewer. It previews GeoJSON, KML, GPX, and Shapefile data in the browser while keeping `@tmcw/togeojson` and `shpjs` lazy-loaded for geospatial files only.
3
+ Standalone geospatial renderer package for Flyfish File Viewer. It previews GeoJSON, KML, GPX, and Shapefile data in the browser while keeping `@tmcw/togeojson`, `shpjs`, `maplibre-gl`, and `proj4` lazy-loaded for geospatial files only.
4
4
 
5
5
  ## Usage
6
6
 
@@ -29,9 +29,67 @@ const options = {
29
29
  - Reads GeoJSON `FeatureCollection`, `Feature`, and standalone geometry objects.
30
30
  - Loads `@tmcw/togeojson` only for KML / GPX and normalizes them into the shared GeoJSON pipeline.
31
31
  - Loads `shpjs` only for SHP / Shapefile previews, including common ZIP or binary Shapefile payloads.
32
- - Does not depend on online map tiles. The default output is an offline SVG vector map, which is suitable for intranet deployment and attachment review.
32
+ - Uses an offline MapLibre empty style to render point, line, and polygon overlays with pan, zoom, and fit-to-bounds controls. Public, intranet, or fully self-hosted basemap tiles can be enabled explicitly.
33
+ - Supports GeoJSON `crs` metadata, explicit `options.geo.projection`, Web Mercator inference, and conversion from `EPSG:4326`, `EPSG:3857`, `EPSG:4490`, `GCJ02`, `BD09`, or proj4 strings to WGS84.
34
+ - Falls back to an SVG vector preview when WebGL or MapLibre initialization is unavailable.
33
35
  - Cleans up DOM resources on unmount and remains compatible with core lifecycle, HTML export, and zoom orchestration.
34
36
 
37
+ ## Projection Options
38
+
39
+ ```ts
40
+ const options = {
41
+ renderers: [geoRenderer],
42
+ geo: {
43
+ projection: 'EPSG:3857',
44
+ inferProjection: true,
45
+ fitPadding: 48,
46
+ },
47
+ }
48
+ ```
49
+
50
+ Standard GeoJSON is read as WGS84 by default. If an export omits `crs` but contains Web Mercator coordinates, the renderer infers EPSG:3857 by default. For non-EPSG systems such as GCJ-02 or BD-09, pass `options.geo.projection` explicitly.
51
+
52
+ ## Basemap and Tile Options
53
+
54
+ The geo renderer does not access public networks by default. When a real basemap is needed, pass a public MapLibre style, a self-hosted style, or a simple raster XYZ/TMS tile template:
55
+
56
+ ```ts
57
+ const options = {
58
+ renderers: [geoRenderer],
59
+ geo: {
60
+ // International open-source basemap, good for demos or light online usage.
61
+ // Production systems should self-host or mirror it when needed.
62
+ basemap: 'openfreemap-liberty',
63
+ },
64
+ }
65
+ ```
66
+
67
+ ```ts
68
+ const options = {
69
+ renderers: [geoRenderer],
70
+ geo: {
71
+ // Simple raster tile entry. It can point to public tiles, an intranet gateway,
72
+ // object storage, or a local static tile directory.
73
+ tileUrl: '/tiles/world/{z}/{x}/{y}.png',
74
+ },
75
+ }
76
+ ```
77
+
78
+ ```ts
79
+ const options = {
80
+ renderers: [geoRenderer],
81
+ geo: {
82
+ basemap: {
83
+ type: 'vector-style',
84
+ label: 'Intranet OpenMapTiles',
85
+ styleUrl: '/maps/styles/liberty/style.json',
86
+ },
87
+ },
88
+ }
89
+ ```
90
+
91
+ Built-in presets include `openfreemap-liberty`, `openfreemap-bright`, `openfreemap-positron`, `openfreemap-dark`, `openfreemap-fiord`, and explicit opt-in `osm-raster`. Use `osm-raster` only for demos or low-volume traffic; production deployments should follow the official OpenStreetMap tile policy, keep the URL replaceable, cache correctly, and show attribution. For China mainland production deployments, prefer self-hosting or mirroring the OpenFreeMap / OpenMapTiles stack to an intranet or domestic CDN, then connect it through `styleUrl` or `tileUrl`.
92
+
35
93
  ## Migration Note
36
94
 
37
95
  `@file-viewer/core` no longer bundles the geo renderer and no longer installs `@tmcw/togeojson` or `shpjs` by default. Install this renderer explicitly, or use `@file-viewer/preset-all`, when GeoJSON / KML / GPX / SHP preview is required.
package/README.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # @file-viewer/renderer-geo
2
2
 
3
- Flyfish File Viewer 的独立地理数据 renderer 包。它负责 GeoJSON、KML、GPX 和 Shapefile 的浏览器端预览,并让 `@tmcw/togeojson`、`shpjs` 只在命中地理数据格式时加载。
3
+ Flyfish File Viewer 的独立地理数据 renderer 包。它负责 GeoJSON、KML、GPX 和 Shapefile 的浏览器端预览,并让 `@tmcw/togeojson`、`shpjs`、`maplibre-gl`、`proj4` 只在命中地理数据格式时加载。
4
4
 
5
5
  ## 使用
6
6
 
@@ -29,9 +29,65 @@ const options = {
29
29
  - GeoJSON 直接读取 `FeatureCollection`、`Feature` 或单个 geometry。
30
30
  - KML / GPX 只在命中格式时按需加载 `@tmcw/togeojson`,转换为统一 GeoJSON 管线。
31
31
  - SHP / Shapefile 只在命中格式时按需加载 `shpjs`,支持常见 ZIP 或二进制 Shapefile 数据转 GeoJSON。
32
- - 渲染层不依赖在线地图瓦片,默认输出离线 SVG 矢量预览,适合内网部署和附件快速审阅。
32
+ - 默认使用离线 MapLibre 空底图渲染点、线、面叠加层,支持平移、缩放和适配范围;显式配置后可叠加公网、内网或离线自托管瓦片底图。
33
+ - 支持 GeoJSON `crs` 元数据、`options.geo.projection` 显式坐标系、Web Mercator 自动推断,以及 `EPSG:4326`、`EPSG:3857`、`EPSG:4490`、`GCJ02`、`BD09` 和 proj4 字符串转换到 WGS84。
34
+ - WebGL 或 MapLibre 初始化失败时自动回退 SVG 矢量预览,适合内网部署和附件快速审阅。
33
35
  - 卸载时清理 DOM 资源,和 core 的生命周期、导出 HTML、缩放能力保持一致。
34
36
 
37
+ ## 坐标系选项
38
+
39
+ ```ts
40
+ const options = {
41
+ renderers: [geoRenderer],
42
+ geo: {
43
+ projection: 'EPSG:3857',
44
+ inferProjection: true,
45
+ fitPadding: 48,
46
+ },
47
+ }
48
+ ```
49
+
50
+ 标准 GeoJSON 默认按 WGS84 读取。如果业务导出没有写 `crs`,但坐标是 Web Mercator,默认会自动推断;GCJ-02 / BD-09 这类非 EPSG 坐标建议通过 `options.geo.projection` 显式声明。
51
+
52
+ ## 底图和瓦片选项
53
+
54
+ Geo renderer 默认不访问公网。需要真实底图时,可以选择公开 MapLibre style、自托管 style,或简单 raster XYZ/TMS 瓦片模板:
55
+
56
+ ```ts
57
+ const options = {
58
+ renderers: [geoRenderer],
59
+ geo: {
60
+ // 国际化开源底图,适合 demo 或轻量在线场景;生产建议按需自托管或镜像到内网/国内 CDN。
61
+ basemap: 'openfreemap-liberty',
62
+ },
63
+ }
64
+ ```
65
+
66
+ ```ts
67
+ const options = {
68
+ renderers: [geoRenderer],
69
+ geo: {
70
+ // 最简单的 raster 瓦片入口,可指向公网、内网网关、对象存储或本地静态目录。
71
+ tileUrl: '/tiles/world/{z}/{x}/{y}.png',
72
+ },
73
+ }
74
+ ```
75
+
76
+ ```ts
77
+ const options = {
78
+ renderers: [geoRenderer],
79
+ geo: {
80
+ basemap: {
81
+ type: 'vector-style',
82
+ label: 'Intranet OpenMapTiles',
83
+ styleUrl: '/maps/styles/liberty/style.json',
84
+ },
85
+ },
86
+ }
87
+ ```
88
+
89
+ 内置 preset 包含 `openfreemap-liberty`、`openfreemap-bright`、`openfreemap-positron`、`openfreemap-dark`、`openfreemap-fiord` 和显式 opt-in 的 `osm-raster`。`osm-raster` 只建议用于 demo 或低频访问,生产环境请遵守 OpenStreetMap 官方 tile policy,配置可替换 URL、缓存和正确 attribution。中国大陆生产环境更推荐用 OpenFreeMap / OpenMapTiles 栈自托管到内网或国内 CDN,再通过 `styleUrl` 或 `tileUrl` 接入。
90
+
35
91
  ## 迁移说明
36
92
 
37
93
  `@file-viewer/core` 已不再内置 geo renderer,也不会默认安装 `@tmcw/togeojson` 和 `shpjs`。需要 GeoJSON / KML / GPX / SHP 预览时,请显式安装本包,或直接使用 `@file-viewer/preset-all` 聚合能力。
package/dist/geo.d.ts CHANGED
@@ -1,2 +1,59 @@
1
- import { type FileRenderContext, type FileViewerRenderedInstance } from '@file-viewer/core';
1
+ import { createFileViewerTranslator, type FileRenderContext, type FileViewerGeoOptions, type FileViewerRenderedInstance } from '@file-viewer/core';
2
+ type Position = [number, number, ...number[]];
3
+ type Geometry = {
4
+ type: 'Point';
5
+ coordinates: Position;
6
+ } | {
7
+ type: 'MultiPoint';
8
+ coordinates: Position[];
9
+ } | {
10
+ type: 'LineString';
11
+ coordinates: Position[];
12
+ } | {
13
+ type: 'MultiLineString';
14
+ coordinates: Position[][];
15
+ } | {
16
+ type: 'Polygon';
17
+ coordinates: Position[][];
18
+ } | {
19
+ type: 'MultiPolygon';
20
+ coordinates: Position[][][];
21
+ } | {
22
+ type: 'GeometryCollection';
23
+ geometries: Geometry[];
24
+ };
25
+ interface Feature {
26
+ type: 'Feature';
27
+ geometry: Geometry | null;
28
+ properties?: Record<string, unknown>;
29
+ id?: string | number;
30
+ }
31
+ interface FeatureCollection {
32
+ type: 'FeatureCollection';
33
+ features: Feature[];
34
+ }
35
+ interface Bounds {
36
+ minX: number;
37
+ minY: number;
38
+ maxX: number;
39
+ maxY: number;
40
+ }
41
+ interface ParseGeoResult {
42
+ collection: FeatureCollection;
43
+ bounds: Bounds | null;
44
+ sourceProjection: string;
45
+ displayProjection: string;
46
+ }
47
+ type FileViewerTranslator = ReturnType<typeof createFileViewerTranslator>;
48
+ type MapLibreStyleLike = string | Record<string, unknown>;
49
+ type GeoBasemapKind = 'offline' | 'raster' | 'vector-style';
50
+ interface ResolvedGeoBasemapConfig {
51
+ kind: GeoBasemapKind;
52
+ label: string;
53
+ style: MapLibreStyleLike;
54
+ attributionControl: boolean;
55
+ }
56
+ export declare const parseFileViewerGeoData: (buffer: ArrayBuffer, type: string | undefined, options: FileViewerGeoOptions | undefined, t: FileViewerTranslator) => Promise<ParseGeoResult>;
57
+ export declare const resolveFileViewerGeoBasemapConfig: (options: FileViewerGeoOptions | undefined, t: FileViewerTranslator) => ResolvedGeoBasemapConfig;
2
58
  export default function renderGeo(buffer: ArrayBuffer, target: HTMLDivElement, type?: string, context?: FileRenderContext): Promise<FileViewerRenderedInstance>;
59
+ export {};
package/dist/geo.js CHANGED
@@ -1,23 +1,60 @@
1
- import { createFileViewerTranslator, readFileViewerText, } from '@file-viewer/core';
1
+ import { createFileViewerTranslator, createFileViewerZoomChangeEmitter, readFileViewerText, registerFileViewerZoomProvider, unregisterFileViewerZoomProvider, } from '@file-viewer/core';
2
2
  const SVG_NS = 'http://www.w3.org/2000/svg';
3
3
  const GEO_WIDTH = 960;
4
4
  const GEO_HEIGHT = 620;
5
5
  const GEO_PADDING = 36;
6
+ const WEB_MERCATOR_LIMIT = 20037508.342789244;
7
+ const DEFAULT_FIT_PADDING = 44;
8
+ const MIN_MAP_ZOOM = 0;
9
+ const MAX_MAP_ZOOM = 22;
10
+ const OPENFREEMAP_STYLE_BASE = 'https://tiles.openfreemap.org/styles/';
11
+ const OSM_RASTER_TILE_URL = 'https://tile.openstreetmap.org/{z}/{x}/{y}.png';
12
+ const OSM_ATTRIBUTION = '&copy; OpenStreetMap contributors';
13
+ const OPENFREEMAP_STYLE_PRESETS = {
14
+ openfreemap: { style: 'liberty', label: 'OpenFreeMap Liberty' },
15
+ 'openfreemap-liberty': { style: 'liberty', label: 'OpenFreeMap Liberty' },
16
+ 'openfreemap-bright': { style: 'bright', label: 'OpenFreeMap Bright' },
17
+ 'openfreemap-positron': { style: 'positron', label: 'OpenFreeMap Positron' },
18
+ 'openfreemap-dark': { style: 'dark', label: 'OpenFreeMap Dark' },
19
+ 'openfreemap-fiord': { style: 'fiord', label: 'OpenFreeMap Fiord' },
20
+ };
6
21
  const geoStyle = `
7
- .geo-viewer{min-height:100%;display:grid;grid-template-columns:minmax(240px,320px) minmax(0,1fr);background:#eef1f4;color:#132235}
8
- .geo-panel{padding:24px;border-right:1px solid rgba(15,23,42,.08);background:#fff;box-sizing:border-box}
9
- .geo-panel>span{color:#0f766e;font-size:12px;font-weight:800}.geo-panel h2{margin:8px 0 22px;font-size:24px}
10
- .geo-panel dl{display:grid;gap:12px;margin:0}.geo-panel dt,.geo-counts strong{color:#64748b;font-size:12px;font-weight:700}.geo-panel dd{margin:4px 0 0;word-break:break-all;font-size:14px}
22
+ .geo-viewer{min-height:540px;height:100%;display:grid;grid-template-columns:minmax(250px,330px) minmax(0,1fr);background:#eef2f5;color:#132235}
23
+ .geo-viewer *{box-sizing:border-box}
24
+ .geo-panel{padding:22px;border-right:1px solid rgba(15,23,42,.08);background:#fff;overflow:auto}
25
+ .geo-panel>span{display:inline-flex;align-items:center;min-height:22px;border-radius:6px;padding:0 8px;background:rgba(15,118,110,.1);color:#0f766e;font-size:12px;font-weight:800}
26
+ .geo-panel h2{margin:10px 0 20px;font-size:22px;line-height:1.2;letter-spacing:0}
27
+ .geo-panel dl{display:grid;gap:12px;margin:0}.geo-panel dt,.geo-counts strong{color:#64748b;font-size:12px;font-weight:700}.geo-panel dd{margin:4px 0 0;word-break:break-word;font-size:14px;line-height:1.45}
11
28
  .geo-counts{margin-top:24px}.geo-counts p{margin:8px 0 0;font-size:14px}
12
- .geo-map{padding:28px;overflow:auto}.geo-map svg{display:block;width:min(100%,1200px);min-width:640px;height:auto;margin:0 auto;overflow:visible}
13
- .geo-map rect{fill:#f8fafc;stroke:rgba(15,23,42,.08)}
14
- .geo-map path{fill:none;stroke:#0f766e;stroke-width:2.2;vector-effect:non-scaling-stroke}.geo-map .geo-polygon{fill:rgba(45,212,191,.18)}
15
- .geo-map circle{fill:#2563eb;stroke:#fff;stroke-width:1.5;vector-effect:non-scaling-stroke}
29
+ .geo-stage{display:flex;min-width:0;min-height:0;flex-direction:column}
30
+ .geo-toolbar{min-height:46px;display:flex;align-items:center;justify-content:flex-end;gap:8px;padding:8px 12px;border-bottom:1px solid rgba(15,23,42,.08);background:rgba(255,255,255,.86)}
31
+ .geo-toolbar button{min-width:86px;min-height:30px;border:0;border-radius:8px;padding:0 10px;background:#0f766e;color:#fff;cursor:pointer;font-size:12px;font-weight:800;letter-spacing:0}
32
+ .geo-toolbar button:hover{background:#0d625c}
33
+ .geo-map-frame{position:relative;flex:1;min-height:460px;overflow:hidden;background:#f8fafc}
34
+ .geo-map-engine,.geo-map-svg{position:absolute;inset:0}
35
+ .geo-map-svg{padding:28px;overflow:auto}.geo-map-svg svg{display:block;width:min(100%,1200px);min-width:640px;height:auto;margin:0 auto;overflow:visible}
36
+ .geo-map-svg rect{fill:#f8fafc;stroke:rgba(15,23,42,.08)}
37
+ .geo-map-svg path{fill:none;stroke:#0f766e;stroke-width:2.2;vector-effect:non-scaling-stroke}.geo-map-svg .geo-polygon{fill:rgba(45,212,191,.18)}
38
+ .geo-map-svg circle{fill:#2563eb;stroke:#fff;stroke-width:1.5;vector-effect:non-scaling-stroke}
16
39
  .geo-state{display:flex;align-items:center;justify-content:center;min-height:280px;border-radius:8px;background:rgba(255,255,255,.82);color:#64748b}
17
40
  .geo-state.error{color:#b42318}
18
- .file-viewer[data-viewer-theme='dark'] .geo-viewer{background:#101820;color:#e5edf6}.file-viewer[data-viewer-theme='dark'] .geo-panel{background:#111827;border-color:rgba(148,163,184,.18)}.file-viewer[data-viewer-theme='dark'] .geo-panel dt,.file-viewer[data-viewer-theme='dark'] .geo-counts strong{color:#94a3b8}.file-viewer[data-viewer-theme='dark'] .geo-map rect{fill:#111827;stroke:rgba(148,163,184,.18)}
19
- @media (prefers-color-scheme:dark){.file-viewer[data-viewer-theme='system'] .geo-viewer{background:#101820;color:#e5edf6}.file-viewer[data-viewer-theme='system'] .geo-panel{background:#111827;border-color:rgba(148,163,184,.18)}.file-viewer[data-viewer-theme='system'] .geo-panel dt,.file-viewer[data-viewer-theme='system'] .geo-counts strong{color:#94a3b8}.file-viewer[data-viewer-theme='system'] .geo-map rect{fill:#111827;stroke:rgba(148,163,184,.18)}}
20
- @media (max-width:860px){.geo-viewer{grid-template-columns:1fr}.geo-panel{border-right:0;border-bottom:1px solid rgba(15,23,42,.08)}}
41
+ .geo-viewer .maplibregl-map{position:relative;width:100%;height:100%;overflow:hidden;font:inherit}
42
+ .geo-viewer .maplibregl-canvas{position:absolute;left:0;top:0;outline:none}
43
+ .geo-viewer .maplibregl-control-container{position:absolute;inset:0;pointer-events:none}
44
+ .geo-viewer .maplibregl-ctrl-top-right{position:absolute;top:12px;right:12px;display:flex;flex-direction:column;gap:8px;pointer-events:auto}
45
+ .geo-viewer .maplibregl-ctrl{display:flex;overflow:hidden;border:1px solid rgba(15,23,42,.12);border-radius:8px;background:#fff;box-shadow:0 10px 24px rgba(15,23,42,.12)}
46
+ .geo-viewer .maplibregl-ctrl button{display:block;width:30px;height:30px;border:0;border-bottom:1px solid rgba(15,23,42,.08);background:#fff;color:#132235;cursor:pointer;font-size:0}
47
+ .geo-viewer .maplibregl-ctrl button:last-child{border-bottom:0}.geo-viewer .maplibregl-ctrl button:hover{background:#f1f5f9}
48
+ .geo-viewer .maplibregl-ctrl-icon.maplibregl-ctrl-zoom-in::before{content:'+';font-size:18px;font-weight:800}.geo-viewer .maplibregl-ctrl-icon.maplibregl-ctrl-zoom-out::before{content:'-';font-size:20px;font-weight:800}
49
+ .geo-viewer .maplibregl-ctrl-compass{display:none!important}
50
+ .geo-viewer .maplibregl-ctrl-bottom-right{position:absolute;right:8px;bottom:8px;pointer-events:auto}
51
+ .geo-viewer .maplibregl-ctrl-attrib{display:block;max-width:min(460px,calc(100vw - 40px));border-radius:6px;padding:3px 7px;background:rgba(255,255,255,.9);box-shadow:0 8px 20px rgba(15,23,42,.12);color:#334155;font-size:11px;line-height:1.45}
52
+ .geo-viewer .maplibregl-ctrl-attrib a{color:#0f766e;text-decoration:none}.geo-viewer .maplibregl-ctrl-attrib-button{display:none}
53
+ .file-viewer[data-viewer-theme='dark'] .geo-viewer{background:#101820;color:#e5edf6}.file-viewer[data-viewer-theme='dark'] .geo-panel{background:#111827;border-color:rgba(148,163,184,.18)}.file-viewer[data-viewer-theme='dark'] .geo-panel dt,.file-viewer[data-viewer-theme='dark'] .geo-counts strong{color:#94a3b8}.file-viewer[data-viewer-theme='dark'] .geo-toolbar{background:rgba(17,24,39,.9);border-color:rgba(148,163,184,.18)}.file-viewer[data-viewer-theme='dark'] .geo-map-frame,.file-viewer[data-viewer-theme='dark'] .geo-map-svg rect{background:#111827;fill:#111827;stroke:rgba(148,163,184,.18)}
54
+ .file-viewer[data-viewer-theme='dark'] .geo-viewer .maplibregl-ctrl-attrib{background:rgba(15,23,42,.9);color:#cbd5e1}.file-viewer[data-viewer-theme='dark'] .geo-viewer .maplibregl-ctrl-attrib a{color:#5eead4}
55
+ @media (prefers-color-scheme:dark){.file-viewer[data-viewer-theme='system'] .geo-viewer{background:#101820;color:#e5edf6}.file-viewer[data-viewer-theme='system'] .geo-panel{background:#111827;border-color:rgba(148,163,184,.18)}.file-viewer[data-viewer-theme='system'] .geo-panel dt,.file-viewer[data-viewer-theme='system'] .geo-counts strong{color:#94a3b8}.file-viewer[data-viewer-theme='system'] .geo-toolbar{background:rgba(17,24,39,.9);border-color:rgba(148,163,184,.18)}.file-viewer[data-viewer-theme='system'] .geo-map-frame,.file-viewer[data-viewer-theme='system'] .geo-map-svg rect{background:#111827;fill:#111827;stroke:rgba(148,163,184,.18)}}
56
+ @media (prefers-color-scheme:dark){.file-viewer[data-viewer-theme='system'] .geo-viewer .maplibregl-ctrl-attrib{background:rgba(15,23,42,.9);color:#cbd5e1}.file-viewer[data-viewer-theme='system'] .geo-viewer .maplibregl-ctrl-attrib a{color:#5eead4}}
57
+ @media (max-width:860px){.geo-viewer{grid-template-columns:1fr}.geo-panel{max-height:230px;border-right:0;border-bottom:1px solid rgba(15,23,42,.08)}.geo-map-frame{min-height:430px}}
21
58
  `;
22
59
  const createStyle = () => {
23
60
  const style = document.createElement('style');
@@ -27,15 +64,64 @@ const createStyle = () => {
27
64
  const createSvgElement = (tag) => {
28
65
  return document.createElementNS(SVG_NS, tag);
29
66
  };
67
+ const createElement = (tagName, className, text) => {
68
+ const element = document.createElement(tagName);
69
+ if (className) {
70
+ element.className = className;
71
+ }
72
+ if (text !== undefined) {
73
+ element.textContent = text;
74
+ }
75
+ return element;
76
+ };
77
+ const isRecord = (value) => {
78
+ return !!value && typeof value === 'object' && !Array.isArray(value);
79
+ };
80
+ const normalizeError = (reason) => {
81
+ if (reason instanceof Error) {
82
+ return reason.message;
83
+ }
84
+ if (typeof reason === 'string') {
85
+ return reason;
86
+ }
87
+ try {
88
+ return JSON.stringify(reason);
89
+ }
90
+ catch {
91
+ return String(reason);
92
+ }
93
+ };
94
+ const normalizeGeoType = (type) => {
95
+ const normalized = (type || 'geojson').trim().toLowerCase();
96
+ if (normalized === 'json') {
97
+ return 'geojson';
98
+ }
99
+ if (normalized === 'shapefile' || normalized === 'shape') {
100
+ return 'shp';
101
+ }
102
+ return normalized;
103
+ };
104
+ const geometryTypes = new Set([
105
+ 'Point',
106
+ 'MultiPoint',
107
+ 'LineString',
108
+ 'MultiLineString',
109
+ 'Polygon',
110
+ 'MultiPolygon',
111
+ 'GeometryCollection',
112
+ ]);
30
113
  const normalizeGeoJson = (value, t) => {
31
114
  const candidate = value;
32
115
  if ((candidate === null || candidate === void 0 ? void 0 : candidate.type) === 'FeatureCollection' && Array.isArray(candidate.features)) {
33
- return candidate;
116
+ return {
117
+ type: 'FeatureCollection',
118
+ features: candidate.features,
119
+ };
34
120
  }
35
121
  if ((candidate === null || candidate === void 0 ? void 0 : candidate.type) === 'Feature') {
36
122
  return { type: 'FeatureCollection', features: [candidate] };
37
123
  }
38
- if ((candidate === null || candidate === void 0 ? void 0 : candidate.type) && candidate.coordinates) {
124
+ if ((candidate === null || candidate === void 0 ? void 0 : candidate.type) && geometryTypes.has(candidate.type)) {
39
125
  return {
40
126
  type: 'FeatureCollection',
41
127
  features: [{ type: 'Feature', geometry: candidate, properties: {} }],
@@ -43,6 +129,30 @@ const normalizeGeoJson = (value, t) => {
43
129
  }
44
130
  throw new Error(t('geo.error.unrecognized'));
45
131
  };
132
+ const normalizeShapefileOutput = (value, t) => {
133
+ if (Array.isArray(value)) {
134
+ return {
135
+ type: 'FeatureCollection',
136
+ features: value.flatMap(item => normalizeShapefileOutput(item, t).features),
137
+ };
138
+ }
139
+ if (isRecord(value) && value.type !== 'FeatureCollection' && !value.geometry && !value.coordinates) {
140
+ const nestedCollections = Object.values(value)
141
+ .filter(item => isRecord(item) || Array.isArray(item))
142
+ .flatMap(item => {
143
+ try {
144
+ return normalizeShapefileOutput(item, t).features;
145
+ }
146
+ catch {
147
+ return [];
148
+ }
149
+ });
150
+ if (nestedCollections.length) {
151
+ return { type: 'FeatureCollection', features: nestedCollections };
152
+ }
153
+ }
154
+ return normalizeGeoJson(value, t);
155
+ };
46
156
  const parseXml = (text, t) => {
47
157
  const doc = new DOMParser().parseFromString(text, 'application/xml');
48
158
  const error = doc.querySelector('parsererror');
@@ -51,28 +161,40 @@ const parseXml = (text, t) => {
51
161
  }
52
162
  return doc;
53
163
  };
54
- const normalizeGeoType = (type) => {
55
- const normalized = (type || 'geojson').trim().toLowerCase();
56
- if (normalized === 'json') {
57
- return 'geojson';
164
+ const extractCrsName = (value) => {
165
+ if (!isRecord(value)) {
166
+ return undefined;
58
167
  }
59
- if (normalized === 'shapefile') {
60
- return 'shp';
168
+ const crs = value.crs;
169
+ if (!isRecord(crs)) {
170
+ return undefined;
61
171
  }
62
- return normalized;
172
+ const properties = crs.properties;
173
+ const name = isRecord(properties) ? properties.name : undefined;
174
+ return typeof name === 'string' ? name : undefined;
63
175
  };
64
176
  const parseGeo = async (buffer, type, t) => {
65
177
  if (type === 'geojson') {
66
- return normalizeGeoJson(JSON.parse(await readFileViewerText(buffer)), t);
178
+ const raw = JSON.parse(await readFileViewerText(buffer));
179
+ return {
180
+ collection: normalizeGeoJson(raw, t),
181
+ declaredProjection: extractCrsName(raw),
182
+ };
67
183
  }
68
184
  if (type === 'kml' || type === 'gpx') {
69
185
  const toGeoJSON = await import('@tmcw/togeojson');
70
186
  const doc = parseXml(await readFileViewerText(buffer), t);
71
- return normalizeGeoJson(type === 'kml' ? toGeoJSON.kml(doc) : toGeoJSON.gpx(doc), t);
187
+ return {
188
+ collection: normalizeGeoJson(type === 'kml' ? toGeoJSON.kml(doc) : toGeoJSON.gpx(doc), t),
189
+ declaredProjection: 'EPSG:4326',
190
+ };
72
191
  }
73
192
  if (type === 'shp') {
74
193
  const { default: shp } = await import('shpjs');
75
- return normalizeGeoJson(await shp(buffer), t);
194
+ return {
195
+ collection: normalizeShapefileOutput(await shp(buffer), t),
196
+ declaredProjection: 'EPSG:4326',
197
+ };
76
198
  }
77
199
  throw new Error(t('geo.error.unsupported', { type }));
78
200
  };
@@ -122,6 +244,199 @@ const collectBounds = (features) => {
122
244
  }
123
245
  return { minX, minY, maxX, maxY };
124
246
  };
247
+ const isWgs84Projection = (projection) => {
248
+ return ['EPSG:4326', 'CRS:84', 'WGS84', 'WGS 84'].includes(projection.toUpperCase());
249
+ };
250
+ const normalizeProjectionAlias = (value) => {
251
+ const raw = value === null || value === void 0 ? void 0 : value.trim();
252
+ if (!raw) {
253
+ return undefined;
254
+ }
255
+ const upper = raw.toUpperCase();
256
+ const epsgMatch = upper.match(/EPSG(?::|::|\/)(\d+)/);
257
+ if (epsgMatch) {
258
+ return `EPSG:${epsgMatch[1]}`;
259
+ }
260
+ if (upper.includes('CRS84') || upper === 'CRS:84' || upper.includes('WGS84') || upper.includes('WGS 84')) {
261
+ return 'EPSG:4326';
262
+ }
263
+ if (upper.includes('WEBMERCATOR') || upper.includes('WEB_MERCATOR') || upper.includes('900913') || upper.includes('102100')) {
264
+ return 'EPSG:3857';
265
+ }
266
+ if (upper.includes('CGCS2000') || upper === 'CGCS' || upper === 'EPSG:4490') {
267
+ return 'EPSG:4490';
268
+ }
269
+ if (upper.includes('GCJ')) {
270
+ return 'GCJ02';
271
+ }
272
+ if (upper.includes('BD09') || upper.includes('BD-09') || upper.includes('BAIDU')) {
273
+ return 'BD09';
274
+ }
275
+ return raw;
276
+ };
277
+ const inferProjectionFromBounds = (bounds, options) => {
278
+ if (!bounds || (options === null || options === void 0 ? void 0 : options.inferProjection) === false) {
279
+ return undefined;
280
+ }
281
+ const maxAbsX = Math.max(Math.abs(bounds.minX), Math.abs(bounds.maxX));
282
+ const maxAbsY = Math.max(Math.abs(bounds.minY), Math.abs(bounds.maxY));
283
+ if ((maxAbsX > 180 || maxAbsY > 90) &&
284
+ maxAbsX <= WEB_MERCATOR_LIMIT * 1.05 &&
285
+ maxAbsY <= WEB_MERCATOR_LIMIT * 1.05) {
286
+ return 'EPSG:3857';
287
+ }
288
+ return undefined;
289
+ };
290
+ const registerCommonProj4Defs = (proj4) => {
291
+ proj4.defs('EPSG:4490', '+proj=longlat +ellps=GRS80 +no_defs +type=crs');
292
+ proj4.defs('CGCS2000', '+proj=longlat +ellps=GRS80 +no_defs +type=crs');
293
+ };
294
+ const transformLat = (lng, lat) => {
295
+ let ret = -100 + 2 * lng + 3 * lat + 0.2 * lat * lat + 0.1 * lng * lat + 0.2 * Math.sqrt(Math.abs(lng));
296
+ ret += ((20 * Math.sin(6 * lng * Math.PI) + 20 * Math.sin(2 * lng * Math.PI)) * 2) / 3;
297
+ ret += ((20 * Math.sin(lat * Math.PI) + 40 * Math.sin((lat / 3) * Math.PI)) * 2) / 3;
298
+ ret += ((160 * Math.sin((lat / 12) * Math.PI) + 320 * Math.sin((lat * Math.PI) / 30)) * 2) / 3;
299
+ return ret;
300
+ };
301
+ const transformLng = (lng, lat) => {
302
+ let ret = 300 + lng + 2 * lat + 0.1 * lng * lng + 0.1 * lng * lat + 0.1 * Math.sqrt(Math.abs(lng));
303
+ ret += ((20 * Math.sin(6 * lng * Math.PI) + 20 * Math.sin(2 * lng * Math.PI)) * 2) / 3;
304
+ ret += ((20 * Math.sin(lng * Math.PI) + 40 * Math.sin((lng / 3) * Math.PI)) * 2) / 3;
305
+ ret += ((150 * Math.sin((lng / 12) * Math.PI) + 300 * Math.sin((lng / 30) * Math.PI)) * 2) / 3;
306
+ return ret;
307
+ };
308
+ const outOfChina = (lng, lat) => {
309
+ return lng < 72.004 || lng > 137.8347 || lat < 0.8293 || lat > 55.8271;
310
+ };
311
+ const wgs84ToGcj02 = (lng, lat) => {
312
+ if (outOfChina(lng, lat)) {
313
+ return [lng, lat];
314
+ }
315
+ const a = 6378245;
316
+ const ee = 0.006693421622965943;
317
+ let dLat = transformLat(lng - 105, lat - 35);
318
+ let dLng = transformLng(lng - 105, lat - 35);
319
+ const radLat = (lat / 180) * Math.PI;
320
+ let magic = Math.sin(radLat);
321
+ magic = 1 - ee * magic * magic;
322
+ const sqrtMagic = Math.sqrt(magic);
323
+ dLat = (dLat * 180) / (((a * (1 - ee)) / (magic * sqrtMagic)) * Math.PI);
324
+ dLng = (dLng * 180) / ((a / sqrtMagic) * Math.cos(radLat) * Math.PI);
325
+ return [lng + dLng, lat + dLat];
326
+ };
327
+ const gcj02ToWgs84 = (lng, lat) => {
328
+ if (outOfChina(lng, lat)) {
329
+ return [lng, lat];
330
+ }
331
+ const [gcjLng, gcjLat] = wgs84ToGcj02(lng, lat);
332
+ return [lng * 2 - gcjLng, lat * 2 - gcjLat];
333
+ };
334
+ const bd09ToGcj02 = (lng, lat) => {
335
+ const x = lng - 0.0065;
336
+ const y = lat - 0.006;
337
+ const z = Math.sqrt(x * x + y * y) - 0.00002 * Math.sin(y * Math.PI * 3000 / 180);
338
+ const theta = Math.atan2(y, x) - 0.000003 * Math.cos(x * Math.PI * 3000 / 180);
339
+ return [z * Math.cos(theta), z * Math.sin(theta)];
340
+ };
341
+ const createProjectionTransformer = async (projection, t) => {
342
+ const normalized = normalizeProjectionAlias(projection) || 'EPSG:4326';
343
+ if (isWgs84Projection(normalized)) {
344
+ return position => position;
345
+ }
346
+ if (normalized === 'GCJ02') {
347
+ return position => {
348
+ const [lng, lat] = gcj02ToWgs84(position[0], position[1]);
349
+ return [lng, lat, ...position.slice(2)];
350
+ };
351
+ }
352
+ if (normalized === 'BD09') {
353
+ return position => {
354
+ const [gcjLng, gcjLat] = bd09ToGcj02(position[0], position[1]);
355
+ const [lng, lat] = gcj02ToWgs84(gcjLng, gcjLat);
356
+ return [lng, lat, ...position.slice(2)];
357
+ };
358
+ }
359
+ try {
360
+ const module = await import('proj4');
361
+ const proj4 = module.default || module;
362
+ registerCommonProj4Defs(proj4);
363
+ return position => {
364
+ const [lng, lat] = proj4(normalized, 'EPSG:4326', [position[0], position[1]]);
365
+ return [lng, lat, ...position.slice(2)];
366
+ };
367
+ }
368
+ catch (error) {
369
+ throw new Error(t('geo.error.projection', { reason: normalizeError(error) }));
370
+ }
371
+ };
372
+ const transformGeometry = (geometry, transform) => {
373
+ if (!geometry) {
374
+ return null;
375
+ }
376
+ switch (geometry.type) {
377
+ case 'Point':
378
+ return { type: 'Point', coordinates: transform(geometry.coordinates) };
379
+ case 'MultiPoint':
380
+ return { type: 'MultiPoint', coordinates: geometry.coordinates.map(transform) };
381
+ case 'LineString':
382
+ return { type: 'LineString', coordinates: geometry.coordinates.map(transform) };
383
+ case 'MultiLineString':
384
+ return { type: 'MultiLineString', coordinates: geometry.coordinates.map(line => line.map(transform)) };
385
+ case 'Polygon':
386
+ return { type: 'Polygon', coordinates: geometry.coordinates.map(line => line.map(transform)) };
387
+ case 'MultiPolygon':
388
+ return {
389
+ type: 'MultiPolygon',
390
+ coordinates: geometry.coordinates.map(polygon => polygon.map(line => line.map(transform))),
391
+ };
392
+ case 'GeometryCollection':
393
+ return { type: 'GeometryCollection', geometries: geometry.geometries.map(item => transformGeometry(item, transform)) };
394
+ }
395
+ };
396
+ const validatePositionBounds = (bounds, t) => {
397
+ if (!bounds) {
398
+ return;
399
+ }
400
+ if (!Number.isFinite(bounds.minX) ||
401
+ !Number.isFinite(bounds.minY) ||
402
+ !Number.isFinite(bounds.maxX) ||
403
+ !Number.isFinite(bounds.maxY) ||
404
+ bounds.minY < -90.000001 ||
405
+ bounds.maxY > 90.000001) {
406
+ throw new Error(t('geo.error.projection', { reason: 'coordinates are outside WGS84 longitude/latitude bounds' }));
407
+ }
408
+ };
409
+ const resolveSourceProjection = (collection, declaredProjection, options) => {
410
+ const rawBounds = collectBounds(collection.features);
411
+ const projection = normalizeProjectionAlias(options === null || options === void 0 ? void 0 : options.projection) ||
412
+ normalizeProjectionAlias(declaredProjection) ||
413
+ inferProjectionFromBounds(rawBounds, options) ||
414
+ 'EPSG:4326';
415
+ return projection;
416
+ };
417
+ export const parseFileViewerGeoData = async (buffer, type, options, t) => {
418
+ const normalizedType = normalizeGeoType(type);
419
+ const { collection, declaredProjection } = await parseGeo(buffer, normalizedType, t);
420
+ const sourceProjection = resolveSourceProjection(collection, declaredProjection, options);
421
+ const transform = await createProjectionTransformer(sourceProjection, t);
422
+ const transformed = {
423
+ type: 'FeatureCollection',
424
+ features: collection.features.map(feature => ({
425
+ type: 'Feature',
426
+ id: feature.id,
427
+ properties: feature.properties || {},
428
+ geometry: transformGeometry(feature.geometry, transform),
429
+ })),
430
+ };
431
+ const bounds = collectBounds(transformed.features);
432
+ validatePositionBounds(bounds, t);
433
+ return {
434
+ collection: transformed,
435
+ bounds,
436
+ sourceProjection,
437
+ displayProjection: 'EPSG:4326',
438
+ };
439
+ };
125
440
  const projectPosition = (position, bounds) => {
126
441
  if (!bounds) {
127
442
  return [GEO_WIDTH / 2, GEO_HEIGHT / 2];
@@ -195,11 +510,17 @@ const appendGeometry = (parent, geometry, bounds) => {
195
510
  };
196
511
  const buildGeometryCounts = (features) => {
197
512
  const counts = new Map();
198
- features.forEach(feature => {
199
- var _a;
200
- const key = ((_a = feature.geometry) === null || _a === void 0 ? void 0 : _a.type) || 'Null';
201
- counts.set(key, (counts.get(key) || 0) + 1);
202
- });
513
+ const visit = (geometry) => {
514
+ if (!geometry) {
515
+ counts.set('Null', (counts.get('Null') || 0) + 1);
516
+ return;
517
+ }
518
+ counts.set(geometry.type, (counts.get(geometry.type) || 0) + 1);
519
+ if (geometry.type === 'GeometryCollection') {
520
+ geometry.geometries.forEach(visit);
521
+ }
522
+ };
523
+ features.forEach(feature => visit(feature.geometry));
203
524
  return [...counts.entries()];
204
525
  };
205
526
  const formatBounds = (bounds) => {
@@ -208,20 +529,29 @@ const formatBounds = (bounds) => {
208
529
  }
209
530
  return `${bounds.minX.toFixed(5)}, ${bounds.minY.toFixed(5)} -> ${bounds.maxX.toFixed(5)}, ${bounds.maxY.toFixed(5)}`;
210
531
  };
211
- const appendDescriptionItem = (list, label, value) => {
532
+ const appendDescriptionItem = (list, label, value, field) => {
212
533
  const row = document.createElement('div');
213
534
  const term = document.createElement('dt');
214
535
  term.textContent = label;
215
536
  const detail = document.createElement('dd');
216
537
  detail.textContent = String(value);
538
+ if (field) {
539
+ detail.dataset.geoPanelField = field;
540
+ }
217
541
  row.append(term, detail);
218
542
  list.appendChild(row);
219
543
  };
220
- const renderCollection = (collection, type, t) => {
221
- const root = document.createElement('div');
222
- root.className = 'geo-viewer';
223
- const features = collection.features || [];
224
- const bounds = collectBounds(features);
544
+ const updatePanelValue = (root, field, value) => {
545
+ const detail = root.querySelector(`[data-geo-panel-field="${field}"]`);
546
+ if (detail) {
547
+ detail.textContent = value;
548
+ }
549
+ };
550
+ const getFitPadding = (options) => {
551
+ const value = options === null || options === void 0 ? void 0 : options.fitPadding;
552
+ return Number.isFinite(value) ? Math.max(8, Math.min(160, Number(value))) : DEFAULT_FIT_PADDING;
553
+ };
554
+ const buildPanel = (parsed, type, engineLabel, basemapLabel, t) => {
225
555
  const panel = document.createElement('aside');
226
556
  panel.className = 'geo-panel';
227
557
  const badge = document.createElement('span');
@@ -229,21 +559,26 @@ const renderCollection = (collection, type, t) => {
229
559
  const heading = document.createElement('h2');
230
560
  heading.textContent = t('geo.title');
231
561
  const description = document.createElement('dl');
232
- appendDescriptionItem(description, t('geo.featureCount'), features.length);
233
- appendDescriptionItem(description, t('geo.bounds'), formatBounds(bounds));
562
+ appendDescriptionItem(description, t('geo.featureCount'), parsed.collection.features.length);
563
+ appendDescriptionItem(description, t('geo.bounds'), formatBounds(parsed.bounds));
564
+ appendDescriptionItem(description, t('geo.projection'), `${parsed.sourceProjection} -> ${parsed.displayProjection}`);
565
+ appendDescriptionItem(description, t('geo.engine'), engineLabel);
566
+ appendDescriptionItem(description, t('geo.basemap'), basemapLabel, 'basemap');
234
567
  const counts = document.createElement('div');
235
568
  counts.className = 'geo-counts';
236
569
  const countsHeading = document.createElement('strong');
237
570
  countsHeading.textContent = t('geo.geometryTypes');
238
571
  counts.appendChild(countsHeading);
239
- buildGeometryCounts(features).forEach(([name, count]) => {
572
+ buildGeometryCounts(parsed.collection.features).forEach(([name, count]) => {
240
573
  const row = document.createElement('p');
241
574
  row.textContent = `${name}: ${count}`;
242
575
  counts.appendChild(row);
243
576
  });
244
577
  panel.append(badge, heading, description, counts);
245
- const map = document.createElement('main');
246
- map.className = 'geo-map';
578
+ return panel;
579
+ };
580
+ const buildSvgPreview = (parsed, t) => {
581
+ const wrapper = createElement('div', 'geo-map-svg');
247
582
  const svg = createSvgElement('svg');
248
583
  svg.setAttribute('viewBox', `0 0 ${GEO_WIDTH} ${GEO_HEIGHT}`);
249
584
  svg.setAttribute('role', 'img');
@@ -253,23 +588,415 @@ const renderCollection = (collection, type, t) => {
253
588
  rect.setAttribute('height', String(GEO_HEIGHT));
254
589
  rect.setAttribute('rx', '8');
255
590
  const group = createSvgElement('g');
256
- features.forEach(feature => appendGeometry(group, feature.geometry, bounds));
591
+ parsed.collection.features.forEach(feature => appendGeometry(group, feature.geometry, parsed.bounds));
257
592
  svg.append(rect, group);
258
- map.appendChild(svg);
259
- root.append(panel, map);
260
- return root;
593
+ wrapper.appendChild(svg);
594
+ return wrapper;
595
+ };
596
+ const niceStep = (span) => {
597
+ const rough = Math.max(span / 5, 0.0001);
598
+ const exponent = Math.floor(Math.log10(rough));
599
+ const base = rough / Math.pow(10, exponent);
600
+ const factor = base <= 1 ? 1 : base <= 2 ? 2 : base <= 5 ? 5 : 10;
601
+ return factor * Math.pow(10, exponent);
602
+ };
603
+ const createGraticule = (bounds) => {
604
+ if (!bounds) {
605
+ return { type: 'FeatureCollection', features: [] };
606
+ }
607
+ const lngStep = niceStep(Math.max(bounds.maxX - bounds.minX, 0.001));
608
+ const latStep = niceStep(Math.max(bounds.maxY - bounds.minY, 0.001));
609
+ const minLng = Math.max(-180, Math.floor(bounds.minX / lngStep) * lngStep - lngStep);
610
+ const maxLng = Math.min(180, Math.ceil(bounds.maxX / lngStep) * lngStep + lngStep);
611
+ const minLat = Math.max(-85, Math.floor(bounds.minY / latStep) * latStep - latStep);
612
+ const maxLat = Math.min(85, Math.ceil(bounds.maxY / latStep) * latStep + latStep);
613
+ const features = [];
614
+ for (let lng = minLng; lng <= maxLng + lngStep / 2; lng += lngStep) {
615
+ features.push({
616
+ type: 'Feature',
617
+ properties: { kind: 'lng' },
618
+ geometry: { type: 'LineString', coordinates: [[lng, minLat], [lng, maxLat]] },
619
+ });
620
+ }
621
+ for (let lat = minLat; lat <= maxLat + latStep / 2; lat += latStep) {
622
+ features.push({
623
+ type: 'Feature',
624
+ properties: { kind: 'lat' },
625
+ geometry: { type: 'LineString', coordinates: [[minLng, lat], [maxLng, lat]] },
626
+ });
627
+ }
628
+ return { type: 'FeatureCollection', features };
629
+ };
630
+ const createOfflineStyle = () => ({
631
+ version: 8,
632
+ sources: {},
633
+ layers: [{
634
+ id: 'geo-background',
635
+ type: 'background',
636
+ paint: {
637
+ 'background-color': '#f8fafc',
638
+ },
639
+ }],
640
+ });
641
+ const normalizeTileUrls = (tileUrl) => {
642
+ const values = Array.isArray(tileUrl) ? tileUrl : tileUrl ? [tileUrl] : [];
643
+ return values.map(value => value.trim()).filter(Boolean);
644
+ };
645
+ const finiteNumber = (value, fallback, min, max) => {
646
+ const number = Number(value);
647
+ if (!Number.isFinite(number)) {
648
+ return fallback;
649
+ }
650
+ return Math.min(max, Math.max(min, number));
651
+ };
652
+ const createRasterBasemapStyle = (tileUrls, basemap) => {
653
+ const tileSize = Math.round(finiteNumber(basemap === null || basemap === void 0 ? void 0 : basemap.tileSize, 256, 64, 1024));
654
+ const opacity = finiteNumber(basemap === null || basemap === void 0 ? void 0 : basemap.rasterOpacity, 1, 0, 1);
655
+ const source = {
656
+ type: 'raster',
657
+ tiles: tileUrls,
658
+ tileSize,
659
+ };
660
+ if (basemap === null || basemap === void 0 ? void 0 : basemap.attribution) {
661
+ source.attribution = basemap.attribution;
662
+ }
663
+ if (Number.isFinite(basemap === null || basemap === void 0 ? void 0 : basemap.minZoom)) {
664
+ source.minzoom = finiteNumber(basemap === null || basemap === void 0 ? void 0 : basemap.minZoom, 0, 0, MAX_MAP_ZOOM);
665
+ }
666
+ if (Number.isFinite(basemap === null || basemap === void 0 ? void 0 : basemap.maxZoom)) {
667
+ source.maxzoom = finiteNumber(basemap === null || basemap === void 0 ? void 0 : basemap.maxZoom, MAX_MAP_ZOOM, 0, MAX_MAP_ZOOM);
668
+ }
669
+ if ((basemap === null || basemap === void 0 ? void 0 : basemap.scheme) === 'tms') {
670
+ source.scheme = 'tms';
671
+ }
672
+ return {
673
+ version: 8,
674
+ sources: {
675
+ 'geo-basemap-raster': source,
676
+ },
677
+ layers: [
678
+ {
679
+ id: 'geo-background',
680
+ type: 'background',
681
+ paint: {
682
+ 'background-color': '#eef2f5',
683
+ },
684
+ },
685
+ {
686
+ id: 'geo-basemap-raster',
687
+ type: 'raster',
688
+ source: 'geo-basemap-raster',
689
+ paint: {
690
+ 'raster-opacity': opacity,
691
+ 'raster-resampling': 'linear',
692
+ },
693
+ },
694
+ ],
695
+ };
696
+ };
697
+ const createOfflineBasemapConfig = (t) => ({
698
+ kind: 'offline',
699
+ label: t('geo.basemap.offline'),
700
+ style: createOfflineStyle(),
701
+ attributionControl: false,
702
+ });
703
+ const createRasterBasemapConfig = (tileUrls, basemap, label) => ({
704
+ kind: 'raster',
705
+ label,
706
+ style: createRasterBasemapStyle(tileUrls, basemap),
707
+ attributionControl: true,
708
+ });
709
+ export const resolveFileViewerGeoBasemapConfig = (options, t) => {
710
+ var _a;
711
+ const basemap = options === null || options === void 0 ? void 0 : options.basemap;
712
+ if (basemap === false || basemap === 'none' || basemap === 'offline') {
713
+ return createOfflineBasemapConfig(t);
714
+ }
715
+ if (typeof basemap === 'string') {
716
+ const openFreeMapPreset = OPENFREEMAP_STYLE_PRESETS[basemap];
717
+ if (openFreeMapPreset) {
718
+ return {
719
+ kind: 'vector-style',
720
+ label: openFreeMapPreset.label,
721
+ style: `${OPENFREEMAP_STYLE_BASE}${openFreeMapPreset.style}`,
722
+ attributionControl: true,
723
+ };
724
+ }
725
+ if (basemap === 'osm-raster') {
726
+ return createRasterBasemapConfig([OSM_RASTER_TILE_URL], { attribution: OSM_ATTRIBUTION }, 'OpenStreetMap Raster');
727
+ }
728
+ }
729
+ if (isRecord(basemap)) {
730
+ const config = basemap;
731
+ const label = ((_a = config.label) === null || _a === void 0 ? void 0 : _a.trim()) || t('geo.basemap.custom');
732
+ if ((config.type === 'vector-style' || config.styleUrl || config.style) && (config.styleUrl || config.style)) {
733
+ return {
734
+ kind: 'vector-style',
735
+ label,
736
+ style: config.styleUrl || config.style || createOfflineStyle(),
737
+ attributionControl: true,
738
+ };
739
+ }
740
+ const tileUrls = normalizeTileUrls(config.tileUrl);
741
+ if ((config.type === 'raster' || tileUrls.length > 0) && tileUrls.length > 0) {
742
+ return createRasterBasemapConfig(tileUrls, config, label);
743
+ }
744
+ }
745
+ const tileUrls = normalizeTileUrls(options === null || options === void 0 ? void 0 : options.tileUrl);
746
+ if (tileUrls.length > 0) {
747
+ return createRasterBasemapConfig(tileUrls, undefined, t('geo.basemap.custom'));
748
+ }
749
+ return createOfflineBasemapConfig(t);
750
+ };
751
+ const fitMapToBounds = (map, bounds, padding) => {
752
+ if (!bounds) {
753
+ map.jumpTo({ center: [0, 0], zoom: 1 });
754
+ return;
755
+ }
756
+ const samePoint = Math.abs(bounds.maxX - bounds.minX) < 1e-9 && Math.abs(bounds.maxY - bounds.minY) < 1e-9;
757
+ if (samePoint) {
758
+ map.jumpTo({ center: [bounds.minX, bounds.minY], zoom: 13 });
759
+ return;
760
+ }
761
+ map.fitBounds([[bounds.minX, bounds.minY], [bounds.maxX, bounds.maxY]], { padding, duration: 0, maxZoom: 16 });
762
+ };
763
+ const createZoomState = (map, bounds) => {
764
+ const zoom = map.getZoom();
765
+ return {
766
+ scale: zoom,
767
+ label: `z${zoom.toFixed(1)}`,
768
+ canZoomIn: zoom < MAX_MAP_ZOOM,
769
+ canZoomOut: zoom > MIN_MAP_ZOOM,
770
+ canReset: !!bounds,
771
+ minScale: MIN_MAP_ZOOM,
772
+ maxScale: MAX_MAP_ZOOM,
773
+ };
774
+ };
775
+ const waitForMapLoad = (map) => {
776
+ return new Promise((resolve, reject) => {
777
+ const cleanup = () => {
778
+ window.clearTimeout(timeout);
779
+ map.off('load', onLoad);
780
+ map.off('error', onError);
781
+ };
782
+ const onLoad = () => {
783
+ cleanup();
784
+ resolve();
785
+ };
786
+ const onError = (event) => {
787
+ cleanup();
788
+ reject(event.error || new Error('MapLibre failed to load'));
789
+ };
790
+ const timeout = window.setTimeout(() => {
791
+ cleanup();
792
+ reject(new Error('MapLibre load timeout'));
793
+ }, 8000);
794
+ map.once('load', onLoad);
795
+ map.once('error', onError);
796
+ });
797
+ };
798
+ const createMapLibreMap = (maplibre, host, basemap) => {
799
+ return new maplibre.Map({
800
+ container: host,
801
+ style: basemap.style,
802
+ attributionControl: basemap.attributionControl ? { compact: true } : false,
803
+ dragRotate: false,
804
+ pitchWithRotate: false,
805
+ minZoom: MIN_MAP_ZOOM,
806
+ maxZoom: MAX_MAP_ZOOM,
807
+ });
808
+ };
809
+ const mountMapLibre = async (host, root, parsed, options, basemap, t) => {
810
+ var _a;
811
+ const maplibre = await import('maplibre-gl');
812
+ let activeBasemap = basemap;
813
+ let map = createMapLibreMap(maplibre, host, activeBasemap);
814
+ map.addControl(new maplibre.NavigationControl({ showCompass: false, visualizePitch: false }), 'top-right');
815
+ try {
816
+ await waitForMapLoad(map);
817
+ }
818
+ catch (error) {
819
+ if (activeBasemap.kind === 'offline') {
820
+ throw error;
821
+ }
822
+ console.warn('[file-viewer] Geo basemap failed; retrying with the offline empty basemap.', error);
823
+ map.remove();
824
+ host.replaceChildren();
825
+ activeBasemap = createOfflineBasemapConfig(t);
826
+ updatePanelValue(root, 'basemap', activeBasemap.label);
827
+ map = createMapLibreMap(maplibre, host, activeBasemap);
828
+ map.addControl(new maplibre.NavigationControl({ showCompass: false, visualizePitch: false }), 'top-right');
829
+ await waitForMapLoad(map);
830
+ }
831
+ const graticule = createGraticule(parsed.bounds);
832
+ map.addSource('geo-graticule', {
833
+ type: 'geojson',
834
+ data: graticule,
835
+ });
836
+ map.addLayer({
837
+ id: 'geo-graticule-line',
838
+ type: 'line',
839
+ source: 'geo-graticule',
840
+ paint: {
841
+ 'line-color': '#cbd5e1',
842
+ 'line-width': 1,
843
+ 'line-opacity': 0.72,
844
+ },
845
+ });
846
+ map.addSource('geo-data', {
847
+ type: 'geojson',
848
+ data: parsed.collection,
849
+ });
850
+ map.addLayer({
851
+ id: 'geo-fill',
852
+ type: 'fill',
853
+ source: 'geo-data',
854
+ filter: ['==', '$type', 'Polygon'],
855
+ paint: {
856
+ 'fill-color': '#14b8a6',
857
+ 'fill-opacity': 0.24,
858
+ },
859
+ });
860
+ map.addLayer({
861
+ id: 'geo-polygon-outline',
862
+ type: 'line',
863
+ source: 'geo-data',
864
+ filter: ['==', '$type', 'Polygon'],
865
+ paint: {
866
+ 'line-color': '#0f766e',
867
+ 'line-width': 2,
868
+ 'line-opacity': 0.95,
869
+ },
870
+ });
871
+ map.addLayer({
872
+ id: 'geo-line',
873
+ type: 'line',
874
+ source: 'geo-data',
875
+ filter: ['==', '$type', 'LineString'],
876
+ paint: {
877
+ 'line-color': '#2563eb',
878
+ 'line-width': 3,
879
+ 'line-opacity': 0.9,
880
+ },
881
+ });
882
+ map.addLayer({
883
+ id: 'geo-point',
884
+ type: 'circle',
885
+ source: 'geo-data',
886
+ filter: ['==', '$type', 'Point'],
887
+ paint: {
888
+ 'circle-color': '#f97316',
889
+ 'circle-radius': 6,
890
+ 'circle-stroke-color': '#ffffff',
891
+ 'circle-stroke-width': 2,
892
+ },
893
+ });
894
+ const padding = getFitPadding(options);
895
+ const fit = () => {
896
+ fitMapToBounds(map, parsed.bounds, padding);
897
+ };
898
+ fit();
899
+ const zoomEmitter = createFileViewerZoomChangeEmitter();
900
+ map.on('zoomend', zoomEmitter.emit);
901
+ registerFileViewerZoomProvider(root, {
902
+ zoomIn: () => {
903
+ map.zoomTo(Math.min(MAX_MAP_ZOOM, map.getZoom() + 1), { duration: 160 });
904
+ zoomEmitter.emit();
905
+ return createZoomState(map, parsed.bounds);
906
+ },
907
+ zoomOut: () => {
908
+ map.zoomTo(Math.max(MIN_MAP_ZOOM, map.getZoom() - 1), { duration: 160 });
909
+ zoomEmitter.emit();
910
+ return createZoomState(map, parsed.bounds);
911
+ },
912
+ resetZoom: () => {
913
+ fit();
914
+ zoomEmitter.emit();
915
+ return createZoomState(map, parsed.bounds);
916
+ },
917
+ setZoom: scale => {
918
+ map.zoomTo(Math.max(MIN_MAP_ZOOM, Math.min(MAX_MAP_ZOOM, scale)), { duration: 160 });
919
+ zoomEmitter.emit();
920
+ return createZoomState(map, parsed.bounds);
921
+ },
922
+ getState: () => createZoomState(map, parsed.bounds),
923
+ subscribe: zoomEmitter.subscribe,
924
+ });
925
+ const ResizeObserverCtor = (_a = host.ownerDocument.defaultView) === null || _a === void 0 ? void 0 : _a.ResizeObserver;
926
+ const resizeObserver = ResizeObserverCtor
927
+ ? new ResizeObserverCtor(() => {
928
+ map.resize();
929
+ })
930
+ : null;
931
+ resizeObserver === null || resizeObserver === void 0 ? void 0 : resizeObserver.observe(host);
932
+ const fitButton = root.querySelector('[data-geo-action="fit"]');
933
+ fitButton === null || fitButton === void 0 ? void 0 : fitButton.addEventListener('click', fit);
934
+ fitButton === null || fitButton === void 0 ? void 0 : fitButton.setAttribute('title', t('geo.action.fit'));
935
+ return {
936
+ map,
937
+ cleanup() {
938
+ fitButton === null || fitButton === void 0 ? void 0 : fitButton.removeEventListener('click', fit);
939
+ resizeObserver === null || resizeObserver === void 0 ? void 0 : resizeObserver.disconnect();
940
+ unregisterFileViewerZoomProvider(root);
941
+ map.remove();
942
+ },
943
+ };
944
+ };
945
+ const buildMapShell = (parsed, type, engineLabel, basemapLabel, t) => {
946
+ const root = createElement('div', 'geo-viewer');
947
+ const stage = createElement('main', 'geo-stage');
948
+ const toolbar = createElement('div', 'geo-toolbar');
949
+ const fitButton = createElement('button', undefined, t('geo.action.fit'));
950
+ fitButton.dataset.geoAction = 'fit';
951
+ const frame = createElement('div', 'geo-map-frame');
952
+ const mapHost = createElement('div', 'geo-map-engine');
953
+ frame.appendChild(mapHost);
954
+ toolbar.appendChild(fitButton);
955
+ stage.append(toolbar, frame);
956
+ root.append(buildPanel(parsed, type, engineLabel, basemapLabel, t), stage);
957
+ return { root, mapHost, frame };
958
+ };
959
+ const renderMapLibreView = async (parsed, type, options, t) => {
960
+ const basemap = resolveFileViewerGeoBasemapConfig(options, t);
961
+ const shell = buildMapShell(parsed, type, t('geo.engine.maplibre'), basemap.label, t);
962
+ const mounted = await mountMapLibre(shell.mapHost, shell.root, parsed, options, basemap, t);
963
+ return {
964
+ element: shell.root,
965
+ cleanup: mounted.cleanup,
966
+ };
967
+ };
968
+ const renderSvgView = (parsed, type, t) => {
969
+ const shell = buildMapShell(parsed, type, t('geo.engine.svg'), t('geo.basemap.offline'), t);
970
+ shell.frame.replaceChildren(buildSvgPreview(parsed, t));
971
+ return shell.root;
261
972
  };
262
973
  export default async function renderGeo(buffer, target, type, context) {
974
+ var _a;
263
975
  const normalizedType = normalizeGeoType(type);
264
976
  const t = createFileViewerTranslator(context === null || context === void 0 ? void 0 : context.options);
977
+ const options = (_a = context === null || context === void 0 ? void 0 : context.options) === null || _a === void 0 ? void 0 : _a.geo;
265
978
  const style = createStyle();
266
979
  const state = document.createElement('div');
267
980
  state.className = 'geo-state';
268
981
  state.textContent = t('geo.loading');
982
+ let cleanup;
269
983
  target.replaceChildren(style, state);
270
984
  try {
271
- const collection = await parseGeo(buffer, normalizedType, t);
272
- target.replaceChildren(style, renderCollection(collection, normalizedType, t));
985
+ const parsed = await parseFileViewerGeoData(buffer, normalizedType, options, t);
986
+ if ((options === null || options === void 0 ? void 0 : options.preferMapEngine) !== false) {
987
+ try {
988
+ const mapView = await renderMapLibreView(parsed, normalizedType, options, t);
989
+ cleanup = mapView.cleanup;
990
+ target.replaceChildren(style, mapView.element);
991
+ }
992
+ catch (mapError) {
993
+ console.warn('[file-viewer] MapLibre geospatial preview failed; using SVG fallback.', mapError);
994
+ target.replaceChildren(style, renderSvgView(parsed, normalizedType, t));
995
+ }
996
+ }
997
+ else {
998
+ target.replaceChildren(style, renderSvgView(parsed, normalizedType, t));
999
+ }
273
1000
  }
274
1001
  catch (error) {
275
1002
  console.error(error);
@@ -279,6 +1006,7 @@ export default async function renderGeo(buffer, target, type, context) {
279
1006
  return {
280
1007
  $el: target,
281
1008
  unmount() {
1009
+ cleanup === null || cleanup === void 0 ? void 0 : cleanup();
282
1010
  target.replaceChildren();
283
1011
  },
284
1012
  };
package/package.json CHANGED
@@ -1,9 +1,9 @@
1
1
  {
2
2
  "name": "@file-viewer/renderer-geo",
3
- "version": "2.1.11",
3
+ "version": "2.1.13",
4
4
  "private": false,
5
5
  "type": "module",
6
- "description": "Standalone geospatial renderer plugin for Flyfish File Viewer with GeoJSON, KML, GPX, and SHP parsing, SVG map preview, and offline-friendly lazy loading.",
6
+ "description": "Standalone geospatial renderer plugin for Flyfish File Viewer with GeoJSON, KML, GPX, SHP parsing, CRS normalization, MapLibre overlay rendering, SVG fallback, and offline-friendly lazy loading.",
7
7
  "keywords": [
8
8
  "file-viewer",
9
9
  "renderer",
@@ -55,7 +55,7 @@
55
55
  "LICENSE"
56
56
  ],
57
57
  "dependencies": {
58
- "@file-viewer/core": "^2.1.11",
58
+ "@file-viewer/core": "^2.1.13",
59
59
  "@tmcw/togeojson": "^7.1.2",
60
60
  "maplibre-gl": "^5.24.0",
61
61
  "proj4": "^2.20.9",