zenit-sdk 0.0.2 → 0.0.3

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