Files
openclaw-market/hooks/use-sse.ts
richarjiang e79d721615 feat: 用 react-map-gl + MapLibre 替换 react-simple-maps 实现 2D 地图
- 替换 react-simple-maps/d3-geo/topojson-client 为 react-map-gl + maplibre-gl
- 使用 CARTO dark-matter 免费暗色瓦片,自带国家/城市名标注
- 基于 locale 动态切换地图标注语言(name:zh / name_en)
- MapLibre 原生 heatmap + circle 双层渲染替代 SVG 热力图
- 提取 MapPopup 组件,配合 react-map-gl Popup 实现点击弹窗
- continent page 改为 dynamic import (ssr: false)
- dev 模式去掉 Turbopack 以兼容 maplibre-gl
- 删除 heatmap-layer.tsx 和 react-simple-maps 类型声明
2026-03-13 14:46:23 +08:00

69 lines
1.7 KiB
TypeScript

"use client";
import { useEffect, useRef, useCallback, useState } from "react";
export interface SSEEvent {
type: string;
data: Record<string, unknown>;
}
interface UseSSEOptions {
url: string;
onEvent?: (event: SSEEvent) => void;
enabled?: boolean;
}
export function useSSE({ url, onEvent, enabled = true }: UseSSEOptions) {
const [isConnected, setIsConnected] = useState(false);
const [lastEvent, setLastEvent] = useState<SSEEvent | null>(null);
const eventSourceRef = useRef<EventSource | null>(null);
const onEventRef = useRef(onEvent);
// Keep callback ref updated
onEventRef.current = onEvent;
const connect = useCallback(() => {
if (eventSourceRef.current) {
eventSourceRef.current.close();
}
const es = new EventSource(url);
eventSourceRef.current = es;
es.onopen = () => setIsConnected(true);
es.onerror = () => {
setIsConnected(false);
// Auto-reconnect is built into EventSource
};
// Listen for all event types
const eventTypes = ["heartbeat", "task", "stats", "online", "offline", "connected", "registered"];
eventTypes.forEach((type) => {
es.addEventListener(type, (e: MessageEvent) => {
try {
const data = JSON.parse(e.data);
const event: SSEEvent = { type, data };
setLastEvent(event);
onEventRef.current?.(event);
} catch {
// skip malformed events
}
});
});
return es;
}, [url]);
useEffect(() => {
if (!enabled) return;
const es = connect();
return () => {
es.close();
setIsConnected(false);
};
}, [connect, enabled]);
return { isConnected, lastEvent };
}