Naprawa obsługi GPX, czyszczenie projektu, naprawa błędów związanych z obrazami

This commit is contained in:
Arek Bykowski
2026-02-15 19:03:02 +01:00
parent 981ce1d1b2
commit 144e28e4c4
10 changed files with 258 additions and 201 deletions

BIN
.DS_Store vendored

Binary file not shown.

22
App.tsx
View File

@@ -131,9 +131,9 @@ const App: React.FC = () => {
const [isLoaded, setIsLoaded] = useState(false);
const [errorMessage, setErrorMessage] = useState<string | null>(null);
// LOGO & AVATAR STATE
const [logoLoaded, setLogoLoaded] = useState(false);
const [avatarLoaded, setAvatarLoaded] = useState(false);
// LOGO & AVATAR STATE: Default to false (no error), so we try to show image first.
const [logoError, setLogoError] = useState(false);
const [avatarError, setAvatarError] = useState(false);
useEffect(() => {
const storedAuth = localStorage.getItem(AUTH_KEY);
@@ -245,14 +245,15 @@ const App: React.FC = () => {
<header className="bg-white sticky top-0 z-10 border-b border-gray-100">
<div className="max-w-4xl mx-auto px-6 py-4 flex justify-between items-center">
<div className="flex items-center space-x-3">
{/* LOGO LOGIC: Image is hidden by default. If it loads, it shows and text hides. */}
{/* LOGO LOGIC: Try to show image. If error, fallback to icon/text. */}
{!logoError ? (
<img
src="logo.png"
alt="Logo"
onLoad={() => setLogoLoaded(true)}
className={`h-10 object-contain ${logoLoaded ? 'block' : 'hidden'}`}
onError={() => setLogoError(true)}
className="h-10 object-contain"
/>
{!logoLoaded && (
) : (
<div className="flex items-center gap-2">
<div className="text-[#EA4420]"><Sparkles size={32} strokeWidth={2} /></div>
<h1 className="text-xl font-bold tracking-tight text-gray-900">{UI_TEXT.header.appTitle}</h1>
@@ -326,13 +327,14 @@ const App: React.FC = () => {
<div className="absolute -inset-0.5 bg-gradient-to-r from-[#EA4420] to-orange-400 rounded-full opacity-30 group-hover:opacity-100 transition duration-500 blur"></div>
{/* AVATAR LOGIC */}
{!avatarError ? (
<img
src={AUTHOR_CONFIG.avatarImage}
alt={AUTHOR_CONFIG.name}
onLoad={() => setAvatarLoaded(true)}
className={`relative w-20 h-20 rounded-full object-cover border border-gray-100 bg-white ${avatarLoaded ? 'block' : 'hidden'}`}
onError={() => setAvatarError(true)}
className="relative w-20 h-20 rounded-full object-cover border border-gray-100 bg-white"
/>
{!avatarLoaded && (
) : (
<div className="relative w-20 h-20 rounded-full border border-gray-100 bg-white flex items-center justify-center text-gray-300">
<User size={40} />
</div>

View File

@@ -1,128 +1 @@
import React, { useRef, useState } from 'react';
import { WizardState } from '../types';
import { UploadCloud, FileJson, AlertCircle } from 'lucide-react';
import { parseGpxFile } from '../utils/gpxUtils';
interface StepDataProps {
data: WizardState;
updateData: (updates: Partial<WizardState>) => void;
}
const StepData: React.FC<StepDataProps> = ({ data, updateData }) => {
const fileInputRef = useRef<HTMLInputElement>(null);
const [error, setError] = useState<string | null>(null);
const [isParsing, setIsParsing] = useState(false);
const handleFileChange = async (e: React.ChangeEvent<HTMLInputElement>) => {
const file = e.target.files?.[0];
if (!file) return;
if (!file.name.toLowerCase().endsWith('.gpx')) {
setError('Proszę wybrać plik .gpx');
return;
}
setError(null);
setIsParsing(true);
try {
const stats = await parseGpxFile(file);
updateData({ stats });
} catch (err) {
console.error(err);
setError('Błąd parsowania pliku GPX. Spróbuj innego pliku lub wpisz dane ręcznie.');
} finally {
setIsParsing(false);
}
};
const handleStatsChange = (key: keyof typeof data.stats, value: string) => {
updateData({
stats: {
...data.stats,
[key]: value
}
});
};
return (
<div className="space-y-10 animate-fade-in">
<div>
<h2 className="text-3xl font-bold tracking-tight text-gray-900 mb-3">Dane Aktywności</h2>
<p className="text-gray-500 mb-8 text-lg">Wgraj plik GPX lub wpisz dane ręcznie.</p>
</div>
{/* Upload Zone */}
<div
className={`border-2 border-dashed rounded-md p-10 flex flex-col items-center justify-center text-center transition-all cursor-pointer group ${
error ? 'border-red-300 bg-red-50' : 'border-gray-200 hover:border-[#EA4420] hover:bg-[#EA4420]/5'
}`}
onClick={() => fileInputRef.current?.click()}
>
<input
type="file"
ref={fileInputRef}
onChange={handleFileChange}
accept=".gpx"
className="hidden"
/>
{isParsing ? (
<div className="animate-pulse flex flex-col items-center">
<FileJson size={48} className="text-[#EA4420] mb-4 stroke-1" />
<p className="text-[#EA4420] font-semibold">Analizowanie pliku...</p>
</div>
) : (
<>
<UploadCloud size={48} className="text-gray-300 group-hover:text-[#EA4420] mb-4 stroke-1 transition-colors" />
<p className="text-gray-900 font-bold text-lg">Kliknij, aby wgrać plik GPX</p>
<p className="text-gray-500 text-sm mt-2">lub przeciągnij i upuść tutaj</p>
</>
)}
</div>
{error && (
<div className="flex items-center space-x-2 text-red-600 bg-red-50 p-4 rounded-md text-sm border border-red-100">
<AlertCircle size={18} />
<span className="font-medium">{error}</span>
</div>
)}
{/* Manual Override Inputs */}
<div className="grid grid-cols-1 md:grid-cols-3 gap-6">
<div>
<label className="block text-sm font-bold text-gray-700 mb-2">Dystans</label>
<input
type="text"
value={data.stats.distance}
onChange={(e) => handleStatsChange('distance', e.target.value)}
className="w-full p-4 border border-gray-200 rounded-md focus:ring-1 focus:ring-[#EA4420] focus:border-[#EA4420] outline-none transition-all font-medium text-gray-900 placeholder-gray-300"
placeholder="np. 12.5 km"
/>
</div>
<div>
<label className="block text-sm font-bold text-gray-700 mb-2">Czas trwania</label>
<input
type="text"
value={data.stats.duration}
onChange={(e) => handleStatsChange('duration', e.target.value)}
className="w-full p-4 border border-gray-200 rounded-md focus:ring-1 focus:ring-[#EA4420] focus:border-[#EA4420] outline-none transition-all font-medium text-gray-900 placeholder-gray-300"
placeholder="np. 1h 45m"
/>
</div>
<div>
<label className="block text-sm font-bold text-gray-700 mb-2">Przewyższenia</label>
<input
type="text"
value={data.stats.elevation}
onChange={(e) => handleStatsChange('elevation', e.target.value)}
className="w-full p-4 border border-gray-200 rounded-md focus:ring-1 focus:ring-[#EA4420] focus:border-[#EA4420] outline-none transition-all font-medium text-gray-900 placeholder-gray-300"
placeholder="np. 350m"
/>
</div>
</div>
</div>
);
};
export default StepData;
// Unused. Logic moved to StepDetails.tsx

View File

@@ -3,6 +3,7 @@ import React, { useRef, useState, useEffect } from 'react';
import { WizardState } from '../types';
import { UploadCloud, FileText, X, Image as ImageIcon, Sparkles, Loader2, MapPin, Navigation, Plus, Trash2, Flag, Target, AlertCircle, CheckCircle2, Car, Footprints, Eye } from 'lucide-react';
import { processFile } from '../utils/fileUtils';
import { parseGpxFile } from '../utils/gpxUtils';
import { getEnvVar } from '../utils/envUtils';
import { UI_TEXT } from '../_EDITABLE_CONFIG/ui_text';
@@ -82,6 +83,7 @@ const StepDetails: React.FC<StepDetailsProps> = ({ data, updateData, onGenerate,
const [error, setError] = useState<string | null>(null);
const [mapError, setMapError] = useState<{title: string, msg: string} | null>(null);
const [scriptLoaded, setScriptLoaded] = useState(false);
const [isParsingGpx, setIsParsingGpx] = useState(false);
// State for GPX Text Preview
const [showGpxPreview, setShowGpxPreview] = useState(false);
@@ -162,8 +164,29 @@ const StepDetails: React.FC<StepDetailsProps> = ({ data, updateData, onGenerate,
return;
}
setError(null);
// 1. Process files for display/Gemini upload
const processedFiles = await Promise.all(newFiles.map(processFile));
updateData(prev => ({ files: [...prev.files, ...processedFiles] }));
// 2. Scan for GPX to parse stats
const gpxFile = newFiles.find(f => f.name.toLowerCase().endsWith('.gpx'));
if (gpxFile) {
setIsParsingGpx(true);
try {
const result = await parseGpxFile(gpxFile);
updateData(prev => ({
...prev,
stats: result.stats,
gpxSummary: result.richSummary
}));
} catch (gpxErr) {
console.error(gpxErr);
setError("Wgrano plik, ale nie udało się odczytać statystyk GPX. Sprawdź format pliku.");
} finally {
setIsParsingGpx(false);
}
}
};
const removeFile = (id: string) => {
@@ -218,34 +241,39 @@ const StepDetails: React.FC<StepDetailsProps> = ({ data, updateData, onGenerate,
const isTripModeValid = data.eventType !== 'trip' || (data.tripData && data.tripData.travelMode !== null);
const isReadyToGenerate = data.title && isTripModeValid;
// Decide what text to show in preview
const previewText = data.gpxSummary
? data.gpxSummary
: `DYSTANS: ${data.stats.distance || "0"}\nCZAS TRWANIA: ${data.stats.duration || "0"}\nPRZEWYŻSZENIA: ${data.stats.elevation || "0"}`;
return (
<div className="space-y-10 animate-fade-in relative">
{/* GPX PREVIEW MODAL */}
{showGpxPreview && (
<div className="fixed inset-0 z-50 bg-black/50 flex items-center justify-center p-4 backdrop-blur-sm animate-fade-in">
<div className="bg-white rounded-lg shadow-xl max-w-lg w-full overflow-hidden flex flex-col max-h-[80vh]">
<div className="bg-white rounded-lg shadow-xl max-w-2xl w-full overflow-hidden flex flex-col max-h-[85vh]">
<div className="p-4 border-b border-gray-100 flex justify-between items-center bg-gray-50">
<h3 className="font-bold text-gray-900 flex items-center gap-2">
<FileText size={18} className="text-[#EA4420]" />
Podgląd kontekstu GPX
Podgląd danych dla AI (Context)
</h3>
<button onClick={() => setShowGpxPreview(false)} className="text-gray-400 hover:text-gray-600">
<X size={20} />
</button>
</div>
<div className="p-4 overflow-y-auto font-mono text-xs text-gray-700 bg-gray-50/50">
<p className="mb-2 text-gray-400 font-sans uppercase font-bold tracking-wider">To widzi AI:</p>
<div className="bg-white border border-gray-200 p-3 rounded">
<p>DYSTANS: {data.stats.distance || "0"}</p>
<p>CZAS TRWANIA: {data.stats.duration || "0"}</p>
<p>PRZEWYŻSZENIA: {data.stats.elevation || "0"}</p>
<div className="p-0 overflow-y-auto bg-gray-50/50 flex-1">
<div className="p-4">
<p className="mb-2 text-gray-400 font-sans uppercase font-bold tracking-wider text-xs">Poniższa treść zostanie dołączona do promptu:</p>
<pre className="bg-white border border-gray-200 p-4 rounded text-xs font-mono text-gray-700 whitespace-pre-wrap overflow-x-auto shadow-sm">
{previewText}
</pre>
</div>
</div>
<div className="p-4 border-t border-gray-100 flex justify-end">
<div className="p-4 border-t border-gray-100 flex justify-end bg-white">
<button
onClick={() => setShowGpxPreview(false)}
className="px-4 py-2 bg-gray-100 hover:bg-gray-200 text-gray-700 rounded text-sm font-bold transition-colors"
className="px-6 py-2 bg-gray-100 hover:bg-gray-200 text-gray-700 rounded text-sm font-bold transition-colors"
>
Zamknij
</button>
@@ -484,9 +512,18 @@ const StepDetails: React.FC<StepDetailsProps> = ({ data, updateData, onGenerate,
accept=".gpx,.pdf,image/*"
className="hidden"
/>
{isParsingGpx ? (
<div className="flex flex-col items-center animate-pulse">
<Loader2 size={32} className="text-[#EA4420] animate-spin mb-2" />
<p className="text-gray-900 font-bold">Analizowanie GPX...</p>
</div>
) : (
<>
<UploadCloud size={32} className="text-gray-300 group-hover:text-[#EA4420] mb-3 transition-colors" />
<p className="text-gray-600 font-medium">{UI_TEXT.stepDetails.fields.filesDrop}</p>
<p className="text-gray-400 text-xs mt-1">{UI_TEXT.stepDetails.fields.filesSub}</p>
</>
)}
</div>
{error && <p className="text-red-500 text-sm mt-2">{error}</p>}
@@ -514,7 +551,7 @@ const StepDetails: React.FC<StepDetailsProps> = ({ data, updateData, onGenerate,
</div>
{/* GPX Preview Button */}
{(data.stats.distance || data.stats.duration || data.files.some(f => f.file.name.endsWith('.gpx'))) && (
{(data.gpxSummary || data.stats.distance || data.stats.duration) && (
<div className="flex justify-end">
<button
onClick={() => setShowGpxPreview(true)}

0
prompts/index.ts Normal file
View File

0
prompts/modular.ts Normal file
View File

View File

@@ -57,7 +57,8 @@ export const generateStoryContent = async (
const BASE_SYSTEM_PROMPT = getSystemPrompt(data);
// 2. PRZYGOTUJ DANE (STATYSTYKI I WAYPOINTS) ZAMIAST SUROWEGO GPX
const statsInfo = `
// Wykorzystujemy bogaty raport z parsera GPX jeśli jest dostępny
const statsInfo = data.gpxSummary ? data.gpxSummary : `
DYSTANS: ${data.stats.distance}
CZAS TRWANIA: ${data.stats.duration}
PRZEWYŻSZENIA: ${data.stats.elevation}
@@ -110,7 +111,7 @@ export const generateStoryContent = async (
TYTUŁ: "${data.title}"
OPIS UŻYTKOWNIKA: "${data.description}"
=== STATYSTYKI AKTYWNOŚCI (Z PLIKU GPX) ===
=== STATYSTYKI I PRZEBIEG AKTYWNOŚCI (GPX) ===
${statsInfo}
=== KLUCZOWE MOMENTY (WAYPOINTS) ===

View File

@@ -59,6 +59,8 @@ export interface WizardState {
description: string;
files: UploadedFile[];
stats: ActivityStats;
// Nowe pole na szczegółowy raport tekstowy z GPX dla AI
gpxSummary?: string;
waypoints: Waypoint[];
tripData?: TripData; // Optional, only for eventType === 'trip'
}

View File

@@ -1 +0,0 @@
// This file was created by mistake and is now cleared.

View File

@@ -1,6 +1,12 @@
import { ActivityStats } from '../types';
export const parseGpxFile = async (file: File): Promise<ActivityStats> => {
interface GpxAnalysisResult {
stats: ActivityStats;
richSummary: string;
}
export const parseGpxFile = async (file: File): Promise<GpxAnalysisResult> => {
return new Promise((resolve, reject) => {
const reader = new FileReader();
@@ -13,54 +19,180 @@ export const parseGpxFile = async (file: File): Promise<ActivityStats> => {
const trkpts = Array.from(xmlDoc.getElementsByTagName('trkpt'));
if (trkpts.length === 0) {
// Fallback for rtept if no trkpt
const rtepts = Array.from(xmlDoc.getElementsByTagName('rtept'));
if (rtepts.length === 0) {
throw new Error('No track points found in GPX');
}
// Fallback logic could be added here for routes without time, but for storytelling we focus on tracks
throw new Error('Nie znaleziono punktów śledzenia (trkpt) w pliku GPX.');
}
let totalDistance = 0;
let totalTime = 0;
let elevationGain = 0;
// --- ZMIENNE AGREGUJĄCE ---
let totalDistanceKm = 0;
let totalElevationGain = 0;
let maxElevation = -Infinity;
let minElevation = Infinity;
let startTime: Date | null = null;
let endTime: Date | null = null;
// Heart Rate & Cadence
let totalHr = 0;
let hrCount = 0;
let maxHr = 0;
let totalCadence = 0;
let cadenceCount = 0;
// Splits (KM) Logic
const splits: { km: number; timeMs: number; avgHr: number; elevGain: number }[] = [];
let currentSplitDistance = 0;
let currentSplitTimeStart = 0;
let currentSplitHrSum = 0;
let currentSplitHrCount = 0;
let currentSplitElevGain = 0;
let splitIndex = 1;
let lastLat: number | null = null;
let lastLon: number | null = null;
let lastEle: number | null = null;
let lastTime: number | null = null;
// --- ITERACJA PO PUNKTACH ---
for (let i = 0; i < trkpts.length; i++) {
const lat1 = parseFloat(trkpts[i].getAttribute('lat') || '0');
const lon1 = parseFloat(trkpts[i].getAttribute('lon') || '0');
const ele = parseFloat(trkpts[i].getElementsByTagName('ele')[0]?.textContent || '0');
const timeStr = trkpts[i].getElementsByTagName('time')[0]?.textContent;
const pt = trkpts[i];
const lat = parseFloat(pt.getAttribute('lat') || '0');
const lon = parseFloat(pt.getAttribute('lon') || '0');
const ele = parseFloat(pt.getElementsByTagName('ele')[0]?.textContent || '0');
const timeStr = pt.getElementsByTagName('time')[0]?.textContent;
if (i > 0) {
const lat2 = parseFloat(trkpts[i - 1].getAttribute('lat') || '0');
const lon2 = parseFloat(trkpts[i - 1].getAttribute('lon') || '0');
totalDistance += getDistanceFromLatLonInKm(lat1, lon1, lat2, lon2);
// Extensions (HR / Cadence)
// Note: Namespaces can vary (ns3:hr, gpxtpx:hr), so we search loosely or by standard tag names inside extensions
const extensions = pt.getElementsByTagName('extensions')[0];
let hr = 0;
let cad = 0;
// Elevation gain
if (lastEle !== null && ele > lastEle) {
elevationGain += (ele - lastEle);
if (extensions) {
// Try standard Garmin/GPX schemes
const hrNode = extensions.getElementsByTagName('gpxtpx:hr')[0] || extensions.getElementsByTagName('ns3:hr')[0] || extensions.getElementsByTagName('hr')[0];
const cadNode = extensions.getElementsByTagName('gpxtpx:cad')[0] || extensions.getElementsByTagName('ns3:cad')[0] || extensions.getElementsByTagName('cad')[0];
if (hrNode?.textContent) {
hr = parseInt(hrNode.textContent);
if (!isNaN(hr) && hr > 0) {
totalHr += hr;
hrCount++;
if (hr > maxHr) maxHr = hr;
currentSplitHrSum += hr;
currentSplitHrCount++;
}
}
if (cadNode?.textContent) {
cad = parseInt(cadNode.textContent);
if (!isNaN(cad) && cad > 0) {
totalCadence += cad;
cadenceCount++;
}
}
}
let currentTime = 0;
if (timeStr) {
const time = new Date(timeStr);
if (!startTime) startTime = time;
endTime = time;
const d = new Date(timeStr);
currentTime = d.getTime();
if (!startTime) {
startTime = d;
currentSplitTimeStart = currentTime;
}
endTime = d;
}
if (!isNaN(ele)) lastEle = ele;
// Elevation Min/Max
if (!isNaN(ele)) {
if (ele > maxElevation) maxElevation = ele;
if (ele < minElevation) minElevation = ele;
}
if (startTime && endTime) {
totalTime = (endTime.getTime() - startTime.getTime()); // ms
// Distance & Calculation
if (lastLat !== null && lastLon !== null) {
const distKm = getDistanceFromLatLonInKm(lastLat, lastLon, lat, lon);
totalDistanceKm += distKm;
currentSplitDistance += distKm;
// Elevation Gain
if (lastEle !== null && !isNaN(ele) && ele > lastEle) {
const gain = ele - lastEle;
totalElevationGain += gain;
currentSplitElevGain += gain;
}
// --- SPLIT LOGIC (Co 1 KM) ---
if (currentSplitDistance >= 1.0) {
const splitTimeMs = currentTime - currentSplitTimeStart;
splits.push({
km: splitIndex,
timeMs: splitTimeMs,
avgHr: currentSplitHrCount > 0 ? Math.round(currentSplitHrSum / currentSplitHrCount) : 0,
elevGain: Math.round(currentSplitElevGain)
});
// Reset Split
splitIndex++;
currentSplitDistance = 0; // or subtract 1.0 specifically for precision, but reset is safer for GPS drift
currentSplitTimeStart = currentTime;
currentSplitHrSum = 0;
currentSplitHrCount = 0;
currentSplitElevGain = 0;
}
}
lastLat = lat;
lastLon = lon;
lastEle = isNaN(ele) ? lastEle : ele;
lastTime = currentTime;
}
// --- PODSUMOWANIE ---
const totalDurationMs = startTime && endTime ? (endTime.getTime() - startTime.getTime()) : 0;
const avgHr = hrCount > 0 ? Math.round(totalHr / hrCount) : 0;
const avgCadence = cadenceCount > 0 ? Math.round(totalCadence / cadenceCount) : 0;
const avgPaceMs = totalDistanceKm > 0 ? totalDurationMs / totalDistanceKm : 0; // ms per km
// Formatowanie statystyk do UI
const uiStats: ActivityStats = {
distance: `${totalDistanceKm.toFixed(2)} km`,
duration: msToTime(totalDurationMs),
elevation: `${Math.round(totalElevationGain)}m (Max: ${Math.round(maxElevation)}m)`
};
// --- BUDOWANIE BOGATEGO RAPORTU DLA AI ---
let report = `=== SZCZEGÓŁOWY RAPORT Z PLIKU GPX ===\n`;
report += `PODSUMOWANIE:\n`;
report += `- Dystans Całkowity: ${totalDistanceKm.toFixed(2)} km\n`;
report += `- Czas Całkowity: ${msToTime(totalDurationMs)}\n`;
report += `- Średnie Tempo: ${formatPace(avgPaceMs)} min/km\n`;
report += `- Przewyższenia: +${Math.round(totalElevationGain)}m / Max Wysokość: ${Math.round(maxElevation)}m\n`;
if (avgHr > 0) {
report += `- Tętno: Średnie ${avgHr} bpm / Max ${maxHr} bpm\n`;
}
if (avgCadence > 0) {
report += `- Kadencja: ${avgCadence} spm\n`;
}
if (splits.length > 0) {
report += `\nANALIZA MIĘDZYCZASÓW (SPLITS - CO 1 KM):\n`;
splits.forEach(s => {
const pace = formatPace(s.timeMs); // time for 1km = pace
const hrStr = s.avgHr > 0 ? `, HR: ${s.avgHr} bpm` : '';
const elevStr = s.elevGain > 5 ? `, Elev: +${s.elevGain}m` : ''; // show only significant gain
report += `Km ${s.km}: ${pace} min/km${hrStr}${elevStr}\n`;
});
} else {
report += `\n(Brak pełnych kilometrów do analizy międzyczasów)\n`;
}
// Zakończenie
report += `\nWSKAZÓWKI DLA AI: Wykorzystaj te dane do opisu walki na trasie. Zauważ momenty kryzysu (zwolnienie tempa, wysokie tętno) oraz momenty "puszczenia" (zbiegi, przyspieszenie).`;
resolve({
distance: `${totalDistance.toFixed(2)} km`,
duration: msToTime(totalTime),
elevation: `${Math.round(elevationGain)}m`,
stats: uiStats,
richSummary: report
});
} catch (error) {
@@ -68,12 +200,13 @@ export const parseGpxFile = async (file: File): Promise<ActivityStats> => {
}
};
reader.onerror = () => reject(new Error('Error reading file'));
reader.onerror = () => reject(new Error('Błąd odczytu pliku'));
reader.readAsText(file);
});
};
// Haversine formula
// --- POMOCNICZE FUNKCJE MATEMATYCZNE ---
function getDistanceFromLatLonInKm(lat1: number, lon1: number, lat2: number, lon2: number) {
const R = 6371; // Radius of the earth in km
const dLat = deg2rad(lat2 - lat1);
@@ -83,7 +216,7 @@ function getDistanceFromLatLonInKm(lat1: number, lon1: number, lat2: number, lon
Math.cos(deg2rad(lat1)) * Math.cos(deg2rad(lat2)) *
Math.sin(dLon / 2) * Math.sin(dLon / 2);
const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
const d = R * c; // Distance in km
const d = R * c;
return d;
}
@@ -96,5 +229,15 @@ function msToTime(duration: number) {
const minutes = Math.floor((duration / (1000 * 60)) % 60);
const hours = Math.floor((duration / (1000 * 60 * 60)) % 24);
// Jeśli mniej niż godzina, pokaż minuty i sekundy (opcjonalnie, tu zostawiamy format h m)
if (hours === 0) return `${minutes}m`;
return `${hours}h ${minutes}m`;
}
}
function formatPace(msPerKm: number): string {
if (msPerKm <= 0 || !isFinite(msPerKm)) return "-:--";
const totalSeconds = Math.floor(msPerKm / 1000);
const minutes = Math.floor(totalSeconds / 60);
const seconds = totalSeconds % 60;
return `${minutes}:${seconds.toString().padStart(2, '0')}`;
}