Compare commits
6 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
e4c3c92cab | ||
|
|
0abc1c6b02 | ||
|
|
5bf4106db2 | ||
|
|
2432e9a17f | ||
|
|
e3f8f14f6a | ||
|
|
0376e71066 |
@@ -49,9 +49,9 @@ const nextConfig = {
|
|||||||
"default-src 'self'",
|
"default-src 'self'",
|
||||||
"script-src 'self' 'unsafe-inline' 'unsafe-eval' blob:",
|
"script-src 'self' 'unsafe-inline' 'unsafe-eval' blob:",
|
||||||
"style-src 'self' 'unsafe-inline'",
|
"style-src 'self' 'unsafe-inline'",
|
||||||
"img-src 'self' data: blob: https://*.tile.openstreetmap.org https://api.maptiler.com http://localhost:9000 http://minio:9000",
|
"img-src 'self' data: blob: https://*.tile.openstreetmap.org https://api.maptiler.com https://server.arcgisonline.com https://*.geo.admin.ch http://localhost:9000 http://minio:9000",
|
||||||
"font-src 'self' data:",
|
"font-src 'self' data:",
|
||||||
"connect-src 'self' ws: wss: https://api.maptiler.com https://*.tile.openstreetmap.org https://api.open-meteo.com",
|
"connect-src 'self' ws: wss: https://api.maptiler.com https://*.tile.openstreetmap.org https://api.open-meteo.com https://server.arcgisonline.com https://*.geo.admin.ch",
|
||||||
"frame-ancestors 'self'",
|
"frame-ancestors 'self'",
|
||||||
"base-uri 'self'",
|
"base-uri 'self'",
|
||||||
"form-action 'self'",
|
"form-action 'self'",
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "lageplan",
|
"name": "lageplan",
|
||||||
"version": "1.0.4",
|
"version": "1.0.6",
|
||||||
"description": "Feuerwehr Lageplan - Krokier-App für Einsatzdokumentation",
|
"description": "Feuerwehr Lageplan - Krokier-App für Einsatzdokumentation",
|
||||||
"private": true,
|
"private": true,
|
||||||
"scripts": {
|
"scripts": {
|
||||||
|
|||||||
BIN
public/logo-icon-maskable.png
Normal file
BIN
public/logo-icon-maskable.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 264 KiB |
@@ -20,7 +20,13 @@
|
|||||||
"src": "/logo-icon.png",
|
"src": "/logo-icon.png",
|
||||||
"sizes": "192x192",
|
"sizes": "192x192",
|
||||||
"type": "image/png",
|
"type": "image/png",
|
||||||
"purpose": "any maskable"
|
"purpose": "any"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"src": "/logo-icon-maskable.png",
|
||||||
|
"sizes": "192x192",
|
||||||
|
"type": "image/png",
|
||||||
|
"purpose": "maskable"
|
||||||
}
|
}
|
||||||
],
|
],
|
||||||
"screenshots": [],
|
"screenshots": [],
|
||||||
|
|||||||
121
public/sw.js
121
public/sw.js
@@ -1,6 +1,10 @@
|
|||||||
const TILE_CACHE = 'lageplan-tiles-v2'
|
const TILE_CACHE = 'lageplan-tiles-v3'
|
||||||
const STATIC_CACHE = 'lageplan-static-v2'
|
const STATIC_CACHE = 'lageplan-static-v3'
|
||||||
const APP_CACHE = 'lageplan-app-v2'
|
const APP_CACHE = 'lageplan-app-v3'
|
||||||
|
const API_CACHE = 'lageplan-api-v3'
|
||||||
|
|
||||||
|
// API routes that should be cached for offline use
|
||||||
|
const CACHEABLE_API = ['/api/icons', '/api/hose-types', '/api/dictionary']
|
||||||
|
|
||||||
// Pre-cache essential app shell on install
|
// Pre-cache essential app shell on install
|
||||||
self.addEventListener('install', (event) => {
|
self.addEventListener('install', (event) => {
|
||||||
@@ -8,6 +12,8 @@ self.addEventListener('install', (event) => {
|
|||||||
caches.open(APP_CACHE).then((cache) =>
|
caches.open(APP_CACHE).then((cache) =>
|
||||||
cache.addAll([
|
cache.addAll([
|
||||||
'/app',
|
'/app',
|
||||||
|
'/login',
|
||||||
|
'/',
|
||||||
'/logo.svg',
|
'/logo.svg',
|
||||||
'/logo-icon.png',
|
'/logo-icon.png',
|
||||||
'/manifest.json',
|
'/manifest.json',
|
||||||
@@ -17,7 +23,6 @@ self.addEventListener('install', (event) => {
|
|||||||
self.skipWaiting()
|
self.skipWaiting()
|
||||||
})
|
})
|
||||||
|
|
||||||
// Cache strategy: Network First for API, Cache First for tiles, Stale While Revalidate for static assets
|
|
||||||
self.addEventListener('fetch', (event) => {
|
self.addEventListener('fetch', (event) => {
|
||||||
const url = event.request.url
|
const url = event.request.url
|
||||||
const { pathname } = new URL(url)
|
const { pathname } = new URL(url)
|
||||||
@@ -25,19 +30,71 @@ self.addEventListener('fetch', (event) => {
|
|||||||
// Skip non-GET requests
|
// Skip non-GET requests
|
||||||
if (event.request.method !== 'GET') return
|
if (event.request.method !== 'GET') return
|
||||||
|
|
||||||
// API requests: network only (don't cache dynamic data)
|
// Never intercept Socket.IO — let it pass through directly
|
||||||
|
if (pathname.startsWith('/socket.io')) return
|
||||||
|
|
||||||
|
// Cacheable API routes: Network First with cache fallback (icons, hose-types, dictionary)
|
||||||
|
if (CACHEABLE_API.some(p => pathname.startsWith(p))) {
|
||||||
|
event.respondWith(
|
||||||
|
caches.open(API_CACHE).then((cache) =>
|
||||||
|
fetch(event.request).then((response) => {
|
||||||
|
if (response.ok) cache.put(event.request, response.clone())
|
||||||
|
return response
|
||||||
|
}).catch(() =>
|
||||||
|
cache.match(event.request).then((cached) => cached || new Response('{"error":"offline"}', {
|
||||||
|
status: 503, headers: { 'Content-Type': 'application/json' }
|
||||||
|
}))
|
||||||
|
)
|
||||||
|
)
|
||||||
|
)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// Projects API: Network First with cache fallback
|
||||||
|
if (pathname === '/api/projects' || pathname.match(/^\/api\/projects\/[^/]+$/)) {
|
||||||
|
event.respondWith(
|
||||||
|
caches.open(API_CACHE).then((cache) =>
|
||||||
|
fetch(event.request).then((response) => {
|
||||||
|
if (response.ok) cache.put(event.request, response.clone())
|
||||||
|
return response
|
||||||
|
}).catch(() =>
|
||||||
|
cache.match(event.request).then((cached) => cached || new Response('{"error":"offline"}', {
|
||||||
|
status: 503, headers: { 'Content-Type': 'application/json' }
|
||||||
|
}))
|
||||||
|
)
|
||||||
|
)
|
||||||
|
)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// Features API: Network First with cache fallback
|
||||||
|
if (pathname.match(/^\/api\/projects\/[^/]+\/features$/)) {
|
||||||
|
event.respondWith(
|
||||||
|
caches.open(API_CACHE).then((cache) =>
|
||||||
|
fetch(event.request).then((response) => {
|
||||||
|
if (response.ok) cache.put(event.request, response.clone())
|
||||||
|
return response
|
||||||
|
}).catch(() =>
|
||||||
|
cache.match(event.request).then((cached) => cached || new Response('{"error":"offline"}', {
|
||||||
|
status: 503, headers: { 'Content-Type': 'application/json' }
|
||||||
|
}))
|
||||||
|
)
|
||||||
|
)
|
||||||
|
)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// Other API requests: network only
|
||||||
if (pathname.startsWith('/api/')) return
|
if (pathname.startsWith('/api/')) return
|
||||||
|
|
||||||
// Cache map tiles from OpenStreetMap (Cache First)
|
// Cache map tiles from OSM / MapTiler / ArcGIS / Swisstopo (Cache First — tiles don't change)
|
||||||
if (url.includes('tile.openstreetmap.org') || url.includes('api.maptiler.com')) {
|
if (url.includes('tile.openstreetmap.org') || url.includes('api.maptiler.com') || url.includes('server.arcgisonline.com') || url.includes('geo.admin.ch')) {
|
||||||
event.respondWith(
|
event.respondWith(
|
||||||
caches.open(TILE_CACHE).then((cache) =>
|
caches.open(TILE_CACHE).then((cache) =>
|
||||||
cache.match(event.request).then((cached) => {
|
cache.match(event.request).then((cached) => {
|
||||||
if (cached) return cached
|
if (cached) return cached
|
||||||
return fetch(event.request).then((response) => {
|
return fetch(event.request).then((response) => {
|
||||||
if (response.ok) {
|
if (response.ok) cache.put(event.request, response.clone())
|
||||||
cache.put(event.request, response.clone())
|
|
||||||
}
|
|
||||||
return response
|
return response
|
||||||
}).catch(() => new Response('', { status: 503 }))
|
}).catch(() => new Response('', { status: 503 }))
|
||||||
})
|
})
|
||||||
@@ -46,7 +103,23 @@ self.addEventListener('fetch', (event) => {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
// Static assets (JS, CSS, images): Stale While Revalidate
|
// Next.js build chunks (_next/static): Cache First (hashed filenames = immutable)
|
||||||
|
if (pathname.startsWith('/_next/static/')) {
|
||||||
|
event.respondWith(
|
||||||
|
caches.open(STATIC_CACHE).then((cache) =>
|
||||||
|
cache.match(event.request).then((cached) => {
|
||||||
|
if (cached) return cached
|
||||||
|
return fetch(event.request).then((response) => {
|
||||||
|
if (response.ok) cache.put(event.request, response.clone())
|
||||||
|
return response
|
||||||
|
}).catch(() => new Response('', { status: 503 }))
|
||||||
|
})
|
||||||
|
)
|
||||||
|
)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// Other static assets (JS, CSS, images, fonts): Stale While Revalidate
|
||||||
if (pathname.match(/\.(js|css|png|jpg|jpeg|svg|ico|woff2?)$/)) {
|
if (pathname.match(/\.(js|css|png|jpg|jpeg|svg|ico|woff2?)$/)) {
|
||||||
event.respondWith(
|
event.respondWith(
|
||||||
caches.open(STATIC_CACHE).then((cache) =>
|
caches.open(STATIC_CACHE).then((cache) =>
|
||||||
@@ -62,8 +135,8 @@ self.addEventListener('fetch', (event) => {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
// App pages: Network First with cache fallback
|
// App pages / navigation: Network First with cache fallback
|
||||||
if (pathname === '/app' || pathname === '/' || pathname.startsWith('/app')) {
|
if (event.request.mode === 'navigate' || pathname === '/app' || pathname === '/' || pathname.startsWith('/app')) {
|
||||||
event.respondWith(
|
event.respondWith(
|
||||||
fetch(event.request).then((response) => {
|
fetch(event.request).then((response) => {
|
||||||
if (response.ok) {
|
if (response.ok) {
|
||||||
@@ -81,7 +154,7 @@ self.addEventListener('fetch', (event) => {
|
|||||||
|
|
||||||
// Clean old caches on activation
|
// Clean old caches on activation
|
||||||
self.addEventListener('activate', (event) => {
|
self.addEventListener('activate', (event) => {
|
||||||
const currentCaches = [TILE_CACHE, STATIC_CACHE, APP_CACHE]
|
const currentCaches = [TILE_CACHE, STATIC_CACHE, APP_CACHE, API_CACHE]
|
||||||
event.waitUntil(
|
event.waitUntil(
|
||||||
caches.keys().then((keys) =>
|
caches.keys().then((keys) =>
|
||||||
Promise.all(
|
Promise.all(
|
||||||
@@ -92,3 +165,23 @@ self.addEventListener('activate', (event) => {
|
|||||||
).then(() => self.clients.claim())
|
).then(() => self.clients.claim())
|
||||||
)
|
)
|
||||||
})
|
})
|
||||||
|
|
||||||
|
// Listen for sync events (Background Sync for queued saves)
|
||||||
|
self.addEventListener('sync', (event) => {
|
||||||
|
if (event.tag === 'sync-saves') {
|
||||||
|
event.waitUntil(syncQueuedSaves())
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
// Process queued saves from IndexedDB/localStorage
|
||||||
|
async function syncQueuedSaves() {
|
||||||
|
try {
|
||||||
|
const clients = await self.clients.matchAll()
|
||||||
|
clients.forEach(client => client.postMessage({ type: 'SYNC_START' }))
|
||||||
|
|
||||||
|
// Read queue from a BroadcastChannel or let the main thread handle it
|
||||||
|
clients.forEach(client => client.postMessage({ type: 'FLUSH_SYNC_QUEUE' }))
|
||||||
|
} catch (e) {
|
||||||
|
console.error('[SW] Sync error:', e)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
@@ -19,9 +19,10 @@ import { Button } from '@/components/ui/button'
|
|||||||
import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/components/ui/dialog'
|
import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/components/ui/dialog'
|
||||||
import { JournalView } from '@/components/journal/journal-view'
|
import { JournalView } from '@/components/journal/journal-view'
|
||||||
import { jsPDF } from 'jspdf'
|
import { jsPDF } from 'jspdf'
|
||||||
import { Lock, Unlock, Eye, AlertTriangle } from 'lucide-react'
|
import { Lock, Unlock, Eye, AlertTriangle, WifiOff } from 'lucide-react'
|
||||||
import { getSocket } from '@/lib/socket'
|
import { getSocket, setSocketRoom } from '@/lib/socket'
|
||||||
import { CustomDragLayer } from '@/components/map/custom-drag-layer'
|
import { CustomDragLayer } from '@/components/map/custom-drag-layer'
|
||||||
|
import { addToSyncQueue, flushSyncQueue, getSyncQueue, isOnline as checkOnline } from '@/lib/offline-sync'
|
||||||
|
|
||||||
export interface Project {
|
export interface Project {
|
||||||
id: string
|
id: string
|
||||||
@@ -366,6 +367,54 @@ export default function AppPage() {
|
|||||||
// Ref to access the map for export
|
// Ref to access the map for export
|
||||||
const mapRef = useRef<any>(null)
|
const mapRef = useRef<any>(null)
|
||||||
|
|
||||||
|
// Offline detection
|
||||||
|
const [isOffline, setIsOffline] = useState(false)
|
||||||
|
const [syncQueueCount, setSyncQueueCount] = useState(0)
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
setIsOffline(!checkOnline())
|
||||||
|
setSyncQueueCount(getSyncQueue().length)
|
||||||
|
|
||||||
|
const goOffline = () => {
|
||||||
|
setIsOffline(true)
|
||||||
|
toast({ title: 'Offline-Modus', description: 'Änderungen werden lokal gespeichert und beim Reconnect synchronisiert.' })
|
||||||
|
}
|
||||||
|
const goOnline = async () => {
|
||||||
|
setIsOffline(false)
|
||||||
|
const queue = getSyncQueue()
|
||||||
|
if (queue.length > 0) {
|
||||||
|
toast({ title: 'Verbindung wiederhergestellt', description: `${queue.length} Änderung(en) werden synchronisiert...` })
|
||||||
|
const result = await flushSyncQueue()
|
||||||
|
setSyncQueueCount(getSyncQueue().length)
|
||||||
|
if (result.success > 0) {
|
||||||
|
toast({ title: 'Synchronisiert', description: `${result.success} Änderung(en) erfolgreich gespeichert.` })
|
||||||
|
}
|
||||||
|
if (result.failed > 0) {
|
||||||
|
toast({ title: 'Sync-Fehler', description: `${result.failed} Änderung(en) konnten nicht gespeichert werden.`, variant: 'destructive' })
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
toast({ title: 'Wieder online' })
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
window.addEventListener('offline', goOffline)
|
||||||
|
window.addEventListener('online', goOnline)
|
||||||
|
|
||||||
|
// Listen for SW sync messages
|
||||||
|
if ('serviceWorker' in navigator) {
|
||||||
|
navigator.serviceWorker.addEventListener('message', (event) => {
|
||||||
|
if (event.data?.type === 'FLUSH_SYNC_QUEUE') {
|
||||||
|
flushSyncQueue().then(() => setSyncQueueCount(getSyncQueue().length))
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
return () => {
|
||||||
|
window.removeEventListener('offline', goOffline)
|
||||||
|
window.removeEventListener('online', goOnline)
|
||||||
|
}
|
||||||
|
}, [])
|
||||||
|
|
||||||
// Undo/Redo history
|
// Undo/Redo history
|
||||||
const undoStackRef = useRef<DrawFeature[][]>([])
|
const undoStackRef = useRef<DrawFeature[][]>([])
|
||||||
const redoStackRef = useRef<DrawFeature[][]>([])
|
const redoStackRef = useRef<DrawFeature[][]>([])
|
||||||
@@ -458,27 +507,31 @@ export default function AppPage() {
|
|||||||
const socketRef = useRef<any>(null)
|
const socketRef = useRef<any>(null)
|
||||||
const prevProjectIdRef = useRef<string | null>(null)
|
const prevProjectIdRef = useRef<string | null>(null)
|
||||||
|
|
||||||
// Throttled socket broadcast for near-real-time sync (1.5s instead of 10s auto-save)
|
// Throttled socket broadcast for near-real-time sync
|
||||||
const lastEmitRef = useRef(0)
|
const lastEmitRef = useRef(0)
|
||||||
const emitTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null)
|
const emitTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null)
|
||||||
|
const currentProjectRef = useRef(currentProject)
|
||||||
|
useEffect(() => { currentProjectRef.current = currentProject }, [currentProject])
|
||||||
|
|
||||||
const broadcastFeatures = useCallback((feats: DrawFeature[]) => {
|
const broadcastFeatures = useCallback((feats: DrawFeature[]) => {
|
||||||
if (!socketRef.current || !currentProject?.id || !isEditingByMe) return
|
const proj = currentProjectRef.current
|
||||||
|
if (!socketRef.current || !proj?.id || !isEditingByMeRef.current) return
|
||||||
const now = Date.now()
|
const now = Date.now()
|
||||||
const emit = () => {
|
const emit = () => {
|
||||||
socketRef.current?.emit('features-updated', {
|
socketRef.current?.emit('features-updated', {
|
||||||
projectId: currentProject!.id,
|
projectId: proj!.id,
|
||||||
features: feats,
|
features: feats,
|
||||||
})
|
})
|
||||||
lastEmitRef.current = Date.now()
|
lastEmitRef.current = Date.now()
|
||||||
}
|
}
|
||||||
// Throttle: emit at most every 1.5 seconds
|
// Throttle: emit at most every 800ms for snappier sync
|
||||||
if (now - lastEmitRef.current > 1500) {
|
if (now - lastEmitRef.current > 800) {
|
||||||
emit()
|
emit()
|
||||||
} else {
|
} else {
|
||||||
if (emitTimerRef.current) clearTimeout(emitTimerRef.current)
|
if (emitTimerRef.current) clearTimeout(emitTimerRef.current)
|
||||||
emitTimerRef.current = setTimeout(emit, 1500 - (now - lastEmitRef.current))
|
emitTimerRef.current = setTimeout(emit, 800 - (now - lastEmitRef.current))
|
||||||
}
|
}
|
||||||
}, [currentProject?.id, isEditingByMe])
|
}, [])
|
||||||
const isEditingByMeRef = useRef(false)
|
const isEditingByMeRef = useRef(false)
|
||||||
|
|
||||||
// Keep ref in sync with state
|
// Keep ref in sync with state
|
||||||
@@ -497,6 +550,7 @@ export default function AppPage() {
|
|||||||
socket.emit('leave-project', prevProjectIdRef.current)
|
socket.emit('leave-project', prevProjectIdRef.current)
|
||||||
}
|
}
|
||||||
socket.emit('join-project', currentProject.id)
|
socket.emit('join-project', currentProject.id)
|
||||||
|
setSocketRoom(currentProject.id)
|
||||||
prevProjectIdRef.current = currentProject.id
|
prevProjectIdRef.current = currentProject.id
|
||||||
|
|
||||||
// Listen for features changes from other clients (only apply if NOT the editor)
|
// Listen for features changes from other clients (only apply if NOT the editor)
|
||||||
@@ -643,11 +697,22 @@ export default function AppPage() {
|
|||||||
const saveTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null)
|
const saveTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null)
|
||||||
const saveFeaturesToApi = useCallback(async () => {
|
const saveFeaturesToApi = useCallback(async () => {
|
||||||
if (!currentProject?.id) return
|
if (!currentProject?.id) return
|
||||||
|
const url = `/api/projects/${currentProject.id}/features`
|
||||||
|
const body = { features: featuresRef.current }
|
||||||
|
|
||||||
|
// If offline, queue the save for later sync
|
||||||
|
if (!navigator.onLine) {
|
||||||
|
addToSyncQueue(url, 'PUT', body)
|
||||||
|
setSyncQueueCount(getSyncQueue().length)
|
||||||
|
console.log('[Auto-Save] Offline — in Sync-Queue gespeichert')
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const res = await fetch(`/api/projects/${currentProject.id}/features`, {
|
const res = await fetch(url, {
|
||||||
method: 'PUT',
|
method: 'PUT',
|
||||||
headers: { 'Content-Type': 'application/json' },
|
headers: { 'Content-Type': 'application/json' },
|
||||||
body: JSON.stringify({ features: featuresRef.current }),
|
body: JSON.stringify(body),
|
||||||
})
|
})
|
||||||
if (res.ok) {
|
if (res.ok) {
|
||||||
console.log('[Auto-Save] Features gespeichert')
|
console.log('[Auto-Save] Features gespeichert')
|
||||||
@@ -659,7 +724,10 @@ export default function AppPage() {
|
|||||||
console.warn('[Auto-Save] Projekt nicht in DB')
|
console.warn('[Auto-Save] Projekt nicht in DB')
|
||||||
}
|
}
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
console.warn('[Auto-Save] Fehler:', e)
|
// Network error — queue for later
|
||||||
|
addToSyncQueue(url, 'PUT', body)
|
||||||
|
setSyncQueueCount(getSyncQueue().length)
|
||||||
|
console.warn('[Auto-Save] Netzwerkfehler — in Sync-Queue:', e)
|
||||||
}
|
}
|
||||||
}, [currentProject])
|
}, [currentProject])
|
||||||
|
|
||||||
@@ -1389,6 +1457,17 @@ export default function AppPage() {
|
|||||||
onLogout={logout}
|
onLogout={logout}
|
||||||
/>
|
/>
|
||||||
|
|
||||||
|
{/* Offline banner */}
|
||||||
|
{isOffline && (
|
||||||
|
<div className="flex items-center justify-center gap-3 px-4 py-2 bg-orange-50 dark:bg-orange-950/40 border-b border-orange-200 dark:border-orange-800 text-sm text-orange-800 dark:text-orange-300">
|
||||||
|
<WifiOff className="w-4 h-4 shrink-0" />
|
||||||
|
<span>
|
||||||
|
<strong>Offline-Modus</strong> — Änderungen werden lokal gespeichert und beim Reconnect synchronisiert.
|
||||||
|
{syncQueueCount > 0 && ` (${syncQueueCount} ausstehend)`}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
{/* Email verification banner */}
|
{/* Email verification banner */}
|
||||||
{user && user.emailVerified === false && (
|
{user && user.emailVerified === false && (
|
||||||
<div className="flex items-center justify-center gap-3 px-4 py-2 bg-amber-50 dark:bg-amber-950/40 border-b border-amber-200 dark:border-amber-800 text-sm text-amber-800 dark:text-amber-300">
|
<div className="flex items-center justify-center gap-3 px-4 py-2 bg-amber-50 dark:bg-amber-950/40 border-b border-amber-200 dark:border-amber-800 text-sm text-amber-800 dark:text-amber-300">
|
||||||
|
|||||||
@@ -23,6 +23,19 @@ function formatDistance(meters: number): string {
|
|||||||
return `${(meters / 1000).toFixed(2)} km`
|
return `${(meters / 1000).toFixed(2)} km`
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Approximate polygon area in m² using the Shoelace formula on spherical coordinates
|
||||||
|
function polygonArea(ring: number[][]): number {
|
||||||
|
const toRad = Math.PI / 180
|
||||||
|
const R = 6371000
|
||||||
|
let area = 0
|
||||||
|
const n = ring.length - 1 // exclude closing duplicate
|
||||||
|
for (let i = 0; i < n; i++) {
|
||||||
|
const j = (i + 1) % n
|
||||||
|
area += (ring[j][0] - ring[i][0]) * toRad * (2 + Math.sin(ring[i][1] * toRad) + Math.sin(ring[j][1] * toRad))
|
||||||
|
}
|
||||||
|
return Math.abs(area * R * R / 2)
|
||||||
|
}
|
||||||
|
|
||||||
// Point-to-segment distance in screen pixels (for click detection on lines)
|
// Point-to-segment distance in screen pixels (for click detection on lines)
|
||||||
function pointToSegmentDist(px: number, py: number, x1: number, y1: number, x2: number, y2: number): number {
|
function pointToSegmentDist(px: number, py: number, x1: number, y1: number, x2: number, y2: number): number {
|
||||||
const dx = x2 - x1, dy = y2 - y1
|
const dx = x2 - x1, dy = y2 - y1
|
||||||
@@ -93,7 +106,7 @@ export function MapView({
|
|||||||
const measureMarkersRef = useRef<maplibregl.Marker[]>([])
|
const measureMarkersRef = useRef<maplibregl.Marker[]>([])
|
||||||
const measureCoordsRef = useRef<number[][]>([])
|
const measureCoordsRef = useRef<number[][]>([])
|
||||||
const [isMapLoaded, setIsMapLoaded] = useState(false)
|
const [isMapLoaded, setIsMapLoaded] = useState(false)
|
||||||
const [isSatellite, setIsSatellite] = useState(false)
|
const [activeBaseLayer, setActiveBaseLayer] = useState<'osm' | 'satellite' | 'swisstopo' | 'swissimage'>('osm')
|
||||||
const [measurePointCount, setMeasurePointCount] = useState(0)
|
const [measurePointCount, setMeasurePointCount] = useState(0)
|
||||||
const [measureFinished, setMeasureFinished] = useState(false)
|
const [measureFinished, setMeasureFinished] = useState(false)
|
||||||
const [drawingPointCount, setDrawingPointCount] = useState(0)
|
const [drawingPointCount, setDrawingPointCount] = useState(0)
|
||||||
@@ -676,6 +689,24 @@ export function MapView({
|
|||||||
attribution: '© Esri, Maxar, Earthstar Geographics',
|
attribution: '© Esri, Maxar, Earthstar Geographics',
|
||||||
maxzoom: 19,
|
maxzoom: 19,
|
||||||
},
|
},
|
||||||
|
'swisstopo': {
|
||||||
|
type: 'raster',
|
||||||
|
tiles: [
|
||||||
|
'https://wmts.geo.admin.ch/1.0.0/ch.swisstopo.pixelkarte-farbe/default/current/3857/{z}/{x}/{y}.jpeg',
|
||||||
|
],
|
||||||
|
tileSize: 256,
|
||||||
|
attribution: '© swisstopo',
|
||||||
|
maxzoom: 17,
|
||||||
|
},
|
||||||
|
'swissimage': {
|
||||||
|
type: 'raster',
|
||||||
|
tiles: [
|
||||||
|
'https://wmts.geo.admin.ch/1.0.0/ch.swisstopo.swissimage/default/current/3857/{z}/{x}/{y}.jpeg',
|
||||||
|
],
|
||||||
|
tileSize: 256,
|
||||||
|
attribution: '© swisstopo SWISSIMAGE',
|
||||||
|
maxzoom: 18,
|
||||||
|
},
|
||||||
},
|
},
|
||||||
layers: [
|
layers: [
|
||||||
{
|
{
|
||||||
@@ -689,6 +720,18 @@ export function MapView({
|
|||||||
source: 'satellite',
|
source: 'satellite',
|
||||||
layout: { visibility: 'none' },
|
layout: { visibility: 'none' },
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
id: 'swisstopo',
|
||||||
|
type: 'raster',
|
||||||
|
source: 'swisstopo',
|
||||||
|
layout: { visibility: 'none' },
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'swissimage',
|
||||||
|
type: 'raster',
|
||||||
|
source: 'swissimage',
|
||||||
|
layout: { visibility: 'none' },
|
||||||
|
},
|
||||||
],
|
],
|
||||||
},
|
},
|
||||||
center: [initialCenter.lng, initialCenter.lat],
|
center: [initialCenter.lng, initialCenter.lat],
|
||||||
@@ -940,7 +983,7 @@ export function MapView({
|
|||||||
// Eraser mode: click on/near a feature to delete it
|
// Eraser mode: click on/near a feature to delete it
|
||||||
if (mode === 'eraser') {
|
if (mode === 'eraser') {
|
||||||
const pixel = e.point
|
const pixel = e.point
|
||||||
const tolerance = 10 // px
|
const tolerance = 20 // px
|
||||||
const currentFeatures = featuresRef.current
|
const currentFeatures = featuresRef.current
|
||||||
let closestIdx = -1
|
let closestIdx = -1
|
||||||
let closestDist = Infinity
|
let closestDist = Infinity
|
||||||
@@ -949,29 +992,44 @@ export function MapView({
|
|||||||
const f = currentFeatures[i]
|
const f = currentFeatures[i]
|
||||||
const geom = f.geometry
|
const geom = f.geometry
|
||||||
|
|
||||||
// Get all coordinates to check proximity
|
|
||||||
let allCoords: number[][] = []
|
|
||||||
if (geom.type === 'Point') {
|
if (geom.type === 'Point') {
|
||||||
allCoords = [geom.coordinates as number[]]
|
const projected = m.project(geom.coordinates as [number, number])
|
||||||
} else if (geom.type === 'LineString') {
|
|
||||||
allCoords = geom.coordinates as number[][]
|
|
||||||
} else if (geom.type === 'Polygon') {
|
|
||||||
allCoords = (geom.coordinates as number[][][])[0] || []
|
|
||||||
}
|
|
||||||
|
|
||||||
for (const c of allCoords) {
|
|
||||||
const projected = m.project([c[0], c[1]])
|
|
||||||
const dx = projected.x - pixel.x
|
const dx = projected.x - pixel.x
|
||||||
const dy = projected.y - pixel.y
|
const dy = projected.y - pixel.y
|
||||||
const dist = Math.sqrt(dx * dx + dy * dy)
|
const dist = Math.sqrt(dx * dx + dy * dy)
|
||||||
if (dist < closestDist) {
|
if (dist < closestDist) { closestDist = dist; closestIdx = i }
|
||||||
closestDist = dist
|
} else if (geom.type === 'LineString') {
|
||||||
closestIdx = i
|
const lineCoords = geom.coordinates as number[][]
|
||||||
|
for (let j = 0; j < lineCoords.length - 1; j++) {
|
||||||
|
const p1 = m.project(lineCoords[j] as [number, number])
|
||||||
|
const p2 = m.project(lineCoords[j + 1] as [number, number])
|
||||||
|
const dist = pointToSegmentDist(pixel.x, pixel.y, p1.x, p1.y, p2.x, p2.y)
|
||||||
|
if (dist < closestDist) { closestDist = dist; closestIdx = i }
|
||||||
}
|
}
|
||||||
|
} else if (geom.type === 'Polygon') {
|
||||||
|
const ring = (geom.coordinates as number[][][])[0] || []
|
||||||
|
// Check edges
|
||||||
|
for (let j = 0; j < ring.length - 1; j++) {
|
||||||
|
const p1 = m.project(ring[j] as [number, number])
|
||||||
|
const p2 = m.project(ring[j + 1] as [number, number])
|
||||||
|
const dist = pointToSegmentDist(pixel.x, pixel.y, p1.x, p1.y, p2.x, p2.y)
|
||||||
|
if (dist < closestDist) { closestDist = dist; closestIdx = i }
|
||||||
|
}
|
||||||
|
// Point-in-polygon test (screen space)
|
||||||
|
const projected = ring.map(c => m.project(c as [number, number]))
|
||||||
|
let inside = false
|
||||||
|
for (let j = 0, k = projected.length - 1; j < projected.length; k = j++) {
|
||||||
|
const xi = projected[j].x, yi = projected[j].y
|
||||||
|
const xk = projected[k].x, yk = projected[k].y
|
||||||
|
if (((yi > pixel.y) !== (yk > pixel.y)) && (pixel.x < (xk - xi) * (pixel.y - yi) / (yk - yi) + xi)) {
|
||||||
|
inside = !inside
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (inside) { closestDist = 0; closestIdx = i }
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if (closestIdx >= 0 && closestDist < tolerance * 3) {
|
if (closestIdx >= 0 && closestDist < tolerance) {
|
||||||
const deleted = currentFeatures[closestIdx]
|
const deleted = currentFeatures[closestIdx]
|
||||||
const newFeatures = currentFeatures.filter((_, i) => i !== closestIdx)
|
const newFeatures = currentFeatures.filter((_, i) => i !== closestIdx)
|
||||||
onFeaturesChangeRef.current(newFeatures)
|
onFeaturesChangeRef.current(newFeatures)
|
||||||
@@ -1396,7 +1454,7 @@ export function MapView({
|
|||||||
pointer-events: none;
|
pointer-events: none;
|
||||||
`
|
`
|
||||||
|
|
||||||
const marker = new maplibregl.Marker({ element: arrowEl, anchor: 'center' })
|
const marker = new maplibregl.Marker({ element: arrowEl, anchor: 'center', rotationAlignment: 'viewport' })
|
||||||
.setLngLat(p2 as [number, number])
|
.setLngLat(p2 as [number, number])
|
||||||
.addTo(map.current)
|
.addTo(map.current)
|
||||||
markersRef.current.push(marker)
|
markersRef.current.push(marker)
|
||||||
@@ -1468,7 +1526,21 @@ export function MapView({
|
|||||||
el.appendChild(labelLine)
|
el.appendChild(labelLine)
|
||||||
el.appendChild(infoLine)
|
el.appendChild(infoLine)
|
||||||
} else {
|
} else {
|
||||||
el.textContent = label
|
// Polygon: show label + area
|
||||||
|
const ring = (f.geometry.coordinates as number[][][])[0]
|
||||||
|
const area = polygonArea(ring)
|
||||||
|
const areaText = area < 10000 ? `${Math.round(area)} m²` : `${(area / 10000).toFixed(2)} ha`
|
||||||
|
|
||||||
|
const labelLine = document.createElement('div')
|
||||||
|
labelLine.textContent = label
|
||||||
|
labelLine.style.cssText = 'font-size:11px;font-weight:600;line-height:1.2;'
|
||||||
|
|
||||||
|
const infoLine = document.createElement('div')
|
||||||
|
infoLine.textContent = areaText
|
||||||
|
infoLine.style.cssText = 'font-size:8px;opacity:0.8;line-height:1.2;font-weight:400;'
|
||||||
|
|
||||||
|
el.appendChild(labelLine)
|
||||||
|
el.appendChild(infoLine)
|
||||||
}
|
}
|
||||||
|
|
||||||
// Double-click to edit label — only in select mode
|
// Double-click to edit label — only in select mode
|
||||||
@@ -1481,7 +1553,7 @@ export function MapView({
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
const marker = new maplibregl.Marker({ element: el, anchor: 'center' })
|
const marker = new maplibregl.Marker({ element: el, anchor: 'center', rotationAlignment: 'viewport' })
|
||||||
.setLngLat(midpoint)
|
.setLngLat(midpoint)
|
||||||
.addTo(map.current)
|
.addTo(map.current)
|
||||||
markersRef.current.push(marker)
|
markersRef.current.push(marker)
|
||||||
@@ -1568,7 +1640,7 @@ export function MapView({
|
|||||||
}
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const marker = new maplibregl.Marker({ element: wrapper, draggable: canEdit, anchor: 'center' })
|
const marker = new maplibregl.Marker({ element: wrapper, draggable: canEdit, anchor: 'center', rotationAlignment: 'viewport' })
|
||||||
.setLngLat(coords)
|
.setLngLat(coords)
|
||||||
.addTo(map.current)
|
.addTo(map.current)
|
||||||
|
|
||||||
@@ -1634,7 +1706,7 @@ export function MapView({
|
|||||||
el.textContent = (f.properties.text as string) || ''
|
el.textContent = (f.properties.text as string) || ''
|
||||||
wrapper.appendChild(el)
|
wrapper.appendChild(el)
|
||||||
|
|
||||||
const marker = new maplibregl.Marker({ element: wrapper, draggable: canEdit, anchor: 'center' })
|
const marker = new maplibregl.Marker({ element: wrapper, draggable: canEdit, anchor: 'center', rotationAlignment: 'viewport' })
|
||||||
.setLngLat(coords)
|
.setLngLat(coords)
|
||||||
.addTo(map.current)
|
.addTo(map.current)
|
||||||
|
|
||||||
@@ -2082,29 +2154,34 @@ export function MapView({
|
|||||||
</>
|
</>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
{/* Layer toggle: OSM / Satellite */}
|
{/* Layer selector dropdown */}
|
||||||
<button
|
<select
|
||||||
onClick={() => {
|
value={activeBaseLayer}
|
||||||
|
onChange={(e) => {
|
||||||
if (!map.current) return
|
if (!map.current) return
|
||||||
const newSat = !isSatellite
|
const newLayer = e.target.value as 'osm' | 'satellite' | 'swisstopo' | 'swissimage'
|
||||||
setIsSatellite(newSat)
|
const allLayers: Array<'osm' | 'satellite' | 'swisstopo' | 'swissimage'> = ['osm', 'satellite', 'swisstopo', 'swissimage']
|
||||||
map.current.setLayoutProperty('osm', 'visibility', newSat ? 'none' : 'visible')
|
for (const l of allLayers) {
|
||||||
map.current.setLayoutProperty('satellite', 'visibility', newSat ? 'visible' : 'none')
|
map.current.setLayoutProperty(l, 'visibility', l === newLayer ? 'visible' : 'none')
|
||||||
|
}
|
||||||
|
setActiveBaseLayer(newLayer)
|
||||||
}}
|
}}
|
||||||
className="absolute top-3 right-3 z-10 flex items-center gap-1.5 px-2.5 py-1.5 rounded-lg text-xs font-semibold shadow-lg border transition-colors"
|
className="absolute top-3 right-3 z-10 px-2.5 py-1.5 rounded-lg text-xs font-semibold shadow-lg border transition-colors cursor-pointer appearance-none pr-7"
|
||||||
style={{
|
style={{
|
||||||
background: isSatellite ? 'rgba(0,0,0,0.7)' : 'rgba(255,255,255,0.95)',
|
background: activeBaseLayer !== 'osm' ? 'rgba(0,0,0,0.75)' : 'rgba(255,255,255,0.95)',
|
||||||
color: isSatellite ? '#fff' : '#333',
|
color: activeBaseLayer !== 'osm' ? '#fff' : '#333',
|
||||||
borderColor: isSatellite ? 'rgba(255,255,255,0.3)' : 'rgba(0,0,0,0.15)',
|
borderColor: activeBaseLayer !== 'osm' ? 'rgba(255,255,255,0.3)' : 'rgba(0,0,0,0.15)',
|
||||||
|
backgroundImage: `url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='12' height='12' viewBox='0 0 24 24' fill='none' stroke='${activeBaseLayer !== 'osm' ? 'white' : '%23333'}' stroke-width='2'%3E%3Cpath d='M6 9l6 6 6-6'/%3E%3C/svg%3E")`,
|
||||||
|
backgroundRepeat: 'no-repeat',
|
||||||
|
backgroundPosition: 'right 6px center',
|
||||||
}}
|
}}
|
||||||
title={isSatellite ? 'Zur Kartenansicht wechseln' : 'Zur Satellitenansicht wechseln'}
|
title="Kartenstil wählen"
|
||||||
>
|
>
|
||||||
{isSatellite ? (
|
<option value="osm">🗺️ OpenStreetMap</option>
|
||||||
<><svg className="w-4 h-4" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M3 7l6-3 6 3 6-3v13l-6 3-6-3-6 3z"/><path d="M9 4v13"/><path d="M15 7v13"/></svg>Karte</>
|
<option value="satellite">🛰️ Satellit (Esri)</option>
|
||||||
) : (
|
<option value="swisstopo">🇨🇭 Swisstopo Karte</option>
|
||||||
<><svg className="w-4 h-4" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><circle cx="12" cy="12" r="10"/><path d="M12 2a14.5 14.5 0 0 0 0 20 14.5 14.5 0 0 0 0-20"/><path d="M2 12h20"/></svg>Satellit</>
|
<option value="swissimage">🇨🇭 Swisstopo Luftbild</option>
|
||||||
)}
|
</select>
|
||||||
</button>
|
|
||||||
|
|
||||||
{/* Zeichnung abschliessen Button (Linie/Polygon/Pfeil) */}
|
{/* Zeichnung abschliessen Button (Linie/Polygon/Pfeil) */}
|
||||||
{(drawMode === 'linestring' || drawMode === 'polygon' || drawMode === 'arrow' || drawMode === 'dangerzone') && drawingPointCount >= 2 && (
|
{(drawMode === 'linestring' || drawMode === 'polygon' || drawMode === 'arrow' || drawMode === 'dangerzone') && drawingPointCount >= 2 && (
|
||||||
|
|||||||
97
src/lib/offline-sync.ts
Normal file
97
src/lib/offline-sync.ts
Normal file
@@ -0,0 +1,97 @@
|
|||||||
|
// Offline detection and sync queue for saving changes when reconnecting
|
||||||
|
|
||||||
|
const SYNC_QUEUE_KEY = 'lageplan-sync-queue'
|
||||||
|
|
||||||
|
interface SyncQueueItem {
|
||||||
|
id: string
|
||||||
|
url: string
|
||||||
|
method: string
|
||||||
|
body: string
|
||||||
|
timestamp: number
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Get all queued saves */
|
||||||
|
export function getSyncQueue(): SyncQueueItem[] {
|
||||||
|
try {
|
||||||
|
const raw = localStorage.getItem(SYNC_QUEUE_KEY)
|
||||||
|
return raw ? JSON.parse(raw) : []
|
||||||
|
} catch {
|
||||||
|
return []
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Add a save operation to the sync queue (called when offline) */
|
||||||
|
export function addToSyncQueue(url: string, method: string, body: any): void {
|
||||||
|
const queue = getSyncQueue()
|
||||||
|
// Deduplicate: if same URL+method exists, replace it with newer data
|
||||||
|
const existing = queue.findIndex(q => q.url === url && q.method === method)
|
||||||
|
const item: SyncQueueItem = {
|
||||||
|
id: `${Date.now()}-${Math.random().toString(36).slice(2, 8)}`,
|
||||||
|
url,
|
||||||
|
method,
|
||||||
|
body: JSON.stringify(body),
|
||||||
|
timestamp: Date.now(),
|
||||||
|
}
|
||||||
|
if (existing >= 0) {
|
||||||
|
queue[existing] = item
|
||||||
|
} else {
|
||||||
|
queue.push(item)
|
||||||
|
}
|
||||||
|
localStorage.setItem(SYNC_QUEUE_KEY, JSON.stringify(queue))
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Flush the sync queue — send all queued requests to the server */
|
||||||
|
export async function flushSyncQueue(): Promise<{ success: number; failed: number }> {
|
||||||
|
const queue = getSyncQueue()
|
||||||
|
if (queue.length === 0) return { success: 0, failed: 0 }
|
||||||
|
|
||||||
|
let success = 0
|
||||||
|
let failed = 0
|
||||||
|
const remaining: SyncQueueItem[] = []
|
||||||
|
|
||||||
|
for (const item of queue) {
|
||||||
|
try {
|
||||||
|
const res = await fetch(item.url, {
|
||||||
|
method: item.method,
|
||||||
|
headers: { 'Content-Type': 'application/json' },
|
||||||
|
body: item.body,
|
||||||
|
})
|
||||||
|
if (res.ok) {
|
||||||
|
success++
|
||||||
|
} else {
|
||||||
|
// Server error — keep in queue for retry
|
||||||
|
remaining.push(item)
|
||||||
|
failed++
|
||||||
|
}
|
||||||
|
} catch {
|
||||||
|
// Still offline — keep in queue
|
||||||
|
remaining.push(item)
|
||||||
|
failed++
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
localStorage.setItem(SYNC_QUEUE_KEY, JSON.stringify(remaining))
|
||||||
|
return { success, failed }
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Clear the sync queue */
|
||||||
|
export function clearSyncQueue(): void {
|
||||||
|
localStorage.removeItem(SYNC_QUEUE_KEY)
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Check if we're online */
|
||||||
|
export function isOnline(): boolean {
|
||||||
|
return navigator.onLine
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Register Background Sync (if supported) */
|
||||||
|
export async function registerBackgroundSync(): Promise<void> {
|
||||||
|
if ('serviceWorker' in navigator && 'SyncManager' in window) {
|
||||||
|
try {
|
||||||
|
const reg = await navigator.serviceWorker.ready
|
||||||
|
await (reg as any).sync.register('sync-saves')
|
||||||
|
} catch {
|
||||||
|
// Background Sync not supported or failed — will use manual flush
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -3,23 +3,50 @@
|
|||||||
import { io, Socket } from 'socket.io-client'
|
import { io, Socket } from 'socket.io-client'
|
||||||
|
|
||||||
let socket: Socket | null = null
|
let socket: Socket | null = null
|
||||||
|
let currentRoom: string | null = null
|
||||||
|
|
||||||
export function getSocket(): Socket {
|
export function getSocket(): Socket {
|
||||||
if (!socket) {
|
if (!socket) {
|
||||||
socket = io({
|
socket = io({
|
||||||
path: '/socket.io',
|
path: '/socket.io',
|
||||||
transports: ['polling', 'websocket'],
|
transports: ['websocket', 'polling'],
|
||||||
upgrade: true,
|
upgrade: true,
|
||||||
reconnectionAttempts: 10,
|
reconnection: true,
|
||||||
reconnectionDelay: 2000,
|
reconnectionAttempts: Infinity,
|
||||||
|
reconnectionDelay: 1000,
|
||||||
|
reconnectionDelayMax: 5000,
|
||||||
timeout: 10000,
|
timeout: 10000,
|
||||||
|
forceNew: false,
|
||||||
})
|
})
|
||||||
socket.on('connect', () => {
|
socket.on('connect', () => {
|
||||||
console.log('[Socket.io] Connected:', socket?.id)
|
console.log('[Socket.io] Connected:', socket?.id)
|
||||||
|
// Re-join project room after reconnect
|
||||||
|
if (currentRoom) {
|
||||||
|
console.log('[Socket.io] Re-joining room:', currentRoom)
|
||||||
|
socket?.emit('join-project', currentRoom)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
socket.on('disconnect', (reason) => {
|
||||||
|
console.warn('[Socket.io] Disconnected:', reason)
|
||||||
|
if (reason === 'io server disconnect') {
|
||||||
|
// Server disconnected us, need to manually reconnect
|
||||||
|
socket?.connect()
|
||||||
|
}
|
||||||
})
|
})
|
||||||
socket.on('connect_error', (err) => {
|
socket.on('connect_error', (err) => {
|
||||||
console.warn('[Socket.io] Connection error:', err.message)
|
console.warn('[Socket.io] Connection error:', err.message)
|
||||||
})
|
})
|
||||||
|
socket.io.on('reconnect', (attempt) => {
|
||||||
|
console.log('[Socket.io] Reconnected after', attempt, 'attempts')
|
||||||
|
})
|
||||||
|
socket.io.on('reconnect_attempt', (attempt) => {
|
||||||
|
console.log('[Socket.io] Reconnect attempt', attempt)
|
||||||
|
})
|
||||||
}
|
}
|
||||||
return socket
|
return socket
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Track which room the socket should be in (for auto-rejoin on reconnect) */
|
||||||
|
export function setSocketRoom(projectId: string | null): void {
|
||||||
|
currentRoom = projectId
|
||||||
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user