more clean up

This commit is contained in:
2025-04-17 21:27:54 -04:00
parent 8e99669487
commit 702da27468
13 changed files with 2727 additions and 404 deletions

File diff suppressed because it is too large Load Diff

View File

@ -10,6 +10,7 @@
},
"dependencies": {
"@tailwindcss/vite": "^4.1.4",
"@turf/turf": "^7.2.0",
"axios": "^1.8.4",
"chart.js": "^4.4.8",
"chartjs-adapter-moment": "^1.0.1",
@ -18,6 +19,7 @@
"moment": "^2.30.1",
"pinia": "^3.0.2",
"pinia-plugin-persistedstate": "^4.2.0",
"rbush": "^4.0.1",
"tailwindcss": "^4.1.4",
"vue": "^3.5.13",
"vue-router": "^4.5.0"

View File

@ -143,16 +143,18 @@ export default class LayersControl {
}
_hideLayer(name) {
console.debug('hideLayer: ', name);
if (this._getLayers().includes(name)) {
this._disableLayerTransitions(name);
this._map.setLayoutProperty(name, 'visibility', 'none');
}
}
_showLayer(name) {
console.debug('showLayer: ', name);
if (this._getLayers().includes(name)) {
this._disableLayerTransitions(name);
this._map.setLayoutProperty(name, 'visibility', 'visible');
}
}
_revertControlAction(config) {
switch(config.type) {

View File

@ -16,6 +16,8 @@ const search = computed({
get: () => ui.searchText,
set: val => ui.search(val),
});
// TODO: reload button is jumpy when it spins
</script>
<template>

View File

@ -4,11 +4,16 @@ import { state } from '@/store';
import CloseActionButton from '@/components/CloseActionButton.vue';
const emit = defineEmits(['dismiss']);
function dismissShowingNodeNeighbours() {
state.selectedNodeToShowNeighbours = null;
emit('dismiss');
const props = defineProps({
node: {
type: Object,
required: false,
validator(value) {
return value === null || typeof value === 'object';
},
}
});
</script>
<template>
@ -21,30 +26,30 @@ function dismissShowingNodeNeighbours() {
leave-from-class="translate-y-0"
leave-to-class="translate-y-full"
>
<div v-show="state.selectedNodeToShowNeighbours" class="fixed left-0 right-0 bottom-0">
<div v-if="state.selectedNodeToShowNeighbours" class="mx-auto w-screen max-w-md p-4">
<div v-show="props.node !== null" class="fixed left-0 right-0 bottom-0">
<div v-if="props.node !== null" class="mx-auto w-screen max-w-md p-4">
<div class="flex h-full flex-col bg-white shadow-xl rounded-xl border">
<div class="p-2">
<div class="flex items-start justify-between">
<div>
<h2 class="font-bold">
{{ state.selectedNodeToShowNeighbours.short_name }} Neighbors
{{ props.node.short_name }} Neighbors
</h2>
<h3
v-if="state.selectedNodeToShowNeighboursType === 'weHeard'"
v-if="state.neighborsModalType === 'weHeard'"
class="text-sm"
>
Nodes heard by {{ state.selectedNodeToShowNeighbours.short_name }}
Nodes heard by {{ props.node.short_name }}
</h3>
<h3
v-if="state.selectedNodeToShowNeighboursType === 'theyHeard'"
v-if="state.neighborsModalType === 'theyHeard'"
class="text-sm"
>
Nodes that heard {{ state.selectedNodeToShowNeighbours.short_name }}
Nodes that heard {{ props.node.short_name }}
</h3>
</div>
<CloseActionButton
@click="dismissShowingNodeNeighbours"
@click="$emit('dismiss')"
class="my-auto ml-3"
/>
</div>

View File

@ -1,13 +1,20 @@
<script setup>
const emit = defineEmits(['dismiss']);
const props = defineProps({
node: {
type: Object,
required: false,
validator(value) {
return value === null || typeof value === 'object';
},
}
});
import { state } from '@/store';
import moment from 'moment';
import { useUIStore } from '@/stores/uiStore';
const ui = useUIStore();
function dismissShowingNodePositionHistory() {
state.selectedNodePositionHistory = [];
state.selectedNodeToShowPositionHistory = null;
ui.collapsePositionHistoryModal();
emit('dismiss');
}
@ -44,8 +51,8 @@ function onPositionHistoryQuickRangeClick(range) {
leave-active-class="transition duration-300 ease-in-out transform"
leave-from-class="translate-y-0"
leave-to-class="translate-y-full">
<div v-show="state.selectedNodeToShowPositionHistory != null" class="fixed left-0 right-0 bottom-0">
<div v-if="state.selectedNodeToShowPositionHistory != null" class="mx-auto w-screen max-w-md p-4">
<div v-show="props.node != null" class="fixed left-0 right-0 bottom-0">
<div v-if="props.node != null" class="mx-auto w-screen max-w-md p-4">
<div class="flex h-full flex-col bg-white shadow-xl rounded-xl border">
<div>
<div class="flex p-2">
@ -61,7 +68,7 @@ function onPositionHistoryQuickRangeClick(range) {
</div>
</a>
</div>
<div class="my-auto mr-auto font-bold">{{ state.selectedNodeToShowPositionHistory.short_name }} Position History</div>
<div class="my-auto mr-auto font-bold">{{ props.node.short_name }} Position History</div>
<div class="flex my-auto ml-3 space-x-2">
<a href="javascript:void(0)" class="rounded-full" @click="dismissShowingNodePositionHistory">
<div class="bg-gray-100 hover:bg-gray-200 p-1 rounded-full">

View File

@ -131,8 +131,8 @@ function formatDate(date) {
<br /><br />
<button @click="state.selectedNode = node" class="border border-gray-300 bg-gray-100 p-1 w-full rounded-sm hover:bg-gray-200 mb-1">Show Full Details</button>
<br />
<button @click="$emit('showNeighbors', 'theyHeard', node.node_id)" class="border border-gray-300 bg-gray-100 p-1 w-full rounded-sm hover:bg-gray-200 mb-1">Show Neighbours (Heard Us)</button>
<button @click="$emit('showNeighbors', node.node_id, 'theyHeard')" class="border border-gray-300 bg-gray-100 p-1 w-full rounded-sm hover:bg-gray-200 mb-1">Show Neighbours (Heard Us)</button>
<br />
<button @click="$emit('showNeighbors', 'weHeard', node.node_id)" class="border border-gray-300 bg-gray-100 p-1 w-full rounded-sm hover:bg-gray-200">Show Neighbours (We Heard)</button>
<button @click="$emit('showNeighbors', node.node_id, 'weHeard')" class="border border-gray-300 bg-gray-100 p-1 w-full rounded-sm hover:bg-gray-200">Show Neighbours (We Heard)</button>
</div>
</template>

View File

@ -0,0 +1,84 @@
import moment from 'moment';
import { useMapStore } from '@/stores/mapStore';
import { useConfigStore } from '@/stores/configStore';
import { isValidCoordinates } from '@/utils';
export function useWaypointProcessor() {
const mapStore = useMapStore();
const config = useConfigStore();
// This function processes new waypoint data
const processNewWaypoints = (newWaypoints) => {
const now = moment();
const processedWaypoints = [];
const processedMarkers = [];
for (const waypoint of newWaypoints) {
// skip waypoints older than configured waypoint max age
if (config.waypointsMaxAge !== null) {
const lastUpdatedAgeInMillis = now.diff(moment(waypoint.updated_at));
if (lastUpdatedAgeInMillis > config.waypointsMaxAge * 1000) {
continue;
}
}
// skip expired waypoints
if (waypoint.expire < Date.now() / 1000) {
continue;
}
// skip waypoints without position
if (!waypoint.latitude || !waypoint.longitude) {
continue;
}
// skip nodes with invalid position
if (isNaN(waypoint.latitude) || isNaN(waypoint.longitude)) {
continue;
}
// fix lat long
waypoint.latitude = waypoint.latitude / 10000000;
waypoint.longitude = waypoint.longitude / 10000000;
// TODO: determine emoji to show as marker icon
const emoji = waypoint.icon === 0 ? 128205 : waypoint.icon;
const emojiText = String.fromCodePoint(emoji);
if (!isValidCoordinates(waypoint.latitude, waypoint.longitude)) {
continue;
}
// create waypoint marker
const marker = {
type: 'Feature',
properties: {
layer: 'waypoints',
},
geometry: {
type: 'Point',
coordinates: [waypoint.longitude, waypoint.latitude]
}
};
// add waypoint & marker to cache
processedWaypoints.push(waypoint);
processedMarkers.push(marker);
}
// Return processed data (waypoints and markers)
return { processedWaypoints, processedMarkers };
};
// Process new data and store it (bulk processing)
const parseWaypointsResponse = (newWaypoints) => {
const { processedWaypoints, processedMarkers } = processNewWaypoints(newWaypoints);
// Clear old data and update in bulk
mapStore.clearWaypoints();
mapStore.setWaypoints(processedWaypoints);
mapStore.setWaypointMarkers(processedMarkers);
};
return {
parseWaypointsResponse,
};
};

View File

@ -1,8 +1,6 @@
export default {
mounted(el, binding) {
console.log('mounted')
el._clickOutsideHandler = (event) => {
console.log('handler')
if (!(el === event.target || el.contains(event.target))) {
binding.value(event);
}

View File

@ -11,6 +11,9 @@ export function setMap(map) {
export function getMap() {
return instance;
}
export function unsetMap() {
instance = null;
}
export const layerGroups = {
nodes: {},

View File

@ -9,12 +9,15 @@ export const state = reactive({
selectedNodeDeviceMetrics: [],
selectedNodePowerMetrics: [],
selectedNodeEnvironmentMetrics: [],
selectedNodeToShowNeighbours: null,
selectedNodeToShowNeighbours: null,
selectedNodeToShowNeighboursType: null,
// new selected node stuff
positionHistoryNode: null,
neighborsNode: null,
// new modal specific stuff
neighborsModalType: null,
// position history
selectedNodeToShowPositionHistory: null,
positionHistoryDateTimeTo: null,
positionHistoryDateTimeFrom: null,
});

View File

@ -1,55 +1,111 @@
import { defineStore } from 'pinia';
import RBush from 'rbush';
import { point, bbox, distance } from '@turf/turf';
export const useMapStore = defineStore('map', {
state: () => ({
// core stuff
nodes: [],
nodeIndex: new RBush(),
waypoints: [],
nodeMarkers: {},
waypointMarkers: [],
// temp stuff
positionHistory: [],
}),
actions: {
// Bulk set nodes and rebuild the spatial index
setNodes(nodes) {
this.nodes = nodes;
this.indexNodes(nodes); // Efficient reindexing after bulk update
},
// Bulk set node markers
setNodeMarkers(markers) {
this.nodeMarkers = markers;
},
addNode(node, marker) {
// TODO do validation i.e. does it exist already?
this.nodes.push(node);
// allow undefined/null marker (nodes don't always have a marker)
if (typeof marker === 'object') this.addNodeMarker(marker);
},
addNodeMarker(marker) {
// TODO do validation checking here -- i.e. do we have the node? is marker.proprties.id set? does it exist already?
this.nodeMarkers[marker.properties.id] = marker;
},
// Clear nodes and markers
clearNodes() {
this.nodes = [];
this.nodeMarkers = {};
this.nodeIndex.clear(); // Clear the spatial index when nodes are cleared
},
// Bulk set waypoints
setWaypoints(waypoints) {
this.waypoints = waypoints;
},
addWaypoint(waypoint, marker) {
this.waypoints.push(waypoint);
this.addWaypointMarker(marker);
},
addWaypointMarker(marker) {
this.waypointMarkers.push(marker);
// Bulk set waypoint markers
setWaypointMarkers(markers) {
this.waypointMarkers = markers;
},
// Clear waypoints and markers
clearWaypoints() {
this.waypoints = [];
this.waypointMarkers = [];
},
// Find a node by ID
findNodeById(id) {
return this.nodes.find((node) => node.node_id.toString() === id.toString()) ?? null;
return this.nodes.find(node => node.node_id.toString() === id.toString()) ?? null;
},
// Find a node marker by ID
findNodeMarkerById(id) {
return this.nodeMarkers[id] ?? null;
},
// Find a random node
findRandomNode() {
return this.nodes[Math.floor(Math.random() * this.nodes.length)] ?? null;
},
// Rebuild the spatial index for a set of nodes
indexNodes(nodes) {
// Clear the previous index
this.nodeIndex.clear();
// Rebuild the index for the new set of nodes
nodes.forEach((node) => {
const nodeMarker = this.findNodeMarkerById(node.node_id);
if (nodeMarker?.geometry?.coordinates) {
const coords = nodeMarker.geometry.coordinates;
const box = bbox(point(coords)); // Get the bounding box for the point
this.nodeIndex.insert({ minX: box[0], minY: box[1], maxX: box[2], maxY: box[3], node });
}
});
},
// Find nearby nodes within a specific distance
findNearbyNodes(node, maxDistance, checkForHeard) {
const nodeMarker = this.findNodeMarkerById(node.node_id);
if (!nodeMarker?.geometry?.coordinates) return [];
const coords = nodeMarker.geometry.coordinates;
const searchBox = bbox(point(coords)); // Get bounding box around the point
// Query the spatial index to find nearby nodes
const nearbyNodes = this.nodeIndex.search({
minX: searchBox[0], minY: searchBox[1], maxX: searchBox[2], maxY: searchBox[3]
});
return nearbyNodes.filter(({ node: nearbyNode }) => {
const nearbyNodeMarker = this.findNodeMarkerById(nearbyNode.node_id);
const distanceToNode = distance(nodeMarker, nearbyNodeMarker, { units: 'meters' });
// For 'theyHeard', check if current node is in the nearby node's neighbors
if (checkForHeard) {
const match = nearbyNode.neighbors?.find(n => n.node_id === node.node_id);
return match && distanceToNode <= maxDistance;
} else {
return distanceToNode <= maxDistance;
}
}).map(({ node: nearbyNode }) => ({
node: nearbyNode,
neighborData: nearbyNode.neighbors?.find(n => n.node_id === node.node_id),
}));
},
},
});

View File

@ -14,14 +14,16 @@ import { useUIStore } from '@/stores/uiStore';
import { useMapStore } from '@/stores/mapStore';
import { useConfigStore } from '@/stores/configStore';
import { useNodeProcessor } from '@/composables/useNodeProcessor';
import { useWaypointProcessor } from '@/composables/useWaypointProcessor';
import axios from 'axios';
import moment from 'moment';
import maplibregl from 'maplibre-gl';
import { point, distance } from '@turf/turf';
import LegendControl from '@/LegendControl';
import LayerControl from '@/LayerControl';
import { onMounted, useTemplateRef, ref, watch, createApp, shallowRef } from 'vue';
import { onMounted, useTemplateRef, ref, watch, createApp, shallowRef, onUnmounted } from 'vue';
import { state } from '@/store';
import {
layerGroups,
@ -33,14 +35,13 @@ import {
clearAllNeighbors,
clearAllWaypoints,
clearAllPositionHistory,
cleanUpPositionHistory,
closeAllTooltips,
closeAllPopups,
cleanUpNodeNeighbors,
clearNodeOutline,
clearMap,
setMap,
getMap,
unsetMap,
} from '@/map';
import { CURRENT_ANNOUNCEMENT_ID } from '@/config';
import {
@ -68,13 +69,14 @@ const ui = useUIStore();
const mapData = useMapStore();
const config = useConfigStore();
const { parseNodesResponse } = useNodeProcessor();
const { parseWaypointsResponse } = useWaypointProcessor();
// watchers
watch(
() => state.positionHistoryDateTimeTo,
(newValue) => {
if (newValue != null) {
loadNodePositionHistory(state.selectedNodeToShowPositionHistory.node_id);
loadNodePositionHistory(state.positionHistoryNode.node_id);
}
}, {deep: true}
);
@ -82,30 +84,60 @@ watch(
() => state.positionHistoryDateTimeFrom,
(newValue) => {
if (newValue != null) {
loadNodePositionHistory(state.selectedNodeToShowPositionHistory.node_id);
loadNodePositionHistory(state.positionHistoryNode.node_id);
}
}, {deep: true}
);
watch(
() => mapData.nodeMarkers,
(newMarkers, oldMarkers) => {
(newMarkers) => {
// This will trigger whenever nodeMarkers change
updateMapNodeSource(newMarkers);
updateMapSourceData('nodes', newMarkers);
},
{ deep: true } // Ensure that nested changes are also observed
);
function updateMapNodeSource(markers) {
const source = getMap().getSource('nodes');
if (source) {
watch(
() => mapData.waypointMarkers,
(newMarkers) => {
// This will trigger whenever waypointMarkers change
updateMapSourceData('waypoints', newMarkers);
},
{ deep: true } // Ensure that nested changes are also observed
);
function updateMapSourceData(sourceName, features) {
const source = getMap().getSource(sourceName);
if (source !== null) {
source.setData({
type: 'FeatureCollection',
features: Object.values(markers),
features: Object.values(features),
});
}
}
function resetNodeNeighbors() {
state.neighborsNode = null;
state.neighborsModalType = null;
cleanUpNodeNeighbors();
}
function cleanUpNodeNeighbors() {
// do map stuff (clean up markers and whatnot)
}
function resetPositionHistory() {
state.positionHistoryNode = null; // clear node, closes ui
mapStore.positionHistory = []; // clears out position history cache
cleanUpPositionHistory();
}
function cleanUpPositionHistory() {
// do map stuff (clean up markers and whatnot)
}
// TODO: this still scales pretty badly, also colors are off
function showNodeOutline(id) {
// remove any existing node circle
clearNodeOutline();
@ -129,7 +161,6 @@ function showNodeOutline(id) {
let adjustedRadius = radiusInMeters * zoomFactor;
// Set a minimum radius (e.g., 10 meters) to avoid disappearing circles
adjustedRadius = Math.max(adjustedRadius, 10);
console.log(adjustedRadius)
// Create a circle as a GeoJSON feature
const geojsonCircle = {
@ -139,330 +170,125 @@ function showNodeOutline(id) {
coordinates: nodeMarker.geometry.coordinates,
},
properties: {
radius: adjustedRadius // You can store the radius in the properties if needed
radius: adjustedRadius,
}
};
getMap().getSource('node-outlines').setData(geojsonCircle);
}
}
function showNeighbors(type, id) {
let func = showNodeNeighboursThatHeardUs;
if (type === 'weHeard') func = showNodeNeighboursThatWeHeard;
func(id);
}
function showNodeNeighboursThatHeardUs(id) {
function showNodeNeighbors(id, direction = 'weHeard') {
cleanUpNodeNeighbors();
// find node
const node = mapData.findNodeById(id);
if (!node) {
const node = useMapStore().findNodeById(id);
if (!node) return;
const nodeMarker = useMapStore().findNodeMarkerById(node.node_id);
if (!nodeMarker?.geometry?.coordinates) return;
state.neighborsNode = node;
state.neighborsModalType = direction;
const neighborFeatures = [];
const neighbors = direction === 'weHeard' ? node.neighbors ?? [] : mapData.findNearbyNodes(node, config.neighborsMaxDistance, true);
// Process neighbors
neighbors.forEach((neighborData) => {
const neighborNode = direction === 'weHeard' ? neighborData : neighborData.node;
const neighbor = direction === 'weHeard' ? neighborData : neighborData.neighborData;
if (neighbor.snr === 0) return;
const neighborNodeMarker = useMapStore().findNodeMarkerById(neighborNode.node_id);
if (!neighborNodeMarker?.geometry?.coordinates) return;
// Calculate the distance in meters between the current node and the neighbor
const from = point(neighborNodeMarker.geometry.coordinates);
const to = point(nodeMarker.geometry.coordinates);
const distanceInMeters = distance(from, to, { units: 'meters' }).toFixed(2);
// Enforce max distance for weHeaerd
if (config.neighborsMaxDistance != null && parseFloat(distanceInMeters) > config.neighborsMaxDistance && direction === 'weHeard') {
return;
}
// find node marker
const nodeMarker = mapData.findNodeMarkerById(node.node_id);
if (!nodeMarker) {
return;
// Create the neighbor feature
const feature = createNeighborFeature(node, neighborNode, neighbor.snr, direction, distanceInMeters);
if (feature) {
neighborFeatures.push(feature);
}
// show overlay
state.selectedNodeToShowNeighbours = node;
state.selectedNodeToShowNeighboursType = 'theyHeard';
// find all nodes that have us as a neighbour
const neighbourNodeInfos = [];
for (const nodeThatMayHaveHeardUs of mapData.nodes) {
// find our node in this nodes neighbours
const nodeNeighbours = nodeThatMayHaveHeardUs.neighbours ?? [];
const neighbour = nodeNeighbours.find(function(neighbour) {
return neighbour.node_id.toString() === node.node_id.toString();
});
// we exist as a neighbour
if (neighbour) {
neighbourNodeInfos.push({
node: nodeThatMayHaveHeardUs,
neighbour: neighbour,
});
}
if (neighborFeatures.length > 0) renderNeighborLines(neighborFeatures);
}
// ensure we have neighbours to show
if (neighbourNodeInfos.length === 0) {
return;
}
// Create a GeoJSON feature for each neighbor
function createNeighborFeature(node, neighborNode, snr, direction, distanceInMeters) {
const neighborNodeMarker = useMapStore().findNodeMarkerById(neighborNode.node_id);
const nodeMarker = useMapStore().findNodeMarkerById(node.node_id);
// add node neighbours
for (const neighbourNodeInfo of neighbourNodeInfos) {
const neighbourNode = neighbourNodeInfo.node;
const neighbour = neighbourNodeInfo.neighbour;
// fixme: skipping zero snr? saw some crazy long neighbours with zero snr...
if (neighbour.snr === 0) {
continue;
}
// find neighbour node marker
const neighbourNodeMarker = mapData.findNodeMarkerById(neighbourNode.node_id);
if (!neighbourNodeMarker) {
continue;
}
// calculate distance in meters between nodes (rounded to 2 decimal places)
const distanceInMeters = neighbourNodeMarker.getLatLng().distanceTo(nodeMarker.getLatLng()).toFixed(2);
// don't show this neighbour connection if further than config allows
if (config.neighborsMaxDistance != null && parseFloat(distanceInMeters) > config.neighborsMaxDistance) {
continue;
}
// add neighbour line to map
const line = L.polyline([
nodeMarker.getLatLng(), // from us
neighbourNodeMarker.getLatLng(), // to neighbour
], {
color: getColourForSnr(neighbour.snr),
opacity: 1,
}).arrowheads({
size: '10px',
fill: true,
offsets: {
start: '25px',
end: '25px',
},
}).addTo(layerGroups.nodeNeighbors);
const tooltip = getNeighbourTooltipContent('theyHeard', node, neighbourNode, distanceInMeters, neighbour.snr);
line.bindTooltip(tooltip, {
sticky: true,
opacity: 1,
interactive: true,
}).bindPopup(tooltip).on('click', function(event) {
// close tooltip on click to prevent tooltip and popup showing at same time
event.target.closeTooltip();
});
}
}
function showNodeNeighboursThatWeHeard(id) {
cleanUpNodeNeighbors();
// find node
const node = mapData.findNodeById(id);
if (!node) {
return;
}
// find node marker
const nodeMarker = mapData.findNodeMarkerById(node.node_id);
if (!nodeMarker) {
return;
}
// show overlay
state.selectedNodeToShowNeighbours = node;
state.selectedNodeToShowNeighboursType = 'weHeard';
// ensure we have neighbours to show
const neighbours = node.neighbours ?? [];
if (neighbours.length === 0) {
return;
}
for (const neighbour of neighbours) {
// fixme: skipping zero snr? saw some crazy long neighbours with zero snr...
if (neighbour.snr === 0) {
continue;
}
// find neighbor node
const neighbourNode = mapData.findNodeById(neighbour.node_id);
if (!neighbourNode) {
continue;
}
// find neighbor node marker
const neighbourNodeMarker = mapData.findNodeMarkerById(neighbour.node_id);
if (!neighbourNodeMarker) {
continue;
}
// calculate distance in meters between nodes (rounded to 2 decimal places)
const distanceInMeters = nodeMarker.getLatLng().distanceTo(neighbourNodeMarker.getLatLng()).toFixed(2);
if (config.neighborsMaxDistance != null && parseFloat(distanceInMeters) > config.neighborsMaxDistance) {
continue;
}
// add neighbour line to map
const line = L.polyline([
neighbourNodeMarker.getLatLng(), // from neighbor
nodeMarker.getLatLng(), // to us
], {
color: getColorForSnr(neighbour.snr),
opacity: 1,
}).arrowheads({
size: '10px',
fill: true,
offsets: {
start: '25px',
end: '25px',
},
}).addTo(layerGroups.nodeNeighbors);
const tooltip = getNeighbourTooltipContent('weHeard', node, neighbourNode, distanceInMeters, neighbour.snr);
line.bindTooltip(tooltip, {
sticky: true,
opacity: 1,
interactive: true,
}).bindPopup(tooltip).on('click', function(event) {
// close tooltip on click to prevent tooltip and popup showing at same time
event.target.closeTooltip();
});
}
}
function onNodesUpdated(nodes) {
const now = moment();
// clear cach
mapData.clearNodes();
for (const node of nodes) {
// skip nodes older than configured node max age
if (config.nodesMaxAge !== null) {
const lastUpdatedAgeInMillis = now.diff(moment(node.updated_at));
if (lastUpdatedAgeInMillis > config.nodesMaxAge * 1000) {
continue;
}
}
// add node to cache
mapData.addNode(node);
// skip nodes without position
if (!node.latitude || !node.longitude) {
continue;
}
// skip nodes with invalid position
if (isNaN(node.latitude) || isNaN(node.longitude)) {
continue;
}
// fix lat long
node.latitude = node.latitude / 10000000;
node.longitude = node.longitude / 10000000;
// icon based on mqtt connection state
let icon = icons.mqttDisconnected;
// use offline icon for nodes older than configured node offline age
if (config.nodesOfflineAge !== null) {
const lastUpdatedAgeInMillis = now.diff(moment(node.updated_at));
if (lastUpdatedAgeInMillis > config.nodesOfflineAge * 1000) {
icon = icons.offline;
}
}
// determine if node was recently heard uplinking packets to mqtt
const nodeHasUplinkedToMqttRecently = hasNodeUplinkedToMqttRecently(node);
if (nodeHasUplinkedToMqttRecently) {
icon = icons.mqttConnected;
}
if (!isValidCoordinates(node.latitude, node.longitude)) {
continue;
}
// create node marker
const marker = {
// Create the GeoJSON line feature for the neighbor connection
return {
id: `line-${node.node_id}-${neighborNode.node_id}`,
type: 'Feature',
properties: {
id: node.node_id,
role: node.role_name,
layer: 'nodes',
color: icon,
},
geometry: {
type: 'Point',
coordinates: [node.longitude, node.latitude]
}
};
// add marker to cache
mapData.addNodeMarker(marker);
}
// set data
const source = getMap().getSource('nodes');
if (source) {
source.setData({
type: 'FeatureCollection',
features: Object.values(mapData.nodeMarkers),
});
}
}
function onWaypointsUpdated(waypoints) {
const now = moment();
// clear cache
mapData.clearWaypoints();
// add waypoints
for (const waypoint of waypoints) {
// skip waypoints older than configured waypoint max age
if (config.waypointsMaxAge !== null) {
const lastUpdatedAgeInMillis = now.diff(moment(waypoint.updated_at));
if (lastUpdatedAgeInMillis > config.waypointsMaxAge * 1000) {
continue;
}
}
// skip expired waypoints
if (waypoint.expire < Date.now() / 1000) {
continue;
}
// skip waypoints without position
if (!waypoint.latitude || !waypoint.longitude) {
continue;
}
// skip nodes with invalid position
if (isNaN(waypoint.latitude) || isNaN(waypoint.longitude)) {
continue;
}
// fix lat long
waypoint.latitude = waypoint.latitude / 10000000;
waypoint.longitude = waypoint.longitude / 10000000;
// TODO: determine emoji to show as marker icon
const emoji = waypoint.icon === 0 ? 128205 : waypoint.icon;
const emojiText = String.fromCodePoint(emoji);
if (!isValidCoordinates(node.latitude, node.longitude)) {
continue;
}
// create waypoint marker
const marker = {
type: 'Feature',
properties: {
layer: 'waypoints',
type: 'LineString',
coordinates: [
neighborNodeMarker.geometry.coordinates, // from neighbor
nodeMarker.geometry.coordinates, // to our node
],
},
properties: {
snr,
color: getColorForSnr(snr),
tooltip: getNeighbourTooltipContent(direction, node, neighborNode, distanceInMeters, snr), // TODO
},
geometry: {
type: 'Point',
coordinates: [waypoint.longitude, waypoint.latitude]
}
};
// add waypoint & marker to cache
mapData.addWaypoint(waypoint, marker);
}
// set data
const source = getMap().getSource('waypoints');
if (source) {
source.setData({
function renderNeighborLines(features) {
const sourceId = 'node-neighbors';
const lineLayerId = 'node-neighbors-line';
// Cleanup any previous layers/sources
if (map.getLayer(lineLayerId)) map.removeLayer(lineLayerId);
if (map.getSource(sourceId)) map.removeSource(sourceId);
// Add source
map.addSource(sourceId, {
type: 'geojson',
data: {
type: 'FeatureCollection',
features: Object.values(mapData.waypointMarkers),
features,
},
});
// Add solid line layer (no animation, no arrows)
map.addLayer({
id: lineLayerId,
type: 'line',
source: sourceId,
paint: {
'line-color': ['get', 'color'],
'line-width': 2,
},
});
// Interactivity: tooltips/popups
map.on('click', lineLayerId, (e) => {
const feature = e.features[0];
new maplibregl.Popup()
.setLngLat(e.lngLat)
.setHTML(feature.properties.tooltip)
.addTo(map);
});
map.on('mouseenter', lineLayerId, () => {
map.getCanvas().style.cursor = 'pointer';
});
map.on('mouseleave', lineLayerId, () => {
map.getCanvas().style.cursor = '';
});
}
}
// TODO
@ -555,7 +381,7 @@ function showNodePositionHistory(nodeId) {
// update ui
state.selectedNode = null;
state.selectedNodeToShowPositionHistory = node;
state.positionHistoryNode = node;
ui.expandPositionHistoryModal();
// close node info tooltip as position history shows under it
@ -571,7 +397,7 @@ function showNodePositionHistory(nodeId) {
}
function loadNodePositionHistory(nodeId) {
state.selectedNodePositionHistory = [];
mapStore.positionHistory = [];
axios.get(buildPath(`/api/v1/nodes/${nodeId}/position-history`), {
params: {
// parse from datetime-local format, and send as unix timestamp in milliseconds
@ -579,8 +405,8 @@ function loadNodePositionHistory(nodeId) {
time_to: moment(state.positionHistoryDateTimeTo, "YYYY-MM-DDTHH:mm").format("x"),
},
}).then((response) => {
state.selectedNodePositionHistory = response.data.position_history;
if (state.selectedNodeToShowPositionHistory != null) {
mapStore.positionHistory = response.data.position_history;
if (state.positionHistoryNode != null) {
clearAllPositionHistory();
onPositionHistoryUpdated(response.data.position_history);
};
@ -610,7 +436,7 @@ function goToNode(id, animate, zoom){
// find node
const node = mapData.findNodeById(id);
if (!node) {
alert("Could not find node: " + id);
alert('Could not find node: ' + id);
return false;
}
@ -658,6 +484,14 @@ function onSearchResultNodeClick(node) {
state.selectedNode = node;
}
onUnmounted(() => {
const map = getMap();
if (map !== null) {
map.remove();
unsetMap();
}
});
onMounted(() => {
const bounds = [
[-100, 70], // top left
@ -674,12 +508,10 @@ onMounted(() => {
layers: [],
glyphs: 'https://demotiles.maplibre.org/font/{fontstack}/{range}.pbf',
},
//center: [-15, 150],
center: [0, 0],
zoom: 2,
fadeDuration: 0,
renderWorldCopies: false
//maxBounds: [[-180, -85], [180, 85]]
});
setMap(map);
map.addControl(new maplibregl.AttributionControl({ compact: true }), 'bottom-right');
@ -692,7 +524,7 @@ onMounted(() => {
}), 'top-left');
const layerControl = new LayerControl({
maps: tileLayers,
initialMap: 'OpenStreetMap',
initialMap: config.selectedTileLayerName,
controls: {
Nodes: {
type: 'radio',
@ -700,7 +532,7 @@ onMounted(() => {
layers: {
'All': {
type: 'layer_control',
hideAllExcept: ['nodes', 'node-outlines'],
hideAllExcept: ['nodes', 'node-outlines', 'node-neighbors-line'],
disableCluster: 'nodes',
},
'Routers': {
@ -711,7 +543,7 @@ onMounted(() => {
},
'Clustered': {
type: 'layer_control',
hideAllExcept: ['clusters', 'unclustered-points', 'cluster-count', 'node-outlines'],
hideAllExcept: ['clusters', 'unclustered-points', 'cluster-count', 'node-outlines', 'node-neighbors-line'],
},
'None': {
type: 'layer_control',
@ -721,7 +553,7 @@ onMounted(() => {
},
Overlays: {
type: 'checkbox',
default: ['Legend', 'Position History'],
default: config.enabledOverlayLayers,
layers: {
'Legend': {
type: 'toggle_element',
@ -1136,10 +968,10 @@ onMounted(() => {
<HardwareModelList />
<Settings />
<NodeInfo @show-position-history="showNodePositionHistory"/>
<NodeNeighborsModal @dismiss="cleanUpNodeNeighbors" />
<NodePositionHistoryModal @dismiss="cleanUpPositionHistory" />
<NodeNeighborsModal @dismiss="resetNodeNeighbors" :node="state.neighborsNode"/>
<NodePositionHistoryModal @dismiss="resetPositionHistory" :node="state.positionHistoryNode"/>
<TracerouteInfo @go-to="goToNode" />
<Teleport v-if="popupTarget && selectedNode" :to="popupTarget">
<NodeTooltip :node="selectedNode" @show-neighbors="showNeighbors"/>
<NodeTooltip :node="selectedNode" @show-neighbors="showNodeNeighbors"/>
</Teleport>
</template>