From c11565aaf816dce316e9054a7c91d99bf52bba09 Mon Sep 17 00:00:00 2001 From: Pepe Ziberi Date: Sat, 21 Feb 2026 14:04:28 +0100 Subject: [PATCH] Fix: Rapport screenshot now uses coordinate-based rendering for correct symbol sizes, labels, arrowheads --- src/app/app/page.tsx | 257 ++++++++++++++++++++++++++++++++----------- 1 file changed, 193 insertions(+), 64 deletions(-) diff --git a/src/app/app/page.tsx b/src/app/app/page.tsx index 1b8e094..79bf53f 100644 --- a/src/app/app/page.tsx +++ b/src/app/app/page.tsx @@ -102,88 +102,217 @@ export default function AppPage() { sessionIdRef.current = `${Date.now()}-${Math.random().toString(36).slice(2, 10)}` } - // Capture map screenshot when switching to journal tab (including HTML symbol markers) + // Capture map screenshot when switching to journal tab (coordinate-based rendering) const handleTabChange = useCallback(async (tab: 'map' | 'journal') => { if (tab === 'journal' && mapRef.current) { try { - const mapCanvas = mapRef.current.getCanvas() - if (mapCanvas) { + const mapInstance = mapRef.current + const mapCanvas = mapInstance.getCanvas() as HTMLCanvasElement + if (mapCanvas && mapCanvas.width > 0) { const offscreen = document.createElement('canvas') offscreen.width = mapCanvas.width offscreen.height = mapCanvas.height const ctx = offscreen.getContext('2d') if (ctx) { ctx.drawImage(mapCanvas, 0, 0) - const dpr = window.devicePixelRatio || 1 - const mapContainer = mapRef.current.getContainer() - const mapRect = mapContainer.getBoundingClientRect() - // Collect all symbol images and preload them (async for URL-based images) - const symbolEntries: { img: HTMLImageElement; x: number; y: number; w: number; h: number; rotation: number }[] = [] - const loadPromises: Promise[] = [] + const container = mapInstance.getContainer() + const dpr = mapCanvas.width / container.offsetWidth + const currentZoom = mapInstance.getZoom() + const currentFeatures = featuresRef.current - document.querySelectorAll('.symbol-marker-wrapper').forEach(wrapper => { - const rect = wrapper.getBoundingClientRect() - const inner = wrapper.querySelector('.symbol-marker') - if (!inner) return - const bgImage = inner.style.backgroundImage - const urlMatch = bgImage.match(/url\("?(.+?)"?\)/) - if (!urlMatch) return - const imgSrc = urlMatch[1] - const img = new Image() - img.crossOrigin = 'anonymous' - img.src = imgSrc - const entry = { - img, - x: (rect.left - mapRect.left) * dpr, - y: (rect.top - mapRect.top) * dpr, - w: rect.width * dpr, - h: rect.height * dpr, - rotation: parseFloat(inner.style.transform?.match(/rotate\((.+?)deg\)/)?.[1] || '0'), - } - symbolEntries.push(entry) - if (!img.complete) { - loadPromises.push(new Promise((resolve) => { - img.onload = () => resolve() - img.onerror = () => resolve() - })) - } - }) - - // Wait for all symbol images to load (max 3s timeout) - if (loadPromises.length > 0) { - await Promise.race([ - Promise.all(loadPromises), - new Promise(r => setTimeout(r, 3000)), - ]) + // Helper: haversine distance + const haversine = (a: number[], b: number[]): number => { + const R = 6371000, toRad = Math.PI / 180 + const dLat = (b[1] - a[1]) * toRad, dLng = (b[0] - a[0]) * toRad + const x = Math.sin(dLat / 2) ** 2 + Math.cos(a[1] * toRad) * Math.cos(b[1] * toRad) * Math.sin(dLng / 2) ** 2 + return R * 2 * Math.atan2(Math.sqrt(x), Math.sqrt(1 - x)) } - // Draw all symbol markers - symbolEntries.forEach(({ img, x, y, w, h, rotation }) => { - if (img.complete && img.naturalWidth > 0) { - ctx.save() - ctx.translate(x + w / 2, y + h / 2) - if (rotation) ctx.rotate((rotation * Math.PI) / 180) - ctx.drawImage(img, -w / 2, -h / 2, w, h) - ctx.restore() - } + // Helper: load image as promise + const loadImage = (src: string): Promise => new Promise((resolve, reject) => { + const img = new Image() + img.crossOrigin = 'anonymous' + img.onload = () => resolve(img) + img.onerror = reject + img.src = src }) - // Draw text markers - document.querySelectorAll('.text-marker').forEach(el => { - const rect = el.getBoundingClientRect() - const x = (rect.left - mapRect.left) * dpr - const y = (rect.top - mapRect.top) * dpr - const text = el.textContent || '' - const fontSize = parseFloat(el.style.fontSize || '14') * dpr - const color = el.style.color || '#000' + // 1. Draw symbol features (coordinate-based) + for (const f of currentFeatures.filter(f => f.type === 'symbol')) { + if (f.geometry.type !== 'Point') continue + const coords = f.geometry.coordinates as [number, number] + const pixel = mapInstance.project(coords) + const px = pixel.x * dpr + const py = pixel.y * dpr + const scale = (f.properties.scale as number) || 1 + const rotation = (f.properties.rotation as number) || 0 + const baseSize = 32 + const placementZoom = (f.properties.placementZoom as number) || 17 + const zoomFactor = Math.pow(2, currentZoom - placementZoom) + const size = Math.max(8, Math.min(400, baseSize * scale * zoomFactor)) * dpr + + const iconId = f.properties.iconId as string + const imageUrl = f.properties.imageUrl as string + let imgSrc = imageUrl || '' + if (!imgSrc && iconId) { + const { getSymbolById, getSymbolDataUri } = await import('@/lib/fw-symbols') + const sym = getSymbolById(iconId) + if (sym) imgSrc = getSymbolDataUri(sym) + } + if (imgSrc) { + try { + const img = await loadImage(imgSrc) + const imgAspect = img.naturalWidth / img.naturalHeight + let drawW = size, drawH = size + if (imgAspect > 1) drawH = size / imgAspect + else drawW = size * imgAspect + ctx.save() + ctx.translate(px, py) + ctx.rotate((rotation * Math.PI) / 180) + ctx.drawImage(img, -drawW / 2, -drawH / 2, drawW, drawH) + ctx.restore() + } catch {} + } + } + + // 2. Draw arrowheads for arrow features + for (const f of currentFeatures.filter(f => f.type === 'arrow')) { + if (f.geometry.type !== 'LineString') continue + const lineCoords = f.geometry.coordinates as number[][] + if (lineCoords.length < 2) continue + const p1 = lineCoords[lineCoords.length - 2] + const p2 = lineCoords[lineCoords.length - 1] + const px1 = mapInstance.project(p1 as [number, number]) + const px2 = mapInstance.project(p2 as [number, number]) + const angle = Math.atan2(px2.y - px1.y, px2.x - px1.x) + const color = (f.properties.color as string) || '#000000' + const arrowSize = 14 * dpr + ctx.save() - ctx.font = `bold ${fontSize}px sans-serif` + ctx.translate(px2.x * dpr, px2.y * dpr) + ctx.rotate(angle + Math.PI / 2) + ctx.beginPath() + ctx.moveTo(0, -arrowSize) + ctx.lineTo(-arrowSize * 0.7, arrowSize * 0.3) + ctx.lineTo(arrowSize * 0.7, arrowSize * 0.3) + ctx.closePath() ctx.fillStyle = color - ctx.textBaseline = 'top' - ctx.fillText(text, x, y) + ctx.fill() ctx.restore() - }) + } + + // 3. Draw line/polygon labels at midpoints + for (const f of currentFeatures.filter(f => f.properties.label && (f.geometry.type === 'LineString' || f.geometry.type === 'Polygon'))) { + const label = f.properties.label as string + let midpoint: [number, number] + + if (f.geometry.type === 'LineString') { + const coords = f.geometry.coordinates as number[][] + const midIdx = Math.floor(coords.length / 2) + if (coords.length === 2) { + midpoint = [(coords[0][0] + coords[1][0]) / 2, (coords[0][1] + coords[1][1]) / 2] + } else { + midpoint = coords[midIdx] as [number, number] + } + } else { + const ring = (f.geometry.coordinates as number[][][])[0] + const len = ring.length - 1 + let cx = 0, cy = 0 + for (let i = 0; i < len; i++) { cx += ring[i][0]; cy += ring[i][1] } + midpoint = [cx / len, cy / len] + } + + const pixel = mapInstance.project(midpoint) + const px = pixel.x * dpr + const py = pixel.y * dpr + const isDanger = f.type === 'dangerzone' + const bgColor = isDanger ? 'rgba(220,38,38,0.85)' : 'rgba(0,0,0,0.75)' + const borderColor = isDanger ? '#dc2626' : 'rgba(255,255,255,0.5)' + + // Build label text with line info + let displayText = label + let infoText = '' + if (f.geometry.type === 'LineString') { + const lineCoords = f.geometry.coordinates as number[][] + let totalLen = 0 + for (let i = 1; i < lineCoords.length; i++) { + totalLen += haversine(lineCoords[i - 1], lineCoords[i]) + } + const hoseCount = Math.ceil(totalLen / 20) + const lenText = totalLen < 1000 ? `${Math.round(totalLen)}m` : `${(totalLen / 1000).toFixed(2)}km` + infoText = `${lenText} / ${hoseCount} Schl.` + } + + const fontSize1 = 11 * dpr + const fontSize2 = 8 * dpr + const padX = 6 * dpr + const padY = 3 * dpr + + ctx.save() + ctx.font = `bold ${fontSize1}px system-ui, sans-serif` + const w1 = ctx.measureText(displayText).width + let w2 = 0 + if (infoText) { + ctx.font = `${fontSize2}px system-ui, sans-serif` + w2 = ctx.measureText(infoText).width + } + const boxW = Math.max(w1, w2) + padX * 2 + const boxH = fontSize1 + (infoText ? fontSize2 + 2 * dpr : 0) + padY * 2 + const radius = 3 * dpr + + // Background + ctx.fillStyle = bgColor + ctx.beginPath() + ctx.roundRect(px - boxW / 2, py - boxH / 2, boxW, boxH, radius) + ctx.fill() + // Border + ctx.strokeStyle = borderColor + ctx.lineWidth = 1 * dpr + ctx.beginPath() + ctx.roundRect(px - boxW / 2, py - boxH / 2, boxW, boxH, radius) + ctx.stroke() + // Label text + ctx.fillStyle = '#ffffff' + ctx.font = `bold ${fontSize1}px system-ui, sans-serif` + ctx.textAlign = 'center' + ctx.textBaseline = 'middle' + const textY = infoText ? py - fontSize2 / 2 : py + ctx.fillText(displayText, px, textY) + // Info text + if (infoText) { + ctx.font = `${fontSize2}px system-ui, sans-serif` + ctx.globalAlpha = 0.8 + ctx.fillText(infoText, px, py + fontSize1 / 2 + 1 * dpr) + ctx.globalAlpha = 1 + } + ctx.restore() + } + + // 4. Draw text features + for (const f of currentFeatures.filter(f => f.type === 'text')) { + if (f.geometry.type !== 'Point') continue + const coords = f.geometry.coordinates as [number, number] + const pixel = mapInstance.project(coords) + const px = pixel.x * dpr + const py = pixel.y * dpr + const text = (f.properties.text as string) || '' + const fontSize = ((f.properties.fontSize as number) || 14) * dpr + const color = (f.properties.color as string) || '#000000' + + ctx.save() + ctx.font = `bold ${fontSize}px system-ui, sans-serif` + ctx.textAlign = 'center' + ctx.textBaseline = 'middle' + ctx.strokeStyle = '#ffffff' + ctx.lineWidth = 3 * dpr + ctx.lineJoin = 'round' + ctx.strokeText(text, px, py) + ctx.fillStyle = color + ctx.fillText(text, px, py) + ctx.restore() + } + setLastMapScreenshot(offscreen.toDataURL('image/png')) } else { setLastMapScreenshot(mapCanvas.toDataURL('image/png'))