Mobile Views jetzt als PWA

This commit is contained in:
concierge committed 2026-10-29 08:08:23 +01:00
1 parent d8692ab20e
commit b41c3bc3a6
11 files changed
+785 -37

No files matched your search

+349 -30
View File
@@ -28,6 +28,9 @@ const state = {
streetById: new Map(),
groups: [],
groupById: new Map(),
accounts: [],
accountById: new Map(),
me: null,
currentGroupId: null,
polylinesByStreetId: new Map(),
groupMarkers: new Map(),
@@ -55,12 +58,22 @@ async function initMobile() {
initMap();
bindTabs();
bindButtons();
registerServiceWorker();
initPwaInstall();
initNotifications();
if (viewMode === 'mobile_dispatcher') {
try {
const groups = await fetchJson(`${apiBase}/init/groups`);
const [groups, accounts, me] = await Promise.all([
fetchJson(`${apiBase}/init/groups`),
fetchJson(`${apiBase}/init/accounts`).catch(() => []),
fetchJson(`${apiBase}/init/me`).catch(() => null)
]);
state.groups = Array.isArray(groups) ? groups : [];
state.accounts = Array.isArray(accounts) ? accounts : [];
state.me = me;
indexGroups();
indexAccounts();
buildGroupSelect();
const firstGroup = state.groups[0];
if (firstGroup) {
@@ -71,13 +84,20 @@ async function initMobile() {
}
} else if (viewMode === 'mobile_group') {
try {
const group = await fetchJson(`${apiBase}/groups/me`);
const [group, accounts, me] = await Promise.all([
fetchJson(`${apiBase}/groups/me`),
fetchJson(`${apiBase}/init/accounts`).catch(() => []),
fetchJson(`${apiBase}/init/me`).catch(() => null)
]);
state.accounts = Array.isArray(accounts) ? accounts : [];
state.me = me;
indexAccounts();
if (group && group.id) {
state.groups = [group];
state.currentGroupId = group.id;
indexGroups();
const nameEl = document.getElementById('groupNameDisplay');
if (nameEl) nameEl.textContent = group.aliasname || group.id || 'Gruppe';
if (nameEl) nameEl.textContent = groupDisplayName(group);
await loadGroupData(group.id);
}
} catch (e) {
@@ -102,6 +122,143 @@ function fetchJson(url, options={}) {
});
}
/* ------------------------------------------------------------------ */
/* Progressive Web App */
/* ------------------------------------------------------------------ */
let deferredInstallPrompt = null;
function isStandaloneMode() {
return window.matchMedia('(display-mode: standalone)').matches
|| window.navigator.standalone === true;
}
function isIosDevice() {
return /iphone|ipad|ipod/i.test(navigator.userAgent)
|| (navigator.platform === 'MacIntel' && navigator.maxTouchPoints > 1);
}
function registerServiceWorker() {
if (!('serviceWorker' in navigator)) return;
const swUrl = window.CMBNET_SW_URL || '/sw.js';
window.addEventListener('load', () => {
navigator.serviceWorker.register(swUrl).catch(error => {
console.warn('Service Worker konnte nicht registriert werden.', error);
});
});
}
function initPwaInstall() {
const button = document.getElementById('mobileInstallBtn');
if (!button) return;
if (isStandaloneMode()) {
button.hidden = true;
return;
}
// Unter iOS gibt es kein beforeinstallprompt. Dort zeigen wir den Button
// dauerhaft an und erklären die Installation über das Teilen-Menü.
if (isIosDevice()) button.hidden = false;
window.addEventListener('beforeinstallprompt', event => {
event.preventDefault();
deferredInstallPrompt = event;
button.hidden = false;
});
window.addEventListener('appinstalled', () => {
deferredInstallPrompt = null;
button.hidden = true;
});
button.addEventListener('click', async () => {
if (deferredInstallPrompt) {
const prompt = deferredInstallPrompt;
deferredInstallPrompt = null;
prompt.prompt();
try {
const choice = await prompt.userChoice;
if (choice.outcome === 'accepted') button.hidden = true;
} catch (error) {
// Der Dialog kann abgelehnt oder geschlossen werden.
}
return;
}
const dialog = document.getElementById('mobileInstallDialog');
const iosHint = document.getElementById('mobileInstallIosHint');
const genericHint = document.getElementById('mobileInstallGenericHint');
if (iosHint) iosHint.hidden = !isIosDevice();
if (genericHint) genericHint.hidden = isIosDevice();
if (dialog && typeof dialog.showModal === 'function') {
dialog.showModal();
} else if (dialog) {
dialog.show();
}
});
}
function closeMobileInstall() {
const dialog = document.getElementById('mobileInstallDialog');
if (dialog && dialog.open) dialog.close();
}
function initNotifications() {
const button = document.getElementById('mobileNotifyBtn');
if (!button) return;
button.addEventListener('click', requestNotifications);
updateNotificationUi();
}
function updateNotificationUi() {
const button = document.getElementById('mobileNotifyBtn');
if (!button) return;
if (!('Notification' in window)) {
button.textContent = 'Nicht verfügbar';
button.disabled = true;
return;
}
const permission = Notification.permission;
button.classList.toggle('is-active', permission === 'granted');
button.disabled = permission === 'denied';
if (permission === 'granted') {
button.textContent = 'Aktiv';
} else if (permission === 'denied') {
button.textContent = 'Blockiert';
} else {
button.textContent = 'Aktivieren';
}
}
async function requestNotifications() {
if (!('Notification' in window)) return;
try {
const permission = await Notification.requestPermission();
updateNotificationUi();
if (permission === 'granted' && navigator.serviceWorker) {
const registration = await navigator.serviceWorker.getRegistration();
if (registration && registration.showNotification) {
await registration.showNotification('CMBNet', {
body: 'Benachrichtigungen sind aktiviert.',
icon: window.CMBNET_ICON_URL || undefined,
tag: 'cmbnet-permission'
});
}
}
} catch (error) {
console.warn('Benachrichtigungen konnten nicht aktiviert werden.', error);
}
}
function loadSettings() {
try {
const raw = localStorage.getItem(storageKey);
@@ -219,6 +376,130 @@ function indexGroups() {
});
}
function indexAccounts() {
state.accountById.clear();
state.accounts.forEach(account => {
const id = Number(account.id);
if (!Number.isFinite(id)) return;
account.id = id;
state.accountById.set(id, account);
});
}
function groupDisplayName(group) {
if (!group) return 'Gruppe';
const alias = group.aliasname && String(group.aliasname).trim();
return alias || 'Gruppe';
}
function findGroupForAccount(accountId) {
const id = Number(accountId);
return state.groups.find(group => Number(group.account_id) === id) || null;
}
/**
* Formatiert "Accountname" bzw. "Accountname (Gruppe: Alias)".
*/
function formatPersonName(name, role, groupAlias) {
const base = String(name || '').trim() || 'Unbekannt';
const alias = groupAlias && String(groupAlias).trim();
if (alias) return `${base} (Gruppe: ${alias})`;
if (role === 'Gruppe') return `${base} (Gruppe)`;
return base;
}
function getAccount(accountId) {
const id = Number(accountId);
if (!Number.isFinite(id)) return null;
return state.accountById.get(id) || null;
}
function getAccountDisplayName(accountId) {
const id = Number(accountId);
if (!Number.isFinite(id)) return null;
const account = getAccount(id);
if (account) {
const group = findGroupForAccount(id);
return formatPersonName(account.name, account.role, group ? group.aliasname : null);
}
if (state.me && Number(state.me.id) === id) {
const group = findGroupForAccount(id);
return formatPersonName(
state.me.name,
state.me.role,
group ? group.aliasname : null
);
}
return null;
}
function getSenderName(message, payload) {
const payloadSender = payload && typeof payload.sender === 'object'
? payload.sender
: null;
if (payloadSender && payloadSender.name) {
return formatPersonName(
payloadSender.name,
payloadSender.role,
payloadSender.group_alias
);
}
const senderId = Number(message.sender_id);
const known = getAccountDisplayName(senderId);
if (known) return known;
if (state.me && senderId === Number(state.me.id)) {
return formatPersonName(state.me.name, state.me.role, null);
}
return 'Unbekannt';
}
function getReceiverName(message, payload) {
const code = Number(message.code);
if (code === 1000 || (payload && payload.broadcast)) return 'alle';
const payloadSender = payload && typeof payload.sender === 'object'
? payload.sender
: null;
const senderRole = payloadSender?.role || getAccount(message.sender_id)?.role;
if (code === 2000 && senderRole === 'Gruppe') {
// Gruppen senden mit Code 2000 an Dispatcher und Beobachter.
return 'Dispatcher';
}
let receiverId = Number(message.receiver_id);
if (!Number.isFinite(receiverId) || receiverId <= 0) {
if (payload && payload.group_id !== undefined) {
receiverId = Number(payload.group_id);
} else if (payload && payload.receiver_id !== undefined) {
receiverId = Number(payload.receiver_id);
}
}
if (!Number.isFinite(receiverId) || receiverId <= 0) return 'alle';
let group = state.groupById.get(receiverId);
if (!group && receiverId === Number(state.currentGroupId) && state.groups.length) {
group = state.groups[0];
}
if (group) {
const accountName = getAccountDisplayName(group.account_id);
return accountName || groupDisplayName(group) || 'Gruppe';
}
const accountName = getAccountDisplayName(receiverId);
if (accountName) return accountName;
return 'Unbekannt';
}
function buildGroupSelect() {
const sel = document.getElementById('mobileGroupSelect');
if (!sel) return;
@@ -599,7 +880,11 @@ function renderChat() {
meta.textContent = new Date(entry.ts).toLocaleString('de-DE');
const fromto = document.createElement('div');
fromto.className = 'mobile-chat-fromto';
fromto.textContent = entry.senderName || `ID ${entry.sender_id}`;
const fromName = entry.fromName
|| getSenderName({sender_id: entry.sender_id}, null);
const toName = entry.toName
|| (Number(entry.code) === 1000 ? 'alle' : 'Unbekannt');
fromto.textContent = `${fromName} -> ${toName}`;
const text = document.createElement('div');
text.className = 'mobile-chat-text';
text.textContent = entry.text;
@@ -625,12 +910,29 @@ function playSound() {
} catch(e) {}
}
function showChatPopup(text) {
// Try to show notification if possible
if ('Notification' in window && Notification.permission === 'granted') {
try { new Notification('CMBNet Nachricht', {body: text}); } catch(e) {}
} else if ('Notification' in window && Notification.permission !== 'denied') {
Notification.requestPermission();
async function showChatPopup(text, senderName) {
if (!('Notification' in window) || Notification.permission !== 'granted') return;
const options = {
body: text,
icon: window.CMBNET_ICON_URL || undefined,
badge: window.CMBNET_ICON_URL || undefined,
tag: 'cmbnet-chat',
renotify: true,
data: {url: window.location.href}
};
try {
if (navigator.serviceWorker) {
const registration = await navigator.serviceWorker.getRegistration();
if (registration && registration.showNotification) {
await registration.showNotification(senderName || 'CMBNet', options);
return;
}
}
new Notification(senderName || 'CMBNet', options);
} catch (error) {
// Benachrichtigungen sind optional.
}
}
@@ -653,6 +955,23 @@ function extractText(msg) {
return String(msg);
}
function parseMessagePayload(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 (e) {
return null;
}
}
function normalizeTs(value) {
const number = Number(value);
if (!Number.isFinite(number) || number <= 0) return null;
return number < 1e12 ? number * 1000 : number;
}
function handleWs(event) {
let message;
try { message = JSON.parse(event.data); } catch(e) { return; }
@@ -692,31 +1011,30 @@ function handleWs(event) {
} catch(e) {}
} else if (message.code === 2000 || message.code === 1000 || message.code === 1100) {
// Chat messages
const text = extractText(message.msg);
const entry = {
sender_id: message.sender_id,
code: message.code,
ts: message.ts || Date.now(),
text,
senderName: undefined
};
// For gruppe view, broker should only send relevant messages; still check
const payload = parseMessagePayload(message.msg);
const text = extractText(payload ?? message.msg);
// Im Gruppen-View nur Nachrichten an alle oder an die eigene Gruppe.
if (viewMode === 'mobile_group') {
const p = typeof message.msg === 'string' ? JSON.parse(message.msg) : message.msg;
const gid = Number(p?.group_id || message.receiver_id);
if (message.code === 1100 && gid && gid !== state.currentGroupId) {
return; // should not happen if broker filters, but be safe
}
if (message.code === 2000 && gid && gid !== state.currentGroupId && message.sender_id !== currentAccountId) {
// Check if it's from our group
const isFromOurGroup = state.groups.some(g => g.account_id && false); // simplified
const gid = Number(payload?.group_id ?? message.receiver_id);
const ownGroupId = Number(state.currentGroupId);
if (Number.isFinite(gid) && gid > 0 && ownGroupId && gid !== ownGroupId) {
return;
}
}
const wasEmpty = state.chatMessages.length === 0;
addChatEntry(entry);
addChatEntry({
sender_id: message.sender_id,
code: message.code,
ts: normalizeTs(message.ts) || Date.now(),
text,
fromName: getSenderName(message, payload),
toName: getReceiverName(message, payload)
});
if (Number(message.sender_id) !== currentAccountId) {
playSound();
showChatPopup(text);
showChatPopup(text, getSenderName(message, payload));
// Switch to chat tab
document.querySelectorAll('.mobile-tab').forEach(b => {
if (b.dataset.tab === 'chat') b.click();
@@ -730,3 +1048,4 @@ window.closeMobileStreetSelect = closeMobileStreetSelect;
window.closeMobileStreetState = closeMobileStreetState;
window.saveMobileStreetState = saveMobileStreetState;
window.closeMobileSettings = closeMobileSettings;
window.closeMobileInstall = closeMobileInstall;