zenit-sdk 0.0.2 → 0.0.5

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.
@@ -0,0 +1,3258 @@
1
+ // src/react/ZenitMap.tsx
2
+ import React, { useCallback, useEffect, useImperativeHandle, useMemo, useRef, useState, forwardRef } from "react";
3
+ import { GeoJSON, MapContainer, Marker, TileLayer, ZoomControl, useMap } from "react-leaflet";
4
+ import L from "leaflet";
5
+
6
+ // src/maps/helpers.ts
7
+ function toNumber(value) {
8
+ if (typeof value === "number" && Number.isFinite(value)) {
9
+ return value;
10
+ }
11
+ if (typeof value === "string") {
12
+ const parsed = parseFloat(value);
13
+ if (Number.isFinite(parsed)) {
14
+ return parsed;
15
+ }
16
+ }
17
+ return void 0;
18
+ }
19
+ function clampOpacity(value) {
20
+ if (!Number.isFinite(value ?? NaN)) {
21
+ return 1;
22
+ }
23
+ return Math.min(1, Math.max(0, value ?? 1));
24
+ }
25
+ function resolveLayerId(mapLayer) {
26
+ if (mapLayer.layerId !== void 0 && mapLayer.layerId !== null) {
27
+ return mapLayer.layerId;
28
+ }
29
+ const embedded = mapLayer.layer;
30
+ return embedded?.id;
31
+ }
32
+ function extractMapDto(map) {
33
+ if (map && typeof map === "object" && "data" in map) {
34
+ const data = map.data;
35
+ return data ?? null;
36
+ }
37
+ if (map && typeof map === "object") {
38
+ return map;
39
+ }
40
+ return null;
41
+ }
42
+ function normalizeMapCenter(map) {
43
+ const center = map.settings?.center;
44
+ if (Array.isArray(center) && center.length >= 2) {
45
+ const [lon, lat] = center;
46
+ return {
47
+ ...map,
48
+ settings: {
49
+ ...map.settings,
50
+ center: { lon, lat }
51
+ }
52
+ };
53
+ }
54
+ return map;
55
+ }
56
+ function normalizeMapLayers(mapOrResponse) {
57
+ const map = extractMapDto(mapOrResponse);
58
+ if (!map?.mapLayers) {
59
+ return [];
60
+ }
61
+ const normalized = [];
62
+ map.mapLayers.forEach((mapLayer, index) => {
63
+ const layerId = resolveLayerId(mapLayer);
64
+ if (layerId === void 0) {
65
+ return;
66
+ }
67
+ const embeddedLayer = mapLayer.layer;
68
+ const visible = mapLayer.isVisible !== false;
69
+ const opacity = clampOpacity(toNumber(mapLayer.opacity) ?? 1);
70
+ const layerType = embeddedLayer?.layerType ?? mapLayer.layerType;
71
+ const geometryType = embeddedLayer?.geometryType ?? mapLayer.geometryType;
72
+ const layerName = embeddedLayer?.name ?? mapLayer.name;
73
+ const orderCandidate = toNumber(mapLayer.displayOrder) ?? toNumber(mapLayer.order) ?? toNumber(embeddedLayer?.displayOrder) ?? index;
74
+ normalized.push({
75
+ layerId,
76
+ displayOrder: orderCandidate ?? index,
77
+ isVisible: visible,
78
+ opacity,
79
+ layer: embeddedLayer,
80
+ layerType,
81
+ geometryType,
82
+ layerName,
83
+ mapLayer
84
+ });
85
+ });
86
+ return normalized.sort((a, b) => a.displayOrder - b.displayOrder);
87
+ }
88
+ function computeBBoxFromFeature(feature) {
89
+ if (!feature || typeof feature !== "object") return null;
90
+ const geometry = feature.geometry;
91
+ if (!geometry || !("coordinates" in geometry)) return null;
92
+ const coords = [];
93
+ const collect = (candidate) => {
94
+ if (!Array.isArray(candidate)) return;
95
+ if (candidate.length === 2 && typeof candidate[0] === "number" && typeof candidate[1] === "number") {
96
+ coords.push([candidate[0], candidate[1]]);
97
+ return;
98
+ }
99
+ candidate.forEach((entry) => collect(entry));
100
+ };
101
+ collect(geometry.coordinates);
102
+ if (coords.length === 0) return null;
103
+ const [firstLon, firstLat] = coords[0];
104
+ const bbox = { minLon: firstLon, minLat: firstLat, maxLon: firstLon, maxLat: firstLat };
105
+ coords.forEach(([lon, lat]) => {
106
+ bbox.minLon = Math.min(bbox.minLon, lon);
107
+ bbox.minLat = Math.min(bbox.minLat, lat);
108
+ bbox.maxLon = Math.max(bbox.maxLon, lon);
109
+ bbox.maxLat = Math.max(bbox.maxLat, lat);
110
+ });
111
+ return bbox;
112
+ }
113
+ function centroidFromBBox(bbox) {
114
+ return [(bbox.minLat + bbox.maxLat) / 2, (bbox.minLon + bbox.maxLon) / 2];
115
+ }
116
+ function applyFilteredGeoJSONStrategy(options) {
117
+ const layerControls = options.normalizedLayers.map((entry) => ({
118
+ layerId: entry.layerId,
119
+ visible: entry.isVisible,
120
+ opacity: entry.opacity
121
+ }));
122
+ return {
123
+ overlay: options.filteredGeojson,
124
+ metadata: options.metadata,
125
+ layerControls
126
+ };
127
+ }
128
+
129
+ // src/engine/LayerStateEngine.ts
130
+ function clampOpacity2(value) {
131
+ if (typeof value === "number" && Number.isFinite(value)) {
132
+ return Math.min(1, Math.max(0, value));
133
+ }
134
+ if (typeof value === "string") {
135
+ const parsed = parseFloat(value);
136
+ if (Number.isFinite(parsed)) {
137
+ return Math.min(1, Math.max(0, parsed));
138
+ }
139
+ }
140
+ return 1;
141
+ }
142
+ var resolveBaseVisibility = (_layer) => false;
143
+ function resolveBaseOpacity(layer) {
144
+ if ("opacity" in layer) {
145
+ return clampOpacity2(layer.opacity);
146
+ }
147
+ return 1;
148
+ }
149
+ function toEffectiveState(base, override) {
150
+ const overrideVisible = override?.overrideVisible ?? void 0;
151
+ const overrideOpacity = override?.overrideOpacity ?? void 0;
152
+ const opacitySource = overrideOpacity !== void 0 && overrideOpacity !== null ? overrideOpacity : base.baseOpacity;
153
+ return {
154
+ layerId: base.layerId,
155
+ baseVisible: base.baseVisible,
156
+ baseOpacity: base.baseOpacity,
157
+ overrideVisible,
158
+ overrideOpacity,
159
+ visible: overrideVisible ?? base.baseVisible,
160
+ opacity: clampOpacity2(opacitySource)
161
+ };
162
+ }
163
+ function initLayerStates(mapLayers) {
164
+ const bases = mapLayers.filter((layer) => layer.layerId !== void 0).map((layer) => ({
165
+ layerId: layer.layerId,
166
+ baseVisible: resolveBaseVisibility(layer),
167
+ baseOpacity: resolveBaseOpacity(layer)
168
+ }));
169
+ return bases.map((base) => toEffectiveState(base));
170
+ }
171
+ function applyLayerOverrides(states, overrides) {
172
+ const overrideMap = /* @__PURE__ */ new Map();
173
+ overrides.forEach((entry) => overrideMap.set(entry.layerId, entry));
174
+ return states.map((state) => {
175
+ const nextOverride = overrideMap.get(state.layerId);
176
+ const mergedOverrideVisible = nextOverride && "overrideVisible" in nextOverride && nextOverride.overrideVisible !== void 0 ? nextOverride.overrideVisible : state.overrideVisible;
177
+ const mergedOverrideOpacity = nextOverride && "overrideOpacity" in nextOverride && nextOverride.overrideOpacity !== void 0 ? nextOverride.overrideOpacity : state.overrideOpacity;
178
+ return toEffectiveState(state, {
179
+ layerId: state.layerId,
180
+ overrideVisible: mergedOverrideVisible ?? void 0,
181
+ overrideOpacity: mergedOverrideOpacity ?? void 0
182
+ });
183
+ });
184
+ }
185
+ function resetOverrides(states) {
186
+ return states.map((state) => toEffectiveState(state));
187
+ }
188
+
189
+ // src/react/layerStyleHelpers.ts
190
+ function resolveLayerAccent(style) {
191
+ if (!style) return null;
192
+ return style.fillColor ?? style.color ?? null;
193
+ }
194
+ function getLayerColor(style, fallback = "#94a3b8") {
195
+ return resolveLayerAccent(style) ?? fallback;
196
+ }
197
+ function getStyleByLayerId(layerId, mapLayers) {
198
+ if (!mapLayers) return null;
199
+ const match = mapLayers.find((ml) => String(ml.layerId) === String(layerId));
200
+ return match?.style ?? null;
201
+ }
202
+ function getAccentByLayerId(layerId, mapLayers) {
203
+ const style = getStyleByLayerId(layerId, mapLayers);
204
+ return resolveLayerAccent(style);
205
+ }
206
+
207
+ // src/react/zoomOpacity.ts
208
+ var DEFAULT_OPTIONS = {
209
+ minZoom: 10,
210
+ maxZoom: 17,
211
+ minFactor: 0.6,
212
+ maxFactor: 1,
213
+ minOpacity: 0.1,
214
+ maxOpacity: 0.92
215
+ };
216
+ function clampNumber(value, min, max) {
217
+ return Math.min(max, Math.max(min, value));
218
+ }
219
+ function clampOpacity3(value) {
220
+ return clampNumber(value, 0, 1);
221
+ }
222
+ function isPolygonLayer(layerType, geometryType) {
223
+ const candidate = (layerType ?? geometryType ?? "").toLowerCase();
224
+ return candidate === "polygon" || candidate === "multipolygon";
225
+ }
226
+ function getZoomOpacityFactor(zoom, options) {
227
+ const settings = { ...DEFAULT_OPTIONS, ...options };
228
+ const { minZoom, maxZoom, minFactor, maxFactor } = settings;
229
+ if (maxZoom <= minZoom) return clampNumber(maxFactor, minFactor, maxFactor);
230
+ const t = clampNumber((zoom - minZoom) / (maxZoom - minZoom), 0, 1);
231
+ const factor = maxFactor + (minFactor - maxFactor) * t;
232
+ return clampNumber(factor, minFactor, maxFactor);
233
+ }
234
+ function getLayerZoomOpacityFactor(zoom, layerType, geometryType, options) {
235
+ if (!isPolygonLayer(layerType, geometryType)) return 1;
236
+ return getZoomOpacityFactor(zoom, options);
237
+ }
238
+ function getEffectiveLayerOpacity(baseOpacity, zoom, layerType, geometryType, options) {
239
+ if (!isPolygonLayer(layerType, geometryType)) {
240
+ return clampOpacity3(baseOpacity);
241
+ }
242
+ const settings = { ...DEFAULT_OPTIONS, ...options };
243
+ const factor = getZoomOpacityFactor(zoom, options);
244
+ const effective = clampOpacity3(baseOpacity) * factor;
245
+ return clampNumber(effective, settings.minOpacity, settings.maxOpacity);
246
+ }
247
+
248
+ // src/react/ZenitMap.tsx
249
+ import { jsx, jsxs } from "react/jsx-runtime";
250
+ var DEFAULT_CENTER = [0, 0];
251
+ var DEFAULT_ZOOM = 3;
252
+ function computeBBoxFromGeojson(geojson) {
253
+ if (!geojson) return null;
254
+ if (!Array.isArray(geojson.features) || geojson.features.length === 0) return null;
255
+ const coords = [];
256
+ const collect = (candidate) => {
257
+ if (!Array.isArray(candidate)) return;
258
+ if (candidate.length === 2 && typeof candidate[0] === "number" && typeof candidate[1] === "number") {
259
+ coords.push([candidate[0], candidate[1]]);
260
+ return;
261
+ }
262
+ candidate.forEach((entry) => collect(entry));
263
+ };
264
+ geojson.features.forEach((feature) => {
265
+ collect(feature.geometry?.coordinates);
266
+ });
267
+ if (coords.length === 0) return null;
268
+ const [firstLon, firstLat] = coords[0];
269
+ const bbox = { minLon: firstLon, minLat: firstLat, maxLon: firstLon, maxLat: firstLat };
270
+ coords.forEach(([lon, lat]) => {
271
+ bbox.minLon = Math.min(bbox.minLon, lon);
272
+ bbox.minLat = Math.min(bbox.minLat, lat);
273
+ bbox.maxLon = Math.max(bbox.maxLon, lon);
274
+ bbox.maxLat = Math.max(bbox.maxLat, lat);
275
+ });
276
+ return bbox;
277
+ }
278
+ function mergeBBoxes(bboxes) {
279
+ const valid = bboxes.filter((bbox) => !!bbox);
280
+ if (valid.length === 0) return null;
281
+ const first = valid[0];
282
+ return valid.slice(1).reduce(
283
+ (acc, bbox) => ({
284
+ minLon: Math.min(acc.minLon, bbox.minLon),
285
+ minLat: Math.min(acc.minLat, bbox.minLat),
286
+ maxLon: Math.max(acc.maxLon, bbox.maxLon),
287
+ maxLat: Math.max(acc.maxLat, bbox.maxLat)
288
+ }),
289
+ { ...first }
290
+ );
291
+ }
292
+ function getFeatureLayerId(feature) {
293
+ const layerId = feature?.properties?.__zenit_layerId ?? feature?.properties?.layerId ?? feature?.properties?.layer_id;
294
+ if (layerId === void 0 || layerId === null) return null;
295
+ return layerId;
296
+ }
297
+ function escapeHtml(value) {
298
+ return value.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&#39;");
299
+ }
300
+ var DESCRIPTION_KEYS = /* @__PURE__ */ new Set(["descripcion", "description"]);
301
+ function normalizeDescriptionValue(value) {
302
+ if (value === void 0 || value === null) return null;
303
+ if (typeof value === "string") {
304
+ const trimmed = value.trim();
305
+ return trimmed ? trimmed : null;
306
+ }
307
+ if (typeof value === "number" || typeof value === "boolean") {
308
+ return String(value);
309
+ }
310
+ return null;
311
+ }
312
+ function extractDescriptionValue(properties) {
313
+ if (!properties) return null;
314
+ const matches = Object.entries(properties).find(
315
+ ([key]) => DESCRIPTION_KEYS.has(key.toLowerCase())
316
+ );
317
+ if (!matches) return null;
318
+ return normalizeDescriptionValue(matches[1]);
319
+ }
320
+ function safeJsonStringify(value) {
321
+ try {
322
+ const json = JSON.stringify(value, null, 2);
323
+ if (json !== void 0) return json;
324
+ } catch {
325
+ }
326
+ return String(value);
327
+ }
328
+ function renderPropertyValue(value) {
329
+ if (value === null || value === void 0) {
330
+ return '<span class="prop-empty">\u2014</span>';
331
+ }
332
+ if (typeof value === "object") {
333
+ const json = safeJsonStringify(value);
334
+ return `<pre class="prop-json">${escapeHtml(json)}</pre>`;
335
+ }
336
+ return `<span class="prop-text">${escapeHtml(String(value))}</span>`;
337
+ }
338
+ var POPUP_TITLE_KEYS = ["name", "title", "nombre", "label", "id"];
339
+ var POPUP_CHIP_KEYS = /* @__PURE__ */ new Set(["churn", "color", "sector"]);
340
+ function isChipValue(value) {
341
+ return typeof value === "string" || typeof value === "number" || typeof value === "boolean";
342
+ }
343
+ function getSanitizedChipColor(value) {
344
+ if (typeof value !== "string") return null;
345
+ const trimmed = value.trim();
346
+ if (/^#([0-9a-fA-F]{3}){1,2}$/.test(trimmed)) {
347
+ return trimmed;
348
+ }
349
+ if (/^rgb\((\s*\d+\s*,){2}\s*\d+\s*\)$/.test(trimmed)) {
350
+ return trimmed;
351
+ }
352
+ if (/^rgba\((\s*\d+\s*,){3}\s*(0|1|0?\.\d+)\s*\)$/.test(trimmed)) {
353
+ return trimmed;
354
+ }
355
+ return null;
356
+ }
357
+ function getPopupTitle(entries) {
358
+ for (const candidate of POPUP_TITLE_KEYS) {
359
+ const match = entries.find((entry) => entry.normalized === candidate);
360
+ if (!match || match.value === null || match.value === void 0) continue;
361
+ const value = String(match.value).trim();
362
+ if (!value) continue;
363
+ return { title: value, key: match.key };
364
+ }
365
+ return null;
366
+ }
367
+ function renderProperties(properties) {
368
+ const description = extractDescriptionValue(properties);
369
+ const entries = Object.entries(properties).filter(([key]) => !DESCRIPTION_KEYS.has(key.toLowerCase())).map(([key, value]) => ({
370
+ key,
371
+ value,
372
+ normalized: key.trim().toLowerCase()
373
+ }));
374
+ if (!description && entries.length === 0) return "";
375
+ const titleEntry = getPopupTitle(entries);
376
+ const titleText = titleEntry?.title ?? "Detalle del elemento";
377
+ const chipEntries = entries.filter(
378
+ (entry) => POPUP_CHIP_KEYS.has(entry.normalized) && isChipValue(entry.value)
379
+ );
380
+ const listEntries = entries.filter((entry) => {
381
+ if (titleEntry && entry.key === titleEntry.key) return false;
382
+ if (chipEntries.find((chip) => chip.key === entry.key)) return false;
383
+ return true;
384
+ });
385
+ const descriptionHtml = description ? `<div class="popup-description">${escapeHtml(description)}</div>` : "";
386
+ const chipsHtml = chipEntries.length ? `<div class="popup-chip-row">${chipEntries.map((entry) => {
387
+ const label = escapeHtml(entry.key.replace(/_/g, " "));
388
+ const value = escapeHtml(String(entry.value));
389
+ const color = getSanitizedChipColor(entry.value);
390
+ const colorStyle = color ? ` style="--chip-color: ${color}"` : "";
391
+ return `<span class="popup-chip"${colorStyle}><span class="popup-chip-label">${label}</span><span class="popup-chip-value">${value}</span></span>`;
392
+ }).join("")}</div>` : "";
393
+ const rowsHtml = listEntries.map((entry) => {
394
+ const label = escapeHtml(entry.key.replace(/_/g, " "));
395
+ const valueHtml = renderPropertyValue(entry.value);
396
+ return `<div class="prop-key">${label}</div><div class="prop-value">${valueHtml}</div>`;
397
+ }).join("");
398
+ const listHtml = rowsHtml ? `<div class="prop-list">${rowsHtml}</div>` : "";
399
+ return `
400
+ <div class="feature-popup">
401
+ <div class="feature-popup-card">
402
+ <div class="feature-popup-header">
403
+ <p class="popup-eyebrow">Informaci\xF3n</p>
404
+ <h3 class="popup-title">${escapeHtml(titleText)}</h3>
405
+ </div>
406
+ <div class="feature-popup-body">
407
+ ${descriptionHtml}
408
+ ${chipsHtml}
409
+ ${listHtml}
410
+ </div>
411
+ </div>
412
+ </div>
413
+ `;
414
+ }
415
+ function withAlpha(color, alpha) {
416
+ const trimmed = color.trim();
417
+ if (trimmed.startsWith("#")) {
418
+ const hex = trimmed.replace("#", "");
419
+ const expanded = hex.length === 3 ? hex.split("").map((char) => `${char}${char}`).join("") : hex;
420
+ if (expanded.length === 6) {
421
+ const r = parseInt(expanded.slice(0, 2), 16);
422
+ const g = parseInt(expanded.slice(2, 4), 16);
423
+ const b = parseInt(expanded.slice(4, 6), 16);
424
+ return `rgba(${r}, ${g}, ${b}, ${alpha})`;
425
+ }
426
+ }
427
+ if (trimmed.startsWith("rgb(")) {
428
+ const inner = trimmed.slice(4, -1);
429
+ return `rgba(${inner}, ${alpha})`;
430
+ }
431
+ if (trimmed.startsWith("rgba(")) {
432
+ const inner = trimmed.slice(5, -1).split(",").slice(0, 3).map((value) => value.trim());
433
+ return `rgba(${inner.join(", ")}, ${alpha})`;
434
+ }
435
+ return color;
436
+ }
437
+ function getRgbFromColor(color) {
438
+ const trimmed = color.trim();
439
+ if (trimmed.startsWith("#")) {
440
+ const hex = trimmed.replace("#", "");
441
+ const expanded = hex.length === 3 ? hex.split("").map((char) => `${char}${char}`).join("") : hex;
442
+ if (expanded.length === 6) {
443
+ const r = parseInt(expanded.slice(0, 2), 16);
444
+ const g = parseInt(expanded.slice(2, 4), 16);
445
+ const b = parseInt(expanded.slice(4, 6), 16);
446
+ return { r, g, b };
447
+ }
448
+ }
449
+ const rgbMatch = trimmed.match(/rgba?\(([^)]+)\)/i);
450
+ if (rgbMatch) {
451
+ const [r, g, b] = rgbMatch[1].split(",").map((value) => parseFloat(value.trim())).slice(0, 3);
452
+ if ([r, g, b].every((value) => Number.isFinite(value))) {
453
+ return { r, g, b };
454
+ }
455
+ }
456
+ return null;
457
+ }
458
+ function getLabelTextStyles(color) {
459
+ const rgb = getRgbFromColor(color);
460
+ if (!rgb) {
461
+ return { color: "#0f172a", shadow: "0 1px 2px rgba(255, 255, 255, 0.6)" };
462
+ }
463
+ const luminance = (0.2126 * rgb.r + 0.7152 * rgb.g + 0.0722 * rgb.b) / 255;
464
+ if (luminance > 0.6) {
465
+ return { color: "#0f172a", shadow: "0 1px 2px rgba(255, 255, 255, 0.7)" };
466
+ }
467
+ return { color: "#ffffff", shadow: "0 1px 2px rgba(0, 0, 0, 0.4)" };
468
+ }
469
+ function getFeatureStyleOverrides(feature) {
470
+ const candidate = feature?.properties?._style;
471
+ if (!candidate || typeof candidate !== "object" || Array.isArray(candidate)) return null;
472
+ const styleCandidate = candidate;
473
+ return {
474
+ color: styleCandidate.color,
475
+ weight: styleCandidate.weight,
476
+ fillColor: styleCandidate.fillColor,
477
+ fillOpacity: styleCandidate.fillOpacity
478
+ };
479
+ }
480
+ function buildFeaturePopupHtml(feature) {
481
+ const properties = feature?.properties;
482
+ if (!properties) return null;
483
+ const rendered = renderProperties(properties);
484
+ return rendered ? rendered : null;
485
+ }
486
+ var POINT_GEOMETRY_TYPES = /* @__PURE__ */ new Set(["Point", "MultiPoint"]);
487
+ function getGeometryType(feature) {
488
+ const t = feature?.geometry?.type;
489
+ return typeof t === "string" ? t : null;
490
+ }
491
+ function isPointGeometry(feature) {
492
+ const geometryType = getGeometryType(feature);
493
+ return geometryType !== null && POINT_GEOMETRY_TYPES.has(geometryType);
494
+ }
495
+ function isNonPointGeometry(feature) {
496
+ const geometryType = getGeometryType(feature);
497
+ return geometryType !== null && !POINT_GEOMETRY_TYPES.has(geometryType);
498
+ }
499
+ function buildFeatureCollection(features) {
500
+ return {
501
+ type: "FeatureCollection",
502
+ features
503
+ };
504
+ }
505
+ function pickIntersectFeature(baseFeature, candidates) {
506
+ if (!Array.isArray(candidates) || candidates.length === 0) return null;
507
+ const baseId = baseFeature?.id;
508
+ if (baseId !== void 0 && baseId !== null) {
509
+ const matchById = candidates.find((candidate) => candidate?.id === baseId);
510
+ if (matchById) return matchById;
511
+ }
512
+ const matchWithDescription = candidates.find(
513
+ (candidate) => extractDescriptionValue(candidate?.properties)
514
+ );
515
+ return matchWithDescription ?? candidates[0];
516
+ }
517
+ function normalizeCenterTuple(center) {
518
+ if (!center) return null;
519
+ if (Array.isArray(center) && center.length >= 2) {
520
+ const lat = center[0];
521
+ const lon = center[1];
522
+ if (typeof lat === "number" && typeof lon === "number") return [lat, lon];
523
+ return null;
524
+ }
525
+ const maybeObj = center;
526
+ if (typeof maybeObj.lat === "number" && typeof maybeObj.lon === "number") {
527
+ return [maybeObj.lat, maybeObj.lon];
528
+ }
529
+ return null;
530
+ }
531
+ var FitToBounds = ({ bbox }) => {
532
+ const mapInstance = useMap();
533
+ const lastAppliedBBox = useRef(null);
534
+ useEffect(() => {
535
+ const targetBBox = bbox;
536
+ if (!targetBBox) return;
537
+ const serialized = JSON.stringify(targetBBox);
538
+ if (lastAppliedBBox.current === serialized) return;
539
+ const bounds = [
540
+ [targetBBox.minLat, targetBBox.minLon],
541
+ [targetBBox.maxLat, targetBBox.maxLon]
542
+ ];
543
+ mapInstance.fitBounds(bounds, { padding: [12, 12] });
544
+ lastAppliedBBox.current = serialized;
545
+ }, [bbox, mapInstance]);
546
+ return null;
547
+ };
548
+ var AutoFitToBounds = ({
549
+ bbox,
550
+ enabled = true
551
+ }) => {
552
+ const mapInstance = useMap();
553
+ const lastAutoBBoxApplied = useRef(null);
554
+ const lastUserInteracted = useRef(false);
555
+ useEffect(() => {
556
+ if (!enabled) return;
557
+ const handleInteraction = () => {
558
+ lastUserInteracted.current = true;
559
+ };
560
+ mapInstance.on("dragstart", handleInteraction);
561
+ mapInstance.on("zoomstart", handleInteraction);
562
+ return () => {
563
+ mapInstance.off("dragstart", handleInteraction);
564
+ mapInstance.off("zoomstart", handleInteraction);
565
+ };
566
+ }, [enabled, mapInstance]);
567
+ useEffect(() => {
568
+ if (!enabled) return;
569
+ if (!bbox) return;
570
+ const serialized = JSON.stringify(bbox);
571
+ if (lastAutoBBoxApplied.current === serialized) return;
572
+ if (lastUserInteracted.current) {
573
+ lastUserInteracted.current = false;
574
+ }
575
+ const bounds = [
576
+ [bbox.minLat, bbox.minLon],
577
+ [bbox.maxLat, bbox.maxLon]
578
+ ];
579
+ mapInstance.fitBounds(bounds, { padding: [12, 12] });
580
+ lastAutoBBoxApplied.current = serialized;
581
+ }, [bbox, enabled, mapInstance]);
582
+ return null;
583
+ };
584
+ var ZoomBasedOpacityHandler = ({ onZoomChange }) => {
585
+ const mapInstance = useMap();
586
+ useEffect(() => {
587
+ const handleZoom = () => {
588
+ onZoomChange(mapInstance.getZoom());
589
+ };
590
+ mapInstance.on("zoomend", handleZoom);
591
+ handleZoom();
592
+ return () => {
593
+ mapInstance.off("zoomend", handleZoom);
594
+ };
595
+ }, [mapInstance, onZoomChange]);
596
+ return null;
597
+ };
598
+ var MapInstanceBridge = ({ onReady }) => {
599
+ const mapInstance = useMap();
600
+ useEffect(() => {
601
+ onReady(mapInstance);
602
+ }, [mapInstance, onReady]);
603
+ return null;
604
+ };
605
+ var ZenitMap = forwardRef(({
606
+ client,
607
+ mapId,
608
+ height = "500px",
609
+ width = "100%",
610
+ initialZoom,
611
+ initialCenter,
612
+ showLayerPanel = true,
613
+ overlayGeojson,
614
+ overlayStyle,
615
+ layerControls,
616
+ layerStates,
617
+ layerGeojson,
618
+ onLayerStateChange,
619
+ onError,
620
+ onLoadingChange,
621
+ onFeatureClick,
622
+ onFeatureHover,
623
+ featureInfoMode = "popup",
624
+ mapLayers,
625
+ zoomToBbox,
626
+ zoomToGeojson,
627
+ onZoomChange,
628
+ onMapReady
629
+ }, ref) => {
630
+ const [map, setMap] = useState(null);
631
+ const [layers, setLayers] = useState([]);
632
+ const [effectiveStates, setEffectiveStates] = useState([]);
633
+ const [loadingMap, setLoadingMap] = useState(false);
634
+ const [mapError, setMapError] = useState(null);
635
+ const [mapInstance, setMapInstance] = useState(null);
636
+ const [panesReady, setPanesReady] = useState(false);
637
+ const [currentZoom, setCurrentZoom] = useState(initialZoom ?? DEFAULT_ZOOM);
638
+ const [isMobile, setIsMobile] = useState(() => {
639
+ if (typeof window === "undefined") return false;
640
+ return window.matchMedia("(max-width: 768px)").matches;
641
+ });
642
+ const normalizedLayers = useMemo(() => normalizeMapLayers(map), [map]);
643
+ useEffect(() => {
644
+ if (typeof window === "undefined") return;
645
+ const mql = window.matchMedia("(max-width: 768px)");
646
+ const onChange = (e) => {
647
+ setIsMobile(e.matches);
648
+ };
649
+ setIsMobile(mql.matches);
650
+ if (typeof mql.addEventListener === "function") {
651
+ mql.addEventListener("change", onChange);
652
+ return () => mql.removeEventListener("change", onChange);
653
+ }
654
+ const legacy = mql;
655
+ if (typeof legacy.addListener === "function") {
656
+ legacy.addListener(onChange);
657
+ return () => legacy.removeListener(onChange);
658
+ }
659
+ return;
660
+ }, []);
661
+ const layerStyleIndex = useMemo(() => {
662
+ const index = /* @__PURE__ */ new Map();
663
+ (map?.mapLayers ?? []).forEach((entry) => {
664
+ const layerStyle = entry.layer?.style ?? entry.mapLayer?.layer?.style ?? entry.style ?? null;
665
+ const layerId = entry.layerId ?? entry.mapLayer?.layerId ?? entry.mapLayer?.layer?.id ?? entry.layer?.id;
666
+ if (layerId !== void 0 && layerId !== null && layerStyle) {
667
+ index.set(String(layerId), layerStyle);
668
+ }
669
+ });
670
+ return index;
671
+ }, [map]);
672
+ const labelKeyIndex = useMemo(() => {
673
+ const index = /* @__PURE__ */ new Map();
674
+ normalizedLayers.forEach((entry) => {
675
+ const label = entry.layer?.label ?? entry.mapLayer?.label ?? entry.mapLayer.layerConfig?.label;
676
+ if (typeof label === "string" && label.trim().length > 0) {
677
+ index.set(String(entry.layerId), label);
678
+ }
679
+ });
680
+ return index;
681
+ }, [normalizedLayers]);
682
+ const layerMetaIndex = useMemo(() => {
683
+ const index = /* @__PURE__ */ new Map();
684
+ normalizedLayers.forEach((entry) => {
685
+ index.set(String(entry.layerId), {
686
+ layerType: typeof entry.layer?.layerType === "string" ? entry.layer.layerType : typeof entry.mapLayer.layerType === "string" ? entry.mapLayer.layerType : void 0,
687
+ geometryType: typeof entry.layer?.geometryType === "string" ? entry.layer.geometryType : typeof entry.mapLayer.layerConfig?.geometryType === "string" ? entry.mapLayer.layerConfig.geometryType : void 0
688
+ });
689
+ });
690
+ return index;
691
+ }, [normalizedLayers]);
692
+ const overlayStyleFunction = useMemo(() => {
693
+ return (feature) => {
694
+ const featureLayerId = getFeatureLayerId(feature);
695
+ const featureStyleOverrides = getFeatureStyleOverrides(feature);
696
+ let style = null;
697
+ if (featureLayerId !== null) {
698
+ style = getStyleByLayerId(featureLayerId, mapLayers) ?? layerStyleIndex.get(String(featureLayerId)) ?? null;
699
+ }
700
+ const resolvedStyle = featureStyleOverrides ? { ...style ?? {}, ...featureStyleOverrides } : style;
701
+ const defaultOptions = {
702
+ color: resolvedStyle?.color ?? resolvedStyle?.fillColor ?? "#2563eb",
703
+ weight: resolvedStyle?.weight ?? 2,
704
+ fillColor: resolvedStyle?.fillColor ?? resolvedStyle?.color ?? "#2563eb",
705
+ fillOpacity: resolvedStyle?.fillOpacity ?? 0.15,
706
+ ...overlayStyle ?? {}
707
+ };
708
+ return defaultOptions;
709
+ };
710
+ }, [layerStyleIndex, mapLayers, overlayStyle]);
711
+ const [baseStates, setBaseStates] = useState([]);
712
+ const [mapOverrides, setMapOverrides] = useState([]);
713
+ const [controlOverrides, setControlOverrides] = useState([]);
714
+ const [uiOverrides, setUiOverrides] = useState([]);
715
+ useEffect(() => {
716
+ let isMounted = true;
717
+ setLoadingMap(true);
718
+ setMapError(null);
719
+ onLoadingChange?.("map", true);
720
+ client.maps.getMap(mapId, true).then((mapResponse) => {
721
+ if (!isMounted) return;
722
+ const extracted = extractMapDto(mapResponse);
723
+ const resolved = extracted ? normalizeMapCenter(extracted) : null;
724
+ setMap(resolved);
725
+ }).catch((err) => {
726
+ if (!isMounted) return;
727
+ setMapError(err instanceof Error ? err.message : "No se pudo obtener el mapa");
728
+ onError?.(err, "map");
729
+ }).finally(() => {
730
+ if (!isMounted) return;
731
+ setLoadingMap(false);
732
+ onLoadingChange?.("map", false);
733
+ });
734
+ return () => {
735
+ isMounted = false;
736
+ };
737
+ }, [client.maps, mapId, onError, onLoadingChange]);
738
+ useEffect(() => {
739
+ if (normalizedLayers.length === 0) {
740
+ setLayers([]);
741
+ setBaseStates([]);
742
+ setMapOverrides([]);
743
+ setUiOverrides([]);
744
+ return;
745
+ }
746
+ const nextLayers = normalizedLayers.map((entry) => ({
747
+ mapLayer: { ...entry.mapLayer, layerId: entry.layerId },
748
+ layer: entry.layer,
749
+ displayOrder: entry.displayOrder
750
+ }));
751
+ const base = initLayerStates(
752
+ normalizedLayers.map((entry) => ({
753
+ ...entry.mapLayer,
754
+ layerId: entry.layerId,
755
+ opacity: entry.opacity,
756
+ isVisible: entry.isVisible
757
+ }))
758
+ );
759
+ const initialOverrides = normalizedLayers.map((entry) => ({
760
+ layerId: entry.layerId,
761
+ overrideVisible: entry.isVisible,
762
+ overrideOpacity: entry.opacity
763
+ }));
764
+ setLayers(nextLayers);
765
+ setBaseStates(base);
766
+ setMapOverrides(initialOverrides);
767
+ setUiOverrides([]);
768
+ }, [normalizedLayers]);
769
+ useEffect(() => {
770
+ if (!layerControls) {
771
+ setControlOverrides([]);
772
+ return;
773
+ }
774
+ const overrides = layerControls.map((entry) => ({
775
+ layerId: entry.layerId,
776
+ overrideVisible: entry.visible,
777
+ overrideOpacity: entry.opacity
778
+ }));
779
+ setControlOverrides(overrides);
780
+ }, [layerControls]);
781
+ useEffect(() => {
782
+ if (layerStates) {
783
+ return;
784
+ }
785
+ if (Array.isArray(layerControls) && layerControls.length === 0 && effectiveStates.length > 0) {
786
+ const reset = resetOverrides(baseStates);
787
+ setEffectiveStates(reset);
788
+ onLayerStateChange?.(reset);
789
+ }
790
+ }, [baseStates, effectiveStates.length, layerControls, layerStates, onLayerStateChange]);
791
+ useEffect(() => {
792
+ if (layerStates) {
793
+ setEffectiveStates(layerStates);
794
+ }
795
+ }, [layerStates]);
796
+ useEffect(() => {
797
+ if (layerStates) {
798
+ return;
799
+ }
800
+ if (mapOverrides.length === 0 && controlOverrides.length === 0 && uiOverrides.length === 0) {
801
+ setEffectiveStates(baseStates);
802
+ return;
803
+ }
804
+ const combined = [...mapOverrides, ...controlOverrides, ...uiOverrides];
805
+ const next = applyLayerOverrides(baseStates, combined);
806
+ setEffectiveStates(next);
807
+ onLayerStateChange?.(next);
808
+ }, [baseStates, controlOverrides, layerStates, mapOverrides, onLayerStateChange, uiOverrides]);
809
+ useEffect(() => {
810
+ if (!Array.isArray(layerControls) || layerControls.length > 0) return;
811
+ setUiOverrides([]);
812
+ }, [layerControls]);
813
+ useEffect(() => {
814
+ if (layerStates) {
815
+ return;
816
+ }
817
+ if (!Array.isArray(layerControls) && effectiveStates.length > 0 && baseStates.length > 0) {
818
+ const next = resetOverrides(baseStates);
819
+ setEffectiveStates(next);
820
+ onLayerStateChange?.(next);
821
+ }
822
+ }, [baseStates, effectiveStates.length, layerControls, layerStates, onLayerStateChange]);
823
+ const upsertUiOverride = (layerId, patch) => {
824
+ setUiOverrides((prev) => {
825
+ const filtered = prev.filter((entry) => entry.layerId !== layerId);
826
+ const nextEntry = {
827
+ layerId,
828
+ ...patch
829
+ };
830
+ return [...filtered, nextEntry];
831
+ });
832
+ };
833
+ const updateOpacityFromUi = useCallback(
834
+ (layerId, uiOpacity) => {
835
+ const meta = layerMetaIndex.get(String(layerId));
836
+ const zoomFactor = getLayerZoomOpacityFactor(
837
+ currentZoom,
838
+ meta?.layerType,
839
+ meta?.geometryType
840
+ );
841
+ const baseOpacity = clampOpacity3(uiOpacity / zoomFactor);
842
+ const effectiveOpacity = getEffectiveLayerOpacity(
843
+ baseOpacity,
844
+ currentZoom,
845
+ meta?.layerType,
846
+ meta?.geometryType
847
+ );
848
+ if (layerStates && onLayerStateChange) {
849
+ const next = effectiveStates.map(
850
+ (state) => state.layerId === layerId ? {
851
+ ...state,
852
+ baseOpacity,
853
+ opacity: effectiveOpacity,
854
+ overrideOpacity: uiOpacity
855
+ } : state
856
+ );
857
+ onLayerStateChange(next);
858
+ return;
859
+ }
860
+ setBaseStates(
861
+ (prev) => prev.map((state) => state.layerId === layerId ? { ...state, baseOpacity } : state)
862
+ );
863
+ setUiOverrides((prev) => {
864
+ const existing = prev.find((entry) => entry.layerId === layerId);
865
+ const filtered = prev.filter((entry) => entry.layerId !== layerId);
866
+ if (existing && existing.overrideVisible !== void 0) {
867
+ return [
868
+ ...filtered,
869
+ { layerId, overrideVisible: existing.overrideVisible }
870
+ ];
871
+ }
872
+ return filtered;
873
+ });
874
+ },
875
+ [currentZoom, effectiveStates, layerMetaIndex, layerStates, onLayerStateChange]
876
+ );
877
+ const center = useMemo(() => {
878
+ if (initialCenter) {
879
+ return initialCenter;
880
+ }
881
+ const normalized = normalizeCenterTuple(map?.settings?.center);
882
+ if (normalized) {
883
+ return normalized;
884
+ }
885
+ return DEFAULT_CENTER;
886
+ }, [initialCenter, map?.settings?.center]);
887
+ const zoom = initialZoom ?? map?.settings?.zoom ?? DEFAULT_ZOOM;
888
+ useEffect(() => {
889
+ setCurrentZoom(zoom);
890
+ }, [zoom]);
891
+ const decoratedLayers = useMemo(() => {
892
+ return layers.map((layer) => ({
893
+ ...layer,
894
+ effective: effectiveStates.find((state) => state.layerId === layer.mapLayer.layerId),
895
+ data: layerGeojson?.[layer.mapLayer.layerId] ?? layerGeojson?.[String(layer.mapLayer.layerId)] ?? null
896
+ }));
897
+ }, [effectiveStates, layerGeojson, layers]);
898
+ const orderedLayers = useMemo(() => {
899
+ return [...decoratedLayers].filter((layer) => layer.effective?.visible && layer.data).sort((a, b) => a.displayOrder - b.displayOrder);
900
+ }, [decoratedLayers]);
901
+ const explicitZoomBBox = useMemo(() => {
902
+ if (zoomToBbox) return zoomToBbox;
903
+ if (zoomToGeojson) return computeBBoxFromGeojson(zoomToGeojson);
904
+ return null;
905
+ }, [zoomToBbox, zoomToGeojson]);
906
+ const autoZoomBBox = useMemo(() => {
907
+ if (explicitZoomBBox) return null;
908
+ const visibleBBoxes = orderedLayers.map((layer) => computeBBoxFromGeojson(layer.data));
909
+ return mergeBBoxes(visibleBBoxes);
910
+ }, [explicitZoomBBox, orderedLayers]);
911
+ const resolveLayerStyle = useCallback(
912
+ (layerId) => {
913
+ return getStyleByLayerId(layerId, mapLayers) ?? layerStyleIndex.get(String(layerId)) ?? null;
914
+ },
915
+ [layerStyleIndex, mapLayers]
916
+ );
917
+ const labelMarkers = useMemo(() => {
918
+ const markers = [];
919
+ decoratedLayers.forEach((layerState) => {
920
+ if (!layerState.effective?.visible) return;
921
+ const labelKey = labelKeyIndex.get(String(layerState.mapLayer.layerId));
922
+ if (!labelKey) return;
923
+ const data = layerState.data;
924
+ if (!data) return;
925
+ const resolvedStyle = resolveLayerStyle(layerState.mapLayer.layerId);
926
+ const layerColor = resolvedStyle?.fillColor ?? resolvedStyle?.color ?? "rgba(37, 99, 235, 1)";
927
+ const opacity = layerState.effective?.opacity ?? 1;
928
+ data.features.forEach((feature, index) => {
929
+ const properties = feature.properties;
930
+ const value = properties?.[labelKey];
931
+ if (value === void 0 || value === null || value === "") return;
932
+ const bbox = computeBBoxFromFeature(feature);
933
+ if (!bbox) return;
934
+ const [lat, lng] = centroidFromBBox(bbox);
935
+ markers.push({
936
+ key: `${layerState.mapLayer.layerId}-label-${index}`,
937
+ position: [lat, lng],
938
+ label: String(value),
939
+ opacity,
940
+ layerId: layerState.mapLayer.layerId,
941
+ color: layerColor
942
+ });
943
+ });
944
+ });
945
+ return markers;
946
+ }, [decoratedLayers, labelKeyIndex, resolveLayerStyle]);
947
+ const ensureLayerPanes = useCallback(
948
+ (targetMap, targetLayers) => {
949
+ const baseZIndex = 400;
950
+ targetLayers.forEach((layer) => {
951
+ const order = Number.isFinite(layer.displayOrder) ? layer.displayOrder : 0;
952
+ const fillPaneName = `zenit-layer-${layer.layerId}-fill`;
953
+ const pointPaneName = `zenit-layer-${layer.layerId}-points`;
954
+ const labelPaneName = `zenit-layer-${layer.layerId}-labels`;
955
+ const fillPane = targetMap.getPane(fillPaneName) ?? targetMap.createPane(fillPaneName);
956
+ const pointPane = targetMap.getPane(pointPaneName) ?? targetMap.createPane(pointPaneName);
957
+ const labelPane = targetMap.getPane(labelPaneName) ?? targetMap.createPane(labelPaneName);
958
+ fillPane.style.zIndex = String(baseZIndex + order);
959
+ pointPane.style.zIndex = String(baseZIndex + order + 1e3);
960
+ labelPane.style.zIndex = String(baseZIndex + order + 2e3);
961
+ });
962
+ },
963
+ []
964
+ );
965
+ const handleMapReady = useCallback(
966
+ (instance) => {
967
+ setPanesReady(false);
968
+ setMapInstance(instance);
969
+ onMapReady?.(instance);
970
+ },
971
+ [onMapReady]
972
+ );
973
+ useEffect(() => {
974
+ if (!mapInstance) {
975
+ setPanesReady(false);
976
+ return;
977
+ }
978
+ if (orderedLayers.length === 0) {
979
+ return;
980
+ }
981
+ const layerTargets = orderedLayers.map((layer) => ({
982
+ layerId: layer.mapLayer.layerId,
983
+ displayOrder: layer.displayOrder
984
+ }));
985
+ ensureLayerPanes(mapInstance, layerTargets);
986
+ const first = layerTargets[0];
987
+ const testPane = mapInstance.getPane(`zenit-layer-${first.layerId}-labels`);
988
+ if (testPane) {
989
+ setPanesReady(true);
990
+ }
991
+ }, [mapInstance, orderedLayers, ensureLayerPanes]);
992
+ const overlayOnEachFeature = useMemo(() => {
993
+ return (feature, layer) => {
994
+ const layerId = getFeatureLayerId(feature) ?? void 0;
995
+ const geometryType = feature?.geometry?.type;
996
+ const isPointFeature = geometryType === "Point" || geometryType === "MultiPoint" || layer instanceof L.CircleMarker;
997
+ const originalStyle = layer instanceof L.Path ? {
998
+ color: layer.options.color,
999
+ weight: layer.options.weight,
1000
+ fillColor: layer.options.fillColor,
1001
+ opacity: layer.options.opacity,
1002
+ fillOpacity: layer.options.fillOpacity
1003
+ } : null;
1004
+ const originalRadius = layer instanceof L.CircleMarker ? layer.getRadius() : null;
1005
+ if (featureInfoMode === "popup") {
1006
+ const content = buildFeaturePopupHtml(feature);
1007
+ if (content) {
1008
+ layer.bindPopup(content, {
1009
+ maxWidth: 420,
1010
+ minWidth: 280,
1011
+ className: "zenit-feature-popup-shell",
1012
+ autoPan: true,
1013
+ closeButton: true,
1014
+ offset: L.point(0, -24)
1015
+ });
1016
+ }
1017
+ }
1018
+ if (isPointFeature && layer.bindTooltip) {
1019
+ layer.bindTooltip("Click para ver detalle", {
1020
+ sticky: true,
1021
+ direction: "top",
1022
+ opacity: 0.9,
1023
+ className: "zenit-map-tooltip"
1024
+ });
1025
+ }
1026
+ layer.on("click", () => {
1027
+ if (featureInfoMode === "popup" && client && layerId !== void 0 && !extractDescriptionValue(feature?.properties) && feature?.geometry) {
1028
+ const trackedFeature = feature;
1029
+ if (!trackedFeature.__zenit_popup_loaded) {
1030
+ trackedFeature.__zenit_popup_loaded = true;
1031
+ client.layers.getLayerGeoJsonIntersect({
1032
+ id: layerId,
1033
+ geometry: feature.geometry
1034
+ }).then((response) => {
1035
+ const candidates = response.data?.features ?? [];
1036
+ const resolved = pickIntersectFeature(feature, candidates);
1037
+ if (!resolved?.properties) return;
1038
+ const mergedProperties = {
1039
+ ...trackedFeature.properties ?? {},
1040
+ ...resolved.properties
1041
+ };
1042
+ trackedFeature.properties = mergedProperties;
1043
+ const updatedHtml = buildFeaturePopupHtml({
1044
+ ...feature,
1045
+ properties: mergedProperties
1046
+ });
1047
+ if (updatedHtml && layer.setPopupContent) {
1048
+ layer.setPopupContent(updatedHtml);
1049
+ }
1050
+ }).catch(() => {
1051
+ trackedFeature.__zenit_popup_loaded = false;
1052
+ });
1053
+ }
1054
+ }
1055
+ onFeatureClick?.(feature, layerId);
1056
+ });
1057
+ layer.on("mouseover", () => {
1058
+ if (layer instanceof L.Path && originalStyle) {
1059
+ layer.setStyle({
1060
+ ...originalStyle,
1061
+ weight: (originalStyle.weight ?? 2) + 1,
1062
+ opacity: Math.min(1, (originalStyle.opacity ?? 1) + 0.2),
1063
+ fillOpacity: Math.min(1, (originalStyle.fillOpacity ?? 0.8) + 0.1)
1064
+ });
1065
+ }
1066
+ if (layer instanceof L.CircleMarker && typeof originalRadius === "number") {
1067
+ layer.setRadius(originalRadius + 1);
1068
+ }
1069
+ onFeatureHover?.(feature, layerId);
1070
+ });
1071
+ layer.on("mouseout", () => {
1072
+ if (layer instanceof L.Path && originalStyle) {
1073
+ layer.setStyle(originalStyle);
1074
+ }
1075
+ if (layer instanceof L.CircleMarker && typeof originalRadius === "number") {
1076
+ layer.setRadius(originalRadius);
1077
+ }
1078
+ });
1079
+ };
1080
+ }, [client, featureInfoMode, onFeatureClick, onFeatureHover]);
1081
+ const buildLayerStyle = (layerId, baseOpacity, feature, layerType) => {
1082
+ const style = resolveLayerStyle(layerId);
1083
+ const featureStyleOverrides = getFeatureStyleOverrides(feature);
1084
+ const resolvedStyle = featureStyleOverrides ? { ...style ?? {}, ...featureStyleOverrides } : style;
1085
+ const geometryType = feature?.geometry?.type;
1086
+ const resolvedLayerType = layerType ?? geometryType;
1087
+ const sanitizedBaseOpacity = clampOpacity3(baseOpacity);
1088
+ const normalizedStyleFill = typeof resolvedStyle?.fillOpacity === "number" ? clampOpacity3(resolvedStyle.fillOpacity) : 0.8;
1089
+ const effectiveOpacity = getEffectiveLayerOpacity(
1090
+ sanitizedBaseOpacity,
1091
+ currentZoom,
1092
+ resolvedLayerType,
1093
+ geometryType
1094
+ );
1095
+ const fillOpacity = clampOpacity3(effectiveOpacity * normalizedStyleFill);
1096
+ const strokeOpacity = clampOpacity3(Math.max(0.35, effectiveOpacity * 0.9));
1097
+ return {
1098
+ color: resolvedStyle?.color ?? resolvedStyle?.fillColor ?? "#2563eb",
1099
+ weight: resolvedStyle?.weight ?? 2,
1100
+ fillColor: resolvedStyle?.fillColor ?? resolvedStyle?.color ?? "#2563eb",
1101
+ opacity: strokeOpacity,
1102
+ fillOpacity
1103
+ };
1104
+ };
1105
+ const buildLabelIcon = useCallback((label, opacity, color) => {
1106
+ const size = 60;
1107
+ const innerSize = 44;
1108
+ const textStyles = getLabelTextStyles(color);
1109
+ const safeLabel = escapeHtml(label);
1110
+ const clampedOpacity = Math.min(1, Math.max(0.92, opacity));
1111
+ const innerBackground = withAlpha(color, 0.9);
1112
+ return L.divIcon({
1113
+ className: "zenit-label-marker",
1114
+ iconSize: [size, size],
1115
+ iconAnchor: [size / 2, size / 2],
1116
+ html: `
1117
+ <div
1118
+ title="${safeLabel}"
1119
+ style="
1120
+ width:${size}px;
1121
+ height:${size}px;
1122
+ border-radius:9999px;
1123
+ background:rgba(255, 255, 255, 0.95);
1124
+ border:3px solid rgba(255, 255, 255, 1);
1125
+ display:flex;
1126
+ align-items:center;
1127
+ justify-content:center;
1128
+ opacity:${clampedOpacity};
1129
+ box-shadow:0 2px 6px rgba(0, 0, 0, 0.25);
1130
+ pointer-events:none;
1131
+ "
1132
+ >
1133
+ <div
1134
+ style="
1135
+ width:${innerSize}px;
1136
+ height:${innerSize}px;
1137
+ border-radius:9999px;
1138
+ background:${innerBackground};
1139
+ display:flex;
1140
+ align-items:center;
1141
+ justify-content:center;
1142
+ box-shadow:inset 0 0 0 1px rgba(15, 23, 42, 0.12);
1143
+ "
1144
+ >
1145
+ <span
1146
+ style="
1147
+ color:${textStyles.color};
1148
+ font-size:20px;
1149
+ font-weight:800;
1150
+ text-shadow:${textStyles.shadow};
1151
+ "
1152
+ >
1153
+ ${safeLabel}
1154
+ </span>
1155
+ </div>
1156
+ </div>
1157
+ `
1158
+ });
1159
+ }, []);
1160
+ useImperativeHandle(ref, () => ({
1161
+ setLayerOpacity: (layerId, opacity) => {
1162
+ upsertUiOverride(layerId, { overrideOpacity: opacity });
1163
+ },
1164
+ setLayerVisibility: (layerId, visible) => {
1165
+ upsertUiOverride(layerId, { overrideVisible: visible });
1166
+ },
1167
+ fitBounds: (bbox, options) => {
1168
+ if (!mapInstance) return;
1169
+ if (typeof bbox.minLat !== "number" || typeof bbox.minLon !== "number" || typeof bbox.maxLat !== "number" || typeof bbox.maxLon !== "number" || !Number.isFinite(bbox.minLat) || !Number.isFinite(bbox.minLon) || !Number.isFinite(bbox.maxLat) || !Number.isFinite(bbox.maxLon)) {
1170
+ console.warn("[ZenitMap.fitBounds] Invalid bbox: missing or non-finite coordinates", bbox);
1171
+ return;
1172
+ }
1173
+ const bounds = [
1174
+ [bbox.minLat, bbox.minLon],
1175
+ [bbox.maxLat, bbox.maxLon]
1176
+ ];
1177
+ const fitOptions = {
1178
+ padding: options?.padding ?? [12, 12],
1179
+ animate: options?.animate ?? true
1180
+ };
1181
+ mapInstance.fitBounds(bounds, fitOptions);
1182
+ },
1183
+ setView: (coordinates, zoom2) => {
1184
+ if (!mapInstance) return;
1185
+ mapInstance.setView([coordinates.lat, coordinates.lon], zoom2 ?? mapInstance.getZoom(), {
1186
+ animate: true
1187
+ });
1188
+ },
1189
+ getLayerSnapshot: () => {
1190
+ return effectiveStates.map((state) => ({
1191
+ layerId: state.layerId,
1192
+ visible: state.visible,
1193
+ opacity: state.opacity
1194
+ }));
1195
+ },
1196
+ restoreLayerSnapshot: (snapshot) => {
1197
+ const overrides = snapshot.map((s) => ({
1198
+ layerId: s.layerId,
1199
+ overrideVisible: s.visible,
1200
+ overrideOpacity: s.opacity
1201
+ }));
1202
+ setUiOverrides(overrides);
1203
+ },
1204
+ highlightFeature: (layerId, featureId) => {
1205
+ upsertUiOverride(layerId, { overrideVisible: true, overrideOpacity: 1 });
1206
+ },
1207
+ getMapInstance: () => mapInstance
1208
+ }), [effectiveStates, mapInstance]);
1209
+ if (loadingMap) {
1210
+ return /* @__PURE__ */ jsx("div", { style: { padding: 16, height, width }, children: "Cargando mapa..." });
1211
+ }
1212
+ if (mapError) {
1213
+ return /* @__PURE__ */ jsxs("div", { style: { padding: 16, height, width, color: "red" }, children: [
1214
+ "Error al cargar mapa: ",
1215
+ mapError
1216
+ ] });
1217
+ }
1218
+ if (!map) {
1219
+ return null;
1220
+ }
1221
+ const handleZoomChange = (zoomValue) => {
1222
+ setCurrentZoom(zoomValue);
1223
+ onZoomChange?.(zoomValue);
1224
+ };
1225
+ return /* @__PURE__ */ jsxs(
1226
+ "div",
1227
+ {
1228
+ style: {
1229
+ display: "flex",
1230
+ height,
1231
+ width,
1232
+ border: "1px solid #e2e8f0",
1233
+ borderRadius: 4,
1234
+ overflow: "hidden",
1235
+ boxSizing: "border-box"
1236
+ },
1237
+ children: [
1238
+ /* @__PURE__ */ jsx("div", { style: { flex: 1, position: "relative" }, children: /* @__PURE__ */ jsxs(
1239
+ MapContainer,
1240
+ {
1241
+ center,
1242
+ zoom,
1243
+ style: { height: "100%", width: "100%" },
1244
+ scrollWheelZoom: true,
1245
+ zoomControl: false,
1246
+ children: [
1247
+ /* @__PURE__ */ jsx(
1248
+ TileLayer,
1249
+ {
1250
+ url: "https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png",
1251
+ attribution: "\xA9 OpenStreetMap contributors"
1252
+ }
1253
+ ),
1254
+ /* @__PURE__ */ jsx(ZoomControl, { position: "topright" }),
1255
+ /* @__PURE__ */ jsx(MapInstanceBridge, { onReady: handleMapReady }),
1256
+ /* @__PURE__ */ jsx(FitToBounds, { bbox: explicitZoomBBox ?? void 0 }),
1257
+ /* @__PURE__ */ jsx(AutoFitToBounds, { bbox: autoZoomBBox ?? void 0, enabled: !explicitZoomBBox }),
1258
+ /* @__PURE__ */ jsx(ZoomBasedOpacityHandler, { onZoomChange: handleZoomChange }),
1259
+ orderedLayers.map((layerState) => {
1260
+ const baseOpacity = layerState.effective?.baseOpacity ?? layerState.effective?.opacity ?? 1;
1261
+ const fillPaneName = `zenit-layer-${layerState.mapLayer.layerId}-fill`;
1262
+ const pointsPaneName = `zenit-layer-${layerState.mapLayer.layerId}-points`;
1263
+ const labelPaneName = `zenit-layer-${layerState.mapLayer.layerId}-labels`;
1264
+ const layerType = layerState.layer?.layerType ?? layerState.mapLayer.layerType ?? void 0;
1265
+ const data = layerState.data?.features ?? [];
1266
+ const fillFeatures = data.filter(isNonPointGeometry);
1267
+ const pointFeatures = data.filter(isPointGeometry);
1268
+ const fillData = fillFeatures.length > 0 ? buildFeatureCollection(fillFeatures) : null;
1269
+ const pointsData = pointFeatures.length > 0 ? buildFeatureCollection(pointFeatures) : null;
1270
+ return /* @__PURE__ */ jsxs(React.Fragment, { children: [
1271
+ fillData && /* @__PURE__ */ jsx(
1272
+ GeoJSON,
1273
+ {
1274
+ data: fillData,
1275
+ pane: panesReady && mapInstance?.getPane(fillPaneName) ? fillPaneName : void 0,
1276
+ style: (feature) => buildLayerStyle(layerState.mapLayer.layerId, baseOpacity, feature, layerType),
1277
+ onEachFeature: overlayOnEachFeature
1278
+ }
1279
+ ),
1280
+ pointsData && /* @__PURE__ */ jsx(
1281
+ GeoJSON,
1282
+ {
1283
+ data: pointsData,
1284
+ pane: panesReady && mapInstance?.getPane(pointsPaneName) ? pointsPaneName : void 0,
1285
+ pointToLayer: (feature, latlng) => L.circleMarker(latlng, {
1286
+ radius: isMobile ? 8 : 6,
1287
+ ...buildLayerStyle(layerState.mapLayer.layerId, baseOpacity, feature, layerType)
1288
+ }),
1289
+ onEachFeature: overlayOnEachFeature
1290
+ }
1291
+ ),
1292
+ panesReady && mapInstance?.getPane(labelPaneName) ? labelMarkers.filter(
1293
+ (marker) => String(marker.layerId) === String(layerState.mapLayer.layerId)
1294
+ ).map((marker) => /* @__PURE__ */ jsx(
1295
+ Marker,
1296
+ {
1297
+ position: marker.position,
1298
+ icon: buildLabelIcon(marker.label, marker.opacity, marker.color),
1299
+ interactive: false,
1300
+ pane: labelPaneName
1301
+ },
1302
+ marker.key
1303
+ )) : null
1304
+ ] }, layerState.mapLayer.layerId.toString());
1305
+ }),
1306
+ overlayGeojson && /* @__PURE__ */ jsx(
1307
+ GeoJSON,
1308
+ {
1309
+ data: overlayGeojson,
1310
+ style: overlayStyleFunction,
1311
+ onEachFeature: overlayOnEachFeature
1312
+ },
1313
+ "zenit-overlay-geojson"
1314
+ )
1315
+ ]
1316
+ },
1317
+ String(mapId)
1318
+ ) }),
1319
+ showLayerPanel && decoratedLayers.length > 0 && /* @__PURE__ */ jsxs(
1320
+ "div",
1321
+ {
1322
+ style: {
1323
+ width: 260,
1324
+ borderLeft: "1px solid #e2e8f0",
1325
+ padding: "12px 16px",
1326
+ background: "#fafafa",
1327
+ fontFamily: 'system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif',
1328
+ fontSize: 14,
1329
+ overflowY: "auto"
1330
+ },
1331
+ children: [
1332
+ overlayGeojson && /* @__PURE__ */ jsxs(
1333
+ "div",
1334
+ {
1335
+ style: {
1336
+ border: "1px solid #bfdbfe",
1337
+ background: "#eff6ff",
1338
+ color: "#1e40af",
1339
+ padding: "8px 10px",
1340
+ borderRadius: 8,
1341
+ marginBottom: 12
1342
+ },
1343
+ children: [
1344
+ /* @__PURE__ */ jsx("div", { style: { fontWeight: 600, marginBottom: 4 }, children: "Overlay activo" }),
1345
+ /* @__PURE__ */ jsxs("div", { style: { fontSize: 13 }, children: [
1346
+ "GeoJSON externo con ",
1347
+ (overlayGeojson.features?.length ?? 0).toLocaleString(),
1348
+ " elementos."
1349
+ ] })
1350
+ ]
1351
+ }
1352
+ ),
1353
+ /* @__PURE__ */ jsx("div", { style: { fontWeight: 600, marginBottom: 12 }, children: "Capas" }),
1354
+ decoratedLayers.map((layerState) => /* @__PURE__ */ jsxs(
1355
+ "div",
1356
+ {
1357
+ style: { borderBottom: "1px solid #e5e7eb", paddingBottom: 10, marginBottom: 10 },
1358
+ children: [
1359
+ /* @__PURE__ */ jsxs("label", { style: { display: "flex", gap: 8, alignItems: "center" }, children: [
1360
+ /* @__PURE__ */ jsx(
1361
+ "input",
1362
+ {
1363
+ type: "checkbox",
1364
+ checked: layerState.effective?.visible ?? false,
1365
+ onChange: (e) => {
1366
+ const visible = e.target.checked;
1367
+ upsertUiOverride(layerState.mapLayer.layerId, { overrideVisible: visible });
1368
+ }
1369
+ }
1370
+ ),
1371
+ /* @__PURE__ */ jsx("span", { children: layerState.layer?.name ?? `Capa ${layerState.mapLayer.layerId}` })
1372
+ ] }),
1373
+ /* @__PURE__ */ jsxs("div", { style: { marginTop: 8 }, children: [
1374
+ /* @__PURE__ */ jsxs("div", { style: { display: "flex", justifyContent: "space-between", marginBottom: 4 }, children: [
1375
+ /* @__PURE__ */ jsx("span", { style: { color: "#4a5568" }, children: "Opacidad" }),
1376
+ /* @__PURE__ */ jsxs("span", { children: [
1377
+ Math.round((layerState.effective?.opacity ?? 1) * 100),
1378
+ "%"
1379
+ ] })
1380
+ ] }),
1381
+ /* @__PURE__ */ jsx(
1382
+ "input",
1383
+ {
1384
+ type: "range",
1385
+ min: 0,
1386
+ max: 1,
1387
+ step: 0.05,
1388
+ value: layerState.effective?.opacity ?? 1,
1389
+ onChange: (e) => {
1390
+ const value = Number(e.target.value);
1391
+ updateOpacityFromUi(layerState.mapLayer.layerId, value);
1392
+ },
1393
+ style: { width: "100%" }
1394
+ }
1395
+ )
1396
+ ] })
1397
+ ]
1398
+ },
1399
+ layerState.mapLayer.layerId.toString()
1400
+ ))
1401
+ ]
1402
+ }
1403
+ )
1404
+ ]
1405
+ }
1406
+ );
1407
+ });
1408
+ ZenitMap.displayName = "ZenitMap";
1409
+
1410
+ // src/react/ZenitLayerManager.tsx
1411
+ import React2, { useEffect as useEffect2, useMemo as useMemo2, useRef as useRef2, useState as useState2 } from "react";
1412
+
1413
+ // src/react/icons.tsx
1414
+ import { Eye, EyeOff, ChevronLeft, ChevronRight, Layers, Upload, X, ZoomIn } from "lucide-react";
1415
+
1416
+ // src/react/ZenitLayerManager.tsx
1417
+ import { jsx as jsx2, jsxs as jsxs2 } from "react/jsx-runtime";
1418
+ var FLOAT_TOLERANCE = 1e-3;
1419
+ function areEffectiveStatesEqual(a, b) {
1420
+ if (a.length !== b.length) return false;
1421
+ return a.every((state, index) => {
1422
+ const other = b[index];
1423
+ if (!other) return false;
1424
+ const opacityDiff = Math.abs((state.opacity ?? 1) - (other.opacity ?? 1));
1425
+ return String(state.layerId) === String(other.layerId) && (state.visible ?? false) === (other.visible ?? false) && opacityDiff <= FLOAT_TOLERANCE;
1426
+ });
1427
+ }
1428
+ function getLayerColor2(style) {
1429
+ if (!style) return "#94a3b8";
1430
+ return style.fillColor ?? style.color ?? "#94a3b8";
1431
+ }
1432
+ function resolveDisplayOrder(value) {
1433
+ if (typeof value === "number" && Number.isFinite(value)) return value;
1434
+ if (typeof value === "string") {
1435
+ const parsed = Number.parseFloat(value);
1436
+ if (Number.isFinite(parsed)) return parsed;
1437
+ }
1438
+ return 0;
1439
+ }
1440
+ var ZenitLayerManager = ({
1441
+ client,
1442
+ mapId,
1443
+ side = "right",
1444
+ className,
1445
+ style,
1446
+ height,
1447
+ layerStates,
1448
+ onLayerStatesChange,
1449
+ mapZoom,
1450
+ autoOpacityOnZoom = false,
1451
+ autoOpacityConfig,
1452
+ showUploadTab = true,
1453
+ showLayerVisibilityIcon = true,
1454
+ layerFeatureCounts,
1455
+ mapLayers
1456
+ }) => {
1457
+ const [map, setMap] = useState2(null);
1458
+ const [loadingMap, setLoadingMap] = useState2(false);
1459
+ const [mapError, setMapError] = useState2(null);
1460
+ const [layers, setLayers] = useState2([]);
1461
+ const [activeTab, setActiveTab] = useState2("layers");
1462
+ const [panelVisible, setPanelVisible] = useState2(true);
1463
+ const lastEmittedStatesRef = useRef2(null);
1464
+ const isControlled = Array.isArray(layerStates) && typeof onLayerStatesChange === "function";
1465
+ const baseStates = useMemo2(
1466
+ () => initLayerStates(
1467
+ layers.map((entry) => ({
1468
+ ...entry.mapLayer,
1469
+ layerId: entry.mapLayer.layerId,
1470
+ isVisible: entry.visible,
1471
+ opacity: entry.opacity
1472
+ }))
1473
+ ),
1474
+ [layers]
1475
+ );
1476
+ const overrideStates = useMemo2(
1477
+ () => layers.map(
1478
+ (entry) => ({
1479
+ layerId: entry.mapLayer.layerId,
1480
+ overrideVisible: entry.visible,
1481
+ overrideOpacity: entry.opacity
1482
+ })
1483
+ ),
1484
+ [layers]
1485
+ );
1486
+ const effectiveStates = useMemo2(
1487
+ () => layerStates ?? applyLayerOverrides(baseStates, overrideStates),
1488
+ [baseStates, layerStates, overrideStates]
1489
+ );
1490
+ const layerMetaIndex = useMemo2(() => {
1491
+ const index = /* @__PURE__ */ new Map();
1492
+ mapLayers?.forEach((entry) => {
1493
+ const key = String(entry.layerId);
1494
+ index.set(key, { layerType: entry.layerType ?? void 0, geometryType: entry.geometryType ?? void 0 });
1495
+ });
1496
+ map?.mapLayers?.forEach((entry) => {
1497
+ const key = String(entry.layerId);
1498
+ if (!index.has(key)) {
1499
+ index.set(key, { layerType: entry.layerType ?? void 0, geometryType: entry.geometryType ?? void 0 });
1500
+ }
1501
+ });
1502
+ return index;
1503
+ }, [map, mapLayers]);
1504
+ const resolveUserOpacity = React2.useCallback((state) => {
1505
+ if (typeof state.overrideOpacity === "number") return state.overrideOpacity;
1506
+ if (typeof state.overrideOpacity === "string") {
1507
+ const parsed = Number.parseFloat(state.overrideOpacity);
1508
+ if (Number.isFinite(parsed)) return parsed;
1509
+ }
1510
+ return state.opacity ?? 1;
1511
+ }, []);
1512
+ const resolveEffectiveOpacity = React2.useCallback(
1513
+ (layerId, userOpacity) => {
1514
+ if (!autoOpacityOnZoom || typeof mapZoom !== "number") {
1515
+ return userOpacity;
1516
+ }
1517
+ const meta = layerMetaIndex.get(String(layerId));
1518
+ return getEffectiveLayerOpacity(
1519
+ userOpacity,
1520
+ mapZoom,
1521
+ meta?.layerType,
1522
+ meta?.geometryType,
1523
+ autoOpacityConfig
1524
+ );
1525
+ },
1526
+ [autoOpacityConfig, autoOpacityOnZoom, layerMetaIndex, mapZoom]
1527
+ );
1528
+ const effectiveStatesWithZoom = useMemo2(() => {
1529
+ if (!autoOpacityOnZoom || typeof mapZoom !== "number") {
1530
+ return effectiveStates;
1531
+ }
1532
+ return effectiveStates.map((state) => {
1533
+ const userOpacity = resolveUserOpacity(state);
1534
+ const adjustedOpacity = resolveEffectiveOpacity(state.layerId, userOpacity);
1535
+ return {
1536
+ ...state,
1537
+ opacity: adjustedOpacity,
1538
+ overrideOpacity: userOpacity
1539
+ };
1540
+ });
1541
+ }, [autoOpacityOnZoom, effectiveStates, mapZoom, resolveEffectiveOpacity, resolveUserOpacity]);
1542
+ useEffect2(() => {
1543
+ let cancelled = false;
1544
+ setLoadingMap(true);
1545
+ setMapError(null);
1546
+ setLayers([]);
1547
+ client.maps.getMap(mapId, true).then((mapResponse) => {
1548
+ if (cancelled) return;
1549
+ const extractedMap = extractMapDto(mapResponse);
1550
+ const resolvedMap = extractedMap ? normalizeMapCenter(extractedMap) : null;
1551
+ setMap(resolvedMap);
1552
+ const normalizedLayers = normalizeMapLayers(resolvedMap);
1553
+ setLayers(
1554
+ normalizedLayers.map((entry, index) => ({
1555
+ mapLayer: { ...entry.mapLayer, layerId: entry.layerId },
1556
+ layer: entry.layer,
1557
+ visible: entry.isVisible,
1558
+ opacity: entry.opacity,
1559
+ displayOrder: entry.displayOrder,
1560
+ initialIndex: index
1561
+ }))
1562
+ );
1563
+ }).catch((err) => {
1564
+ if (cancelled) return;
1565
+ const message = err instanceof Error ? err.message : "No se pudo cargar el mapa";
1566
+ setMapError(message);
1567
+ }).finally(() => {
1568
+ if (!cancelled) setLoadingMap(false);
1569
+ });
1570
+ return () => {
1571
+ cancelled = true;
1572
+ };
1573
+ }, [client.maps, mapId]);
1574
+ useEffect2(() => {
1575
+ if (!showUploadTab && activeTab === "upload") {
1576
+ setActiveTab("layers");
1577
+ }
1578
+ }, [activeTab, showUploadTab]);
1579
+ useEffect2(() => {
1580
+ if (isControlled) return;
1581
+ if (!onLayerStatesChange) return;
1582
+ const emitStates = autoOpacityOnZoom && typeof mapZoom === "number" ? effectiveStatesWithZoom : effectiveStates;
1583
+ const previous = lastEmittedStatesRef.current;
1584
+ if (previous && areEffectiveStatesEqual(previous, emitStates)) {
1585
+ return;
1586
+ }
1587
+ lastEmittedStatesRef.current = emitStates;
1588
+ onLayerStatesChange(emitStates);
1589
+ }, [
1590
+ autoOpacityOnZoom,
1591
+ effectiveStates,
1592
+ effectiveStatesWithZoom,
1593
+ isControlled,
1594
+ mapZoom,
1595
+ onLayerStatesChange
1596
+ ]);
1597
+ const updateLayerVisible = React2.useCallback(
1598
+ (layerId, visible) => {
1599
+ if (!onLayerStatesChange) return;
1600
+ const next = effectiveStates.map(
1601
+ (state) => state.layerId === layerId ? { ...state, visible, overrideVisible: visible } : state
1602
+ );
1603
+ onLayerStatesChange(next);
1604
+ },
1605
+ [effectiveStates, onLayerStatesChange]
1606
+ );
1607
+ const updateLayerOpacity = React2.useCallback(
1608
+ (layerId, opacity) => {
1609
+ if (!onLayerStatesChange) return;
1610
+ const adjustedOpacity = resolveEffectiveOpacity(layerId, opacity);
1611
+ const next = effectiveStates.map(
1612
+ (state) => state.layerId === layerId ? { ...state, opacity: adjustedOpacity, overrideOpacity: opacity } : state
1613
+ );
1614
+ onLayerStatesChange(next);
1615
+ },
1616
+ [effectiveStates, onLayerStatesChange, resolveEffectiveOpacity]
1617
+ );
1618
+ const resolveFeatureCount = React2.useCallback(
1619
+ (layerId, layer) => {
1620
+ const resolvedFeatureCount = layerFeatureCounts?.[layerId] ?? layerFeatureCounts?.[String(layerId)];
1621
+ if (typeof resolvedFeatureCount === "number") return resolvedFeatureCount;
1622
+ const featureCount = layer?.featuresCount ?? layer?.featureCount ?? layer?.totalFeatures;
1623
+ return typeof featureCount === "number" ? featureCount : null;
1624
+ },
1625
+ [layerFeatureCounts]
1626
+ );
1627
+ const decoratedLayers = useMemo2(() => {
1628
+ return layers.map((entry) => ({
1629
+ ...entry,
1630
+ effective: effectiveStates.find((state) => state.layerId === entry.mapLayer.layerId),
1631
+ featureCount: resolveFeatureCount(entry.mapLayer.layerId, entry.layer),
1632
+ layerName: entry.layer?.name ?? entry.mapLayer.name ?? `Capa ${entry.mapLayer.layerId}`
1633
+ })).sort((a, b) => {
1634
+ const aOrder = resolveDisplayOrder(
1635
+ a.displayOrder ?? a.mapLayer.displayOrder ?? a.mapLayer.order
1636
+ );
1637
+ const bOrder = resolveDisplayOrder(
1638
+ b.displayOrder ?? b.mapLayer.displayOrder ?? b.mapLayer.order
1639
+ );
1640
+ const aHasOrder = a.displayOrder ?? a.mapLayer.displayOrder ?? a.mapLayer.order ?? null;
1641
+ const bHasOrder = b.displayOrder ?? b.mapLayer.displayOrder ?? b.mapLayer.order ?? null;
1642
+ if (aHasOrder !== null && bHasOrder !== null) {
1643
+ const orderCompare = aOrder - bOrder;
1644
+ if (orderCompare !== 0) return orderCompare;
1645
+ }
1646
+ const aInitial = a.initialIndex ?? 0;
1647
+ const bInitial = b.initialIndex ?? 0;
1648
+ if (aInitial !== bInitial) return aInitial - bInitial;
1649
+ const aName = a.layerName ?? String(a.mapLayer.layerId);
1650
+ const bName = b.layerName ?? String(b.mapLayer.layerId);
1651
+ const nameCompare = aName.localeCompare(bName, void 0, { sensitivity: "base" });
1652
+ if (nameCompare !== 0) return nameCompare;
1653
+ return String(a.mapLayer.layerId).localeCompare(String(b.mapLayer.layerId));
1654
+ });
1655
+ }, [effectiveStates, layers, resolveFeatureCount]);
1656
+ const resolveLayerStyle = React2.useCallback(
1657
+ (layerId) => {
1658
+ const layerKey = String(layerId);
1659
+ const fromProp = mapLayers?.find((entry) => String(entry.layerId) === layerKey)?.style;
1660
+ if (fromProp) return fromProp;
1661
+ const fromMapDto = map?.mapLayers?.find((entry) => String(entry.layerId) === layerKey);
1662
+ if (fromMapDto?.layer) {
1663
+ const layer = fromMapDto.layer;
1664
+ if (layer.style) return layer.style;
1665
+ }
1666
+ return void 0;
1667
+ },
1668
+ [map, mapLayers]
1669
+ );
1670
+ const panelStyle = {
1671
+ width: 360,
1672
+ borderLeft: side === "right" ? "1px solid #e2e8f0" : void 0,
1673
+ borderRight: side === "left" ? "1px solid #e2e8f0" : void 0,
1674
+ background: "#f1f5f9",
1675
+ fontFamily: 'system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif',
1676
+ fontSize: 14,
1677
+ boxSizing: "border-box",
1678
+ height: height ?? "100%",
1679
+ display: "flex",
1680
+ flexDirection: "column",
1681
+ boxShadow: "0 12px 28px rgba(15, 23, 42, 0.08)",
1682
+ ...style,
1683
+ ...height ? { height } : {}
1684
+ };
1685
+ if (loadingMap) {
1686
+ return /* @__PURE__ */ jsx2("div", { className, style: panelStyle, children: "Cargando capas\u2026" });
1687
+ }
1688
+ if (mapError) {
1689
+ return /* @__PURE__ */ jsxs2("div", { className, style: { ...panelStyle, color: "#c53030" }, children: [
1690
+ "Error al cargar mapa: ",
1691
+ mapError
1692
+ ] });
1693
+ }
1694
+ if (!map) {
1695
+ return null;
1696
+ }
1697
+ const headerStyle = {
1698
+ padding: "14px 16px",
1699
+ borderBottom: "1px solid #e2e8f0",
1700
+ background: "#fff",
1701
+ position: "sticky",
1702
+ top: 0,
1703
+ zIndex: 2,
1704
+ boxShadow: "0 1px 0 rgba(148, 163, 184, 0.25)"
1705
+ };
1706
+ const renderLayerCards = () => {
1707
+ return /* @__PURE__ */ jsx2("div", { style: { display: "flex", flexDirection: "column", gap: 12 }, children: decoratedLayers.map((layerState) => {
1708
+ const layerId = layerState.mapLayer.layerId;
1709
+ const layerName = layerState.layerName ?? `Capa ${layerId}`;
1710
+ const visible = layerState.effective?.visible ?? false;
1711
+ const userOpacity = layerState.effective ? resolveUserOpacity(layerState.effective) : 1;
1712
+ const featureCount = layerState.featureCount;
1713
+ const layerColor = getLayerColor2(resolveLayerStyle(layerId));
1714
+ const muted = !visible;
1715
+ const opacityPercent = Math.round(userOpacity * 100);
1716
+ const sliderBackground = `linear-gradient(to right, ${layerColor} 0%, ${layerColor} ${opacityPercent}%, #e5e7eb ${opacityPercent}%, #e5e7eb 100%)`;
1717
+ return /* @__PURE__ */ jsxs2(
1718
+ "div",
1719
+ {
1720
+ className: `zlm-card${muted ? " is-muted" : ""}`,
1721
+ style: {
1722
+ border: "1px solid #e2e8f0",
1723
+ borderRadius: 12,
1724
+ padding: 12,
1725
+ background: "#fff",
1726
+ display: "flex",
1727
+ flexDirection: "column",
1728
+ gap: 10,
1729
+ width: "100%"
1730
+ },
1731
+ children: [
1732
+ /* @__PURE__ */ jsxs2("div", { style: { display: "flex", justifyContent: "space-between", gap: 12 }, children: [
1733
+ /* @__PURE__ */ jsxs2("div", { style: { display: "flex", gap: 10, alignItems: "flex-start", minWidth: 0, flex: 1 }, children: [
1734
+ /* @__PURE__ */ jsx2(
1735
+ "div",
1736
+ {
1737
+ style: {
1738
+ width: 14,
1739
+ height: 14,
1740
+ borderRadius: "50%",
1741
+ backgroundColor: layerColor,
1742
+ border: "2px solid #e2e8f0",
1743
+ flexShrink: 0,
1744
+ marginTop: 4
1745
+ },
1746
+ title: "Color de la capa"
1747
+ }
1748
+ ),
1749
+ showLayerVisibilityIcon && /* @__PURE__ */ jsx2(
1750
+ "button",
1751
+ {
1752
+ type: "button",
1753
+ className: `zlm-icon-button${visible ? " is-active" : ""}`,
1754
+ onClick: () => isControlled ? updateLayerVisible(layerId, !visible) : setLayers(
1755
+ (prev) => prev.map(
1756
+ (entry) => entry.mapLayer.layerId === layerId ? { ...entry, visible: !visible } : entry
1757
+ )
1758
+ ),
1759
+ "aria-label": visible ? "Ocultar capa" : "Mostrar capa",
1760
+ children: visible ? /* @__PURE__ */ jsx2(Eye, { size: 16 }) : /* @__PURE__ */ jsx2(EyeOff, { size: 16 })
1761
+ }
1762
+ ),
1763
+ /* @__PURE__ */ jsxs2("div", { style: { minWidth: 0, flex: 1 }, children: [
1764
+ /* @__PURE__ */ jsx2(
1765
+ "div",
1766
+ {
1767
+ className: "zlm-layer-name",
1768
+ style: {
1769
+ fontWeight: 700,
1770
+ display: "-webkit-box",
1771
+ WebkitLineClamp: 2,
1772
+ WebkitBoxOrient: "vertical",
1773
+ overflow: "hidden",
1774
+ overflowWrap: "anywhere",
1775
+ lineHeight: 1.2,
1776
+ color: muted ? "#64748b" : "#0f172a"
1777
+ },
1778
+ title: layerName,
1779
+ children: layerName
1780
+ }
1781
+ ),
1782
+ /* @__PURE__ */ jsxs2("div", { style: { color: muted ? "#94a3b8" : "#64748b", fontSize: 12 }, children: [
1783
+ "ID ",
1784
+ layerId
1785
+ ] })
1786
+ ] })
1787
+ ] }),
1788
+ /* @__PURE__ */ jsx2("div", { style: { display: "flex", alignItems: "flex-start", gap: 6, flexShrink: 0 }, children: typeof featureCount === "number" && /* @__PURE__ */ jsxs2("span", { className: "zlm-badge", children: [
1789
+ featureCount.toLocaleString(),
1790
+ " features"
1791
+ ] }) })
1792
+ ] }),
1793
+ /* @__PURE__ */ jsx2("div", { style: { display: "flex", gap: 10, alignItems: "center" }, children: /* @__PURE__ */ jsxs2("div", { style: { flex: 1 }, children: [
1794
+ /* @__PURE__ */ jsxs2("div", { style: { display: "flex", justifyContent: "space-between", marginBottom: 6, color: "#64748b", fontSize: 12 }, children: [
1795
+ /* @__PURE__ */ jsx2("span", { children: "Opacidad" }),
1796
+ /* @__PURE__ */ jsxs2("span", { children: [
1797
+ opacityPercent,
1798
+ "%"
1799
+ ] })
1800
+ ] }),
1801
+ /* @__PURE__ */ jsx2(
1802
+ "input",
1803
+ {
1804
+ className: "zlm-range",
1805
+ type: "range",
1806
+ min: 0,
1807
+ max: 1,
1808
+ step: 0.05,
1809
+ value: userOpacity,
1810
+ style: {
1811
+ width: "100%",
1812
+ accentColor: layerColor,
1813
+ background: sliderBackground,
1814
+ height: 6,
1815
+ borderRadius: 999
1816
+ },
1817
+ onChange: (e) => {
1818
+ const value = Number(e.target.value);
1819
+ if (isControlled) {
1820
+ updateLayerOpacity(layerId, value);
1821
+ return;
1822
+ }
1823
+ setLayers(
1824
+ (prev) => prev.map(
1825
+ (entry) => entry.mapLayer.layerId === layerId ? { ...entry, opacity: value } : entry
1826
+ )
1827
+ );
1828
+ },
1829
+ "aria-label": `Opacidad de la capa ${layerName}`
1830
+ }
1831
+ )
1832
+ ] }) })
1833
+ ]
1834
+ },
1835
+ layerId.toString()
1836
+ );
1837
+ }) });
1838
+ };
1839
+ return /* @__PURE__ */ jsxs2("div", { className: ["zenit-layer-manager", className].filter(Boolean).join(" "), style: panelStyle, children: [
1840
+ /* @__PURE__ */ jsx2("style", { children: `
1841
+ .zenit-layer-manager .zlm-card {
1842
+ transition: box-shadow 0.2s ease, transform 0.2s ease, opacity 0.2s ease;
1843
+ box-shadow: 0 6px 16px rgba(15, 23, 42, 0.08);
1844
+ }
1845
+ .zenit-layer-manager .zlm-card.is-muted {
1846
+ opacity: 0.7;
1847
+ }
1848
+ .zenit-layer-manager .zlm-badge {
1849
+ display: inline-flex;
1850
+ align-items: center;
1851
+ gap: 4px;
1852
+ margin-top: 6px;
1853
+ padding: 2px 8px;
1854
+ border-radius: 999px;
1855
+ background: #f1f5f9;
1856
+ color: #475569;
1857
+ font-size: 11px;
1858
+ font-weight: 600;
1859
+ }
1860
+ .zenit-layer-manager .zlm-icon-button {
1861
+ border: 1px solid #e2e8f0;
1862
+ background: #f8fafc;
1863
+ color: #475569;
1864
+ border-radius: 8px;
1865
+ width: 34px;
1866
+ height: 34px;
1867
+ display: inline-flex;
1868
+ align-items: center;
1869
+ justify-content: center;
1870
+ cursor: pointer;
1871
+ transition: all 0.15s ease;
1872
+ }
1873
+ .zenit-layer-manager .zlm-icon-button.is-active {
1874
+ background: #0f172a;
1875
+ color: #fff;
1876
+ border-color: #0f172a;
1877
+ }
1878
+ .zenit-layer-manager .zlm-icon-button:hover {
1879
+ box-shadow: 0 4px 10px rgba(15, 23, 42, 0.12);
1880
+ }
1881
+ .zenit-layer-manager .zlm-icon-button:focus-visible {
1882
+ outline: 2px solid #60a5fa;
1883
+ outline-offset: 2px;
1884
+ }
1885
+ .zenit-layer-manager .zlm-range {
1886
+ width: 100%;
1887
+ accent-color: #0f172a;
1888
+ }
1889
+ .zenit-layer-manager .zlm-tab {
1890
+ flex: 1;
1891
+ padding: 8px 12px;
1892
+ border: none;
1893
+ background: transparent;
1894
+ color: #475569;
1895
+ font-weight: 600;
1896
+ cursor: pointer;
1897
+ display: inline-flex;
1898
+ align-items: center;
1899
+ justify-content: center;
1900
+ gap: 6px;
1901
+ font-size: 13px;
1902
+ }
1903
+ .zenit-layer-manager .zlm-tab.is-active {
1904
+ background: #fff;
1905
+ color: #0f172a;
1906
+ box-shadow: 0 4px 10px rgba(15, 23, 42, 0.08);
1907
+ border-radius: 10px;
1908
+ }
1909
+ .zenit-layer-manager .zlm-tab:focus-visible {
1910
+ outline: 2px solid #60a5fa;
1911
+ outline-offset: 2px;
1912
+ }
1913
+ .zenit-layer-manager .zlm-panel-toggle {
1914
+ border: 1px solid #e2e8f0;
1915
+ background: #fff;
1916
+ color: #0f172a;
1917
+ border-radius: 10px;
1918
+ padding: 6px 10px;
1919
+ display: inline-flex;
1920
+ align-items: center;
1921
+ gap: 6px;
1922
+ font-size: 12px;
1923
+ font-weight: 600;
1924
+ cursor: pointer;
1925
+ transition: all 0.15s ease;
1926
+ }
1927
+ .zenit-layer-manager .zlm-panel-toggle:hover {
1928
+ box-shadow: 0 4px 10px rgba(15, 23, 42, 0.12);
1929
+ }
1930
+ .zenit-layer-manager .zlm-panel-toggle:focus-visible {
1931
+ outline: 2px solid #60a5fa;
1932
+ outline-offset: 2px;
1933
+ }
1934
+ ` }),
1935
+ /* @__PURE__ */ jsxs2("div", { style: headerStyle, children: [
1936
+ /* @__PURE__ */ jsxs2("div", { style: { display: "flex", justifyContent: "space-between", alignItems: "center" }, children: [
1937
+ /* @__PURE__ */ jsxs2("div", { children: [
1938
+ /* @__PURE__ */ jsx2("div", { style: { fontWeight: 800, fontSize: 16, color: "#0f172a" }, children: "Gesti\xF3n de Capas" }),
1939
+ /* @__PURE__ */ jsxs2("div", { style: { color: "#64748b", fontSize: 12 }, children: [
1940
+ "Mapa #",
1941
+ map.id
1942
+ ] })
1943
+ ] }),
1944
+ /* @__PURE__ */ jsxs2(
1945
+ "button",
1946
+ {
1947
+ type: "button",
1948
+ onClick: () => setPanelVisible((prev) => !prev),
1949
+ className: "zlm-panel-toggle",
1950
+ "aria-label": panelVisible ? "Ocultar panel de capas" : "Mostrar panel de capas",
1951
+ children: [
1952
+ panelVisible ? /* @__PURE__ */ jsx2(Eye, { size: 16 }) : /* @__PURE__ */ jsx2(EyeOff, { size: 16 }),
1953
+ panelVisible ? "Ocultar" : "Mostrar"
1954
+ ]
1955
+ }
1956
+ )
1957
+ ] }),
1958
+ /* @__PURE__ */ jsxs2(
1959
+ "div",
1960
+ {
1961
+ style: {
1962
+ display: "flex",
1963
+ gap: 6,
1964
+ marginTop: 12,
1965
+ padding: 4,
1966
+ border: "1px solid #e2e8f0",
1967
+ borderRadius: 12,
1968
+ background: "#f1f5f9"
1969
+ },
1970
+ children: [
1971
+ /* @__PURE__ */ jsxs2(
1972
+ "button",
1973
+ {
1974
+ type: "button",
1975
+ className: `zlm-tab${activeTab === "layers" ? " is-active" : ""}`,
1976
+ onClick: () => setActiveTab("layers"),
1977
+ children: [
1978
+ /* @__PURE__ */ jsx2(Layers, { size: 16 }),
1979
+ "Capas"
1980
+ ]
1981
+ }
1982
+ ),
1983
+ showUploadTab && /* @__PURE__ */ jsxs2(
1984
+ "button",
1985
+ {
1986
+ type: "button",
1987
+ className: `zlm-tab${activeTab === "upload" ? " is-active" : ""}`,
1988
+ onClick: () => setActiveTab("upload"),
1989
+ children: [
1990
+ /* @__PURE__ */ jsx2(Upload, { size: 16 }),
1991
+ "Subir"
1992
+ ]
1993
+ }
1994
+ )
1995
+ ]
1996
+ }
1997
+ )
1998
+ ] }),
1999
+ panelVisible && /* @__PURE__ */ jsxs2("div", { style: { padding: "12px 10px 18px", overflowY: "auto", flex: 1, minHeight: 0 }, children: [
2000
+ activeTab === "layers" && renderLayerCards(),
2001
+ showUploadTab && activeTab === "upload" && /* @__PURE__ */ jsx2("div", { style: { color: "#475569", fontSize: 13 }, children: "Pr\xF3ximamente podr\xE1s subir capas desde este panel." })
2002
+ ] })
2003
+ ] });
2004
+ };
2005
+
2006
+ // src/react/ZenitFeatureFilterPanel.tsx
2007
+ import { jsx as jsx3, jsxs as jsxs3 } from "react/jsx-runtime";
2008
+ var ZenitFeatureFilterPanel = ({
2009
+ title = "Filtros",
2010
+ description,
2011
+ className,
2012
+ style,
2013
+ children
2014
+ }) => {
2015
+ return /* @__PURE__ */ jsxs3(
2016
+ "section",
2017
+ {
2018
+ className,
2019
+ style: {
2020
+ border: "1px solid #e2e8f0",
2021
+ borderRadius: 12,
2022
+ padding: 16,
2023
+ background: "#fff",
2024
+ fontFamily: 'system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif',
2025
+ ...style
2026
+ },
2027
+ children: [
2028
+ /* @__PURE__ */ jsxs3("header", { style: { marginBottom: 12 }, children: [
2029
+ /* @__PURE__ */ jsx3("h3", { style: { margin: 0, fontSize: 16 }, children: title }),
2030
+ description && /* @__PURE__ */ jsx3("p", { style: { margin: "6px 0 0", color: "#475569", fontSize: 13 }, children: description })
2031
+ ] }),
2032
+ /* @__PURE__ */ jsx3("div", { children })
2033
+ ]
2034
+ }
2035
+ );
2036
+ };
2037
+
2038
+ // src/react/ai/FloatingChatBox.tsx
2039
+ import { useCallback as useCallback3, useEffect as useEffect3, useMemo as useMemo3, useRef as useRef4, useState as useState4 } from "react";
2040
+ import { createPortal } from "react-dom";
2041
+
2042
+ // src/react/hooks/use-chat.ts
2043
+ import { useCallback as useCallback2, useRef as useRef3, useState as useState3 } from "react";
2044
+
2045
+ // src/ai/chat.service.ts
2046
+ var DEFAULT_ERROR_MESSAGE = "No fue posible completar la solicitud al asistente.";
2047
+ var normalizeBaseUrl = (baseUrl) => baseUrl.replace(/\/$/, "");
2048
+ var resolveBaseUrl = (config, options) => {
2049
+ const baseUrl = options?.baseUrl ?? config?.baseUrl;
2050
+ if (!baseUrl) {
2051
+ throw new Error("baseUrl es requerido para usar el chat de Zenit AI.");
2052
+ }
2053
+ return normalizeBaseUrl(baseUrl);
2054
+ };
2055
+ var resolveAccessToken = async (config, options) => {
2056
+ if (options?.accessToken) return options.accessToken;
2057
+ if (config?.accessToken) return config.accessToken;
2058
+ if (options?.getAccessToken) return await options.getAccessToken();
2059
+ if (config?.getAccessToken) return await config.getAccessToken();
2060
+ return void 0;
2061
+ };
2062
+ var buildAuthHeaders = (token) => {
2063
+ if (!token) return {};
2064
+ return { Authorization: `Bearer ${token}` };
2065
+ };
2066
+ var parseError = async (response) => {
2067
+ try {
2068
+ const contentType = response.headers.get("content-type") ?? "";
2069
+ if (contentType.includes("application/json")) {
2070
+ const payload = await response.json();
2071
+ const message = payload?.message ?? DEFAULT_ERROR_MESSAGE;
2072
+ return new Error(message);
2073
+ }
2074
+ const text = await response.text();
2075
+ return new Error(text || DEFAULT_ERROR_MESSAGE);
2076
+ } catch (error) {
2077
+ return error instanceof Error ? error : new Error(DEFAULT_ERROR_MESSAGE);
2078
+ }
2079
+ };
2080
+ var sendMessage = async (mapId, request, options, config) => {
2081
+ const baseUrl = resolveBaseUrl(config, options);
2082
+ const token = await resolveAccessToken(config, options);
2083
+ const response = await fetch(`${baseUrl}/ai/maps/chat/${mapId}`, {
2084
+ method: "POST",
2085
+ headers: {
2086
+ "Content-Type": "application/json",
2087
+ ...buildAuthHeaders(token)
2088
+ },
2089
+ body: JSON.stringify(request),
2090
+ signal: options?.signal
2091
+ });
2092
+ if (!response.ok) {
2093
+ throw await parseError(response);
2094
+ }
2095
+ return await response.json();
2096
+ };
2097
+ var mergeResponse = (previous, chunk, aggregatedAnswer) => ({
2098
+ ...previous ?? chunk,
2099
+ ...chunk,
2100
+ answer: aggregatedAnswer
2101
+ });
2102
+ var resolveAggregatedAnswer = (current, incoming) => {
2103
+ if (!incoming) return current;
2104
+ if (incoming.startsWith(current)) return incoming;
2105
+ return current + incoming;
2106
+ };
2107
+ var sendMessageStream = async (mapId, request, callbacks = {}, options, config) => {
2108
+ const baseUrl = resolveBaseUrl(config, options);
2109
+ const token = await resolveAccessToken(config, options);
2110
+ const response = await fetch(`${baseUrl}/ai/maps/chat/${mapId}/stream`, {
2111
+ method: "POST",
2112
+ headers: {
2113
+ Accept: "text/event-stream",
2114
+ "Content-Type": "application/json",
2115
+ ...buildAuthHeaders(token)
2116
+ },
2117
+ body: JSON.stringify(request),
2118
+ signal: options?.signal
2119
+ });
2120
+ if (!response.ok) {
2121
+ const error = await parseError(response);
2122
+ callbacks.onError?.(error);
2123
+ throw error;
2124
+ }
2125
+ const reader = response.body?.getReader();
2126
+ if (!reader) {
2127
+ const error = new Error("No se pudo iniciar el streaming de Zenit AI.");
2128
+ callbacks.onError?.(error);
2129
+ throw error;
2130
+ }
2131
+ const decoder = new TextDecoder("utf-8");
2132
+ let buffer = "";
2133
+ let aggregated = "";
2134
+ let latestResponse = null;
2135
+ try {
2136
+ while (true) {
2137
+ const { value, done } = await reader.read();
2138
+ if (done) break;
2139
+ buffer += decoder.decode(value, { stream: true });
2140
+ const lines = buffer.split(/\r?\n/);
2141
+ buffer = lines.pop() ?? "";
2142
+ for (const line of lines) {
2143
+ const trimmed = line.trim();
2144
+ if (!trimmed || trimmed.startsWith("event:")) continue;
2145
+ if (!trimmed.startsWith("data:")) continue;
2146
+ const payload = trimmed.replace(/^data:\s*/, "");
2147
+ if (!payload || payload === "[DONE]") continue;
2148
+ try {
2149
+ const parsed = JSON.parse(payload);
2150
+ aggregated = resolveAggregatedAnswer(aggregated, parsed.answer ?? "");
2151
+ latestResponse = mergeResponse(latestResponse, parsed, aggregated);
2152
+ if (latestResponse) {
2153
+ callbacks.onChunk?.(latestResponse, aggregated);
2154
+ }
2155
+ } catch (error) {
2156
+ callbacks.onError?.(error);
2157
+ }
2158
+ }
2159
+ }
2160
+ } catch (error) {
2161
+ callbacks.onError?.(error);
2162
+ throw error;
2163
+ }
2164
+ if (!latestResponse) {
2165
+ const error = new Error(DEFAULT_ERROR_MESSAGE);
2166
+ callbacks.onError?.(error);
2167
+ throw error;
2168
+ }
2169
+ callbacks.onComplete?.(latestResponse);
2170
+ return latestResponse;
2171
+ };
2172
+ var createChatService = (config) => ({
2173
+ sendMessage: (mapId, request, options) => sendMessage(mapId, request, options, config),
2174
+ sendMessageStream: (mapId, request, callbacks, options) => sendMessageStream(mapId, request, callbacks, options, config)
2175
+ });
2176
+
2177
+ // src/react/hooks/use-chat.ts
2178
+ var useSendMessage = (config) => {
2179
+ const [isLoading, setIsLoading] = useState3(false);
2180
+ const [error, setError] = useState3(null);
2181
+ const send = useCallback2(
2182
+ async (mapId, request, options) => {
2183
+ setIsLoading(true);
2184
+ setError(null);
2185
+ try {
2186
+ return await sendMessage(mapId, request, options, config);
2187
+ } catch (err) {
2188
+ setError(err);
2189
+ throw err;
2190
+ } finally {
2191
+ setIsLoading(false);
2192
+ }
2193
+ },
2194
+ [config]
2195
+ );
2196
+ return { sendMessage: send, isLoading, error };
2197
+ };
2198
+ var useSendMessageStream = (config) => {
2199
+ const [isStreaming, setIsStreaming] = useState3(false);
2200
+ const [streamingText, setStreamingText] = useState3("");
2201
+ const [completeResponse, setCompleteResponse] = useState3(null);
2202
+ const [error, setError] = useState3(null);
2203
+ const requestIdRef = useRef3(0);
2204
+ const reset = useCallback2(() => {
2205
+ setIsStreaming(false);
2206
+ setStreamingText("");
2207
+ setCompleteResponse(null);
2208
+ setError(null);
2209
+ }, []);
2210
+ const send = useCallback2(
2211
+ async (mapId, request, options) => {
2212
+ const requestId = requestIdRef.current + 1;
2213
+ requestIdRef.current = requestId;
2214
+ setIsStreaming(true);
2215
+ setStreamingText("");
2216
+ setCompleteResponse(null);
2217
+ setError(null);
2218
+ try {
2219
+ const response = await sendMessageStream(
2220
+ mapId,
2221
+ request,
2222
+ {
2223
+ onChunk: (_chunk, aggregated) => {
2224
+ if (requestIdRef.current !== requestId) return;
2225
+ setStreamingText(aggregated);
2226
+ },
2227
+ onError: (err) => {
2228
+ if (requestIdRef.current !== requestId) return;
2229
+ setError(err);
2230
+ },
2231
+ onComplete: (finalResponse) => {
2232
+ if (requestIdRef.current !== requestId) return;
2233
+ setCompleteResponse(finalResponse);
2234
+ }
2235
+ },
2236
+ options,
2237
+ config
2238
+ );
2239
+ return response;
2240
+ } catch (err) {
2241
+ setError(err);
2242
+ throw err;
2243
+ } finally {
2244
+ if (requestIdRef.current === requestId) {
2245
+ setIsStreaming(false);
2246
+ }
2247
+ }
2248
+ },
2249
+ [config]
2250
+ );
2251
+ return {
2252
+ sendMessage: send,
2253
+ isStreaming,
2254
+ streamingText,
2255
+ completeResponse,
2256
+ error,
2257
+ reset
2258
+ };
2259
+ };
2260
+
2261
+ // src/react/components/MarkdownRenderer.tsx
2262
+ import ReactMarkdown from "react-markdown";
2263
+ import remarkGfm from "remark-gfm";
2264
+ import { jsx as jsx4 } from "react/jsx-runtime";
2265
+ function normalizeAssistantMarkdown(text) {
2266
+ if (!text || typeof text !== "string") return "";
2267
+ let normalized = text;
2268
+ normalized = normalized.replace(/\r\n/g, "\n");
2269
+ normalized = normalized.replace(/^\s*#{1,6}\s*$/gm, "");
2270
+ normalized = normalized.replace(/\n{3,}/g, "\n\n");
2271
+ normalized = normalized.split("\n").map((line) => line.trimEnd()).join("\n");
2272
+ normalized = normalized.trim();
2273
+ return normalized;
2274
+ }
2275
+ var MarkdownRenderer = ({ content, className }) => {
2276
+ const normalizedContent = normalizeAssistantMarkdown(content);
2277
+ if (!normalizedContent) {
2278
+ return null;
2279
+ }
2280
+ return /* @__PURE__ */ jsx4("div", { className, style: { wordBreak: "break-word" }, children: /* @__PURE__ */ jsx4(
2281
+ ReactMarkdown,
2282
+ {
2283
+ remarkPlugins: [remarkGfm],
2284
+ components: {
2285
+ // Headings with proper spacing
2286
+ h1: ({ children, ...props }) => /* @__PURE__ */ jsx4("h1", { style: { fontSize: "1.5em", fontWeight: 700, marginTop: "1em", marginBottom: "0.5em" }, ...props, children }),
2287
+ h2: ({ children, ...props }) => /* @__PURE__ */ jsx4("h2", { style: { fontSize: "1.3em", fontWeight: 700, marginTop: "0.9em", marginBottom: "0.45em" }, ...props, children }),
2288
+ h3: ({ children, ...props }) => /* @__PURE__ */ jsx4("h3", { style: { fontSize: "1.15em", fontWeight: 600, marginTop: "0.75em", marginBottom: "0.4em" }, ...props, children }),
2289
+ h4: ({ children, ...props }) => /* @__PURE__ */ jsx4("h4", { style: { fontSize: "1.05em", fontWeight: 600, marginTop: "0.6em", marginBottom: "0.35em" }, ...props, children }),
2290
+ h5: ({ children, ...props }) => /* @__PURE__ */ jsx4("h5", { style: { fontSize: "1em", fontWeight: 600, marginTop: "0.5em", marginBottom: "0.3em" }, ...props, children }),
2291
+ h6: ({ children, ...props }) => /* @__PURE__ */ jsx4("h6", { style: { fontSize: "0.95em", fontWeight: 600, marginTop: "0.5em", marginBottom: "0.3em" }, ...props, children }),
2292
+ // Paragraphs with comfortable line height
2293
+ p: ({ children, ...props }) => /* @__PURE__ */ jsx4("p", { style: { marginTop: "0.5em", marginBottom: "0.5em", lineHeight: 1.6 }, ...props, children }),
2294
+ // Lists with proper indentation
2295
+ ul: ({ children, ...props }) => /* @__PURE__ */ jsx4("ul", { style: { paddingLeft: "1.5em", marginTop: "0.5em", marginBottom: "0.5em" }, ...props, children }),
2296
+ ol: ({ children, ...props }) => /* @__PURE__ */ jsx4("ol", { style: { paddingLeft: "1.5em", marginTop: "0.5em", marginBottom: "0.5em" }, ...props, children }),
2297
+ li: ({ children, ...props }) => /* @__PURE__ */ jsx4("li", { style: { marginTop: "0.25em", marginBottom: "0.25em" }, ...props, children }),
2298
+ // Code blocks
2299
+ code: ({ inline, children, ...props }) => {
2300
+ if (inline) {
2301
+ return /* @__PURE__ */ jsx4(
2302
+ "code",
2303
+ {
2304
+ style: {
2305
+ backgroundColor: "rgba(0, 0, 0, 0.08)",
2306
+ padding: "0.15em 0.4em",
2307
+ borderRadius: "4px",
2308
+ fontSize: "0.9em",
2309
+ fontFamily: "monospace"
2310
+ },
2311
+ ...props,
2312
+ children
2313
+ }
2314
+ );
2315
+ }
2316
+ return /* @__PURE__ */ jsx4(
2317
+ "code",
2318
+ {
2319
+ style: {
2320
+ display: "block",
2321
+ backgroundColor: "rgba(0, 0, 0, 0.08)",
2322
+ padding: "0.75em",
2323
+ borderRadius: "6px",
2324
+ fontSize: "0.9em",
2325
+ fontFamily: "monospace",
2326
+ overflowX: "auto",
2327
+ marginTop: "0.5em",
2328
+ marginBottom: "0.5em"
2329
+ },
2330
+ ...props,
2331
+ children
2332
+ }
2333
+ );
2334
+ },
2335
+ // Pre (code block wrapper)
2336
+ pre: ({ children, ...props }) => /* @__PURE__ */ jsx4("pre", { style: { margin: 0 }, ...props, children }),
2337
+ // Blockquotes
2338
+ blockquote: ({ children, ...props }) => /* @__PURE__ */ jsx4(
2339
+ "blockquote",
2340
+ {
2341
+ style: {
2342
+ borderLeft: "4px solid rgba(0, 0, 0, 0.2)",
2343
+ paddingLeft: "1em",
2344
+ marginLeft: 0,
2345
+ marginTop: "0.5em",
2346
+ marginBottom: "0.5em",
2347
+ color: "rgba(0, 0, 0, 0.7)"
2348
+ },
2349
+ ...props,
2350
+ children
2351
+ }
2352
+ ),
2353
+ // Strong/bold
2354
+ strong: ({ children, ...props }) => /* @__PURE__ */ jsx4("strong", { style: { fontWeight: 600 }, ...props, children }),
2355
+ // Emphasis/italic
2356
+ em: ({ children, ...props }) => /* @__PURE__ */ jsx4("em", { style: { fontStyle: "italic" }, ...props, children }),
2357
+ // Horizontal rule
2358
+ hr: (props) => /* @__PURE__ */ jsx4(
2359
+ "hr",
2360
+ {
2361
+ style: {
2362
+ border: "none",
2363
+ borderTop: "1px solid rgba(0, 0, 0, 0.1)",
2364
+ marginTop: "1em",
2365
+ marginBottom: "1em"
2366
+ },
2367
+ ...props
2368
+ }
2369
+ ),
2370
+ // Tables (GFM)
2371
+ table: ({ children, ...props }) => /* @__PURE__ */ jsx4("div", { style: { overflowX: "auto", marginTop: "0.5em", marginBottom: "0.5em" }, children: /* @__PURE__ */ jsx4(
2372
+ "table",
2373
+ {
2374
+ style: {
2375
+ borderCollapse: "collapse",
2376
+ width: "100%",
2377
+ fontSize: "0.9em"
2378
+ },
2379
+ ...props,
2380
+ children
2381
+ }
2382
+ ) }),
2383
+ th: ({ children, ...props }) => /* @__PURE__ */ jsx4(
2384
+ "th",
2385
+ {
2386
+ style: {
2387
+ border: "1px solid rgba(0, 0, 0, 0.2)",
2388
+ padding: "0.5em",
2389
+ backgroundColor: "rgba(0, 0, 0, 0.05)",
2390
+ fontWeight: 600,
2391
+ textAlign: "left"
2392
+ },
2393
+ ...props,
2394
+ children
2395
+ }
2396
+ ),
2397
+ td: ({ children, ...props }) => /* @__PURE__ */ jsx4(
2398
+ "td",
2399
+ {
2400
+ style: {
2401
+ border: "1px solid rgba(0, 0, 0, 0.2)",
2402
+ padding: "0.5em"
2403
+ },
2404
+ ...props,
2405
+ children
2406
+ }
2407
+ )
2408
+ },
2409
+ children: normalizedContent
2410
+ }
2411
+ ) });
2412
+ };
2413
+
2414
+ // src/react/ai/FloatingChatBox.tsx
2415
+ import { Fragment, jsx as jsx5, jsxs as jsxs4 } from "react/jsx-runtime";
2416
+ var ChatIcon = () => /* @__PURE__ */ jsx5("svg", { width: "20", height: "20", viewBox: "0 0 24 24", fill: "none", stroke: "currentColor", strokeWidth: "2", strokeLinecap: "round", strokeLinejoin: "round", children: /* @__PURE__ */ jsx5("path", { d: "M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z" }) });
2417
+ var CloseIcon = () => /* @__PURE__ */ jsxs4("svg", { width: "20", height: "20", viewBox: "0 0 24 24", fill: "none", stroke: "currentColor", strokeWidth: "2", strokeLinecap: "round", strokeLinejoin: "round", children: [
2418
+ /* @__PURE__ */ jsx5("line", { x1: "18", y1: "6", x2: "6", y2: "18" }),
2419
+ /* @__PURE__ */ jsx5("line", { x1: "6", y1: "6", x2: "18", y2: "18" })
2420
+ ] });
2421
+ var ExpandIcon = () => /* @__PURE__ */ jsxs4("svg", { width: "18", height: "18", viewBox: "0 0 24 24", fill: "none", stroke: "currentColor", strokeWidth: "2", strokeLinecap: "round", strokeLinejoin: "round", children: [
2422
+ /* @__PURE__ */ jsx5("polyline", { points: "15 3 21 3 21 9" }),
2423
+ /* @__PURE__ */ jsx5("polyline", { points: "9 21 3 21 3 15" }),
2424
+ /* @__PURE__ */ jsx5("line", { x1: "21", y1: "3", x2: "14", y2: "10" }),
2425
+ /* @__PURE__ */ jsx5("line", { x1: "3", y1: "21", x2: "10", y2: "14" })
2426
+ ] });
2427
+ var CollapseIcon = () => /* @__PURE__ */ jsxs4("svg", { width: "18", height: "18", viewBox: "0 0 24 24", fill: "none", stroke: "currentColor", strokeWidth: "2", strokeLinecap: "round", strokeLinejoin: "round", children: [
2428
+ /* @__PURE__ */ jsx5("polyline", { points: "4 14 10 14 10 20" }),
2429
+ /* @__PURE__ */ jsx5("polyline", { points: "20 10 14 10 14 4" }),
2430
+ /* @__PURE__ */ jsx5("line", { x1: "14", y1: "10", x2: "21", y2: "3" }),
2431
+ /* @__PURE__ */ jsx5("line", { x1: "3", y1: "21", x2: "10", y2: "14" })
2432
+ ] });
2433
+ var SendIcon = () => /* @__PURE__ */ jsxs4("svg", { width: "16", height: "16", viewBox: "0 0 24 24", fill: "none", stroke: "currentColor", strokeWidth: "2", strokeLinecap: "round", strokeLinejoin: "round", children: [
2434
+ /* @__PURE__ */ jsx5("line", { x1: "22", y1: "2", x2: "11", y2: "13" }),
2435
+ /* @__PURE__ */ jsx5("polygon", { points: "22 2 15 22 11 13 2 9 22 2" })
2436
+ ] });
2437
+ var LayersIcon = () => /* @__PURE__ */ jsxs4("svg", { width: "14", height: "14", viewBox: "0 0 24 24", fill: "none", stroke: "currentColor", strokeWidth: "2", strokeLinecap: "round", strokeLinejoin: "round", children: [
2438
+ /* @__PURE__ */ jsx5("polygon", { points: "12 2 2 7 12 12 22 7 12 2" }),
2439
+ /* @__PURE__ */ jsx5("polyline", { points: "2 17 12 22 22 17" }),
2440
+ /* @__PURE__ */ jsx5("polyline", { points: "2 12 12 17 22 12" })
2441
+ ] });
2442
+ var styles = {
2443
+ root: {
2444
+ fontFamily: 'system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif'
2445
+ },
2446
+ // Floating button (closed state - wide with text, open state - circular with X)
2447
+ floatingButton: {
2448
+ position: "fixed",
2449
+ bottom: 24,
2450
+ right: 24,
2451
+ borderRadius: "999px",
2452
+ border: "none",
2453
+ cursor: "pointer",
2454
+ background: "linear-gradient(135deg, #10b981, #059669)",
2455
+ color: "#fff",
2456
+ boxShadow: "0 12px 28px rgba(16, 185, 129, 0.4)",
2457
+ display: "flex",
2458
+ alignItems: "center",
2459
+ justifyContent: "center",
2460
+ fontSize: 15,
2461
+ fontWeight: 600,
2462
+ zIndex: 99999,
2463
+ transition: "all 0.3s cubic-bezier(0.4, 0, 0.2, 1)"
2464
+ },
2465
+ floatingButtonClosed: {
2466
+ padding: "14px 24px",
2467
+ gap: 8
2468
+ },
2469
+ floatingButtonOpen: {
2470
+ width: 56,
2471
+ height: 56,
2472
+ padding: 0
2473
+ },
2474
+ floatingButtonMobile: {
2475
+ width: 56,
2476
+ height: 56,
2477
+ padding: 0
2478
+ },
2479
+ // Panel (expandable)
2480
+ panel: {
2481
+ position: "fixed",
2482
+ bottom: 92,
2483
+ right: 24,
2484
+ background: "#fff",
2485
+ borderRadius: 16,
2486
+ boxShadow: "0 20px 60px rgba(15, 23, 42, 0.3), 0 0 0 1px rgba(15, 23, 42, 0.05)",
2487
+ display: "flex",
2488
+ flexDirection: "column",
2489
+ overflow: "hidden",
2490
+ zIndex: 99999,
2491
+ transition: "all 0.3s cubic-bezier(0.4, 0, 0.2, 1)"
2492
+ },
2493
+ panelNormal: {
2494
+ width: 400,
2495
+ height: 550
2496
+ },
2497
+ panelExpanded: {
2498
+ width: 520,
2499
+ height: 700
2500
+ },
2501
+ // Header with green gradient
2502
+ header: {
2503
+ padding: "16px 18px",
2504
+ background: "linear-gradient(135deg, #10b981, #059669)",
2505
+ color: "#fff",
2506
+ display: "flex",
2507
+ alignItems: "center",
2508
+ justifyContent: "space-between"
2509
+ },
2510
+ title: {
2511
+ margin: 0,
2512
+ fontSize: 16,
2513
+ fontWeight: 600,
2514
+ letterSpacing: "-0.01em"
2515
+ },
2516
+ headerButtons: {
2517
+ display: "flex",
2518
+ alignItems: "center",
2519
+ gap: 8
2520
+ },
2521
+ headerButton: {
2522
+ border: "none",
2523
+ background: "rgba(255, 255, 255, 0.15)",
2524
+ color: "#fff",
2525
+ width: 32,
2526
+ height: 32,
2527
+ borderRadius: 8,
2528
+ cursor: "pointer",
2529
+ display: "flex",
2530
+ alignItems: "center",
2531
+ justifyContent: "center",
2532
+ transition: "background 0.2s"
2533
+ },
2534
+ // Messages area
2535
+ messages: {
2536
+ flex: 1,
2537
+ padding: "20px 18px",
2538
+ overflowY: "auto",
2539
+ background: "#f8fafc",
2540
+ display: "flex",
2541
+ flexDirection: "column",
2542
+ gap: 16
2543
+ },
2544
+ // Message bubbles
2545
+ messageWrapper: {
2546
+ display: "flex",
2547
+ flexDirection: "column",
2548
+ gap: 8
2549
+ },
2550
+ messageBubble: {
2551
+ maxWidth: "85%",
2552
+ padding: "12px 14px",
2553
+ borderRadius: 16,
2554
+ lineHeight: 1.5,
2555
+ fontSize: 14,
2556
+ whiteSpace: "pre-wrap",
2557
+ wordBreak: "break-word"
2558
+ },
2559
+ userMessage: {
2560
+ alignSelf: "flex-end",
2561
+ background: "linear-gradient(135deg, #10b981, #059669)",
2562
+ color: "#fff",
2563
+ borderBottomRightRadius: 4
2564
+ },
2565
+ assistantMessage: {
2566
+ alignSelf: "flex-start",
2567
+ background: "#e2e8f0",
2568
+ color: "#0f172a",
2569
+ borderBottomLeftRadius: 4
2570
+ },
2571
+ // Streaming cursor
2572
+ cursor: {
2573
+ display: "inline-block",
2574
+ width: 2,
2575
+ height: 16,
2576
+ background: "#0f172a",
2577
+ marginLeft: 2,
2578
+ animation: "zenitBlink 1s infinite",
2579
+ verticalAlign: "text-bottom"
2580
+ },
2581
+ thinkingText: {
2582
+ fontStyle: "italic",
2583
+ opacity: 0.7,
2584
+ display: "flex",
2585
+ alignItems: "center",
2586
+ gap: 8
2587
+ },
2588
+ typingIndicator: {
2589
+ display: "flex",
2590
+ gap: 4,
2591
+ alignItems: "center"
2592
+ },
2593
+ typingDot: {
2594
+ width: 8,
2595
+ height: 8,
2596
+ borderRadius: "50%",
2597
+ backgroundColor: "#059669",
2598
+ animation: "typingDotBounce 1.4s infinite ease-in-out"
2599
+ },
2600
+ // Metadata section (Referenced Layers)
2601
+ metadataSection: {
2602
+ marginTop: 12,
2603
+ padding: "10px 12px",
2604
+ background: "rgba(255, 255, 255, 0.5)",
2605
+ borderRadius: 10,
2606
+ fontSize: 12
2607
+ },
2608
+ metadataTitle: {
2609
+ fontWeight: 600,
2610
+ color: "#059669",
2611
+ marginBottom: 6,
2612
+ display: "flex",
2613
+ alignItems: "center",
2614
+ gap: 6
2615
+ },
2616
+ metadataList: {
2617
+ margin: 0,
2618
+ paddingLeft: 18,
2619
+ color: "#475569"
2620
+ },
2621
+ metadataItem: {
2622
+ marginBottom: 2
2623
+ },
2624
+ // Suggested actions
2625
+ actionsSection: {
2626
+ marginTop: 12
2627
+ },
2628
+ sectionLabel: {
2629
+ fontSize: 11,
2630
+ fontWeight: 600,
2631
+ color: "#64748b",
2632
+ marginBottom: 8,
2633
+ textTransform: "uppercase",
2634
+ letterSpacing: "0.05em"
2635
+ },
2636
+ actionsGrid: {
2637
+ display: "flex",
2638
+ flexWrap: "wrap",
2639
+ gap: 6
2640
+ },
2641
+ actionButton: {
2642
+ border: "1px solid #d1fae5",
2643
+ background: "#d1fae5",
2644
+ color: "#065f46",
2645
+ borderRadius: 999,
2646
+ padding: "6px 12px",
2647
+ fontSize: 12,
2648
+ fontWeight: 500,
2649
+ cursor: "pointer",
2650
+ transition: "all 0.2s"
2651
+ },
2652
+ // Follow-up questions
2653
+ followUpButton: {
2654
+ border: "1px solid #cbd5e1",
2655
+ background: "#fff",
2656
+ color: "#475569",
2657
+ borderRadius: 10,
2658
+ padding: "8px 12px",
2659
+ fontSize: 12,
2660
+ fontWeight: 500,
2661
+ cursor: "pointer",
2662
+ textAlign: "left",
2663
+ width: "100%",
2664
+ transition: "all 0.2s"
2665
+ },
2666
+ // Input area
2667
+ inputWrapper: {
2668
+ borderTop: "1px solid #e2e8f0",
2669
+ padding: "14px 16px",
2670
+ display: "flex",
2671
+ gap: 10,
2672
+ alignItems: "flex-end",
2673
+ background: "#fff"
2674
+ },
2675
+ textarea: {
2676
+ flex: 1,
2677
+ resize: "none",
2678
+ borderRadius: 12,
2679
+ border: "1.5px solid #cbd5e1",
2680
+ padding: "10px 12px",
2681
+ fontSize: 14,
2682
+ fontFamily: "inherit",
2683
+ lineHeight: 1.4,
2684
+ transition: "border-color 0.2s"
2685
+ },
2686
+ textareaFocus: {
2687
+ borderColor: "#10b981",
2688
+ outline: "none"
2689
+ },
2690
+ sendButton: {
2691
+ borderRadius: 12,
2692
+ border: "none",
2693
+ padding: "10px 14px",
2694
+ background: "linear-gradient(135deg, #10b981, #059669)",
2695
+ color: "#fff",
2696
+ cursor: "pointer",
2697
+ fontSize: 14,
2698
+ fontWeight: 600,
2699
+ display: "flex",
2700
+ alignItems: "center",
2701
+ justifyContent: "center",
2702
+ transition: "opacity 0.2s, transform 0.2s",
2703
+ minWidth: 44,
2704
+ height: 44
2705
+ },
2706
+ // Status messages
2707
+ statusNote: {
2708
+ padding: "0 16px 14px",
2709
+ fontSize: 12,
2710
+ color: "#64748b",
2711
+ textAlign: "center"
2712
+ },
2713
+ errorText: {
2714
+ padding: "0 16px 14px",
2715
+ fontSize: 12,
2716
+ color: "#dc2626",
2717
+ textAlign: "center"
2718
+ }
2719
+ };
2720
+ var FloatingChatBox = ({
2721
+ mapId,
2722
+ filteredLayerIds,
2723
+ filters,
2724
+ userId,
2725
+ baseUrl,
2726
+ accessToken,
2727
+ getAccessToken,
2728
+ onActionClick,
2729
+ onOpenChange,
2730
+ hideButton,
2731
+ open: openProp
2732
+ }) => {
2733
+ const isControlled = openProp !== void 0;
2734
+ const [internalOpen, setInternalOpen] = useState4(false);
2735
+ const open = isControlled ? openProp : internalOpen;
2736
+ const setOpen = useCallback3((value) => {
2737
+ const newValue = typeof value === "function" ? value(open) : value;
2738
+ if (!isControlled) {
2739
+ setInternalOpen(newValue);
2740
+ }
2741
+ onOpenChange?.(newValue);
2742
+ }, [isControlled, open, onOpenChange]);
2743
+ const [expanded, setExpanded] = useState4(false);
2744
+ const [messages, setMessages] = useState4([]);
2745
+ const [inputValue, setInputValue] = useState4("");
2746
+ const [conversationId, setConversationId] = useState4();
2747
+ const [errorMessage, setErrorMessage] = useState4(null);
2748
+ const [isFocused, setIsFocused] = useState4(false);
2749
+ const [isMobile, setIsMobile] = useState4(false);
2750
+ const messagesEndRef = useRef4(null);
2751
+ const messagesContainerRef = useRef4(null);
2752
+ const chatBoxRef = useRef4(null);
2753
+ const chatConfig = useMemo3(() => {
2754
+ if (!baseUrl) return void 0;
2755
+ return { baseUrl, accessToken, getAccessToken };
2756
+ }, [accessToken, baseUrl, getAccessToken]);
2757
+ const { sendMessage: sendMessage2, isStreaming, streamingText, completeResponse } = useSendMessageStream(chatConfig);
2758
+ const canSend = Boolean(mapId) && Boolean(baseUrl) && inputValue.trim().length > 0 && !isStreaming;
2759
+ useEffect3(() => {
2760
+ if (open && isMobile) {
2761
+ setExpanded(true);
2762
+ }
2763
+ }, [open, isMobile]);
2764
+ const scrollToBottom = useCallback3(() => {
2765
+ if (messagesEndRef.current) {
2766
+ messagesEndRef.current.scrollIntoView({ behavior: "smooth" });
2767
+ }
2768
+ }, []);
2769
+ useEffect3(() => {
2770
+ if (open && messages.length === 0) {
2771
+ setMessages([
2772
+ {
2773
+ id: "welcome",
2774
+ role: "assistant",
2775
+ content: "Hola, soy el asistente de IA de ZENIT. Estoy aqu\xED para ayudarte a analizar tu mapa y responder tus preguntas sobre las capas y datos. \xBFEn qu\xE9 puedo ayudarte hoy?"
2776
+ }
2777
+ ]);
2778
+ }
2779
+ }, [open, messages.length]);
2780
+ useEffect3(() => {
2781
+ scrollToBottom();
2782
+ }, [messages, streamingText, scrollToBottom]);
2783
+ useEffect3(() => {
2784
+ if (!open) return;
2785
+ if (isMobile && expanded) return;
2786
+ const handleClickOutside = (event) => {
2787
+ if (chatBoxRef.current && !chatBoxRef.current.contains(event.target)) {
2788
+ setOpen(false);
2789
+ }
2790
+ };
2791
+ document.addEventListener("mousedown", handleClickOutside);
2792
+ return () => {
2793
+ document.removeEventListener("mousedown", handleClickOutside);
2794
+ };
2795
+ }, [open, isMobile, expanded]);
2796
+ useEffect3(() => {
2797
+ if (typeof window === "undefined") return;
2798
+ const mediaQuery = window.matchMedia("(max-width: 768px)");
2799
+ const updateMobile = () => setIsMobile(mediaQuery.matches);
2800
+ updateMobile();
2801
+ if (mediaQuery.addEventListener) {
2802
+ mediaQuery.addEventListener("change", updateMobile);
2803
+ } else {
2804
+ mediaQuery.addListener(updateMobile);
2805
+ }
2806
+ return () => {
2807
+ if (mediaQuery.removeEventListener) {
2808
+ mediaQuery.removeEventListener("change", updateMobile);
2809
+ } else {
2810
+ mediaQuery.removeListener(updateMobile);
2811
+ }
2812
+ };
2813
+ }, []);
2814
+ useEffect3(() => {
2815
+ if (typeof document === "undefined") return;
2816
+ if (!open || !isMobile) return;
2817
+ document.body.style.overflow = "hidden";
2818
+ return () => {
2819
+ document.body.style.overflow = "";
2820
+ };
2821
+ }, [open, isMobile]);
2822
+ const addMessage = useCallback3((message) => {
2823
+ setMessages((prev) => [...prev, message]);
2824
+ }, []);
2825
+ const handleSend = useCallback3(async () => {
2826
+ if (!mapId) {
2827
+ setErrorMessage("Selecciona un mapa para usar el asistente.");
2828
+ return;
2829
+ }
2830
+ if (!baseUrl) {
2831
+ setErrorMessage("Configura la baseUrl del SDK para usar Zenit AI.");
2832
+ return;
2833
+ }
2834
+ if (!inputValue.trim()) return;
2835
+ const messageText = inputValue.trim();
2836
+ setInputValue("");
2837
+ setErrorMessage(null);
2838
+ addMessage({
2839
+ id: `user-${Date.now()}`,
2840
+ role: "user",
2841
+ content: messageText
2842
+ });
2843
+ const request = {
2844
+ message: messageText,
2845
+ conversationId,
2846
+ filteredLayerIds,
2847
+ filters,
2848
+ userId
2849
+ };
2850
+ try {
2851
+ const response = await sendMessage2(mapId, request);
2852
+ setConversationId(response.conversationId ?? conversationId);
2853
+ addMessage({
2854
+ id: `assistant-${Date.now()}`,
2855
+ role: "assistant",
2856
+ content: response.answer,
2857
+ response
2858
+ });
2859
+ } catch (error) {
2860
+ setErrorMessage(error instanceof Error ? error.message : "Ocurri\xF3 un error inesperado.");
2861
+ addMessage({
2862
+ id: `error-${Date.now()}`,
2863
+ role: "assistant",
2864
+ content: `\u274C Error: ${error instanceof Error ? error.message : "Ocurri\xF3 un error inesperado."}`
2865
+ });
2866
+ }
2867
+ }, [
2868
+ addMessage,
2869
+ baseUrl,
2870
+ conversationId,
2871
+ filteredLayerIds,
2872
+ filters,
2873
+ inputValue,
2874
+ mapId,
2875
+ sendMessage2,
2876
+ userId
2877
+ ]);
2878
+ const handleKeyDown = useCallback3(
2879
+ (event) => {
2880
+ if (event.key === "Enter" && !event.shiftKey) {
2881
+ event.preventDefault();
2882
+ if (canSend) {
2883
+ void handleSend();
2884
+ }
2885
+ }
2886
+ },
2887
+ [canSend, handleSend]
2888
+ );
2889
+ const handleFollowUpClick = useCallback3((question) => {
2890
+ setInputValue(question);
2891
+ }, []);
2892
+ const renderMetadata = (response) => {
2893
+ if (!response?.metadata) return null;
2894
+ const referencedLayers = response.metadata.referencedLayers;
2895
+ if (!referencedLayers || referencedLayers.length === 0) return null;
2896
+ return /* @__PURE__ */ jsxs4("div", { style: styles.metadataSection, children: [
2897
+ /* @__PURE__ */ jsxs4("div", { style: styles.metadataTitle, children: [
2898
+ /* @__PURE__ */ jsx5(LayersIcon, {}),
2899
+ "Capas Analizadas"
2900
+ ] }),
2901
+ /* @__PURE__ */ jsx5("ul", { style: styles.metadataList, children: referencedLayers.map((layer, index) => /* @__PURE__ */ jsxs4("li", { style: styles.metadataItem, children: [
2902
+ /* @__PURE__ */ jsx5("strong", { children: layer.layerName }),
2903
+ " (",
2904
+ layer.featureCount,
2905
+ " ",
2906
+ layer.featureCount === 1 ? "elemento" : "elementos",
2907
+ ")"
2908
+ ] }, index)) })
2909
+ ] });
2910
+ };
2911
+ const handleActionClick = useCallback3((action) => {
2912
+ if (isStreaming) return;
2913
+ setOpen(false);
2914
+ requestAnimationFrame(() => {
2915
+ onActionClick?.(action);
2916
+ });
2917
+ }, [isStreaming, setOpen, onActionClick]);
2918
+ const renderActions = (response) => {
2919
+ if (!response?.suggestedActions?.length) return null;
2920
+ return /* @__PURE__ */ jsxs4("div", { style: styles.actionsSection, children: [
2921
+ /* @__PURE__ */ jsx5("div", { style: styles.sectionLabel, children: "Acciones Sugeridas" }),
2922
+ /* @__PURE__ */ jsx5("div", { style: styles.actionsGrid, children: response.suggestedActions.map((action, index) => /* @__PURE__ */ jsx5(
2923
+ "button",
2924
+ {
2925
+ type: "button",
2926
+ style: {
2927
+ ...styles.actionButton,
2928
+ opacity: isStreaming ? 0.5 : 1,
2929
+ cursor: isStreaming ? "not-allowed" : "pointer"
2930
+ },
2931
+ onClick: () => handleActionClick(action),
2932
+ disabled: isStreaming,
2933
+ onMouseEnter: (e) => {
2934
+ if (!isStreaming) {
2935
+ e.currentTarget.style.background = "#a7f3d0";
2936
+ e.currentTarget.style.borderColor = "#a7f3d0";
2937
+ }
2938
+ },
2939
+ onMouseLeave: (e) => {
2940
+ if (!isStreaming) {
2941
+ e.currentTarget.style.background = "#d1fae5";
2942
+ e.currentTarget.style.borderColor = "#d1fae5";
2943
+ }
2944
+ },
2945
+ children: action.label ?? action.action ?? "Acci\xF3n"
2946
+ },
2947
+ `${action.label ?? action.action ?? "action"}-${index}`
2948
+ )) })
2949
+ ] });
2950
+ };
2951
+ const renderFollowUps = (response) => {
2952
+ if (!response?.followUpQuestions?.length) return null;
2953
+ return /* @__PURE__ */ jsxs4("div", { style: styles.actionsSection, children: [
2954
+ /* @__PURE__ */ jsx5("div", { style: styles.sectionLabel, children: "Preguntas Relacionadas" }),
2955
+ /* @__PURE__ */ jsx5("div", { style: { display: "flex", flexDirection: "column", gap: 6 }, children: response.followUpQuestions.map((question, index) => /* @__PURE__ */ jsx5(
2956
+ "button",
2957
+ {
2958
+ type: "button",
2959
+ style: {
2960
+ ...styles.followUpButton,
2961
+ opacity: isStreaming ? 0.5 : 1,
2962
+ cursor: isStreaming ? "not-allowed" : "pointer"
2963
+ },
2964
+ onClick: () => !isStreaming && handleFollowUpClick(question),
2965
+ disabled: isStreaming,
2966
+ onMouseEnter: (e) => {
2967
+ if (!isStreaming) {
2968
+ e.currentTarget.style.background = "#f8fafc";
2969
+ e.currentTarget.style.borderColor = "#10b981";
2970
+ }
2971
+ },
2972
+ onMouseLeave: (e) => {
2973
+ if (!isStreaming) {
2974
+ e.currentTarget.style.background = "#fff";
2975
+ e.currentTarget.style.borderColor = "#cbd5e1";
2976
+ }
2977
+ },
2978
+ children: question
2979
+ },
2980
+ `followup-${index}`
2981
+ )) })
2982
+ ] });
2983
+ };
2984
+ const chatContent = /* @__PURE__ */ jsxs4("div", { style: styles.root, children: [
2985
+ /* @__PURE__ */ jsx5("style", { children: `
2986
+ @keyframes zenitBlink {
2987
+ 0%, 49% { opacity: 1; }
2988
+ 50%, 100% { opacity: 0; }
2989
+ }
2990
+ @keyframes zenitPulse {
2991
+ 0% { box-shadow: 0 0 0 0 rgba(16, 185, 129, 0.7); }
2992
+ 70% { box-shadow: 0 0 0 14px rgba(16, 185, 129, 0); }
2993
+ 100% { box-shadow: 0 0 0 0 rgba(16, 185, 129, 0); }
2994
+ }
2995
+ @keyframes typingDotBounce {
2996
+ 0%, 60%, 100% { transform: translateY(0); }
2997
+ 30% { transform: translateY(-8px); }
2998
+ }
2999
+ .zenit-typing-dot:nth-child(1) { animation-delay: 0s; }
3000
+ .zenit-typing-dot:nth-child(2) { animation-delay: 0.2s; }
3001
+ .zenit-typing-dot:nth-child(3) { animation-delay: 0.4s; }
3002
+ .zenit-ai-button:not(.open) {
3003
+ animation: zenitPulse 2.5s infinite;
3004
+ }
3005
+ .zenit-ai-button:hover {
3006
+ transform: scale(1.05);
3007
+ }
3008
+ .zenit-ai-button:active {
3009
+ transform: scale(0.95);
3010
+ }
3011
+ .zenit-send-button:disabled {
3012
+ opacity: 0.5;
3013
+ cursor: not-allowed;
3014
+ }
3015
+ .zenit-send-button:not(:disabled):hover {
3016
+ opacity: 0.9;
3017
+ transform: translateY(-1px);
3018
+ }
3019
+ .zenit-send-button:not(:disabled):active {
3020
+ transform: translateY(0);
3021
+ }
3022
+ .zenit-chat-panel {
3023
+ box-sizing: border-box;
3024
+ }
3025
+ @media (max-width: 768px) {
3026
+ .zenit-chat-panel.zenit-chat-panel--fullscreen {
3027
+ position: fixed !important;
3028
+ inset: 0 !important;
3029
+ width: 100vw !important;
3030
+ max-width: 100vw !important;
3031
+ height: 100vh !important;
3032
+ height: 100dvh !important;
3033
+ border-radius: 0 !important;
3034
+ display: flex !important;
3035
+ flex-direction: column !important;
3036
+ overflow: hidden !important;
3037
+ z-index: 100000 !important;
3038
+ padding-top: env(safe-area-inset-top);
3039
+ }
3040
+ .zenit-chat-panel.zenit-chat-panel--fullscreen .zenit-ai-body {
3041
+ flex: 1;
3042
+ min-height: 0;
3043
+ overflow-y: auto;
3044
+ -webkit-overflow-scrolling: touch;
3045
+ }
3046
+ .zenit-chat-panel.zenit-chat-panel--fullscreen .zenit-ai-input-area {
3047
+ flex-shrink: 0;
3048
+ padding-bottom: max(14px, env(safe-area-inset-bottom));
3049
+ }
3050
+ .zenit-ai-button.zenit-ai-button--hidden-mobile {
3051
+ display: none !important;
3052
+ }
3053
+ }
3054
+ ` }),
3055
+ open && /* @__PURE__ */ jsxs4(
3056
+ "div",
3057
+ {
3058
+ ref: chatBoxRef,
3059
+ className: `zenit-chat-panel${expanded ? " zenit-chat-panel--expanded" : ""}${isMobile ? " zenit-chat-panel--fullscreen" : ""}`,
3060
+ style: {
3061
+ ...styles.panel,
3062
+ ...expanded ? styles.panelExpanded : styles.panelNormal
3063
+ },
3064
+ children: [
3065
+ /* @__PURE__ */ jsxs4("header", { style: styles.header, children: [
3066
+ /* @__PURE__ */ jsx5("h3", { style: styles.title, children: "Asistente Zenit AI" }),
3067
+ /* @__PURE__ */ jsxs4("div", { style: styles.headerButtons, children: [
3068
+ /* @__PURE__ */ jsx5(
3069
+ "button",
3070
+ {
3071
+ type: "button",
3072
+ style: styles.headerButton,
3073
+ onClick: () => setExpanded(!expanded),
3074
+ onMouseEnter: (e) => {
3075
+ e.currentTarget.style.background = "rgba(255, 255, 255, 0.25)";
3076
+ },
3077
+ onMouseLeave: (e) => {
3078
+ e.currentTarget.style.background = "rgba(255, 255, 255, 0.15)";
3079
+ },
3080
+ "aria-label": expanded ? "Contraer" : "Expandir",
3081
+ children: expanded ? /* @__PURE__ */ jsx5(CollapseIcon, {}) : /* @__PURE__ */ jsx5(ExpandIcon, {})
3082
+ }
3083
+ ),
3084
+ /* @__PURE__ */ jsx5(
3085
+ "button",
3086
+ {
3087
+ type: "button",
3088
+ style: styles.headerButton,
3089
+ onClick: () => setOpen(false),
3090
+ onMouseEnter: (e) => {
3091
+ e.currentTarget.style.background = "rgba(255, 255, 255, 0.25)";
3092
+ },
3093
+ onMouseLeave: (e) => {
3094
+ e.currentTarget.style.background = "rgba(255, 255, 255, 0.15)";
3095
+ },
3096
+ "aria-label": "Cerrar",
3097
+ children: /* @__PURE__ */ jsx5(CloseIcon, {})
3098
+ }
3099
+ )
3100
+ ] })
3101
+ ] }),
3102
+ /* @__PURE__ */ jsxs4("div", { ref: messagesContainerRef, className: "zenit-ai-body", style: styles.messages, children: [
3103
+ messages.map((message) => /* @__PURE__ */ jsx5(
3104
+ "div",
3105
+ {
3106
+ style: {
3107
+ ...styles.messageWrapper,
3108
+ alignItems: message.role === "user" ? "flex-end" : "flex-start"
3109
+ },
3110
+ children: /* @__PURE__ */ jsxs4(
3111
+ "div",
3112
+ {
3113
+ style: {
3114
+ ...styles.messageBubble,
3115
+ ...message.role === "user" ? styles.userMessage : styles.assistantMessage
3116
+ },
3117
+ children: [
3118
+ message.role === "assistant" ? /* @__PURE__ */ jsx5(MarkdownRenderer, { content: message.content }) : message.content,
3119
+ message.role === "assistant" && renderMetadata(message.response),
3120
+ message.role === "assistant" && renderActions(message.response),
3121
+ message.role === "assistant" && renderFollowUps(message.response)
3122
+ ]
3123
+ }
3124
+ )
3125
+ },
3126
+ message.id
3127
+ )),
3128
+ isStreaming && /* @__PURE__ */ jsx5(
3129
+ "div",
3130
+ {
3131
+ style: {
3132
+ ...styles.messageWrapper,
3133
+ alignItems: "flex-start"
3134
+ },
3135
+ children: /* @__PURE__ */ jsx5(
3136
+ "div",
3137
+ {
3138
+ style: {
3139
+ ...styles.messageBubble,
3140
+ ...styles.assistantMessage
3141
+ },
3142
+ children: streamingText ? /* @__PURE__ */ jsxs4(Fragment, { children: [
3143
+ /* @__PURE__ */ jsx5(MarkdownRenderer, { content: streamingText }),
3144
+ /* @__PURE__ */ jsx5("span", { style: styles.cursor })
3145
+ ] }) : /* @__PURE__ */ jsxs4("div", { style: styles.thinkingText, children: [
3146
+ /* @__PURE__ */ jsx5("span", { children: "Analizando" }),
3147
+ /* @__PURE__ */ jsxs4("div", { style: styles.typingIndicator, children: [
3148
+ /* @__PURE__ */ jsx5("div", { className: "zenit-typing-dot", style: styles.typingDot }),
3149
+ /* @__PURE__ */ jsx5("div", { className: "zenit-typing-dot", style: styles.typingDot }),
3150
+ /* @__PURE__ */ jsx5("div", { className: "zenit-typing-dot", style: styles.typingDot })
3151
+ ] })
3152
+ ] })
3153
+ }
3154
+ )
3155
+ }
3156
+ ),
3157
+ /* @__PURE__ */ jsx5("div", { ref: messagesEndRef })
3158
+ ] }),
3159
+ /* @__PURE__ */ jsxs4("div", { className: "zenit-ai-input-area", style: styles.inputWrapper, children: [
3160
+ /* @__PURE__ */ jsx5(
3161
+ "textarea",
3162
+ {
3163
+ style: {
3164
+ ...styles.textarea,
3165
+ ...isFocused ? styles.textareaFocus : {}
3166
+ },
3167
+ rows: 2,
3168
+ value: inputValue,
3169
+ onChange: (event) => setInputValue(event.target.value),
3170
+ onKeyDown: handleKeyDown,
3171
+ onFocus: () => setIsFocused(true),
3172
+ onBlur: () => setIsFocused(false),
3173
+ placeholder: !mapId ? "Selecciona un mapa para comenzar" : isStreaming ? "Esperando respuesta..." : "Escribe tu pregunta...",
3174
+ disabled: !mapId || !baseUrl || isStreaming
3175
+ }
3176
+ ),
3177
+ /* @__PURE__ */ jsx5(
3178
+ "button",
3179
+ {
3180
+ type: "button",
3181
+ className: "zenit-send-button",
3182
+ style: styles.sendButton,
3183
+ onClick: () => void handleSend(),
3184
+ disabled: !canSend,
3185
+ "aria-label": "Enviar mensaje",
3186
+ children: /* @__PURE__ */ jsx5(SendIcon, {})
3187
+ }
3188
+ )
3189
+ ] }),
3190
+ errorMessage && /* @__PURE__ */ jsx5("div", { style: styles.errorText, children: errorMessage }),
3191
+ !mapId && !errorMessage && /* @__PURE__ */ jsx5("div", { style: styles.statusNote, children: "Selecciona un mapa para usar el asistente" }),
3192
+ !baseUrl && !errorMessage && /* @__PURE__ */ jsx5("div", { style: styles.statusNote, children: "Configura la baseUrl del SDK" })
3193
+ ]
3194
+ }
3195
+ ),
3196
+ !(hideButton && !open) && /* @__PURE__ */ jsx5(
3197
+ "button",
3198
+ {
3199
+ type: "button",
3200
+ className: `zenit-ai-button ${open ? "open" : ""}${open && isMobile ? " zenit-ai-button--hidden-mobile" : ""}`,
3201
+ style: {
3202
+ ...styles.floatingButton,
3203
+ ...open ? styles.floatingButtonOpen : isMobile ? styles.floatingButtonMobile : styles.floatingButtonClosed
3204
+ },
3205
+ onClick: () => setOpen((prev) => !prev),
3206
+ "aria-label": open ? "Cerrar asistente" : "Abrir asistente Zenit AI",
3207
+ children: open ? /* @__PURE__ */ jsx5(CloseIcon, {}) : /* @__PURE__ */ jsxs4(Fragment, { children: [
3208
+ /* @__PURE__ */ jsx5(ChatIcon, {}),
3209
+ !isMobile && /* @__PURE__ */ jsx5("span", { children: "Asistente IA" })
3210
+ ] })
3211
+ }
3212
+ )
3213
+ ] });
3214
+ if (typeof document !== "undefined") {
3215
+ return createPortal(chatContent, document.body);
3216
+ }
3217
+ return chatContent;
3218
+ };
3219
+
3220
+ export {
3221
+ extractMapDto,
3222
+ normalizeMapCenter,
3223
+ normalizeMapLayers,
3224
+ computeBBoxFromFeature,
3225
+ centroidFromBBox,
3226
+ applyFilteredGeoJSONStrategy,
3227
+ initLayerStates,
3228
+ applyLayerOverrides,
3229
+ resetOverrides,
3230
+ sendMessage,
3231
+ sendMessageStream,
3232
+ createChatService,
3233
+ resolveLayerAccent,
3234
+ getLayerColor,
3235
+ getStyleByLayerId,
3236
+ getAccentByLayerId,
3237
+ clampNumber,
3238
+ clampOpacity3 as clampOpacity,
3239
+ isPolygonLayer,
3240
+ getZoomOpacityFactor,
3241
+ getLayerZoomOpacityFactor,
3242
+ getEffectiveLayerOpacity,
3243
+ ZenitMap,
3244
+ Eye,
3245
+ EyeOff,
3246
+ ChevronLeft,
3247
+ ChevronRight,
3248
+ Layers,
3249
+ Upload,
3250
+ X,
3251
+ ZoomIn,
3252
+ ZenitLayerManager,
3253
+ ZenitFeatureFilterPanel,
3254
+ useSendMessage,
3255
+ useSendMessageStream,
3256
+ FloatingChatBox
3257
+ };
3258
+ //# sourceMappingURL=chunk-LX2N2BXV.mjs.map