2947 lines
97 KiB
JavaScript
2947 lines
97 KiB
JavaScript
/*
|
||
* Dispatcher-View
|
||
*
|
||
* Initialisierung:
|
||
* 1. Straßen und Gruppen per AJAX laden
|
||
* 2. Zugriffstoken holen und WebSocket mit Code 0 authentifizieren
|
||
* 3. Karte, Polylines, Marker und Kontrollansicht aufbauen
|
||
*/
|
||
|
||
const tenant = window.CMBNET_TENANT || window.location.pathname.split('/')[1];
|
||
const apiBase = `/${tenant}/api`;
|
||
const wsUrl = `${window.location.protocol === 'https:' ? 'wss' : 'ws'}://${window.location.host}/${tenant}/ws`;
|
||
const storageKey = `cmbnet:${tenant}:map`;
|
||
const themeStorageKey = 'cmbnet:theme';
|
||
const currentAccountId = Number(window.CMBNET_ACCOUNT_ID) || null;
|
||
|
||
const DEFAULT_SETTINGS = {
|
||
opacity: 0.7,
|
||
weight: 20, // Meter
|
||
baseLayer: 'osm',
|
||
center: null,
|
||
zoom: null
|
||
};
|
||
|
||
const STREET_STATES = ['unbearbeitet', 'zugewiesen', 'erledigt'];
|
||
const GROUP_STATES = ['offen', 'unterwegs', 'online', 'pausierend', 'fertig'];
|
||
const GROUP_MARKER_MAX_AGE_SECONDS = 30 * 60;
|
||
const STREET_COLORS = {
|
||
unbearbeitet: '#1f6feb',
|
||
zugewiesen: '#d62828',
|
||
erledigt: '#2e9e4f'
|
||
};
|
||
|
||
const dispatcherState = {
|
||
settings: {...DEFAULT_SETTINGS},
|
||
streets: [],
|
||
streetById: new Map(),
|
||
groups: [],
|
||
groupById: new Map(),
|
||
accounts: [],
|
||
accountById: new Map(),
|
||
lastCode0ReceivedAt: Date.now(),
|
||
heartbeatTimeoutId: null,
|
||
heartbeatWarningShown: false,
|
||
groupMessageTargetId: null,
|
||
polylinesByStreetId: new Map(),
|
||
markersByGroupId: new Map(),
|
||
browserLatLng: null,
|
||
ws: null,
|
||
authenticated: false,
|
||
reconnectTimer: null,
|
||
crosshairGroupId: null,
|
||
currentStreetId: null,
|
||
streetsDialogGroupId: null,
|
||
aliasGroupId: null,
|
||
chatGroupId: null,
|
||
chatByGroup: new Map(),
|
||
chatKeysByGroup: new Map(),
|
||
infoMessages: [],
|
||
infoMessageKeys: new Set(),
|
||
streetSearchResults: [],
|
||
streetSearchActiveIndex: -1,
|
||
streetSearchRequestId: 0,
|
||
houseNumberMarker: null,
|
||
unloading: false
|
||
};
|
||
|
||
const AudioContext = window.AudioContext || window.webkitAudioContext;
|
||
const audioCtx = new AudioContext();
|
||
|
||
let map;
|
||
let osmLayer;
|
||
let aerialLayer;
|
||
let currentBaseLayer;
|
||
|
||
document.addEventListener('DOMContentLoaded', initDispatcher);
|
||
|
||
async function initDispatcher() {
|
||
loadStoredSettings();
|
||
initMap();
|
||
bindStaticUi();
|
||
updateClock();
|
||
setInterval(updateClock, 1000);
|
||
|
||
try {
|
||
const [streets, groups, accounts] = await Promise.all([
|
||
fetchJson(`${apiBase}/init/streets`),
|
||
fetchJson(`${apiBase}/init/groups`),
|
||
fetchJson(`${apiBase}/init/accounts`).catch(() => [])
|
||
]);
|
||
dispatcherState.streets = Array.isArray(streets) ? streets : [];
|
||
dispatcherState.groups = Array.isArray(groups) ? groups : [];
|
||
dispatcherState.accounts = Array.isArray(accounts) ? accounts : [];
|
||
indexData();
|
||
buildPolylines();
|
||
if (window.CMBNET_VIEW_MODE === 'observer') {
|
||
const accordion = document.getElementById('groupAccordion');
|
||
if (accordion) {
|
||
accordion.innerHTML = '';
|
||
}
|
||
} else {
|
||
buildGroupAccordion();
|
||
}
|
||
applySettingsToUi();
|
||
placeKnownGroupMarkers();
|
||
} catch (error) {
|
||
console.error('Initialdaten konnten nicht geladen werden:', error);
|
||
const accordion = document.getElementById('groupAccordion');
|
||
if (accordion && typeof showAccordionError === 'function') {
|
||
showAccordionError('Die Straßen und Gruppen konnten nicht geladen werden.');
|
||
}
|
||
}
|
||
|
||
ensureInitialView();
|
||
updateAllPolylineStyles();
|
||
placeUnknownGroupMarkers();
|
||
if (window.CMBNET_VIEW_MODE === 'observer') {
|
||
setInterval(() => {
|
||
const now = Date.now();
|
||
dispatcherState.groups.forEach(group => {
|
||
updateGroupMarkerOpacity(group, now);
|
||
const marker = dispatcherState.markersByGroupId.get(Number(group.id));
|
||
if (marker) {
|
||
updateGroupMarkerLabel(group, marker);
|
||
updateGroupMarkerTooltip(group, marker);
|
||
}
|
||
});
|
||
}, 30000);
|
||
}
|
||
setConnectionStatus('Verbinde …', '');
|
||
connectWebSocket();
|
||
|
||
window.addEventListener('beforeunload', () => {
|
||
dispatcherState.unloading = true;
|
||
if (dispatcherState.reconnectTimer) clearTimeout(dispatcherState.reconnectTimer);
|
||
if (dispatcherState.ws) dispatcherState.ws.close();
|
||
});
|
||
}
|
||
|
||
/* ------------------------------------------------------------------ */
|
||
/* Initialdaten und LocalStorage */
|
||
/* ------------------------------------------------------------------ */
|
||
|
||
async function fetchJson(url, options = {}) {
|
||
const response = await fetch(url, {credentials: 'same-origin', ...options});
|
||
if (!response.ok) {
|
||
throw new Error(`${url}: HTTP ${response.status}`);
|
||
}
|
||
return response.json();
|
||
}
|
||
|
||
function loadStoredSettings() {
|
||
let saved = {};
|
||
try {
|
||
const raw = localStorage.getItem(storageKey);
|
||
if (raw) saved = JSON.parse(raw);
|
||
} catch (error) {
|
||
console.warn('Gespeicherte Karteneinstellungen konnten nicht gelesen werden.', error);
|
||
}
|
||
|
||
const center = Array.isArray(saved.center) && saved.center.length === 2
|
||
? saved.center.map(Number)
|
||
: null;
|
||
const validCenter = center
|
||
&& center.every(Number.isFinite)
|
||
&& Math.abs(center[0]) <= 90
|
||
&& Math.abs(center[1]) <= 180
|
||
? center
|
||
: null;
|
||
|
||
dispatcherState.settings = {
|
||
opacity: clampNumber(saved.opacity, 0, 1, DEFAULT_SETTINGS.opacity),
|
||
weight: clampNumber(saved.weight, 1, 100, DEFAULT_SETTINGS.weight),
|
||
baseLayer: saved.baseLayer === 'aerial' ? 'aerial' : 'osm',
|
||
center: validCenter,
|
||
zoom: Number.isFinite(Number(saved.zoom)) && Number(saved.zoom) > 0
|
||
? Number(saved.zoom)
|
||
: null
|
||
};
|
||
}
|
||
|
||
function saveStoredSettings() {
|
||
if (map) {
|
||
const center = map.getCenter();
|
||
dispatcherState.settings.center = [center.lat, center.lng];
|
||
dispatcherState.settings.zoom = map.getZoom();
|
||
}
|
||
|
||
try {
|
||
localStorage.setItem(storageKey, JSON.stringify(dispatcherState.settings));
|
||
} catch (error) {
|
||
console.warn('Karteneinstellungen konnten nicht gespeichert werden.', error);
|
||
}
|
||
}
|
||
|
||
function clampNumber(value, min, max, fallback) {
|
||
const number = Number(value);
|
||
if (!Number.isFinite(number)) return fallback;
|
||
return Math.min(max, Math.max(min, number));
|
||
}
|
||
|
||
function initTheme() {
|
||
applyTheme(document.documentElement.dataset.theme, false);
|
||
|
||
document.getElementById('darkModeToggle').addEventListener('change', event => {
|
||
applyTheme(event.target.checked ? 'dark' : 'light', true);
|
||
});
|
||
|
||
window.addEventListener('storage', event => {
|
||
if (event.key === themeStorageKey) applyTheme(event.newValue, false);
|
||
});
|
||
}
|
||
|
||
function applyTheme(theme, persist) {
|
||
const normalized = theme === 'dark' ? 'dark' : 'light';
|
||
document.documentElement.dataset.theme = normalized;
|
||
|
||
const toggle = document.getElementById('darkModeToggle');
|
||
if (toggle) toggle.checked = normalized === 'dark';
|
||
|
||
if (!persist) return;
|
||
|
||
try {
|
||
localStorage.setItem(themeStorageKey, normalized);
|
||
} catch (error) {
|
||
console.warn('Theme-Einstellung konnte nicht gespeichert werden.', error);
|
||
}
|
||
}
|
||
|
||
function indexData() {
|
||
dispatcherState.streetById.clear();
|
||
dispatcherState.streets.forEach(street => {
|
||
dispatcherState.streetById.set(Number(street.id), street);
|
||
});
|
||
|
||
dispatcherState.groupById.clear();
|
||
dispatcherState.groups.forEach(group => {
|
||
group.id = Number(group.id);
|
||
group.last_pos_ts = parseTimestamp(group.last_pos_at);
|
||
dispatcherState.groupById.set(group.id, group);
|
||
});
|
||
|
||
dispatcherState.groups.sort((a, b) => a.id - b.id);
|
||
|
||
dispatcherState.accountById.clear();
|
||
dispatcherState.accounts.forEach(account => {
|
||
account.id = Number(account.id);
|
||
dispatcherState.accountById.set(account.id, account);
|
||
});
|
||
}
|
||
|
||
/* ------------------------------------------------------------------ */
|
||
/* Karte */
|
||
/* ------------------------------------------------------------------ */
|
||
|
||
function initMap() {
|
||
map = L.map('map', {
|
||
zoomControl: true,
|
||
preferCanvas: true,
|
||
minZoom: 2
|
||
});
|
||
map.setView([51.0, 10.0], 6);
|
||
|
||
osmLayer = L.tileLayer('https://tile.openstreetmap.org/{z}/{x}/{y}.png', {
|
||
maxZoom: 19,
|
||
attribution: '© OpenStreetMap-Mitwirkende'
|
||
});
|
||
aerialLayer = L.tileLayer(
|
||
'https://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}',
|
||
{
|
||
maxZoom: 19,
|
||
attribution: 'Tiles © Esri'
|
||
}
|
||
);
|
||
|
||
setBaseLayer(dispatcherState.settings.baseLayer, false);
|
||
map.on('moveend zoomend', saveStoredSettings);
|
||
map.on('zoomend', updateAllPolylineStyles);
|
||
map.on('click', handleMapClick);
|
||
|
||
window.addEventListener('resize', () => map.invalidateSize());
|
||
setTimeout(() => map.invalidateSize(), 0);
|
||
}
|
||
|
||
function setBaseLayer(name, persist = true) {
|
||
if (currentBaseLayer) {
|
||
map.removeLayer(currentBaseLayer);
|
||
}
|
||
|
||
currentBaseLayer = name === 'aerial' ? aerialLayer : osmLayer;
|
||
currentBaseLayer.addTo(map);
|
||
dispatcherState.settings.baseLayer = name === 'aerial' ? 'aerial' : 'osm';
|
||
|
||
const mapContainer = map.getContainer();
|
||
mapContainer.classList.toggle(
|
||
'is-aerial-base',
|
||
dispatcherState.settings.baseLayer === 'aerial'
|
||
);
|
||
|
||
const select = document.getElementById('baseLayerSelect');
|
||
if (select) select.value = dispatcherState.settings.baseLayer;
|
||
|
||
if (persist) saveStoredSettings();
|
||
}
|
||
|
||
function ensureInitialView() {
|
||
if (dispatcherState.settings.center && dispatcherState.settings.zoom !== null) {
|
||
map.setView(dispatcherState.settings.center, dispatcherState.settings.zoom);
|
||
return;
|
||
}
|
||
|
||
const bounds = collectAllStreetBounds();
|
||
if (bounds.isValid()) {
|
||
map.fitBounds(bounds, {padding: [24, 24], maxZoom: 16});
|
||
}
|
||
}
|
||
|
||
function collectAllStreetBounds() {
|
||
const bounds = L.latLngBounds([]);
|
||
|
||
dispatcherState.streets.forEach(street => {
|
||
const streetBounds = bboxToBounds(street.bbox);
|
||
if (streetBounds) bounds.extend(streetBounds);
|
||
});
|
||
|
||
if (!bounds.isValid()) {
|
||
dispatcherState.polylinesByStreetId.forEach(lines => {
|
||
lines.forEach(line => {
|
||
line.getLatLngs().forEach(latlng => bounds.extend(latlng));
|
||
});
|
||
});
|
||
}
|
||
|
||
return bounds;
|
||
}
|
||
|
||
/**
|
||
* Unterstützt das im Projekt verwendete Format [[nwLon, nwLat], [seLon, seLat]]
|
||
* sowie flache GeoJSON-Bounding-Boxen [west, south, east, north].
|
||
*/
|
||
function bboxToBounds(bbox) {
|
||
if (!bbox) return null;
|
||
|
||
if (Array.isArray(bbox) && bbox.length === 2
|
||
&& Array.isArray(bbox[0]) && Array.isArray(bbox[1])
|
||
&& bbox[0].length >= 2 && bbox[1].length >= 2) {
|
||
const lon1 = Number(bbox[0][0]);
|
||
const lat1 = Number(bbox[0][1]);
|
||
const lon2 = Number(bbox[1][0]);
|
||
const lat2 = Number(bbox[1][1]);
|
||
if ([lon1, lat1, lon2, lat2].every(Number.isFinite)) {
|
||
return L.latLngBounds([lat1, lon1], [lat2, lon2]);
|
||
}
|
||
}
|
||
|
||
if (Array.isArray(bbox) && bbox.length === 4 && bbox.every(Number.isFinite)) {
|
||
const [west, south, east, north] = bbox.map(Number);
|
||
return L.latLngBounds([south, west], [north, east]);
|
||
}
|
||
|
||
if (bbox && typeof bbox === 'object' && !Array.isArray(bbox)) {
|
||
const south = Number(bbox.south ?? bbox.minLat);
|
||
const west = Number(bbox.west ?? bbox.minLon);
|
||
const north = Number(bbox.north ?? bbox.maxLat);
|
||
const east = Number(bbox.east ?? bbox.maxLon);
|
||
if ([south, west, north, east].every(Number.isFinite)) {
|
||
return L.latLngBounds([south, west], [north, east]);
|
||
}
|
||
}
|
||
|
||
return null;
|
||
}
|
||
|
||
function fitAllStreetBounds() {
|
||
const bounds = collectAllStreetBounds();
|
||
if (bounds.isValid()) {
|
||
map.fitBounds(bounds, {padding: [24, 24], maxZoom: 16});
|
||
} else {
|
||
map.setView([51.0, 10.0], 6);
|
||
}
|
||
}
|
||
|
||
/* ------------------------------------------------------------------ */
|
||
/* Polylines */
|
||
/* ------------------------------------------------------------------ */
|
||
|
||
function getStreetFragments() {
|
||
// Unterstützt sowohl window-Zuweisungen (window.Strasse2Polylines /
|
||
// window.STRASSE2POLYLINES) als auch globale const/let-Deklarationen im
|
||
// externen str2pl.js-Fragment.
|
||
if (typeof Strasse2Polylines !== 'undefined') return Strasse2Polylines;
|
||
if (typeof STRASSE2POLYLINES !== 'undefined') return STRASSE2POLYLINES;
|
||
return window.Strasse2Polylines || window.STRASSE2POLYLINES || {};
|
||
}
|
||
|
||
function tooltipElement(text) {
|
||
// Leaflet interpretiert String-Inhalte als HTML. Gruppennamen und
|
||
// Straßennamen stammen aus der Datenbank und werden deshalb als
|
||
// Textknoten übergeben.
|
||
const element = document.createElement('span');
|
||
element.textContent = String(text);
|
||
return element;
|
||
}
|
||
|
||
function buildPolylines() {
|
||
const fragments = getStreetFragments();
|
||
const regionBounds = dispatcherState.streets
|
||
.map(street => bboxToBounds(street.bbox))
|
||
.find(bounds => bounds && bounds.isValid()) || null;
|
||
const fallbackCenter = regionBounds
|
||
? regionBounds.getCenter()
|
||
: (dispatcherState.settings.center
|
||
? L.latLng(dispatcherState.settings.center)
|
||
: map.getCenter());
|
||
|
||
dispatcherState.streets.forEach(street => {
|
||
const segments = findStreetSegments(fragments, street.name);
|
||
if (!Array.isArray(segments)) return;
|
||
|
||
const streetBounds = bboxToBounds(street.bbox) || regionBounds;
|
||
const lines = [];
|
||
segments.forEach(segment => {
|
||
if (!Array.isArray(segment)) return;
|
||
const latlngs = segment
|
||
.map(point => normalizeStreetPoint(point, streetBounds, fallbackCenter))
|
||
.filter(Boolean);
|
||
|
||
if (latlngs.length < 2) return;
|
||
|
||
const line = L.polyline(latlngs, polylineStyle(street.state));
|
||
line.bindTooltip(tooltipElement(`${street.name} (${street.state})`), {sticky: true});
|
||
line.on('click', () => {
|
||
if (dispatcherState.crosshairGroupId) return;
|
||
openStreetModal(street.id);
|
||
});
|
||
line.addTo(map);
|
||
lines.push(line);
|
||
});
|
||
|
||
if (lines.length) {
|
||
dispatcherState.polylinesByStreetId.set(Number(street.id), lines);
|
||
}
|
||
});
|
||
}
|
||
|
||
function findStreetSegments(fragments, name) {
|
||
if (!name) return null;
|
||
if (fragments[name]) return fragments[name];
|
||
|
||
const lower = String(name).toLowerCase();
|
||
const matchingKey = Object.keys(fragments).find(key => key.toLowerCase() === lower);
|
||
return matchingKey ? fragments[matchingKey] : null;
|
||
}
|
||
|
||
function normalizeStreetPoint(point, bounds, fallbackCenter) {
|
||
if (!Array.isArray(point) || point.length < 2) return null;
|
||
|
||
const first = Number(point[0]);
|
||
const second = Number(point[1]);
|
||
if (!Number.isFinite(first) || !Number.isFinite(second)) return null;
|
||
|
||
// Die Spezifikation erwartet [Longitude, Latitude]. Das mitgelieferte
|
||
// Godesberg-Fragment enthält historisch bedingt [Latitude, Longitude].
|
||
// Beide Varianten werden akzeptiert und anhand der Straßen-Bounding-Box
|
||
// (bzw. des Kartenmittelpunkts) eindeutig zugeordnet.
|
||
const candidates = [
|
||
[second, first], // [lon, lat]
|
||
[first, second] // [lat, lon]
|
||
].filter(([lat, lon]) => (
|
||
Number.isFinite(lat) && Number.isFinite(lon)
|
||
&& lat >= -90 && lat <= 90
|
||
&& lon >= -180 && lon <= 180
|
||
));
|
||
|
||
if (!candidates.length) return null;
|
||
if (candidates.length === 1) return candidates[0];
|
||
|
||
let pool = candidates;
|
||
if (bounds && bounds.isValid()) {
|
||
const inside = candidates.filter(([lat, lon]) => bounds.contains([lat, lon]));
|
||
if (inside.length) pool = inside;
|
||
}
|
||
|
||
const center = bounds && bounds.isValid() ? bounds.getCenter() : fallbackCenter;
|
||
if (!center) return pool[0];
|
||
|
||
let best = pool[0];
|
||
let bestDistance = squaredCoordinateDistance(best, center);
|
||
for (let i = 1; i < pool.length; i += 1) {
|
||
const distance = squaredCoordinateDistance(pool[i], center);
|
||
if (distance < bestDistance) {
|
||
best = pool[i];
|
||
bestDistance = distance;
|
||
}
|
||
}
|
||
return best;
|
||
}
|
||
|
||
function squaredCoordinateDistance(latlng, center) {
|
||
const dLat = latlng[0] - center.lat;
|
||
const dLng = latlng[1] - center.lng;
|
||
return dLat * dLat + dLng * dLng;
|
||
}
|
||
|
||
/**
|
||
* Rechnet eine reale Länge an der Position `latlng` in Pixel beim aktuellen
|
||
* Zoom der Karte um. Grundlage ist die Längenausdehnung eines Grads am
|
||
* angegebenen Breitengrad.
|
||
*/
|
||
function getPixelsForMeters(mapInstance, latlng, meters) {
|
||
const value = Number(meters);
|
||
if (!Number.isFinite(value) || value <= 0) return 1;
|
||
if (!mapInstance || !latlng) return value;
|
||
|
||
const metersPerDegreeLng = 111320 * Math.cos(latlng.lat * Math.PI / 180);
|
||
if (!Number.isFinite(metersPerDegreeLng) || metersPerDegreeLng <= 0) {
|
||
return value;
|
||
}
|
||
|
||
const lngDelta = value / metersPerDegreeLng;
|
||
const zoom = mapInstance.getZoom();
|
||
const p1 = mapInstance.project(latlng, zoom);
|
||
const p2 = mapInstance.project(L.latLng(latlng.lat, latlng.lng + lngDelta), zoom);
|
||
return p1.distanceTo(p2);
|
||
}
|
||
|
||
function currentPolylineWeight() {
|
||
if (!map) return dispatcherState.settings.weight;
|
||
return getPixelsForMeters(map, map.getCenter(), dispatcherState.settings.weight);
|
||
}
|
||
|
||
function polylineStyle(state) {
|
||
return {
|
||
color: STREET_COLORS[state] || STREET_COLORS.unbearbeitet,
|
||
opacity: dispatcherState.settings.opacity,
|
||
weight: currentPolylineWeight(),
|
||
lineCap: 'round',
|
||
lineJoin: 'round'
|
||
};
|
||
}
|
||
|
||
function recolorStreet(street) {
|
||
const lines = dispatcherState.polylinesByStreetId.get(Number(street.id));
|
||
if (!lines) return;
|
||
|
||
const color = STREET_COLORS[street.state] || STREET_COLORS.unbearbeitet;
|
||
lines.forEach(line => {
|
||
line.setStyle({
|
||
color,
|
||
opacity: dispatcherState.settings.opacity,
|
||
weight: currentPolylineWeight()
|
||
});
|
||
line.setTooltipContent(tooltipElement(`${street.name} (${street.state})`));
|
||
});
|
||
}
|
||
|
||
function updateAllPolylineStyles() {
|
||
const weight = currentPolylineWeight();
|
||
dispatcherState.polylinesByStreetId.forEach(lines => {
|
||
lines.forEach(line => {
|
||
line.setStyle({
|
||
opacity: dispatcherState.settings.opacity,
|
||
weight
|
||
});
|
||
});
|
||
});
|
||
}
|
||
|
||
/* ------------------------------------------------------------------ */
|
||
/* Gruppen, Marker und Accordion */
|
||
/* ------------------------------------------------------------------ */
|
||
|
||
function groupDisplayName(group) {
|
||
return group.aliasname && String(group.aliasname).trim()
|
||
? String(group.aliasname)
|
||
: String(group.id);
|
||
}
|
||
|
||
function groupColor(group) {
|
||
const id = Number(group.id) || 0;
|
||
const hue = Math.round((id * 137.508) % 360);
|
||
return `hsl(${hue}, 72%, 45%)`;
|
||
}
|
||
|
||
function hasPosition(group) {
|
||
return group.last_lat !== null && group.last_lat !== undefined
|
||
&& group.last_lon !== null && group.last_lon !== undefined
|
||
&& Number.isFinite(Number(group.last_lat))
|
||
&& Number.isFinite(Number(group.last_lon));
|
||
}
|
||
|
||
function getGroupAgeInfo(group, now = Date.now()) {
|
||
if (!group.last_pos_ts) {
|
||
return {text: 'unbekannt', ageSeconds: null};
|
||
}
|
||
const ageSeconds = Math.max(0, (now - group.last_pos_ts) / 1000);
|
||
if (ageSeconds <= 120) {
|
||
return {text: 'live', ageSeconds};
|
||
}
|
||
if (ageSeconds <= 600) {
|
||
return {text: 'aktuell', ageSeconds};
|
||
}
|
||
const minutes = Math.floor(ageSeconds / 60);
|
||
if (minutes < 60) {
|
||
return {text: `${minutes} min`, ageSeconds};
|
||
}
|
||
const hours = Math.floor(minutes / 60);
|
||
const restMinutes = minutes % 60;
|
||
if (restMinutes === 0) {
|
||
return {text: `${hours} h`, ageSeconds};
|
||
}
|
||
return {text: `${hours} h ${restMinutes} min`, ageSeconds};
|
||
}
|
||
|
||
function getGroupLastMessagePreview(groupId) {
|
||
const entries = dispatcherState.chatByGroup.get(Number(groupId)) || [];
|
||
if (!entries.length) return '';
|
||
const sorted = entries.slice().sort((a, b) => (b.ts || 0) - (a.ts || 0));
|
||
const latest = sorted[0];
|
||
const text = extractMessageText(latest.text ?? latest.msg ?? '');
|
||
if (!text) return '';
|
||
return text.length > 80 ? `${text.slice(0, 77)}...` : text;
|
||
}
|
||
|
||
function updateGroupMarkerLabel(group, marker) {
|
||
const ageInfo = getGroupAgeInfo(group);
|
||
const element = marker.getElement();
|
||
if (!element) return;
|
||
let label = element.querySelector('.group-marker-label');
|
||
if (!label) {
|
||
label = document.createElement('div');
|
||
label.className = 'group-marker-label';
|
||
const name = document.createElement('div');
|
||
name.className = 'group-marker-label-name';
|
||
const age = document.createElement('div');
|
||
age.className = 'group-marker-label-age';
|
||
label.append(name, age);
|
||
element.appendChild(label);
|
||
}
|
||
const nameEl = label.querySelector('.group-marker-label-name');
|
||
const ageEl = label.querySelector('.group-marker-label-age');
|
||
if (nameEl) nameEl.textContent = groupDisplayName(group);
|
||
if (ageEl) ageEl.textContent = ageInfo.text;
|
||
}
|
||
|
||
function updateGroupMarkerTooltip(group, marker) {
|
||
if (window.CMBNET_VIEW_MODE !== 'observer') {
|
||
marker.bindTooltip(tooltipElement(groupDisplayName(group)), {direction: 'top', offset: [0, -12]});
|
||
return;
|
||
}
|
||
const preview = getGroupLastMessagePreview(group.id);
|
||
if (preview) {
|
||
marker.bindTooltip(tooltipElement(preview), {direction: 'top', offset: [0, -12]});
|
||
} else if (marker.getTooltip()) {
|
||
marker.unbindTooltip();
|
||
}
|
||
}
|
||
|
||
function createGroupMarker(group, latlng) {
|
||
const color = groupColor(group);
|
||
const isObserver = window.CMBNET_VIEW_MODE === 'observer';
|
||
const marker = L.marker(latlng, {
|
||
title: groupDisplayName(group),
|
||
riseOnHover: true,
|
||
icon: L.divIcon({
|
||
className: isObserver ? 'group-marker-icon group-marker-icon--with-label' : 'group-marker-icon',
|
||
html: `<span style="--marker-color:${color}"></span>${isObserver ? '<div class="group-marker-label"><div class="group-marker-label-name"></div><div class="group-marker-label-age"></div></div>' : ''}`,
|
||
iconSize: isObserver ? [28, 28] : [22, 22],
|
||
iconAnchor: isObserver ? [14, 14] : [11, 11]
|
||
})
|
||
});
|
||
if (isObserver) {
|
||
updateGroupMarkerTooltip(group, marker);
|
||
} else {
|
||
marker.bindTooltip(tooltipElement(groupDisplayName(group)), {direction: 'top', offset: [0, -12]});
|
||
}
|
||
marker.on('click', () => {
|
||
if (isObserver) {
|
||
openGroupStreetsModal(group.id);
|
||
}
|
||
});
|
||
marker.addTo(map);
|
||
dispatcherState.markersByGroupId.set(Number(group.id), marker);
|
||
if (isObserver) {
|
||
updateGroupMarkerLabel(group, marker);
|
||
}
|
||
updateGroupMarkerOpacity(group);
|
||
return marker;
|
||
}
|
||
|
||
function markerOpacityForAge(ageSeconds) {
|
||
if (ageSeconds === null || ageSeconds === undefined || !Number.isFinite(ageSeconds)) {
|
||
return 1;
|
||
}
|
||
if (ageSeconds >= GROUP_MARKER_MAX_AGE_SECONDS) return 0;
|
||
return Math.max(0, Math.min(
|
||
1,
|
||
1 - Math.max(0, ageSeconds) / GROUP_MARKER_MAX_AGE_SECONDS
|
||
));
|
||
}
|
||
|
||
function updateGroupMarkerOpacity(group, now = Date.now()) {
|
||
const marker = dispatcherState.markersByGroupId.get(Number(group.id));
|
||
if (!marker) return;
|
||
|
||
const ageSeconds = group.last_pos_ts
|
||
? Math.max(0, (now - group.last_pos_ts) / 1000)
|
||
: null;
|
||
const opacity = markerOpacityForAge(ageSeconds);
|
||
|
||
if (window.CMBNET_VIEW_MODE === 'observer') {
|
||
const element = marker.getElement();
|
||
if (element) {
|
||
element.style.opacity = opacity <= 0 ? '0.3' : String(opacity);
|
||
element.classList.toggle('is-marker-hidden', opacity <= 0);
|
||
updateGroupMarkerLabel(group, marker);
|
||
}
|
||
if (opacity <= 0) marker.closeTooltip();
|
||
return;
|
||
}
|
||
|
||
marker.setOpacity(opacity);
|
||
const element = marker.getElement();
|
||
if (element) element.classList.toggle('is-marker-hidden', opacity <= 0);
|
||
if (opacity <= 0) marker.closeTooltip();
|
||
}
|
||
|
||
function placeKnownGroupMarkers() {
|
||
dispatcherState.groups.forEach(group => {
|
||
if (!hasPosition(group)) return;
|
||
createGroupMarker(group, [Number(group.last_lat), Number(group.last_lon)]);
|
||
});
|
||
}
|
||
|
||
async function placeUnknownGroupMarkers() {
|
||
if (!dispatcherState.groups.some(group => !hasPosition(group))) return;
|
||
|
||
dispatcherState.browserLatLng = await getBrowserLatLng();
|
||
dispatcherState.groups.forEach(group => {
|
||
if (hasPosition(group)) return;
|
||
const existing = dispatcherState.markersByGroupId.get(Number(group.id));
|
||
if (existing) {
|
||
existing.setLatLng(dispatcherState.browserLatLng);
|
||
} else {
|
||
createGroupMarker(group, dispatcherState.browserLatLng);
|
||
}
|
||
});
|
||
}
|
||
|
||
function getBrowserLatLng() {
|
||
return new Promise(resolve => {
|
||
if (!navigator.geolocation) {
|
||
resolve(map.getCenter());
|
||
return;
|
||
}
|
||
|
||
navigator.geolocation.getCurrentPosition(
|
||
position => resolve(L.latLng(
|
||
position.coords.latitude,
|
||
position.coords.longitude
|
||
)),
|
||
() => resolve(map.getCenter()),
|
||
{timeout: 8000, maximumAge: 60000}
|
||
);
|
||
});
|
||
}
|
||
|
||
function updateMarkerPosition(group) {
|
||
if (!hasPosition(group)) return;
|
||
|
||
const latlng = [Number(group.last_lat), Number(group.last_lon)];
|
||
const existing = dispatcherState.markersByGroupId.get(Number(group.id));
|
||
if (existing) {
|
||
existing.setLatLng(latlng);
|
||
if (window.CMBNET_VIEW_MODE === 'observer') {
|
||
updateGroupMarkerTooltip(group, existing);
|
||
updateGroupMarkerLabel(group, existing);
|
||
} else {
|
||
existing.setTooltipContent(tooltipElement(groupDisplayName(group)));
|
||
}
|
||
} else {
|
||
createGroupMarker(group, latlng);
|
||
}
|
||
updateGroupMarkerOpacity(group);
|
||
}
|
||
|
||
function buildGroupAccordion() {
|
||
const container = document.getElementById('groupAccordion');
|
||
container.innerHTML = '';
|
||
|
||
if (!dispatcherState.groups.length) {
|
||
const empty = document.createElement('p');
|
||
empty.className = 'group-empty';
|
||
empty.textContent = 'Keine Gruppen vorhanden.';
|
||
container.appendChild(empty);
|
||
return;
|
||
}
|
||
|
||
dispatcherState.groups.forEach(group => {
|
||
container.appendChild(createGroupElement(group));
|
||
});
|
||
|
||
refreshGroupControls();
|
||
}
|
||
|
||
function createGroupElement(group) {
|
||
const details = document.createElement('details');
|
||
details.className = 'group-item';
|
||
details.dataset.groupId = group.id;
|
||
|
||
const summary = document.createElement('summary');
|
||
|
||
const dot = document.createElement('span');
|
||
dot.className = 'group-dot';
|
||
dot.style.background = groupColor(group);
|
||
|
||
const name = document.createElement('span');
|
||
name.className = 'group-name';
|
||
name.textContent = groupDisplayName(group);
|
||
|
||
const stateBadge = document.createElement('span');
|
||
stateBadge.className = 'group-state';
|
||
stateBadge.textContent = group.state || 'offen';
|
||
|
||
summary.append(dot, name, stateBadge);
|
||
details.appendChild(summary);
|
||
|
||
const content = document.createElement('div');
|
||
content.className = 'group-details';
|
||
|
||
const positionRow = document.createElement('div');
|
||
positionRow.className = 'group-position-row';
|
||
|
||
const locateButton = document.createElement('button');
|
||
locateButton.type = 'button';
|
||
locateButton.className = 'icon-button group-locate';
|
||
locateButton.textContent = '📍';
|
||
locateButton.title = 'Karte auf Gruppenposition zentrieren';
|
||
locateButton.setAttribute('aria-label', 'Karte auf Gruppenposition zentrieren');
|
||
locateButton.addEventListener('click', () => locateGroup(group.id));
|
||
|
||
const progress = document.createElement('progress');
|
||
progress.className = 'group-progress';
|
||
progress.max = 100;
|
||
progress.value = 0;
|
||
|
||
positionRow.append(locateButton, progress);
|
||
|
||
const meta = document.createElement('div');
|
||
meta.className = 'group-position-meta';
|
||
meta.textContent = 'Position unbekannt';
|
||
|
||
const actions = document.createElement('div');
|
||
actions.className = 'group-actions';
|
||
|
||
const crosshairButton = document.createElement('button');
|
||
crosshairButton.type = 'button';
|
||
crosshairButton.className = 'icon-button group-crosshair';
|
||
crosshairButton.dataset.groupId = group.id;
|
||
crosshairButton.textContent = '⌖';
|
||
crosshairButton.title = 'Position auf der Karte setzen';
|
||
crosshairButton.setAttribute('aria-label', 'Position auf der Karte setzen');
|
||
crosshairButton.addEventListener('click', () => toggleCrosshair(group.id));
|
||
|
||
const streetsButton = document.createElement('button');
|
||
streetsButton.type = 'button';
|
||
streetsButton.className = 'icon-button group-streets';
|
||
streetsButton.dataset.groupId = group.id;
|
||
streetsButton.textContent = '☑';
|
||
streetsButton.title = 'Straßen dieser Gruppe anzeigen';
|
||
streetsButton.setAttribute('aria-label', 'Straßen dieser Gruppe anzeigen');
|
||
streetsButton.addEventListener('click', () => openGroupStreetsModal(group.id));
|
||
|
||
const aliasButton = document.createElement('button');
|
||
aliasButton.type = 'button';
|
||
aliasButton.className = 'icon-button group-alias';
|
||
aliasButton.dataset.groupId = group.id;
|
||
aliasButton.textContent = '✎';
|
||
aliasButton.title = 'Aliasnamen ändern';
|
||
aliasButton.setAttribute('aria-label', 'Aliasnamen ändern');
|
||
aliasButton.addEventListener('click', () => openGroupAliasModal(group.id));
|
||
|
||
const stateSelect = document.createElement('select');
|
||
stateSelect.className = 'group-state-select';
|
||
stateSelect.dataset.groupId = group.id;
|
||
stateSelect.title = 'Status der Gruppe ändern';
|
||
stateSelect.setAttribute('aria-label', `Status von ${groupDisplayName(group)} ändern`);
|
||
GROUP_STATES.forEach(state => {
|
||
const option = document.createElement('option');
|
||
option.value = state;
|
||
option.textContent = state;
|
||
option.selected = state === (group.state || 'offen');
|
||
stateSelect.appendChild(option);
|
||
});
|
||
stateSelect.addEventListener('change', () => changeGroupState(group.id, stateSelect));
|
||
|
||
actions.append(crosshairButton, streetsButton, aliasButton, stateSelect);
|
||
|
||
const messageInput = document.createElement('input');
|
||
messageInput.type = 'text';
|
||
messageInput.className = 'group-message';
|
||
messageInput.readOnly = true;
|
||
messageInput.placeholder = 'Noch keine Gruppennachricht';
|
||
messageInput.title = 'Chatverlauf öffnen';
|
||
messageInput.addEventListener('click', () => openChat(group.id));
|
||
|
||
content.append(positionRow, meta, actions, messageInput);
|
||
details.appendChild(content);
|
||
|
||
return details;
|
||
}
|
||
|
||
function updateGroupLastMessagePreview(groupId) {
|
||
const item = document.querySelector(`.group-item[data-group-id="${groupId}"]`);
|
||
if (!item) return;
|
||
const input = item.querySelector('.group-message');
|
||
if (!input) return;
|
||
const entries = dispatcherState.chatByGroup.get(Number(groupId)) || [];
|
||
if (!entries.length) {
|
||
input.value = '';
|
||
input.placeholder = 'Noch keine Gruppennachricht';
|
||
return;
|
||
}
|
||
const last = entries.slice().sort((a, b) => a.ts - b.ts).pop();
|
||
if (!last) {
|
||
input.value = '';
|
||
input.placeholder = 'Noch keine Gruppennachricht';
|
||
return;
|
||
}
|
||
input.placeholder = 'Chatverlauf öffnen';
|
||
const preview = extractMessageText(last.text);
|
||
input.value = `${getSenderDisplay(last.sender_id, last).name}: ${String(preview || '').replace(/\s+/g, ' ')}`;
|
||
}
|
||
|
||
function refreshGroupControls(now = Date.now()) {
|
||
dispatcherState.groups.forEach(group => {
|
||
updateGroupMarkerOpacity(group, now);
|
||
|
||
const item = document.querySelector(`.group-item[data-group-id="${group.id}"]`);
|
||
if (!item) return;
|
||
|
||
const locateButton = item.querySelector('.group-locate');
|
||
const progress = item.querySelector('.group-progress');
|
||
const meta = item.querySelector('.group-position-meta');
|
||
|
||
const known = hasPosition(group);
|
||
const positionTs = group.last_pos_ts;
|
||
const ageSeconds = positionTs ? Math.max(0, (now - positionTs) / 1000) : null;
|
||
|
||
let value = 0;
|
||
let enabled = false;
|
||
|
||
if (known) {
|
||
if (ageSeconds === null) {
|
||
enabled = true;
|
||
value = 0;
|
||
} else {
|
||
value = progressForAge(ageSeconds);
|
||
enabled = ageSeconds <= 3600;
|
||
}
|
||
}
|
||
|
||
locateButton.disabled = !enabled;
|
||
progress.value = Math.round(value);
|
||
|
||
if (known) {
|
||
meta.textContent = positionAgeLabel(ageSeconds);
|
||
} else {
|
||
meta.textContent = 'Position unbekannt';
|
||
}
|
||
});
|
||
}
|
||
|
||
function positionAgeLabel(ageSeconds) {
|
||
if (ageSeconds === null) return 'unbekannt';
|
||
if (ageSeconds < 30) return 'live';
|
||
if (ageSeconds < 120) return 'aktuell';
|
||
return `${Math.floor(ageSeconds / 60)} min`;
|
||
}
|
||
|
||
function progressForAge(ageSeconds) {
|
||
if (ageSeconds < 60) return 100;
|
||
if (ageSeconds >= 3600) return 0;
|
||
return Math.max(0, Math.min(100, 100 * (3600 - ageSeconds) / 3540));
|
||
}
|
||
|
||
function updateGroupSummary(group) {
|
||
const item = document.querySelector(`.group-item[data-group-id="${group.id}"]`);
|
||
if (!item) return;
|
||
|
||
const state = group.state || 'offen';
|
||
const badge = item.querySelector('.group-state');
|
||
if (badge) badge.textContent = state;
|
||
|
||
const select = item.querySelector('.group-state-select');
|
||
if (select && select.value !== state) select.value = state;
|
||
}
|
||
|
||
function changeGroupState(groupId, select) {
|
||
const group = dispatcherState.groupById.get(Number(groupId));
|
||
if (!group) return;
|
||
|
||
const newState = select.value;
|
||
if (!GROUP_STATES.includes(newState)) {
|
||
select.value = group.state || 'offen';
|
||
return;
|
||
}
|
||
if (newState === (group.state || 'offen')) return;
|
||
|
||
const sent = sendWs({
|
||
code: 200,
|
||
msg: JSON.stringify({
|
||
group_id: group.id,
|
||
state: newState,
|
||
actor: currentAccountId
|
||
})
|
||
});
|
||
|
||
if (!sent) {
|
||
select.value = group.state || 'offen';
|
||
return;
|
||
}
|
||
|
||
group.state = newState;
|
||
updateGroupSummary(group);
|
||
}
|
||
|
||
function applyGroupAlias(group) {
|
||
const item = document.querySelector(`.group-item[data-group-id="${group.id}"]`);
|
||
if (item) {
|
||
const name = item.querySelector('.group-name');
|
||
if (name) name.textContent = groupDisplayName(group);
|
||
|
||
const stateSelect = item.querySelector('.group-state-select');
|
||
if (stateSelect) {
|
||
stateSelect.setAttribute(
|
||
'aria-label',
|
||
`Status von ${groupDisplayName(group)} ändern`
|
||
);
|
||
}
|
||
}
|
||
|
||
const marker = dispatcherState.markersByGroupId.get(Number(group.id));
|
||
if (marker) {
|
||
marker.setTooltipContent(tooltipElement(groupDisplayName(group)));
|
||
}
|
||
|
||
if (dispatcherState.streetsDialogGroupId === Number(group.id)
|
||
&& document.getElementById('groupStreetsModal').open) {
|
||
renderGroupStreetsDialog(group.id);
|
||
}
|
||
|
||
if (dispatcherState.chatGroupId === Number(group.id)
|
||
&& document.getElementById('chatModal').open) {
|
||
renderChat();
|
||
}
|
||
|
||
const streetModal = document.getElementById('streetModal');
|
||
if (streetModal.open) {
|
||
const selectedGroupId = document.getElementById('streetGroupSelect').value;
|
||
fillStreetGroupOptions(selectedGroupId);
|
||
}
|
||
}
|
||
|
||
function openGroupAliasModal(groupId) {
|
||
const group = dispatcherState.groupById.get(Number(groupId));
|
||
if (!group) return;
|
||
|
||
dispatcherState.aliasGroupId = Number(group.id);
|
||
document.getElementById('groupAliasTitle').textContent =
|
||
`Aliasname – ${groupDisplayName(group)}`;
|
||
|
||
const input = document.getElementById('groupAliasInput');
|
||
input.value = group.aliasname || '';
|
||
|
||
const dialog = document.getElementById('groupAliasModal');
|
||
if (!dialog.open) dialog.showModal();
|
||
input.focus();
|
||
input.select();
|
||
}
|
||
|
||
function closeGroupAliasModal() {
|
||
const dialog = document.getElementById('groupAliasModal');
|
||
if (dialog.open) dialog.close();
|
||
dispatcherState.aliasGroupId = null;
|
||
}
|
||
|
||
async function saveGroupAlias() {
|
||
const group = dispatcherState.groupById.get(Number(dispatcherState.aliasGroupId));
|
||
if (!group) {
|
||
closeGroupAliasModal();
|
||
return;
|
||
}
|
||
|
||
const input = document.getElementById('groupAliasInput');
|
||
const saveButton = document.getElementById('groupAliasSave');
|
||
const aliasname = input.value.trim();
|
||
|
||
if (saveButton.disabled) return;
|
||
saveButton.disabled = true;
|
||
try {
|
||
const response = await fetch(`${apiBase}/groups/${group.id}/alias`, {
|
||
method: 'POST',
|
||
credentials: 'same-origin',
|
||
headers: {'Content-Type': 'application/json'},
|
||
body: JSON.stringify({aliasname})
|
||
});
|
||
|
||
let data = {};
|
||
try {
|
||
data = await response.json();
|
||
} catch (error) {
|
||
data = {};
|
||
}
|
||
|
||
if (!response.ok || !data.success) {
|
||
throw new Error(data.error || `HTTP ${response.status}`);
|
||
}
|
||
|
||
group.aliasname = data.aliasname ?? aliasname;
|
||
applyGroupAlias(group);
|
||
closeGroupAliasModal();
|
||
} catch (error) {
|
||
console.error('Aliasname konnte nicht gespeichert werden:', error);
|
||
alert(`Aliasname konnte nicht gespeichert werden: ${error.message}`);
|
||
} finally {
|
||
saveButton.disabled = false;
|
||
}
|
||
}
|
||
|
||
function locateGroup(groupId) {
|
||
const group = dispatcherState.groupById.get(Number(groupId));
|
||
if (!group || !hasPosition(group)) return;
|
||
map.setView([Number(group.last_lat), Number(group.last_lon)], 15);
|
||
}
|
||
|
||
function toggleCrosshair(groupId) {
|
||
const id = Number(groupId);
|
||
if (dispatcherState.crosshairGroupId === id) {
|
||
cancelCrosshair();
|
||
return;
|
||
}
|
||
|
||
dispatcherState.crosshairGroupId = id;
|
||
map.getContainer().classList.add('crosshair');
|
||
updateCrosshairButtons();
|
||
}
|
||
|
||
function cancelCrosshair() {
|
||
dispatcherState.crosshairGroupId = null;
|
||
map.getContainer().classList.remove('crosshair');
|
||
updateCrosshairButtons();
|
||
}
|
||
|
||
function updateCrosshairButtons() {
|
||
document.querySelectorAll('.group-crosshair').forEach(button => {
|
||
button.classList.toggle(
|
||
'active',
|
||
Number(button.dataset.groupId) === dispatcherState.crosshairGroupId
|
||
);
|
||
});
|
||
}
|
||
|
||
function handleMapClick(event) {
|
||
const groupId = dispatcherState.crosshairGroupId;
|
||
if (!groupId) return;
|
||
|
||
const group = dispatcherState.groupById.get(Number(groupId));
|
||
if (!group) {
|
||
cancelCrosshair();
|
||
return;
|
||
}
|
||
|
||
const lat = event.latlng.lat;
|
||
const lon = event.latlng.lng;
|
||
const timestamp = Date.now();
|
||
|
||
const sent = sendWs({
|
||
code: 300,
|
||
msg: JSON.stringify({
|
||
group_id: group.id,
|
||
lat,
|
||
lon,
|
||
ts: timestamp,
|
||
actor: currentAccountId
|
||
})
|
||
});
|
||
if (!sent) {
|
||
cancelCrosshair();
|
||
return;
|
||
}
|
||
|
||
group.last_lat = lat;
|
||
group.last_lon = lon;
|
||
group.last_pos_ts = timestamp;
|
||
group.last_pos_at = new Date(timestamp).toISOString();
|
||
|
||
updateMarkerPosition(group);
|
||
refreshGroupControls();
|
||
cancelCrosshair();
|
||
}
|
||
|
||
function startHeartbeatMonitoring() {
|
||
if (dispatcherState.heartbeatTimeoutId) {
|
||
clearTimeout(dispatcherState.heartbeatTimeoutId);
|
||
}
|
||
dispatcherState.heartbeatTimeoutId = setTimeout(checkHeartbeatTimeout, 95000);
|
||
}
|
||
|
||
function checkHeartbeatTimeout() {
|
||
const now = Date.now();
|
||
if (dispatcherState.lastCode0ReceivedAt
|
||
&& now - dispatcherState.lastCode0ReceivedAt > 90000) {
|
||
setConnectionStatus('Nicht verbunden', 'disconnected');
|
||
if (!dispatcherState.heartbeatWarningShown) {
|
||
dispatcherState.heartbeatWarningShown = true;
|
||
showHeartbeatWarning();
|
||
}
|
||
} else {
|
||
dispatcherState.heartbeatWarningShown = false;
|
||
}
|
||
startHeartbeatMonitoring();
|
||
}
|
||
|
||
function showHeartbeatWarning() {
|
||
const dialog = document.getElementById('heartbeatWarningModal');
|
||
if (!dialog) {
|
||
alert('Seit mehr als 90 Sekunden kein Kontakt zum Server.');
|
||
return;
|
||
}
|
||
if (typeof dialog.showModal === 'function') {
|
||
dialog.showModal();
|
||
} else {
|
||
dialog.show();
|
||
}
|
||
}
|
||
|
||
function closeHeartbeatWarningModal() {
|
||
const dialog = document.getElementById('heartbeatWarningModal');
|
||
if (dialog && dialog.open) dialog.close();
|
||
}
|
||
|
||
/* ------------------------------------------------------------------ */
|
||
/* Straßen einer Gruppe */
|
||
/* ------------------------------------------------------------------ */
|
||
|
||
function positionGroupStreetsDialog(dialog, left, top, width = null, height = null) {
|
||
const rect = dialog.getBoundingClientRect();
|
||
const dialogWidth = width ?? rect.width;
|
||
const dialogHeight = height ?? rect.height;
|
||
const maxLeft = Math.max(0, window.innerWidth - dialogWidth);
|
||
const maxTop = Math.max(0, window.innerHeight - dialogHeight);
|
||
|
||
dialog.style.left = `${Math.min(Math.max(left, 0), maxLeft)}px`;
|
||
dialog.style.top = `${Math.min(Math.max(top, 0), maxTop)}px`;
|
||
}
|
||
|
||
function initGroupStreetsDialogDrag() {
|
||
const dialog = document.getElementById('groupStreetsModal');
|
||
const header = dialog.querySelector('header');
|
||
let dragState = null;
|
||
|
||
const finishDrag = event => {
|
||
if (!dragState || event.pointerId !== dragState.pointerId) return;
|
||
if (header.hasPointerCapture?.(event.pointerId)) {
|
||
header.releasePointerCapture(event.pointerId);
|
||
}
|
||
dialog.classList.remove('is-dragging');
|
||
dragState = null;
|
||
};
|
||
|
||
header.addEventListener('pointerdown', event => {
|
||
if (event.button !== 0 || event.isPrimary === false) return;
|
||
if (event.target.closest('button, a, input, select, textarea')) return;
|
||
|
||
const rect = dialog.getBoundingClientRect();
|
||
dragState = {
|
||
pointerId: event.pointerId,
|
||
startX: event.clientX,
|
||
startY: event.clientY,
|
||
left: rect.left,
|
||
top: rect.top,
|
||
width: rect.width,
|
||
height: rect.height
|
||
};
|
||
|
||
dialog.style.left = `${rect.left}px`;
|
||
dialog.style.top = `${rect.top}px`;
|
||
dialog.classList.add('is-dragging');
|
||
header.setPointerCapture?.(event.pointerId);
|
||
event.preventDefault();
|
||
});
|
||
|
||
header.addEventListener('pointermove', event => {
|
||
if (!dragState || event.pointerId !== dragState.pointerId) return;
|
||
|
||
positionGroupStreetsDialog(
|
||
dialog,
|
||
dragState.left + event.clientX - dragState.startX,
|
||
dragState.top + event.clientY - dragState.startY,
|
||
dragState.width,
|
||
dragState.height
|
||
);
|
||
});
|
||
|
||
header.addEventListener('pointerup', finishDrag);
|
||
header.addEventListener('pointercancel', finishDrag);
|
||
|
||
window.addEventListener('resize', () => {
|
||
if (!dialog.open) return;
|
||
const rect = dialog.getBoundingClientRect();
|
||
positionGroupStreetsDialog(dialog, rect.left, rect.top);
|
||
});
|
||
}
|
||
|
||
function openGroupStreetsModal(groupId) {
|
||
const group = dispatcherState.groupById.get(Number(groupId));
|
||
if (!group) return;
|
||
|
||
dispatcherState.streetsDialogGroupId = Number(group.id);
|
||
renderGroupStreetsDialog(group.id);
|
||
|
||
const dialog = document.getElementById('groupStreetsModal');
|
||
if (!dialog.open) dialog.show();
|
||
|
||
const rect = dialog.getBoundingClientRect();
|
||
positionGroupStreetsDialog(dialog, rect.left, rect.top);
|
||
}
|
||
|
||
function closeGroupStreetsModal() {
|
||
const dialog = document.getElementById('groupStreetsModal');
|
||
if (dialog.open) dialog.close();
|
||
dispatcherState.streetsDialogGroupId = null;
|
||
}
|
||
|
||
function renderGroupStreetsDialog(groupId) {
|
||
const group = dispatcherState.groupById.get(Number(groupId));
|
||
if (!group) {
|
||
closeGroupStreetsModal();
|
||
return;
|
||
}
|
||
|
||
document.getElementById('groupStreetsTitle').textContent =
|
||
`Straßen – ${groupDisplayName(group)}`;
|
||
|
||
const container = document.getElementById('groupStreetsContent');
|
||
container.innerHTML = '';
|
||
|
||
const assigned = dispatcherState.streets
|
||
.filter(street => Number(street.group_id) === Number(group.id))
|
||
.sort((a, b) => String(a.name).localeCompare(String(b.name), 'de'));
|
||
|
||
if (!assigned.length) {
|
||
const empty = document.createElement('p');
|
||
empty.className = 'group-streets-empty';
|
||
empty.textContent = 'Dieser Gruppe sind noch keine Straßen zugewiesen.';
|
||
container.appendChild(empty);
|
||
return;
|
||
}
|
||
|
||
const assignedStreets = assigned.filter(street => street.state === 'zugewiesen');
|
||
const completedStreets = assigned.filter(street => street.state === 'erledigt');
|
||
const otherStreets = assigned.filter(
|
||
street => street.state !== 'zugewiesen' && street.state !== 'erledigt'
|
||
);
|
||
|
||
appendGroupStreetSection(container, 'Zugewiesen', assignedStreets, true);
|
||
if (completedStreets.length) {
|
||
appendGroupStreetSection(container, 'Erledigt', completedStreets, false);
|
||
}
|
||
if (otherStreets.length) {
|
||
appendGroupStreetSection(container, 'Weitere', otherStreets, false);
|
||
}
|
||
}
|
||
|
||
function appendGroupStreetSection(container, title, streets, showEmpty) {
|
||
const section = document.createElement('section');
|
||
section.className = 'group-streets-section';
|
||
|
||
const heading = document.createElement('h4');
|
||
heading.textContent = title;
|
||
section.appendChild(heading);
|
||
|
||
if (!streets.length) {
|
||
if (showEmpty) {
|
||
const empty = document.createElement('p');
|
||
empty.className = 'group-streets-empty';
|
||
empty.textContent = 'Keine Straßen im Zustand „zugewiesen“.';
|
||
section.appendChild(empty);
|
||
}
|
||
container.appendChild(section);
|
||
return;
|
||
}
|
||
|
||
const list = document.createElement('ul');
|
||
list.className = 'group-streets-list';
|
||
|
||
streets.forEach(street => {
|
||
const item = document.createElement('li');
|
||
|
||
const button = document.createElement('button');
|
||
button.type = 'button';
|
||
button.className = 'group-street-entry';
|
||
button.title = `Auf die Bounding Box von ${street.name} zoomen`;
|
||
|
||
const name = document.createElement('span');
|
||
name.className = 'group-street-name';
|
||
name.textContent = street.name;
|
||
|
||
const state = document.createElement('span');
|
||
state.className = 'group-street-state';
|
||
state.textContent = street.state;
|
||
|
||
button.append(name, state);
|
||
button.addEventListener('click', () => zoomToStreet(street.id));
|
||
item.appendChild(button);
|
||
list.appendChild(item);
|
||
});
|
||
|
||
section.appendChild(list);
|
||
container.appendChild(section);
|
||
}
|
||
|
||
function zoomToStreet(streetId) {
|
||
const street = dispatcherState.streetById.get(Number(streetId));
|
||
if (!street) return;
|
||
|
||
let bounds = bboxToBounds(street.bbox);
|
||
|
||
if (!bounds || !bounds.isValid()) {
|
||
const lines = dispatcherState.polylinesByStreetId.get(Number(street.id)) || [];
|
||
const fallback = L.latLngBounds([]);
|
||
lines.forEach(line => {
|
||
line.getLatLngs().forEach(latlng => fallback.extend(latlng));
|
||
});
|
||
if (fallback.isValid()) bounds = fallback;
|
||
}
|
||
|
||
if (!bounds || !bounds.isValid()) return;
|
||
map.fitBounds(bounds, {padding: [30, 30], maxZoom: 18});
|
||
}
|
||
|
||
/* ------------------------------------------------------------------ */
|
||
/* Straßensuche und Hausnummern */
|
||
/* ------------------------------------------------------------------ */
|
||
|
||
const STREET_SEARCH_MIN_CHARS = 2;
|
||
const STREET_SEARCH_MAX_RESULTS = 8;
|
||
|
||
function normalizeStreetSearchText(value) {
|
||
return String(value || '')
|
||
.trim()
|
||
.toLocaleLowerCase('de-DE')
|
||
.replace(/ß/g, 'ss')
|
||
.normalize('NFD')
|
||
.replace(/[\u0300-\u036f]/g, '')
|
||
.replace(/\s+/g, ' ');
|
||
}
|
||
|
||
function findStreetBySearchName(value) {
|
||
const normalized = normalizeStreetSearchText(value);
|
||
if (!normalized) return null;
|
||
|
||
return dispatcherState.streets.find(street => (
|
||
normalizeStreetSearchText(street.name) === normalized
|
||
)) || null;
|
||
}
|
||
|
||
function splitStreetAndHouseNumber(value) {
|
||
const text = String(value || '').trim();
|
||
const match = text.match(/^(.*\S)\s+([0-9][0-9A-Za-zÄÖÜäöüß.\/-]*)$/u);
|
||
if (!match) return {streetText: text, houseNumber: null};
|
||
|
||
return {
|
||
streetText: match[1].trim(),
|
||
houseNumber: match[2]
|
||
};
|
||
}
|
||
|
||
function parseStreetSearch(value) {
|
||
const text = String(value || '').trim();
|
||
if (!text) {
|
||
return {text: '', streetText: '', houseNumber: null, street: null};
|
||
}
|
||
|
||
// Ein vollständiger Straßenname hat Vorrang, auch wenn er auf eine Zahl endet.
|
||
const exactStreet = findStreetBySearchName(text);
|
||
if (exactStreet) {
|
||
return {
|
||
text,
|
||
streetText: exactStreet.name,
|
||
houseNumber: null,
|
||
street: exactStreet
|
||
};
|
||
}
|
||
|
||
const split = splitStreetAndHouseNumber(text);
|
||
if (split.houseNumber) {
|
||
const street = findStreetBySearchName(split.streetText);
|
||
return {
|
||
text,
|
||
streetText: street ? street.name : split.streetText,
|
||
houseNumber: split.houseNumber,
|
||
street
|
||
};
|
||
}
|
||
|
||
return {text, streetText: text, houseNumber: null, street: null};
|
||
}
|
||
|
||
function getStreetSearchResults(streetText) {
|
||
const normalized = normalizeStreetSearchText(streetText);
|
||
if (normalized.length < STREET_SEARCH_MIN_CHARS) return [];
|
||
|
||
return dispatcherState.streets
|
||
.filter(street => normalizeStreetSearchText(street.name).startsWith(normalized))
|
||
.sort((a, b) => String(a.name).localeCompare(String(b.name), 'de'))
|
||
.slice(0, STREET_SEARCH_MAX_RESULTS);
|
||
}
|
||
|
||
function setStreetSearchStatus(text, isError = false) {
|
||
const element = document.getElementById('streetSearchStatus');
|
||
if (!element) return;
|
||
|
||
element.textContent = text || '';
|
||
element.classList.toggle('error', Boolean(text) && isError);
|
||
}
|
||
|
||
function closeStreetSearchResults() {
|
||
const list = document.getElementById('streetSearchResults');
|
||
const input = document.getElementById('streetSearchInput');
|
||
|
||
if (list) {
|
||
list.hidden = true;
|
||
list.innerHTML = '';
|
||
}
|
||
if (input) {
|
||
input.setAttribute('aria-expanded', 'false');
|
||
input.removeAttribute('aria-activedescendant');
|
||
}
|
||
|
||
dispatcherState.streetSearchResults = [];
|
||
dispatcherState.streetSearchActiveIndex = -1;
|
||
}
|
||
|
||
function setActiveStreetSearchIndex(index) {
|
||
const list = document.getElementById('streetSearchResults');
|
||
const input = document.getElementById('streetSearchInput');
|
||
const results = dispatcherState.streetSearchResults;
|
||
if (!list || !input || !results.length) return;
|
||
|
||
const normalizedIndex = ((index % results.length) + results.length) % results.length;
|
||
dispatcherState.streetSearchActiveIndex = normalizedIndex;
|
||
|
||
list.querySelectorAll('.street-search-option').forEach((option, optionIndex) => {
|
||
const active = optionIndex === normalizedIndex;
|
||
option.classList.toggle('is-active', active);
|
||
option.setAttribute('aria-selected', active ? 'true' : 'false');
|
||
});
|
||
|
||
const activeOption = list.querySelector(
|
||
`.street-search-option[data-index="${normalizedIndex}"]`
|
||
);
|
||
if (activeOption) {
|
||
input.setAttribute('aria-activedescendant', activeOption.id);
|
||
activeOption.scrollIntoView?.({block: 'nearest'});
|
||
}
|
||
}
|
||
|
||
function renderStreetSearchResults(results) {
|
||
const list = document.getElementById('streetSearchResults');
|
||
const input = document.getElementById('streetSearchInput');
|
||
if (!list || !input) return;
|
||
|
||
if (!results.length) {
|
||
closeStreetSearchResults();
|
||
return;
|
||
}
|
||
|
||
dispatcherState.streetSearchResults = results;
|
||
dispatcherState.streetSearchActiveIndex = -1;
|
||
list.innerHTML = '';
|
||
|
||
results.forEach((street, index) => {
|
||
const option = document.createElement('li');
|
||
option.id = `streetSearchOption${index}`;
|
||
option.className = 'street-search-option';
|
||
option.dataset.index = String(index);
|
||
option.setAttribute('role', 'option');
|
||
option.setAttribute('aria-selected', 'false');
|
||
option.textContent = street.name;
|
||
|
||
// Fokus im Eingabefeld halten, damit der Klick nicht vom blur-
|
||
// Handler verschluckt wird.
|
||
option.addEventListener('mousedown', event => event.preventDefault());
|
||
option.addEventListener('mouseenter', () => setActiveStreetSearchIndex(index));
|
||
option.addEventListener('click', () => selectStreetSearchResult(street));
|
||
|
||
list.appendChild(option);
|
||
});
|
||
|
||
list.hidden = false;
|
||
input.setAttribute('aria-expanded', 'true');
|
||
setActiveStreetSearchIndex(0);
|
||
}
|
||
|
||
function updateStreetSearchSuggestions() {
|
||
const input = document.getElementById('streetSearchInput');
|
||
if (!input) return;
|
||
|
||
const parsed = parseStreetSearch(input.value);
|
||
if (parsed.streetText.length < STREET_SEARCH_MIN_CHARS) {
|
||
closeStreetSearchResults();
|
||
return;
|
||
}
|
||
|
||
const results = parsed.street
|
||
? [parsed.street]
|
||
: getStreetSearchResults(parsed.streetText);
|
||
renderStreetSearchResults(results);
|
||
}
|
||
|
||
function handleStreetSearchInput() {
|
||
setStreetSearchStatus('');
|
||
updateStreetSearchSuggestions();
|
||
}
|
||
|
||
function handleStreetSearchKeydown(event) {
|
||
if (event.key === 'ArrowDown' || event.key === 'ArrowUp') {
|
||
if (!dispatcherState.streetSearchResults.length) {
|
||
updateStreetSearchSuggestions();
|
||
}
|
||
if (!dispatcherState.streetSearchResults.length) return;
|
||
|
||
event.preventDefault();
|
||
const direction = event.key === 'ArrowDown' ? 1 : -1;
|
||
setActiveStreetSearchIndex(
|
||
dispatcherState.streetSearchActiveIndex + direction
|
||
);
|
||
return;
|
||
}
|
||
|
||
if (event.key === 'Escape') {
|
||
closeStreetSearchResults();
|
||
return;
|
||
}
|
||
|
||
if (event.key !== 'Enter') return;
|
||
event.preventDefault();
|
||
|
||
const input = document.getElementById('streetSearchInput');
|
||
const parsed = parseStreetSearch(input.value);
|
||
|
||
if (dispatcherState.streetSearchResults.length
|
||
&& dispatcherState.streetSearchActiveIndex >= 0) {
|
||
selectStreetSearchResult(
|
||
dispatcherState.streetSearchResults[
|
||
dispatcherState.streetSearchActiveIndex
|
||
]
|
||
);
|
||
return;
|
||
}
|
||
|
||
if (parsed.street) {
|
||
performStreetSearch(input.value, parsed.street);
|
||
return;
|
||
}
|
||
|
||
const results = getStreetSearchResults(parsed.streetText);
|
||
if (results.length) {
|
||
selectStreetSearchResult(results[0]);
|
||
return;
|
||
}
|
||
|
||
closeStreetSearchResults();
|
||
setStreetSearchStatus('Keine Straße gefunden.', true);
|
||
}
|
||
|
||
function selectStreetSearchResult(street) {
|
||
const input = document.getElementById('streetSearchInput');
|
||
const parsed = parseStreetSearch(input.value);
|
||
const houseNumber = parsed.houseNumber;
|
||
|
||
input.value = houseNumber ? `${street.name} ${houseNumber}` : street.name;
|
||
closeStreetSearchResults();
|
||
performStreetSearch(input.value, street);
|
||
}
|
||
|
||
async function performStreetSearch(value, selectedStreet = null) {
|
||
const input = document.getElementById('streetSearchInput');
|
||
const text = String(value ?? input.value ?? '').trim();
|
||
const parsed = parseStreetSearch(text);
|
||
|
||
let street = selectedStreet || parsed.street;
|
||
if (!street) {
|
||
const results = getStreetSearchResults(parsed.streetText);
|
||
street = results[0] || null;
|
||
}
|
||
|
||
if (!street) {
|
||
closeStreetSearchResults();
|
||
setStreetSearchStatus('Keine Straße gefunden.', true);
|
||
return;
|
||
}
|
||
|
||
const houseNumber = parsed.houseNumber;
|
||
const requestId = ++dispatcherState.streetSearchRequestId;
|
||
|
||
clearHouseNumberMarker();
|
||
closeStreetSearchResults();
|
||
setStreetSearchStatus('');
|
||
input.value = houseNumber ? `${street.name} ${houseNumber}` : street.name;
|
||
zoomToStreet(street.id);
|
||
|
||
if (!houseNumber) return;
|
||
|
||
setStreetSearchStatus(`Hausnummer ${houseNumber} wird gesucht …`);
|
||
|
||
try {
|
||
const params = new URLSearchParams({
|
||
street: street.name,
|
||
house_number: houseNumber
|
||
});
|
||
const data = await fetchJson(`${apiBase}/init/hausnummern?${params.toString()}`);
|
||
if (requestId !== dispatcherState.streetSearchRequestId) return;
|
||
|
||
const latitude = Number(data.latitude);
|
||
const longitude = Number(data.longitude);
|
||
if (!data.found || !Number.isFinite(latitude) || !Number.isFinite(longitude)) {
|
||
setStreetSearchStatus(
|
||
`Für Hausnummer ${houseNumber} ist keine Koordinate hinterlegt.`
|
||
);
|
||
return;
|
||
}
|
||
|
||
setHouseNumberMarker(
|
||
[latitude, longitude],
|
||
`${street.name} ${houseNumber}`
|
||
);
|
||
setStreetSearchStatus(`Hausnummer ${houseNumber} markiert.`);
|
||
} catch (error) {
|
||
if (requestId !== dispatcherState.streetSearchRequestId) return;
|
||
console.error('Hausnummer konnte nicht geladen werden:', error);
|
||
setStreetSearchStatus('Hausnummer konnte nicht geladen werden.', true);
|
||
}
|
||
}
|
||
|
||
function clearHouseNumberMarker() {
|
||
if (!dispatcherState.houseNumberMarker) return;
|
||
|
||
map.removeLayer(dispatcherState.houseNumberMarker);
|
||
dispatcherState.houseNumberMarker = null;
|
||
}
|
||
|
||
function setHouseNumberMarker(latlng, label) {
|
||
clearHouseNumberMarker();
|
||
|
||
const marker = L.marker(latlng, {
|
||
title: label,
|
||
keyboard: true,
|
||
icon: L.divIcon({
|
||
className: 'house-number-marker-icon',
|
||
html: '<span class="house-number-flag"><span class="house-number-flag-label"></span></span>',
|
||
iconSize: null,
|
||
iconAnchor: [0, 34]
|
||
})
|
||
});
|
||
|
||
marker.addTo(map);
|
||
|
||
const labelElement = marker.getElement()?.querySelector('.house-number-flag-label');
|
||
if (labelElement) labelElement.textContent = label;
|
||
|
||
marker.bindTooltip(tooltipElement(label), {direction: 'top', offset: [0, -8]});
|
||
marker.on('click', event => {
|
||
if (event.originalEvent) L.DomEvent.stopPropagation(event.originalEvent);
|
||
clearHouseNumberMarker();
|
||
setStreetSearchStatus('Markierung entfernt.');
|
||
});
|
||
|
||
dispatcherState.houseNumberMarker = marker;
|
||
}
|
||
|
||
function initStreetSearch() {
|
||
const input = document.getElementById('streetSearchInput');
|
||
if (!input) return;
|
||
|
||
input.addEventListener('input', handleStreetSearchInput);
|
||
input.addEventListener('keydown', handleStreetSearchKeydown);
|
||
input.addEventListener('focus', () => {
|
||
if (input.value.trim()) updateStreetSearchSuggestions();
|
||
});
|
||
input.addEventListener('blur', () => {
|
||
window.setTimeout(closeStreetSearchResults, 120);
|
||
});
|
||
}
|
||
|
||
/* ------------------------------------------------------------------ */
|
||
/* Straßen-Dialog */
|
||
/* ------------------------------------------------------------------ */
|
||
|
||
function openStreetModal(streetId) {
|
||
const street = dispatcherState.streetById.get(Number(streetId));
|
||
if (!street) return;
|
||
|
||
dispatcherState.currentStreetId = Number(streetId);
|
||
document.getElementById('streetModalTitle').textContent = `Straße: ${street.name}`;
|
||
document.getElementById('streetStateSelect').value = street.state || 'unbearbeitet';
|
||
fillStreetGroupOptions(street.group_id);
|
||
updateStreetGroupVisibility();
|
||
document.getElementById('streetModal').showModal();
|
||
}
|
||
|
||
function closeStreetModal() {
|
||
document.getElementById('streetModal').close();
|
||
}
|
||
|
||
function fillStreetGroupOptions(selectedGroupId) {
|
||
const select = document.getElementById('streetGroupSelect');
|
||
select.innerHTML = '';
|
||
|
||
const empty = document.createElement('option');
|
||
empty.value = '';
|
||
empty.textContent = '-';
|
||
select.appendChild(empty);
|
||
|
||
dispatcherState.groups.forEach(group => {
|
||
const option = document.createElement('option');
|
||
option.value = group.id;
|
||
option.textContent = groupDisplayName(group);
|
||
option.selected = Number(selectedGroupId) === Number(group.id);
|
||
select.appendChild(option);
|
||
});
|
||
}
|
||
|
||
function updateStreetGroupVisibility() {
|
||
const state = document.getElementById('streetStateSelect').value;
|
||
const groupSelect = document.getElementById('streetGroupSelect');
|
||
const groupLabel = document.getElementById('streetGroupLabel');
|
||
const enabled = state === 'zugewiesen';
|
||
|
||
groupSelect.disabled = !enabled;
|
||
groupLabel.classList.toggle('muted', !enabled);
|
||
}
|
||
|
||
function saveStreetState() {
|
||
const street = dispatcherState.streetById.get(dispatcherState.currentStreetId);
|
||
if (!street) return;
|
||
|
||
const newState = document.getElementById('streetStateSelect').value;
|
||
if (!STREET_STATES.includes(newState)) return;
|
||
|
||
let groupId = null;
|
||
if (newState === 'zugewiesen') {
|
||
groupId = Number(document.getElementById('streetGroupSelect').value) || null;
|
||
if (!groupId) {
|
||
alert('Bitte eine Gruppe auswählen.');
|
||
return;
|
||
}
|
||
} else if (newState === 'erledigt' && street.group_id) {
|
||
// Bei "erledigt" bleibt eine bestehende Gruppenzuordnung erhalten.
|
||
groupId = Number(street.group_id);
|
||
}
|
||
|
||
const sent = sendWs({
|
||
code: 100,
|
||
msg: JSON.stringify({
|
||
name: street.name,
|
||
state: newState,
|
||
actor: currentAccountId,
|
||
street_id: street.id,
|
||
group_id: groupId
|
||
})
|
||
});
|
||
|
||
if (sent) closeStreetModal();
|
||
}
|
||
|
||
/* ------------------------------------------------------------------ */
|
||
/* Beobachter-Modus */
|
||
/* ------------------------------------------------------------------ */
|
||
|
||
const observerChatMessages = [];
|
||
const observerChatKeys = new Set();
|
||
|
||
function playNotificationSound() {
|
||
try {
|
||
const AudioContext = window.AudioContext || window.webkitAudioContext;
|
||
if (!AudioContext) return;
|
||
const ctx = new AudioContext();
|
||
const oscillator = ctx.createOscillator();
|
||
const gain = ctx.createGain();
|
||
oscillator.connect(gain);
|
||
gain.connect(ctx.destination);
|
||
oscillator.frequency.setValueAtTime(880, ctx.currentTime);
|
||
oscillator.frequency.exponentialRampToValueAtTime(440, ctx.currentTime + 0.15);
|
||
gain.gain.setValueAtTime(0.1, ctx.currentTime);
|
||
gain.gain.exponentialRampToValueAtTime(0.01, ctx.currentTime + 0.3);
|
||
oscillator.start(ctx.currentTime);
|
||
oscillator.stop(ctx.currentTime + 0.3);
|
||
} catch (error) {
|
||
// ignore
|
||
}
|
||
}
|
||
|
||
function formatObserverTime(timestamp) {
|
||
const ts = normalizeTimestamp(timestamp) || Date.now();
|
||
const date = new Date(ts);
|
||
if (Number.isNaN(date.getTime())) return '';
|
||
return date.toLocaleString('de-DE', {
|
||
day: '2-digit',
|
||
month: '2-digit',
|
||
hour: '2-digit',
|
||
minute: '2-digit',
|
||
second: '2-digit',
|
||
hour12: false
|
||
});
|
||
}
|
||
|
||
function addObserverMessage(message) {
|
||
if (window.CMBNET_VIEW_MODE !== 'observer') return;
|
||
const code = Number(message.code);
|
||
if (!Number.isFinite(code) || code < 1000) return;
|
||
|
||
const senderInfo = getSenderDisplay(message.sender_id, message);
|
||
const payload = extractMessagePayload(message.msg);
|
||
let receiverId = Number(message.receiver_id);
|
||
if (!Number.isFinite(receiverId) && payload && payload.group_id !== undefined) {
|
||
receiverId = Number(payload.group_id);
|
||
}
|
||
if (!Number.isFinite(receiverId) && payload && payload.receiver_id !== undefined) {
|
||
receiverId = Number(payload.receiver_id);
|
||
}
|
||
|
||
let receiver = '';
|
||
if (Number.isFinite(receiverId) && receiverId > 0) {
|
||
const group = dispatcherState.groupById.get(receiverId);
|
||
const account = dispatcherState.accountById.get(receiverId);
|
||
if (group) {
|
||
receiver = `Gruppe ${groupDisplayName(group)}`;
|
||
} else if (account) {
|
||
receiver = account.name;
|
||
} else {
|
||
receiver = `ID ${receiverId}`;
|
||
}
|
||
} else if (code === 1000 || (payload && payload.broadcast)) {
|
||
receiver = 'alle';
|
||
}
|
||
|
||
const text = extractMessageText(message.msg);
|
||
const time = formatObserverTime(message.ts);
|
||
const key = `${code}|${message.sender_id}|${message.receiver_id}|${time}|${text}`;
|
||
if (observerChatKeys.has(key)) return;
|
||
observerChatKeys.add(key);
|
||
|
||
observerChatMessages.push({
|
||
time,
|
||
sender: senderInfo.name,
|
||
receiver,
|
||
text
|
||
});
|
||
|
||
renderObserverChat();
|
||
playNotificationSound();
|
||
}
|
||
|
||
function renderObserverChat() {
|
||
const container = document.getElementById('observerChatMessages');
|
||
if (!container) return;
|
||
container.innerHTML = '';
|
||
|
||
if (!observerChatMessages.length) {
|
||
const empty = document.createElement('div');
|
||
empty.className = 'observer-chat-empty';
|
||
empty.textContent = 'Noch keine Nachrichten.';
|
||
container.appendChild(empty);
|
||
container.scrollTop = container.scrollHeight;
|
||
return;
|
||
}
|
||
|
||
observerChatMessages.forEach((entry, index) => {
|
||
const card = document.createElement('article');
|
||
card.className = 'observer-chat-card';
|
||
if (index % 2 === 1) {
|
||
card.classList.add('observer-chat-card--alt');
|
||
}
|
||
|
||
const meta = document.createElement('div');
|
||
meta.className = 'observer-chat-meta';
|
||
meta.textContent = entry.time;
|
||
|
||
const fromTo = document.createElement('div');
|
||
fromTo.className = 'observer-chat-fromto';
|
||
if (entry.receiver) {
|
||
fromTo.textContent = `${entry.sender} -> ${entry.receiver}`;
|
||
} else {
|
||
fromTo.textContent = entry.sender;
|
||
}
|
||
|
||
const text = document.createElement('div');
|
||
text.className = 'observer-chat-text';
|
||
text.textContent = entry.text;
|
||
|
||
card.append(meta, fromTo, text);
|
||
container.appendChild(card);
|
||
});
|
||
|
||
container.scrollTop = container.scrollHeight;
|
||
}
|
||
|
||
/* ------------------------------------------------------------------ */
|
||
/* Nachrichten und Chat */
|
||
/* ------------------------------------------------------------------ */
|
||
|
||
function openChat(groupId) {
|
||
dispatcherState.chatGroupId = Number(groupId);
|
||
renderChat();
|
||
const dialog = document.getElementById('chatModal');
|
||
if (dialog && typeof dialog.showModal === 'function') {
|
||
dialog.showModal();
|
||
} else if (dialog) {
|
||
dialog.show();
|
||
}
|
||
const container = document.getElementById('chatMessages');
|
||
if (container) {
|
||
container.scrollTop = container.scrollHeight;
|
||
}
|
||
}
|
||
|
||
function closeChatModal() {
|
||
const dialog = document.getElementById('chatModal');
|
||
if (dialog && dialog.open) dialog.close();
|
||
}
|
||
|
||
function sendChatMessageFromModal() {
|
||
const groupId = dispatcherState.chatGroupId;
|
||
const group = groupId !== null ? dispatcherState.groupById.get(Number(groupId)) : null;
|
||
const input = document.getElementById('chatInput');
|
||
if (!group || !input) return;
|
||
const text = String(input.value).trim();
|
||
if (!text) return;
|
||
sendWs({
|
||
code: 1100,
|
||
receiver_id: group.id,
|
||
msg: JSON.stringify({group_id: group.id, text})
|
||
});
|
||
input.value = '';
|
||
input.focus();
|
||
}
|
||
|
||
function renderChat() {
|
||
const group = dispatcherState.groupById.get(Number(dispatcherState.chatGroupId));
|
||
if (!group) return;
|
||
|
||
document.getElementById('chatTitle').textContent =
|
||
`Chat – ${groupDisplayName(group)}`;
|
||
|
||
const container = document.getElementById('chatMessages');
|
||
container.innerHTML = '';
|
||
|
||
const entries = dispatcherState.chatByGroup.get(Number(group.id)) || [];
|
||
if (!entries.length) {
|
||
const empty = document.createElement('div');
|
||
empty.className = 'chat-empty';
|
||
empty.textContent = 'Noch keine Nachrichten.';
|
||
container.appendChild(empty);
|
||
} else {
|
||
entries
|
||
.slice()
|
||
.sort((a, b) => a.ts - b.ts)
|
||
.forEach(entry => {
|
||
const message = document.createElement('div');
|
||
message.className = 'chat-message';
|
||
const senderInfo = getSenderDisplay(entry.sender_id, entry);
|
||
if (senderInfo.isMe) {
|
||
message.classList.add('own');
|
||
}
|
||
|
||
const header = document.createElement('div');
|
||
header.className = 'chat-message-header';
|
||
|
||
const sender = document.createElement('span');
|
||
sender.textContent = senderInfo.name;
|
||
|
||
const time = document.createElement('span');
|
||
time.textContent = formatChatTime(entry.ts);
|
||
|
||
header.append(sender, time);
|
||
|
||
const text = document.createElement('div');
|
||
text.className = 'chat-message-text';
|
||
const textContent = extractMessageText(entry.text);
|
||
text.textContent = textContent;
|
||
|
||
message.append(header, text);
|
||
container.appendChild(message);
|
||
});
|
||
}
|
||
|
||
container.scrollTop = container.scrollHeight;
|
||
}
|
||
|
||
|
||
function getSenderDisplay(senderId, messageOrPayload = null) {
|
||
let payload = null;
|
||
if (messageOrPayload && typeof messageOrPayload === 'object') {
|
||
payload = extractMessagePayload(messageOrPayload.msg ?? messageOrPayload);
|
||
if (!payload && (messageOrPayload.sender || messageOrPayload.group_id)) {
|
||
payload = messageOrPayload;
|
||
}
|
||
}
|
||
|
||
const payloadSender = payload && typeof payload.sender === 'object' ? payload.sender : null;
|
||
const id = Number(
|
||
payloadSender?.account_id
|
||
?? (typeof senderId === 'object' ? senderId.sender_id : senderId)
|
||
);
|
||
|
||
if (payloadSender && payloadSender.name) {
|
||
const name = payloadSender.name;
|
||
const alias = payloadSender.group_alias || payload?.group_alias;
|
||
if (alias && payloadSender.role === 'Gruppe') {
|
||
const display = `${name} (Gruppe: ${alias})`;
|
||
return {name: display, isMe: id === currentAccountId};
|
||
}
|
||
if (alias) {
|
||
const display = `${name} (Gruppe: ${alias})`;
|
||
return {name: display, isMe: id === currentAccountId};
|
||
}
|
||
if (payloadSender.role === 'Gruppe') {
|
||
return {name: `${name} (Gruppe)`, isMe: id === currentAccountId};
|
||
}
|
||
return {name, isMe: id === currentAccountId};
|
||
}
|
||
|
||
if (!Number.isFinite(id) || id <= 0) {
|
||
return {name: 'System', isMe: false};
|
||
}
|
||
if (id === currentAccountId) {
|
||
return {name: 'Ich', isMe: true};
|
||
}
|
||
|
||
const account = dispatcherState.accountById.get(id);
|
||
const group = dispatcherState.groups.find(item => Number(item.account_id) === id);
|
||
const accountName = account && account.name ? account.name : `Account ${id}`;
|
||
if (group) {
|
||
const alias = group.aliasname && String(group.aliasname).trim();
|
||
if (alias) {
|
||
return {name: `${accountName} (Gruppe: ${alias})`, isMe: false};
|
||
}
|
||
return {name: `${accountName} (Gruppe ${group.id})`, isMe: false};
|
||
}
|
||
if (account && account.role === 'Gruppe') {
|
||
return {name: `${accountName} (Gruppe)`, isMe: false};
|
||
}
|
||
return {name: accountName, isMe: false};
|
||
}
|
||
|
||
function senderLabel(senderId) {
|
||
return getSenderDisplay(senderId).name;
|
||
}
|
||
|
||
function formatChatTime(timestamp) {
|
||
if (!timestamp) return '';
|
||
const date = new Date(timestamp);
|
||
if (Number.isNaN(date.getTime())) return '';
|
||
return date.toLocaleString('de-DE', {
|
||
day: '2-digit',
|
||
month: '2-digit',
|
||
hour: '2-digit',
|
||
minute: '2-digit',
|
||
second: '2-digit',
|
||
hour12: false
|
||
});
|
||
}
|
||
|
||
function addChatMessage(groupId, entry) {
|
||
const id = Number(groupId);
|
||
if (!dispatcherState.groupById.has(id)) return;
|
||
|
||
if (!dispatcherState.chatByGroup.has(id)) {
|
||
dispatcherState.chatByGroup.set(id, []);
|
||
}
|
||
if (!dispatcherState.chatKeysByGroup.has(id)) {
|
||
dispatcherState.chatKeysByGroup.set(id, new Set());
|
||
}
|
||
|
||
const textForKey = extractMessageText(entry.text ?? entry.msg ?? entry);
|
||
const keys = dispatcherState.chatKeysByGroup.get(id);
|
||
const key = `${entry.code}|${entry.sender_id}|${entry.ts}|${textForKey}`;
|
||
if (keys.has(key)) {
|
||
updateGroupLastMessagePreview(id);
|
||
return;
|
||
}
|
||
|
||
keys.add(key);
|
||
dispatcherState.chatByGroup.get(id).push({
|
||
...entry,
|
||
text: textForKey,
|
||
msg: entry.msg ?? textForKey
|
||
});
|
||
updateGroupLastMessagePreview(id);
|
||
|
||
if (window.CMBNET_VIEW_MODE === 'observer') {
|
||
const marker = dispatcherState.markersByGroupId.get(Number(id));
|
||
if (marker) {
|
||
updateGroupMarkerTooltip(dispatcherState.groupById.get(Number(id)) || {id}, marker);
|
||
}
|
||
return;
|
||
}
|
||
|
||
if (dispatcherState.chatGroupId === id
|
||
&& document.getElementById('chatModal').open) {
|
||
renderChat();
|
||
}
|
||
}
|
||
|
||
function playNotificationSound() {
|
||
try {
|
||
if (!AudioContext) return;
|
||
if (audioCtx.state === 'suspended') {
|
||
audioCtx.resume();
|
||
}
|
||
const oscillator = audioCtx.createOscillator();
|
||
const gain = audioCtx.createGain();
|
||
oscillator.connect(gain);
|
||
gain.connect(audioCtx.destination);
|
||
oscillator.frequency.setValueAtTime(880, audioCtx.currentTime);
|
||
oscillator.frequency.exponentialRampToValueAtTime(440, audioCtx.currentTime + 0.15);
|
||
gain.gain.setValueAtTime(0.1, audioCtx.currentTime);
|
||
gain.gain.exponentialRampToValueAtTime(0.01, audioCtx.currentTime + 0.3);
|
||
oscillator.start(audioCtx.currentTime);
|
||
oscillator.stop(audioCtx.currentTime + 0.3);
|
||
} catch (error) {
|
||
// ignore
|
||
}
|
||
}
|
||
|
||
function renderInfoMessages() {
|
||
const container = document.getElementById('infoMessages');
|
||
if (!container) return;
|
||
container.innerHTML = '';
|
||
|
||
if (!dispatcherState.infoMessages.length) {
|
||
const empty = document.createElement('div');
|
||
empty.className = 'chat-empty';
|
||
empty.textContent = 'Noch keine Nachrichten.';
|
||
container.appendChild(empty);
|
||
} else {
|
||
dispatcherState.infoMessages.forEach(entry => {
|
||
const message = document.createElement('div');
|
||
message.className = 'chat-message';
|
||
|
||
const header = document.createElement('div');
|
||
header.className = 'chat-message-header';
|
||
|
||
const sender = document.createElement('span');
|
||
sender.textContent = entry.senderLabel;
|
||
|
||
const time = document.createElement('span');
|
||
time.textContent = entry.time;
|
||
|
||
header.append(sender, time);
|
||
|
||
const meta = document.createElement('div');
|
||
meta.className = 'chat-message-text';
|
||
meta.style.fontSize = '0.8rem';
|
||
meta.style.opacity = '0.8';
|
||
meta.textContent = entry.meta;
|
||
|
||
const text = document.createElement('div');
|
||
text.className = 'chat-message-text';
|
||
text.textContent = entry.text;
|
||
|
||
message.append(header, meta, text);
|
||
container.appendChild(message);
|
||
});
|
||
}
|
||
|
||
container.scrollTop = container.scrollHeight;
|
||
}
|
||
|
||
function showInfoMessage(message) {
|
||
const dialog = document.getElementById('infoMessageModal');
|
||
if (!dialog) return;
|
||
|
||
const code = Number(message.code);
|
||
const senderInfo = getSenderDisplay(message.sender_id, message);
|
||
const sender = senderInfo.name;
|
||
const payload = extractMessagePayload(message.msg);
|
||
let receiverId = Number(message.receiver_id);
|
||
if (!Number.isFinite(receiverId) && payload && payload.group_id !== undefined) {
|
||
receiverId = Number(payload.group_id);
|
||
}
|
||
if (!Number.isFinite(receiverId) && payload && payload.receiver_id !== undefined) {
|
||
receiverId = Number(payload.receiver_id);
|
||
}
|
||
let receiver = '';
|
||
if (Number.isFinite(receiverId) && receiverId > 0) {
|
||
const group = dispatcherState.groupById.get(receiverId);
|
||
const account = dispatcherState.accountById.get(receiverId);
|
||
if (group) {
|
||
receiver = `Gruppe ${groupDisplayName(group)}`;
|
||
} else if (account) {
|
||
receiver = account.name;
|
||
} else {
|
||
receiver = `ID ${receiverId}`;
|
||
}
|
||
} else if (code === 1000 || (payload && payload.broadcast)) {
|
||
receiver = 'alle';
|
||
}
|
||
|
||
const time = formatChatTime(normalizeTimestamp(message.ts) || Date.now());
|
||
const text = extractMessageText(message.msg);
|
||
const senderLabel = receiver ? `${sender}` : sender;
|
||
const key = `${code}|${message.sender_id}|${message.receiver_id}|${time}|${text}`;
|
||
|
||
if (!dispatcherState.infoMessageKeys.has(key)) {
|
||
dispatcherState.infoMessageKeys.add(key);
|
||
dispatcherState.infoMessages.push({
|
||
senderLabel,
|
||
time,
|
||
text
|
||
});
|
||
playNotificationSound();
|
||
}
|
||
|
||
renderInfoMessages();
|
||
|
||
if (typeof dialog.showModal === 'function') {
|
||
dialog.showModal();
|
||
} else {
|
||
dialog.show();
|
||
}
|
||
const container = document.getElementById('infoMessages');
|
||
if (container) {
|
||
container.scrollTop = container.scrollHeight;
|
||
}
|
||
}
|
||
|
||
function closeInfoMessageModal() {
|
||
const dialog = document.getElementById('infoMessageModal');
|
||
if (dialog && dialog.open) dialog.close();
|
||
dispatcherState.infoMessages = [];
|
||
dispatcherState.infoMessageKeys = new Set();
|
||
const container = document.getElementById('infoMessages');
|
||
if (container) {
|
||
container.innerHTML = '';
|
||
}
|
||
}
|
||
|
||
function extractMessagePayload(value) {
|
||
if (value === null || value === undefined) return null;
|
||
if (typeof value === 'object') {
|
||
return value;
|
||
}
|
||
if (typeof value === 'string') {
|
||
let text = value;
|
||
const trimmed = text.trim();
|
||
if (!trimmed) return null;
|
||
const colonIndex = trimmed.indexOf(':');
|
||
if (colonIndex > 0 && colonIndex < 80) {
|
||
const afterColon = trimmed.slice(colonIndex + 1).trim();
|
||
if ((afterColon.startsWith('{') && afterColon.endsWith('}'))
|
||
|| (afterColon.startsWith('[') && afterColon.endsWith(']'))) {
|
||
try {
|
||
const parsed = JSON.parse(afterColon);
|
||
if (parsed && typeof parsed === 'object') return parsed;
|
||
} catch (error) {
|
||
// ignore
|
||
}
|
||
}
|
||
}
|
||
if ((trimmed.startsWith('{') && trimmed.endsWith('}'))
|
||
|| (trimmed.startsWith('[') && trimmed.endsWith(']'))) {
|
||
try {
|
||
const parsed = JSON.parse(trimmed);
|
||
if (parsed && typeof parsed === 'object') return parsed;
|
||
} catch (error) {
|
||
// ignore
|
||
}
|
||
}
|
||
}
|
||
return null;
|
||
}
|
||
|
||
function extractMessageText(value) {
|
||
const payload = extractMessagePayload(value);
|
||
if (payload && typeof payload === 'object') {
|
||
if (Object.prototype.hasOwnProperty.call(payload, 'text')) {
|
||
return String(payload.text ?? '');
|
||
}
|
||
if (Object.prototype.hasOwnProperty.call(payload, 'msg')) {
|
||
return extractMessageText(payload.msg);
|
||
}
|
||
return '';
|
||
}
|
||
if (value === null || value === undefined) return '';
|
||
if (typeof value === 'string') {
|
||
let text = value;
|
||
const trimmed = text.trim();
|
||
if (!trimmed) return '';
|
||
const colonIndex = trimmed.indexOf(':');
|
||
if (colonIndex > 0 && colonIndex < 80) {
|
||
const afterColon = trimmed.slice(colonIndex + 1).trim();
|
||
if (afterColon) return afterColon;
|
||
}
|
||
return trimmed;
|
||
}
|
||
return String(value);
|
||
}
|
||
|
||
function parsePayload(value) {
|
||
if (value && typeof value === 'object') return value;
|
||
if (typeof value !== 'string') return null;
|
||
try {
|
||
const parsed = JSON.parse(value);
|
||
return parsed && typeof parsed === 'object' ? parsed : null;
|
||
} catch (error) {
|
||
return null;
|
||
}
|
||
}
|
||
|
||
function handleGroupChatMessage(message) {
|
||
const payload = parsePayload(message.msg) || {};
|
||
const groupId = Number(payload.group_id ?? message.receiver_id);
|
||
const group = dispatcherState.groupById.get(groupId);
|
||
if (!group) return;
|
||
|
||
const text = extractMessageText(payload.text ?? payload.msg ?? '');
|
||
|
||
const input = document.querySelector(
|
||
`.group-item[data-group-id="${group.id}"] .group-message`
|
||
);
|
||
if (input) input.value = text;
|
||
|
||
addChatMessage(group.id, {
|
||
sender_id: message.sender_id,
|
||
code: message.code,
|
||
ts: normalizeTimestamp(message.ts) || Date.now(),
|
||
text
|
||
});
|
||
}
|
||
|
||
/* ------------------------------------------------------------------ */
|
||
/* WebSocket */
|
||
/* ------------------------------------------------------------------ */
|
||
|
||
async function connectWebSocket() {
|
||
if (dispatcherState.unloading) return;
|
||
if (dispatcherState.ws
|
||
&& (dispatcherState.ws.readyState === WebSocket.OPEN
|
||
|| dispatcherState.ws.readyState === WebSocket.CONNECTING)) {
|
||
return;
|
||
}
|
||
|
||
try {
|
||
const tokenResponse = await fetchJson(`${apiBase}/auth/ws-token`);
|
||
const token = tokenResponse.token;
|
||
const ws = new WebSocket(wsUrl);
|
||
dispatcherState.ws = ws;
|
||
|
||
ws.addEventListener('open', () => {
|
||
ws.send(JSON.stringify({code: 0, msg: token}));
|
||
dispatcherState.authenticated = true;
|
||
setConnectionStatus('Verbunden', 'connected');
|
||
dispatcherState.lastCode0ReceivedAt = Date.now();
|
||
dispatcherState.heartbeatWarningShown = false;
|
||
startHeartbeatMonitoring();
|
||
});
|
||
|
||
ws.addEventListener('message', handleWsMessage);
|
||
|
||
ws.addEventListener('close', () => {
|
||
dispatcherState.authenticated = false;
|
||
setConnectionStatus('Getrennt – neuer Versuch …', 'disconnected');
|
||
scheduleReconnect();
|
||
});
|
||
|
||
ws.addEventListener('error', () => {
|
||
setConnectionStatus('Verbindungsfehler', 'disconnected');
|
||
});
|
||
} catch (error) {
|
||
console.error('WebSocket-Token konnte nicht geladen werden:', error);
|
||
setConnectionStatus('Token nicht verfügbar – neuer Versuch …', 'disconnected');
|
||
scheduleReconnect();
|
||
}
|
||
}
|
||
|
||
function scheduleReconnect() {
|
||
if (dispatcherState.unloading || dispatcherState.reconnectTimer) return;
|
||
|
||
dispatcherState.reconnectTimer = setTimeout(() => {
|
||
dispatcherState.reconnectTimer = null;
|
||
connectWebSocket();
|
||
}, 3000);
|
||
}
|
||
|
||
function setConnectionStatus(text, cssClass) {
|
||
const element = document.getElementById('connectionStatus');
|
||
if (!element) return;
|
||
element.textContent = text;
|
||
element.classList.remove('connected', 'disconnected');
|
||
if (cssClass) element.classList.add(cssClass);
|
||
}
|
||
|
||
function sendWs(message) {
|
||
if (!dispatcherState.ws
|
||
|| dispatcherState.ws.readyState !== WebSocket.OPEN
|
||
|| !dispatcherState.authenticated) {
|
||
alert('Die WebSocket-Verbindung ist noch nicht verfügbar.');
|
||
return false;
|
||
}
|
||
|
||
dispatcherState.ws.send(JSON.stringify(message));
|
||
return true;
|
||
}
|
||
|
||
function handleWsMessage(event) {
|
||
let message;
|
||
try {
|
||
message = JSON.parse(event.data);
|
||
} catch (error) {
|
||
console.warn('Ungültige WebSocket-Nachricht:', event.data);
|
||
return;
|
||
}
|
||
|
||
console.debug('[WS RX]', message);
|
||
console.log('[WS RX]', JSON.stringify(message));
|
||
|
||
switch (Number(message.code)) {
|
||
case 0:
|
||
dispatcherState.lastCode0ReceivedAt = Date.now();
|
||
dispatcherState.heartbeatWarningShown = false;
|
||
setConnectionStatus('Verbunden', 'connected');
|
||
startHeartbeatMonitoring();
|
||
break;
|
||
case 1:
|
||
dispatcherState.lastCode0ReceivedAt = Date.now();
|
||
dispatcherState.heartbeatWarningShown = false;
|
||
setConnectionStatus('Verbunden', 'connected');
|
||
startHeartbeatMonitoring();
|
||
// Heartbeat des Servers beantworten.
|
||
if (dispatcherState.ws && dispatcherState.ws.readyState === WebSocket.OPEN) {
|
||
dispatcherState.ws.send(JSON.stringify({code: 2, msg: 'pong'}));
|
||
}
|
||
break;
|
||
case 100:
|
||
handleStreetUpdate(message);
|
||
break;
|
||
case 200:
|
||
handleGroupStateUpdate(message);
|
||
break;
|
||
case 300:
|
||
handleGroupPositionUpdate(message);
|
||
break;
|
||
case 1000: {
|
||
const text = extractMessageText(message.msg);
|
||
if (window.CMBNET_VIEW_MODE !== 'observer') {
|
||
dispatcherState.groups.forEach(group => {
|
||
addChatMessage(group.id, {
|
||
sender_id: message.sender_id,
|
||
code: message.code,
|
||
ts: normalizeTimestamp(message.ts) || Date.now(),
|
||
text
|
||
});
|
||
});
|
||
}
|
||
if (window.CMBNET_VIEW_MODE === 'observer') {
|
||
addObserverMessage({
|
||
code: message.code,
|
||
sender_id: message.sender_id,
|
||
receiver_id: message.receiver_id,
|
||
msg: text,
|
||
ts: message.ts
|
||
});
|
||
} else if (Number(message.sender_id) !== currentAccountId) {
|
||
showInfoMessage({
|
||
code: message.code,
|
||
sender_id: message.sender_id,
|
||
receiver_id: message.receiver_id,
|
||
msg: text,
|
||
ts: message.ts
|
||
});
|
||
}
|
||
break;
|
||
}
|
||
case 1100: {
|
||
const groupId = Number(message.receiver_id) || Number((message.msg && typeof message.msg === 'object' && message.msg.group_id));
|
||
const text = extractMessageText(message.msg);
|
||
if (window.CMBNET_VIEW_MODE !== 'observer') {
|
||
if (groupId) {
|
||
addChatMessage(groupId, {
|
||
sender_id: message.sender_id,
|
||
code: message.code,
|
||
ts: normalizeTimestamp(message.ts) || Date.now(),
|
||
text
|
||
});
|
||
}
|
||
}
|
||
if (window.CMBNET_VIEW_MODE === 'observer') {
|
||
addObserverMessage({
|
||
code: message.code,
|
||
sender_id: message.sender_id,
|
||
receiver_id: groupId || message.receiver_id,
|
||
msg: text,
|
||
ts: message.ts
|
||
});
|
||
} else if (Number(message.sender_id) !== currentAccountId) {
|
||
showInfoMessage({
|
||
code: message.code,
|
||
sender_id: message.sender_id,
|
||
receiver_id: groupId || message.receiver_id,
|
||
msg: text,
|
||
ts: message.ts
|
||
});
|
||
}
|
||
break;
|
||
}
|
||
case 2000:
|
||
if (window.CMBNET_VIEW_MODE !== 'observer') {
|
||
handleGroupChatMessage(message);
|
||
}
|
||
break;
|
||
default:
|
||
if (Number(message.code) >= 1000) {
|
||
const text = extractMessageText(message.msg);
|
||
if (window.CMBNET_VIEW_MODE === 'observer') {
|
||
addObserverMessage({
|
||
code: message.code,
|
||
sender_id: message.sender_id,
|
||
receiver_id: message.receiver_id,
|
||
msg: text,
|
||
ts: message.ts
|
||
});
|
||
break;
|
||
}
|
||
if (Number(message.code) === 1000) {
|
||
dispatcherState.groups.forEach(group => {
|
||
addChatMessage(group.id, {
|
||
sender_id: message.sender_id,
|
||
code: message.code,
|
||
ts: normalizeTimestamp(message.ts) || Date.now(),
|
||
text
|
||
});
|
||
});
|
||
}
|
||
if (Number(message.sender_id) !== currentAccountId) {
|
||
showInfoMessage({
|
||
code: message.code,
|
||
sender_id: message.sender_id,
|
||
receiver_id: message.receiver_id,
|
||
msg: text,
|
||
ts: message.ts
|
||
});
|
||
}
|
||
break;
|
||
}
|
||
break;
|
||
}
|
||
}
|
||
|
||
function handleStreetUpdate(message) {
|
||
const payload = parsePayload(message.msg) || {};
|
||
let street = payload.street_id
|
||
? dispatcherState.streetById.get(Number(payload.street_id))
|
||
: null;
|
||
|
||
if (!street && payload.name) {
|
||
street = dispatcherState.streets.find(item => item.name === payload.name);
|
||
}
|
||
if (!street) return;
|
||
|
||
if (STREET_STATES.includes(payload.state)) {
|
||
street.state = payload.state;
|
||
}
|
||
if (Object.prototype.hasOwnProperty.call(payload, 'group_id')) {
|
||
street.group_id = payload.group_id === null || payload.group_id === ''
|
||
? null
|
||
: Number(payload.group_id);
|
||
}
|
||
|
||
recolorStreet(street);
|
||
|
||
const streetsDialog = document.getElementById('groupStreetsModal');
|
||
if (dispatcherState.streetsDialogGroupId && streetsDialog.open) {
|
||
renderGroupStreetsDialog(dispatcherState.streetsDialogGroupId);
|
||
}
|
||
}
|
||
|
||
function handleGroupStateUpdate(message) {
|
||
const payload = parsePayload(message.msg) || {};
|
||
const groupId = Number(payload.group_id ?? message.receiver_id);
|
||
const group = dispatcherState.groupById.get(groupId);
|
||
if (!group) return;
|
||
|
||
if (GROUP_STATES.includes(payload.state)) {
|
||
group.state = payload.state;
|
||
updateGroupSummary(group);
|
||
}
|
||
}
|
||
|
||
function handleGroupPositionUpdate(message) {
|
||
const payload = parsePayload(message.msg) || {};
|
||
const groupId = Number(payload.group_id ?? message.receiver_id);
|
||
const group = dispatcherState.groupById.get(groupId);
|
||
if (!group) return;
|
||
|
||
const lat = Number(payload.lat);
|
||
const lon = Number(payload.lon);
|
||
|
||
if (Number.isFinite(lat) && Number.isFinite(lon)
|
||
&& payload.lat !== null && payload.lon !== null) {
|
||
group.last_lat = lat;
|
||
group.last_lon = lon;
|
||
// Code 300 kann den Zeitstempel als Millisekunden (Broker) oder als
|
||
// SQLite-/ISO-Zeitstring (z. B. aus der History-Wiederherstellung)
|
||
// enthalten.
|
||
group.last_pos_ts = parseTimestamp(payload.ts) || Date.now();
|
||
group.last_pos_at = new Date(group.last_pos_ts).toISOString();
|
||
updateMarkerPosition(group);
|
||
} else {
|
||
// Positionslöschung (null-Koordinaten): Marker an die Browserposition
|
||
// verschieben, da der eigentliche Standort unbekannt ist.
|
||
group.last_lat = null;
|
||
group.last_lon = null;
|
||
group.last_pos_at = null;
|
||
group.last_pos_ts = null;
|
||
const marker = dispatcherState.markersByGroupId.get(group.id);
|
||
if (marker) marker.setLatLng(dispatcherState.browserLatLng || map.getCenter());
|
||
}
|
||
|
||
refreshGroupControls();
|
||
}
|
||
|
||
/* ------------------------------------------------------------------ */
|
||
/* Uhr, Slider und Footer */
|
||
/* ------------------------------------------------------------------ */
|
||
|
||
function updateClock() {
|
||
const now = new Date();
|
||
|
||
const timeElement = document.getElementById('clockTime');
|
||
if (timeElement) {
|
||
timeElement.textContent = now.toLocaleTimeString('de-DE', {hour12: false});
|
||
}
|
||
|
||
const weekdayElement = document.getElementById('clockWeekday');
|
||
if (weekdayElement) {
|
||
weekdayElement.textContent = now
|
||
.toLocaleDateString('de-DE', {weekday: 'short'})
|
||
.replace('.', '')
|
||
.slice(0, 2);
|
||
}
|
||
|
||
const dayElement = document.getElementById('clockDay');
|
||
if (dayElement) {
|
||
dayElement.textContent = now.toLocaleDateString('de-DE', {
|
||
day: '2-digit',
|
||
month: '2-digit',
|
||
year: 'numeric'
|
||
});
|
||
}
|
||
|
||
refreshGroupControls(now.getTime());
|
||
}
|
||
|
||
function applySettingsToUi() {
|
||
const opacitySlider = document.getElementById('opacitySlider');
|
||
const weightSlider = document.getElementById('weightSlider');
|
||
|
||
if (opacitySlider) opacitySlider.value = dispatcherState.settings.opacity;
|
||
if (weightSlider) weightSlider.value = dispatcherState.settings.weight;
|
||
|
||
updateOpacityOutput();
|
||
updateWeightOutput();
|
||
updateAllPolylineStyles();
|
||
}
|
||
|
||
function updateOpacityOutput() {
|
||
const output = document.getElementById('opacityValue');
|
||
if (output) output.textContent = Number(dispatcherState.settings.opacity).toFixed(2);
|
||
}
|
||
|
||
function updateWeightOutput() {
|
||
const output = document.getElementById('weightValue');
|
||
if (output) output.textContent = `${dispatcherState.settings.weight} m`;
|
||
}
|
||
|
||
function parseTimestamp(value) {
|
||
if (value === null || value === undefined || value === '') return null;
|
||
if (typeof value === 'number') return normalizeTimestamp(value);
|
||
|
||
const text = String(value).trim();
|
||
if (/^\d+$/.test(text)) return normalizeTimestamp(Number(text));
|
||
|
||
let iso = text.replace(' ', 'T');
|
||
if (!/[zZ]|[+-]\d{2}:?\d{2}$/.test(iso)) {
|
||
iso += 'Z';
|
||
}
|
||
|
||
const parsed = Date.parse(iso);
|
||
return Number.isNaN(parsed) ? null : parsed;
|
||
}
|
||
|
||
function normalizeTimestamp(value) {
|
||
const number = Number(value);
|
||
if (!Number.isFinite(number) || number <= 0) return null;
|
||
return number < 1e12 ? number * 1000 : number;
|
||
}
|
||
|
||
/* ------------------------------------------------------------------ */
|
||
/* Statische UI-Elemente */
|
||
/* ------------------------------------------------------------------ */
|
||
|
||
function bindStaticUi() {
|
||
initTheme();
|
||
initStreetSearch();
|
||
|
||
const baseLayerSelect = document.getElementById('baseLayerSelect');
|
||
if (baseLayerSelect) {
|
||
baseLayerSelect.addEventListener('change', event => {
|
||
setBaseLayer(event.target.value);
|
||
});
|
||
}
|
||
|
||
const opacitySlider = document.getElementById('opacitySlider');
|
||
if (opacitySlider) {
|
||
opacitySlider.addEventListener('input', event => {
|
||
dispatcherState.settings.opacity = clampNumber(
|
||
event.target.value, 0, 1, DEFAULT_SETTINGS.opacity
|
||
);
|
||
updateOpacityOutput();
|
||
updateAllPolylineStyles();
|
||
saveStoredSettings();
|
||
});
|
||
}
|
||
|
||
const weightSlider = document.getElementById('weightSlider');
|
||
if (weightSlider) {
|
||
weightSlider.addEventListener('input', event => {
|
||
dispatcherState.settings.weight = clampNumber(
|
||
event.target.value, 1, 100, DEFAULT_SETTINGS.weight
|
||
);
|
||
updateWeightOutput();
|
||
updateAllPolylineStyles();
|
||
saveStoredSettings();
|
||
});
|
||
}
|
||
|
||
const fitBoundsButton = document.getElementById('fitBoundsButton');
|
||
if (fitBoundsButton) {
|
||
fitBoundsButton.addEventListener('click', fitAllStreetBounds);
|
||
}
|
||
const speakerButton = document.getElementById('speakerButton');
|
||
if (speakerButton && window.CMBNET_VIEW_MODE !== 'observer') {
|
||
speakerButton.addEventListener('click', openSpeakerModal);
|
||
}
|
||
const streetStateSelect = document.getElementById('streetStateSelect');
|
||
if (streetStateSelect && window.CMBNET_VIEW_MODE !== 'observer') {
|
||
streetStateSelect.addEventListener('change', updateStreetGroupVisibility);
|
||
}
|
||
const groupAliasInput = document.getElementById('groupAliasInput');
|
||
if (groupAliasInput && window.CMBNET_VIEW_MODE !== 'observer') {
|
||
groupAliasInput.addEventListener('keydown', event => {
|
||
if (event.key !== 'Enter') return;
|
||
event.preventDefault();
|
||
saveGroupAlias();
|
||
});
|
||
}
|
||
initGroupStreetsDialogDrag();
|
||
|
||
document.addEventListener('keydown', event => {
|
||
if (event.key === 'Escape' && dispatcherState.crosshairGroupId) {
|
||
cancelCrosshair();
|
||
}
|
||
});
|
||
}
|
||
|
||
function openSpeakerModal() {
|
||
document.getElementById('speakerText').value = '';
|
||
document.getElementById('speakerModal').showModal();
|
||
}
|
||
|
||
function closeSpeakerModal() {
|
||
document.getElementById('speakerModal').close();
|
||
}
|
||
|
||
function closeSpeakerQrModal() {
|
||
const dialog = document.getElementById('speakerQrModal');
|
||
if (dialog && dialog.open) dialog.close();
|
||
}
|
||
|
||
function sendSpeakerMessage() {
|
||
const input = document.getElementById('speakerText');
|
||
const text = input.value.trim();
|
||
if (!text) return;
|
||
|
||
if (sendWs({code: 1000, msg: JSON.stringify({text})})) {
|
||
closeSpeakerModal();
|
||
showSpeakerQr(text);
|
||
input.value = '';
|
||
}
|
||
}
|
||
|
||
function showSpeakerQr(text) {
|
||
const dialog = document.getElementById('speakerQrModal');
|
||
if (!dialog) return;
|
||
const encoded = encodeURIComponent(text);
|
||
const url = `https://api.whatsapp.com/send?text=${encoded}`;
|
||
const canvas = document.getElementById('speakerQrCanvas');
|
||
const qrLink = document.getElementById('speakerQrLink');
|
||
if (canvas && typeof QRious !== 'undefined') {
|
||
try {
|
||
new QRious({
|
||
element: canvas,
|
||
value: url,
|
||
size: 240
|
||
});
|
||
} catch (e) {
|
||
console.error('QRious error', e);
|
||
}
|
||
}
|
||
if (qrLink) {
|
||
qrLink.href = url;
|
||
qrLink.textContent = 'WhatsApp öffnen';
|
||
}
|
||
if (typeof dialog.showModal === 'function') {
|
||
dialog.showModal();
|
||
} else {
|
||
dialog.show();
|
||
}
|
||
}
|
||
|
||
function openGroupMessageModal() {}
|
||
function closeGroupMessageModal() {}
|
||
function sendGroupMessageFromDialog() {}
|
||
|
||
function showAccordionError(text) {
|
||
const container = document.getElementById('groupAccordion');
|
||
container.innerHTML = '';
|
||
const message = document.createElement('p');
|
||
message.className = 'group-empty';
|
||
message.textContent = text;
|
||
container.appendChild(message);
|
||
}
|