we got some data

This commit is contained in:
ajvpot
2025-07-03 00:00:00 +00:00
parent 5242ba6fdd
commit a72f201cca
13 changed files with 338 additions and 231 deletions
+9
View File
@@ -15,6 +15,7 @@
"clickhouse": "^2.6.0",
"clsx": "^2.1.1",
"leaflet": "^1.9.4",
"leaflet.markercluster": "^1.5.3",
"lucide-react": "^0.525.0",
"next": "15.3.4",
"next-themes": "^0.4.6",
@@ -4420,6 +4421,14 @@
"resolved": "https://registry.npmjs.org/leaflet/-/leaflet-1.9.4.tgz",
"integrity": "sha512-nxS1ynzJOmOlHp+iL3FyWqK89GtNL8U8rvlMOsQdTTssxZwCXh8N2NB3GDQOL+YR3XnWyZAxwQixURb+FA74PA=="
},
"node_modules/leaflet.markercluster": {
"version": "1.5.3",
"resolved": "https://registry.npmjs.org/leaflet.markercluster/-/leaflet.markercluster-1.5.3.tgz",
"integrity": "sha512-vPTw/Bndq7eQHjLBVlWpnGeLa3t+3zGiuM7fJwCkiMFq+nmRuG3RI3f7f4N4TDX7T4NpbAXpR2+NTRSEGfCSeA==",
"peerDependencies": {
"leaflet": "^1.3.1"
}
},
"node_modules/levn": {
"version": "0.4.1",
"resolved": "https://registry.npmjs.org/levn/-/levn-0.4.1.tgz",
+1
View File
@@ -16,6 +16,7 @@
"clickhouse": "^2.6.0",
"clsx": "^2.1.1",
"leaflet": "^1.9.4",
"leaflet.markercluster": "^1.5.3",
"lucide-react": "^0.525.0",
"next": "15.3.4",
"next-themes": "^0.4.6",
+16
View File
@@ -0,0 +1,16 @@
import { NextResponse } from "next/server";
import { getNodePositions } from "@/lib/clickhouse/actions";
export async function GET(req: Request) {
try {
const { searchParams } = new URL(req.url);
const minLat = searchParams.get("minLat");
const maxLat = searchParams.get("maxLat");
const minLng = searchParams.get("minLng");
const maxLng = searchParams.get("maxLng");
const positions = await getNodePositions({ minLat, maxLat, minLng, maxLng });
return NextResponse.json(positions);
} catch (error) {
return NextResponse.json({ error: "Failed to fetch node positions" }, { status: 500 });
}
}
+54
View File
@@ -120,3 +120,57 @@
@apply bg-background text-foreground;
}
}
.custom-node-marker {
width: 16px;
height: 16px;
background: #2563eb; /* blue-600 */
border: 2px solid #fff;
border-radius: 50%;
box-shadow: 0 0 4px rgba(0,0,0,0.2);
display: block;
position: relative;
z-index: 2;
}
.custom-node-marker--green {
background: #22c55e; /* green-500 */
}
.custom-node-marker--blue {
background: #2563eb; /* blue-600 */
}
.custom-node-marker--top {
z-index: 1002 !important;
position: relative;
}
.map-spinner {
width: 28px;
height: 28px;
border: 4px solid #e5e7eb; /* gray-200 */
border-top: 4px solid #2563eb; /* blue-600 */
border-radius: 50%;
animation: map-spin 1s linear infinite;
}
@keyframes map-spin {
0% { transform: rotate(0deg); }
100% { transform: rotate(360deg); }
}
.custom-node-label {
position: absolute;
top: 18px;
left: 50%;
transform: translateX(-50%);
font-size: 12px;
color: #222;
background: rgba(255,255,255,0.85);
padding: 0 4px;
border-radius: 3px;
white-space: nowrap;
pointer-events: none;
font-weight: 500;
box-shadow: 0 1px 2px rgba(0,0,0,0.07);
z-index: 1;
}
+6 -1
View File
@@ -1,6 +1,7 @@
import type { Metadata } from "next";
import { Geist, Geist_Mono } from "next/font/google";
import "./globals.css";
import Header from "../components/Header";
const geistSans = Geist({
variable: "--font-geist-sans",
@@ -26,8 +27,12 @@ export default function RootLayout({
<html lang="en">
<body
className={`${geistSans.variable} ${geistMono.variable} antialiased`}
style={{ '--header-height': '64px' } as React.CSSProperties}
>
{children}
<div className="flex flex-col min-h-screen w-full">
<Header />
<main className="flex-1 flex flex-col w-full">{children}</main>
</div>
</body>
</html>
);
+19
View File
@@ -0,0 +1,19 @@
import Link from "next/link";
export default function NotFound() {
return (
<div className="flex flex-1 flex-col items-center justify-center min-h-[60vh] text-center px-4">
<h1 className="text-6xl font-bold text-primary mb-4">404</h1>
<h2 className="text-2xl font-semibold mb-2">Page Not Found</h2>
<p className="text-muted-foreground mb-6 max-w-md">
Sorry, the page you are looking for does not exist or has been moved.
</p>
<Link
href="/"
className="inline-block bg-blue-600 text-white px-6 py-2 rounded shadow hover:bg-blue-700 transition-colors"
>
Go Home
</Link>
</div>
);
}
+3 -19
View File
@@ -1,21 +1,5 @@
import MapWithChat from "../components/MapWithChat";
import { clickhouse } from "../lib/clickhouse";
import MapWithChatClient from "../components/MapWithChatClient";
// --- Server action ---
export async function getNodePositions() {
const rows = await clickhouse.query(
"SELECT from_node_id, latitude, longitude, altitude, last_seen FROM meshtastic_position_latest"
).toPromise();
return rows as Array<{
from_node_id: string;
latitude: number;
longitude: number;
altitude?: number;
last_seen?: string;
}>;
}
export default async function Home() {
const nodePositions = await getNodePositions();
return <MapWithChat nodePositions={nodePositions} />;
export default function Home() {
return <MapWithChatClient />;
}
+23 -23
View File
@@ -1,35 +1,35 @@
"use client";
import { useState } from "react";
import { MinusIcon, PlusIcon } from "@heroicons/react/24/outline";
export default function ChatBox() {
const [value, setValue] = useState("");
const [minimized, setMinimized] = useState(true);
return (
<div className="w-80 bg-white dark:bg-neutral-900 rounded-lg shadow-lg p-4 flex flex-col h-96">
<div className="flex-1 overflow-y-auto mb-2 text-sm text-gray-700 dark:text-gray-200">
<div className="text-gray-400 text-center mt-8">Chat coming soon...</div>
</div>
<form
className="flex gap-2"
onSubmit={e => {
e.preventDefault();
setValue("");
}}
>
<input
className="flex-1 border rounded px-2 py-1 bg-neutral-100 dark:bg-neutral-800 text-black dark:text-white"
placeholder="Type a message..."
value={value}
onChange={e => setValue(e.target.value)}
disabled
/>
<div
className={`w-80 bg-white dark:bg-neutral-900 rounded-lg shadow-lg flex flex-col ${
minimized ? "min-h-[2.5rem] px-4 py-2" : "h-96 px-4 py-4"
}`}
>
<div className="flex items-center justify-between" style={{ minHeight: '2rem' }}>
<span className="font-semibold text-gray-800 dark:text-gray-100">Chat</span>
<button
type="submit"
className="bg-blue-600 text-white px-3 py-1 rounded disabled:opacity-50"
disabled
className="p-1 rounded hover:bg-neutral-200 dark:hover:bg-neutral-800"
onClick={() => setMinimized((m) => !m)}
aria-label={minimized ? "Maximize chat" : "Minimize chat"}
>
Send
{minimized ? (
<PlusIcon className="h-5 w-5" />
) : (
<MinusIcon className="h-5 w-5" />
)}
</button>
</form>
</div>
{!minimized && (
<div className="flex-1 overflow-y-auto text-sm text-gray-700 dark:text-gray-200">
<div className="text-gray-400 text-center mt-8">Chat coming soon...</div>
</div>
)}
</div>
);
}
+5 -106
View File
@@ -1,113 +1,12 @@
"use client";
import React, { createContext, useContext, useState, useEffect, ReactNode, useRef } from "react";
interface Config {
theme: "light" | "dark";
// Add more config options as needed
}
interface ConfigContextType {
config: Config;
setConfig: (config: Config) => void;
openConfig: () => void;
}
const defaultConfig: Config = {
theme: "light",
};
const ConfigContext = createContext<ConfigContextType | undefined>(undefined);
import React, { ReactNode } from "react";
// Placeholder ConfigProvider that just renders children
export function ConfigProvider({ children }: { children: ReactNode }) {
const [config, setConfigState] = useState<Config>(defaultConfig);
const [showPopover, setShowPopover] = useState(false);
const buttonRef = useRef<HTMLButtonElement | null>(null);
const popoverRef = useRef<HTMLDivElement | null>(null);
useEffect(() => {
const stored = localStorage.getItem("globalConfig");
if (stored) setConfigState(JSON.parse(stored));
}, []);
useEffect(() => {
localStorage.setItem("globalConfig", JSON.stringify(config));
}, [config]);
// Close popover on outside click or Escape
useEffect(() => {
if (!showPopover) return;
function onClick(e: MouseEvent) {
if (
popoverRef.current &&
!popoverRef.current.contains(e.target as Node) &&
buttonRef.current &&
!buttonRef.current.contains(e.target as Node)
) {
setShowPopover(false);
}
}
function onKey(e: KeyboardEvent) {
if (e.key === "Escape") setShowPopover(false);
}
document.addEventListener("mousedown", onClick);
document.addEventListener("keydown", onKey);
return () => {
document.removeEventListener("mousedown", onClick);
document.removeEventListener("keydown", onKey);
};
}, [showPopover]);
const setConfig = (newConfig: Config) => setConfigState(newConfig);
const openConfig = () => setShowPopover(v => !v);
// Provide ref to button for Header
const contextValue = React.useMemo(() => ({ config, setConfig, openConfig }), [config]);
return (
<ConfigContext.Provider value={contextValue}>
{/* Clone header to inject ref */}
{React.Children.map(children, child => {
if (
React.isValidElement(child) &&
child.type &&
(child as any).type.name === "Header"
) {
return React.cloneElement(child, { configButtonRef: buttonRef });
}
return child;
})}
{/* Popover */}
{showPopover && (
<div
ref={popoverRef}
style={{
position: "absolute",
top: buttonRef.current?.getBoundingClientRect().bottom ?? 60,
left: buttonRef.current?.getBoundingClientRect().right ?? window.innerWidth - 300,
zIndex: 1000,
}}
className="fixed bg-white dark:bg-neutral-900 p-6 rounded shadow-lg min-w-[300px] border border-neutral-200 dark:border-neutral-700"
>
<h2 className="text-lg font-bold mb-4">Configuration</h2>
<label className="block mb-2">
Theme:
<select
value={config.theme}
onChange={e => setConfig({ ...config, theme: e.target.value as Config["theme"] })}
className="ml-2 border rounded px-2 py-1"
>
<option value="light">Light</option>
<option value="dark">Dark</option>
</select>
</label>
</div>
)}
</ConfigContext.Provider>
);
return <>{children}</>;
}
// Dummy useConfig hook
export function useConfig() {
const ctx = useContext(ConfigContext);
if (!ctx) throw new Error("useConfig must be used within a ConfigProvider");
return ctx;
return {};
}
+164 -76
View File
@@ -1,7 +1,12 @@
"use client";
import { MapContainer, TileLayer, useMapEvents, Marker, Popup } from "react-leaflet";
import { MapContainer, TileLayer, useMapEvents, Marker, Popup, MapContainerProps, useMap } from "react-leaflet";
import { useRouter, useSearchParams } from "next/navigation";
import { useEffect, useMemo, useRef } from "react";
import { useEffect, useMemo, useRef, useState } from "react";
import 'leaflet/dist/leaflet.css';
import L from "leaflet";
import 'leaflet.markercluster/dist/leaflet.markercluster.js';
import 'leaflet.markercluster/dist/MarkerCluster.css';
import 'leaflet.markercluster/dist/MarkerCluster.Default.css';
const DEFAULT = {
lat: 47.6062, // Seattle
@@ -9,90 +14,173 @@ const DEFAULT = {
zoom: 12,
};
function parseQuery(searchParams: ReturnType<typeof useSearchParams>) {
const lat = parseFloat(searchParams.get("lat") || "");
const lng = parseFloat(searchParams.get("lng") || "");
const zoom = parseInt(searchParams.get("zoom") || "");
return {
lat: isNaN(lat) ? DEFAULT.lat : lat,
lng: isNaN(lng) ? DEFAULT.lng : lng,
zoom: isNaN(zoom) ? DEFAULT.zoom : zoom,
};
}
function MapSync() {
const map = useMapEvents({});
const router = useRouter();
const searchParams = useSearchParams();
const last = useRef({ lat: 0, lng: 0, zoom: 0 });
useEffect(() => {
const onMove = () => {
const center = map.getCenter();
const zoom = map.getZoom();
if (
Math.abs(center.lat - last.current.lat) > 1e-6 ||
Math.abs(center.lng - last.current.lng) > 1e-6 ||
zoom !== last.current.zoom
) {
last.current = { lat: center.lat, lng: center.lng, zoom };
const params = new URLSearchParams(searchParams.toString());
params.set("lat", center.lat.toFixed(5));
params.set("lng", center.lng.toFixed(5));
params.set("zoom", String(zoom));
router.replace("?" + params.toString(), { scroll: false });
}
};
map.on("moveend", onMove);
map.on("zoomend", onMove);
return () => {
map.off("moveend", onMove);
map.off("zoomend", onMove);
};
}, [map, router, searchParams]);
return null;
}
type NodePosition = {
from_node_id: string;
latitude: number;
longitude: number;
altitude?: number;
last_seen?: string;
type?: string;
short_name?: string;
};
interface MapViewProps {
nodePositions?: NodePosition[];
type ClusteredMarkersProps = { nodes: NodePosition[] };
function ClusteredMarkers({ nodes }: ClusteredMarkersProps) {
const map = useMap();
useEffect(() => {
if (!map) return;
const markers = (L as any).markerClusterGroup();
nodes.forEach((node: NodePosition) => {
const markerClass =
node.type === "meshtastic"
? "custom-node-marker custom-node-marker--green"
: node.type === "meshcore"
? "custom-node-marker custom-node-marker--blue custom-node-marker--top"
: "custom-node-marker";
const label = node.short_name ? `<div class='custom-node-label'>${node.short_name}</div>` : '';
const icon = L.divIcon({
className: 'custom-node-marker-container',
iconSize: [16, 32],
iconAnchor: [8, 8],
html: `${label}<div class='${markerClass}'></div>`,
});
const marker = L.marker([node.latitude, node.longitude], { icon });
let popupHtml = `<div><div><b>ID:</b> ${node.from_node_id}</div><div><b>Lat:</b> ${node.latitude}</div><div><b>Lng:</b> ${node.longitude}</div>`;
if (node.altitude !== undefined) popupHtml += `<div><b>Alt:</b> ${node.altitude}</div>`;
if (node.last_seen) popupHtml += `<div><b>Last seen:</b> ${node.last_seen}</div>`;
if (node.type) popupHtml += `<div><b>Type:</b> ${node.type}</div>`;
popupHtml += `</div>`;
marker.bindPopup(popupHtml);
markers.addLayer(marker);
});
map.addLayer(markers);
return () => {
map.removeLayer(markers);
};
}, [map, nodes]);
return null;
}
export default function MapView({ nodePositions = [] }: MapViewProps) {
const searchParams = useSearchParams();
const { lat, lng, zoom } = useMemo(() => parseQuery(searchParams), [searchParams]);
export default function MapView() {
const [nodePositions, setNodePositions] = useState<NodePosition[]>([]);
const [bounds, setBounds] = useState<[[number, number], [number, number]] | null>(null);
const [loading, setLoading] = useState(false);
const fetchController = useRef<AbortController | null>(null);
const lastRequestedBounds = useRef<[[number, number], [number, number]] | null>(null);
function fetchNodes(bounds?: [[number, number], [number, number]]) {
if (fetchController.current) {
fetchController.current.abort();
}
const controller = new AbortController();
fetchController.current = controller;
setLoading(true);
let url = "/api/node-positions";
if (bounds) {
const [[minLat, minLng], [maxLat, maxLng]] = bounds;
url += `?minLat=${minLat}&maxLat=${maxLat}&minLng=${minLng}&maxLng=${maxLng}`;
}
fetch(url, { signal: controller.signal })
.then((res) => res.json())
.then((data) => {
if (Array.isArray(data)) setNodePositions(data);
if (fetchController.current === controller) setLoading(false);
})
.catch((err) => {
if (err.name !== "AbortError") setNodePositions([]);
if (fetchController.current === controller) setLoading(false);
});
}
function isBoundsInside(inner: [[number, number], [number, number]], outer: [[number, number], [number, number]]) {
// inner: [[minLat, minLng], [maxLat, maxLng]]
// outer: [[minLat, minLng], [maxLat, maxLng]]
return (
inner[0][0] >= outer[0][0] && // minLat
inner[0][1] >= outer[0][1] && // minLng
inner[1][0] <= outer[1][0] && // maxLat
inner[1][1] <= outer[1][1] // maxLng
);
}
function MapEventCatcher() {
useMapEvents({
moveend: (e) => {
const b = e.target.getBounds();
const buffer = 0.2; // 20% buffer
const latDiff = b.getNorthEast().lat - b.getSouthWest().lat;
const lngDiff = b.getNorthEast().lng - b.getSouthWest().lng;
const newBounds: [[number, number], [number, number]] = [
[
b.getSouthWest().lat - latDiff * buffer,
b.getSouthWest().lng - lngDiff * buffer,
],
[
b.getNorthEast().lat + latDiff * buffer,
b.getNorthEast().lng + lngDiff * buffer,
],
];
if (!lastRequestedBounds.current || !isBoundsInside(newBounds, lastRequestedBounds.current)) {
setBounds(newBounds);
}
},
zoomend: (e) => {
const b = e.target.getBounds();
const buffer = 0.2; // 20% buffer
const latDiff = b.getNorthEast().lat - b.getSouthWest().lat;
const lngDiff = b.getNorthEast().lng - b.getSouthWest().lng;
const newBounds: [[number, number], [number, number]] = [
[
b.getSouthWest().lat - latDiff * buffer,
b.getSouthWest().lng - lngDiff * buffer,
],
[
b.getNorthEast().lat + latDiff * buffer,
b.getNorthEast().lng + lngDiff * buffer,
],
];
if (!lastRequestedBounds.current || !isBoundsInside(newBounds, lastRequestedBounds.current)) {
setBounds(newBounds);
}
},
});
return null;
}
useEffect(() => {
fetchController.current?.abort(); // abort any in-flight request on effect cleanup
if (bounds) {
fetchNodes(bounds);
lastRequestedBounds.current = bounds;
} else {
fetchNodes();
lastRequestedBounds.current = null;
}
return () => {
fetchController.current?.abort();
};
}, [bounds]);
return (
<MapContainer
center={[lat, lng]}
zoom={zoom}
style={{ width: "100%", height: "100%", zIndex: 1 }}
className="bg-gray-200"
>
<TileLayer
attribution='&copy; OpenStreetMap contributors'
url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
/>
{nodePositions.map((node) => (
<Marker key={node.from_node_id} position={[node.latitude, node.longitude]}>
<Popup>
<div>
<div><b>ID:</b> {node.from_node_id}</div>
<div><b>Lat:</b> {node.latitude}</div>
<div><b>Lng:</b> {node.longitude}</div>
{node.altitude !== undefined && <div><b>Alt:</b> {node.altitude}</div>}
{node.last_seen && <div><b>Last seen:</b> {node.last_seen}</div>}
</div>
</Popup>
</Marker>
))}
<MapSync />
</MapContainer>
<div style={{ width: "100%", height: "100%", position: "relative" }}>
{loading && (
<div style={{ position: "absolute", top: 16, right: 16, zIndex: 1000 }}>
<div className="map-spinner" />
</div>
)}
<MapContainer
center={[DEFAULT.lat, DEFAULT.lng]}
zoom={DEFAULT.zoom}
style={{ width: "100%", height: "100%", zIndex: 1 }}
className="bg-gray-200"
>
<MapEventCatcher />
<TileLayer
attribution='&copy; OpenStreetMap contributors'
url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
/>
<ClusteredMarkers nodes={nodePositions} />
</MapContainer>
</div>
);
}
@@ -1,6 +1,5 @@
"use client";
import MapView from "./MapView";
import ChatBox from "./ChatBox";
import dynamic from "next/dynamic";
type NodePosition = {
from_node_id: string;
@@ -11,14 +10,23 @@ type NodePosition = {
};
interface MapWithChatProps {
nodePositions: NodePosition[];
nodePositions?: NodePosition[];
}
const MapView = dynamic<MapWithChatProps>(
() => import("./MapView"),
{ ssr: false }
);
const ChatBox = dynamic(() => import("./ChatBox"), { ssr: false });
export default function MapWithChat({ nodePositions }: MapWithChatProps) {
return (
<div className="flex flex-col h-[100dvh] w-screen overflow-hidden">
<div
className="flex flex-col w-screen overflow-hidden"
style={{ height: 'calc(100dvh - var(--header-height))' }}
>
<div className="flex-1 relative">
<MapView nodePositions={nodePositions} />
<MapView />
<div className="absolute bottom-6 right-6 z-30">
<ChatBox />
</div>
+24
View File
@@ -0,0 +1,24 @@
"use server";
import { clickhouse } from "./clickhouse";
export async function getNodePositions({ minLat, maxLat, minLng, maxLng }: { minLat?: string | null, maxLat?: string | null, minLng?: string | null, maxLng?: string | null } = {}) {
let where = [
"latitude IS NOT NULL",
"longitude IS NOT NULL"
];
if (minLat) where.push(`latitude >= ${minLat}`);
if (maxLat) where.push(`latitude <= ${maxLat}`);
if (minLng) where.push(`longitude >= ${minLng}`);
if (maxLng) where.push(`longitude <= ${maxLng}`);
const query = `SELECT node_id, name, short_name, latitude, longitude, last_seen, type FROM unified_latest_nodeinfo WHERE ${where.join(" AND ")}`;
const rows = await clickhouse.query(query).toPromise();
return rows as Array<{
node_id: string;
name?: string | null;
short_name?: string | null;
latitude: number;
longitude: number;
last_seen: string;
type: string;
}>;
}
@@ -11,4 +11,4 @@ export const clickhouse = new ClickHouse({
basicAuth: { username: user, password },
isUseGzip: false,
format: 'json',
});
});