local conversion
This commit is contained in:
@@ -7,6 +7,7 @@
|
||||
import ActivityMap from './ActivityMap.svelte';
|
||||
import ActivityCharts from './ActivityCharts.svelte';
|
||||
import EditDrawer from './EditDrawer.svelte';
|
||||
import { loadActivity } from '../lib/dataloader';
|
||||
|
||||
export let activity: ActivitySummary;
|
||||
export let base: string = '/';
|
||||
@@ -28,9 +29,8 @@
|
||||
onMount(async () => {
|
||||
if (!activity.detail_url) return;
|
||||
try {
|
||||
const res = await fetch(`${base}data/${activity.detail_url}`);
|
||||
if (!res.ok) throw new Error(`HTTP ${res.status}`);
|
||||
detail = await res.json();
|
||||
detail = await loadActivity(activity.id, activity.detail_url, base);
|
||||
if (!detail) throw new Error('Activity not found');
|
||||
} catch (e: any) {
|
||||
error = e.message;
|
||||
}
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
import { onMount } from 'svelte';
|
||||
import type { ActivitySummary, BASIndex, Sport } from '../lib/types';
|
||||
import { formatDistance, formatDuration, formatElevation, formatDate, sportIcon, sportColor, sportLabel } from '../lib/format';
|
||||
import { loadIndex } from '../lib/dataloader';
|
||||
|
||||
/** Render preview_coords as an SVG polyline path string. */
|
||||
function trackPath(coords: [number, number][] | null, w: number, h: number): string {
|
||||
@@ -53,9 +54,7 @@
|
||||
sport = (new URLSearchParams(window.location.search).get('sport') as Sport | 'all') ?? 'all';
|
||||
mounted = true;
|
||||
try {
|
||||
const res = await fetch(`${import.meta.env.BASE_URL}data/index.json`);
|
||||
if (!res.ok) throw new Error(`HTTP ${res.status}`);
|
||||
const index: BASIndex = await res.json();
|
||||
const index = await loadIndex(import.meta.env.BASE_URL);
|
||||
all = index.activities.filter(a => a.privacy !== 'private');
|
||||
} catch (e: any) {
|
||||
error = e.message;
|
||||
|
||||
@@ -4,6 +4,7 @@
|
||||
import MmpChart from './MmpChart.svelte';
|
||||
import RecordsView from './RecordsView.svelte';
|
||||
import AthleteDrawer from './AthleteDrawer.svelte';
|
||||
import { loadIndex, loadAthlete } from '../lib/dataloader';
|
||||
|
||||
export let base: string = '/';
|
||||
|
||||
@@ -32,13 +33,12 @@
|
||||
activeTab = TABS.includes(rawTab as Tab) ? (rawTab as Tab) : 'power';
|
||||
mounted = true;
|
||||
try {
|
||||
const [athleteRes, indexRes] = await Promise.all([
|
||||
fetch(`${import.meta.env.BASE_URL}data/athlete.json`),
|
||||
fetch(`${import.meta.env.BASE_URL}data/index.json`),
|
||||
const [athleteData, index] = await Promise.all([
|
||||
loadAthlete(import.meta.env.BASE_URL),
|
||||
loadIndex(import.meta.env.BASE_URL),
|
||||
]);
|
||||
if (!athleteRes.ok) throw new Error('athlete.json not found — run bincio extract first');
|
||||
athlete = await athleteRes.json();
|
||||
const index: BASIndex = await indexRes.json();
|
||||
if (!athleteData) throw new Error('athlete.json not found — run bincio extract first');
|
||||
athlete = athleteData;
|
||||
activities = index.activities.filter(a => a.mmp && a.privacy !== 'private');
|
||||
} catch (e: any) {
|
||||
error = e.message;
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
import { onMount } from 'svelte';
|
||||
import type { ActivitySummary, BASIndex, Sport } from '../lib/types';
|
||||
import { formatDistance, formatDuration, sportIcon, sportColor, sportLabel } from '../lib/format';
|
||||
import { loadIndex } from '../lib/dataloader';
|
||||
|
||||
const PAGE_YEARS = 4;
|
||||
|
||||
@@ -30,9 +31,7 @@
|
||||
page = parseInt(params.get('page') ?? '0', 10) || 0;
|
||||
mounted = true;
|
||||
try {
|
||||
const res = await fetch(`${import.meta.env.BASE_URL}data/index.json`);
|
||||
if (!res.ok) throw new Error(`HTTP ${res.status}`);
|
||||
const index: BASIndex = await res.json();
|
||||
const index = await loadIndex(import.meta.env.BASE_URL);
|
||||
all = index.activities.filter(a => a.privacy !== 'private' && a.distance_m);
|
||||
} catch (e: any) {
|
||||
error = e.message;
|
||||
|
||||
@@ -208,6 +208,13 @@ const baseUrl = import.meta.env.BASE_URL ?? '/';
|
||||
<slot />
|
||||
</main>
|
||||
|
||||
<script>
|
||||
// Register service worker for local activity storage (offline support)
|
||||
if ('serviceWorker' in navigator) {
|
||||
navigator.serviceWorker.register('/sw.js').catch(() => {});
|
||||
}
|
||||
</script>
|
||||
|
||||
<script>
|
||||
const btn = document.getElementById('theme-toggle') as HTMLButtonElement;
|
||||
|
||||
|
||||
@@ -0,0 +1,123 @@
|
||||
/**
|
||||
* Data access abstraction layer.
|
||||
*
|
||||
* All Svelte components load BAS data through these functions instead of
|
||||
* calling fetch() directly. Each function merges server/bundled data with
|
||||
* any activities stored locally in IndexedDB (via localstore.ts), so the
|
||||
* app works the same whether it is connected to a cloud instance, running
|
||||
* offline, or somewhere in between.
|
||||
*
|
||||
* Design notes:
|
||||
* - Server fetch and IDB read run concurrently (Promise.allSettled).
|
||||
* - If the server is unreachable, local-only data is returned.
|
||||
* - If IDB is empty, pure server data is returned — zero overhead.
|
||||
* - Local activities override server ones with the same ID (local is authoritative
|
||||
* for anything the user recorded or converted on this device).
|
||||
*/
|
||||
|
||||
import type { ActivityDetail, ActivitySummary, BASIndex } from './types';
|
||||
import { listLocalActivities } from './localstore';
|
||||
|
||||
// ── Helpers ───────────────────────────────────────────────────────────────────
|
||||
|
||||
async function fetchJSON<T>(url: string): Promise<T> {
|
||||
const r = await fetch(url);
|
||||
if (!r.ok) throw new Error(`HTTP ${r.status}`);
|
||||
return r.json() as Promise<T>;
|
||||
}
|
||||
|
||||
async function idbGetActivity(id: string): Promise<ActivityDetail | null> {
|
||||
// Inline IDB read — avoids importing openDB into every caller
|
||||
return new Promise(resolve => {
|
||||
try {
|
||||
const req = indexedDB.open('bincio', 1);
|
||||
req.onsuccess = e => {
|
||||
const db: IDBDatabase = (e.target as IDBOpenDBRequest).result;
|
||||
const tx = db.transaction('files', 'readonly');
|
||||
const get = tx.objectStore('files').get(`/data/activities/${id}.json`);
|
||||
get.onsuccess = ge => resolve((ge.target as IDBRequest).result?.data ?? null);
|
||||
get.onerror = () => resolve(null);
|
||||
};
|
||||
req.onerror = () => resolve(null);
|
||||
} catch {
|
||||
resolve(null);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
function emptyIndex(): BASIndex {
|
||||
return {
|
||||
bas_version: '1.0',
|
||||
owner: { handle: 'unknown', display_name: '' },
|
||||
generated_at: '',
|
||||
shards: [],
|
||||
activities: [],
|
||||
};
|
||||
}
|
||||
|
||||
// ── Public API ────────────────────────────────────────────────────────────────
|
||||
|
||||
/**
|
||||
* Load the activity index, merging the server's copy with any locally-stored
|
||||
* activities. Local entries override server entries with the same ID.
|
||||
*/
|
||||
export async function loadIndex(baseUrl: string): Promise<BASIndex> {
|
||||
const [serverResult, localResult] = await Promise.allSettled([
|
||||
fetchJSON<BASIndex>(`${baseUrl}data/index.json`),
|
||||
listLocalActivities(),
|
||||
]);
|
||||
|
||||
const server = serverResult.status === 'fulfilled' ? serverResult.value : null;
|
||||
const local = localResult.status === 'fulfilled' ? localResult.value : [];
|
||||
|
||||
if (local.length === 0) return server ?? emptyIndex();
|
||||
if (!server) return { ...emptyIndex(), activities: local as ActivitySummary[] };
|
||||
|
||||
// Local overrides server for the same ID; new local entries are appended
|
||||
const merged = new Map<string, ActivitySummary>();
|
||||
for (const a of server.activities ?? []) merged.set(a.id, a);
|
||||
for (const a of local as ActivitySummary[]) merged.set(a.id, a);
|
||||
|
||||
return {
|
||||
...server,
|
||||
activities: [...merged.values()].sort(
|
||||
(a, b) => (b.started_at ?? '').localeCompare(a.started_at ?? ''),
|
||||
),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Load a single activity detail, checking IndexedDB first so locally-converted
|
||||
* activities are available offline.
|
||||
*
|
||||
* @param id Activity ID (used for the IDB lookup)
|
||||
* @param detailUrl Relative path from the BAS index (e.g. "activities/id.json")
|
||||
* @param baseUrl Site base URL
|
||||
*/
|
||||
export async function loadActivity(
|
||||
id: string,
|
||||
detailUrl: string,
|
||||
baseUrl: string,
|
||||
): Promise<ActivityDetail | null> {
|
||||
// IDB first — instant and works offline
|
||||
const cached = await idbGetActivity(id);
|
||||
if (cached) return cached;
|
||||
|
||||
try {
|
||||
return await fetchJSON<ActivityDetail>(`${baseUrl}data/${detailUrl}`);
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Load athlete profile. Athlete data is not stored locally yet, so this is
|
||||
* always a network fetch with a graceful null on failure.
|
||||
*/
|
||||
export async function loadAthlete(baseUrl: string): Promise<Record<string, unknown> | null> {
|
||||
try {
|
||||
return await fetchJSON(`${baseUrl}data/athlete.json`);
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,89 @@
|
||||
/**
|
||||
* IndexedDB helper for local activity storage.
|
||||
*
|
||||
* Activities converted on-device are written here. The service worker (sw.js)
|
||||
* reads from the same database and merges local activities into the feed.
|
||||
*/
|
||||
|
||||
const DB_NAME = 'bincio';
|
||||
const DB_VERSION = 1;
|
||||
const STORE = 'files';
|
||||
|
||||
function openDB(): Promise<IDBDatabase> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const req = indexedDB.open(DB_NAME, DB_VERSION);
|
||||
req.onupgradeneeded = e =>
|
||||
(e.target as IDBOpenDBRequest).result.createObjectStore(STORE, { keyPath: 'path' });
|
||||
req.onsuccess = e => resolve((e.target as IDBOpenDBRequest).result);
|
||||
req.onerror = e => reject((e.target as IDBOpenDBRequest).error);
|
||||
});
|
||||
}
|
||||
|
||||
async function idbPut(path: string, data: unknown): Promise<void> {
|
||||
const db = await openDB();
|
||||
return new Promise((resolve, reject) => {
|
||||
const tx = db.transaction(STORE, 'readwrite');
|
||||
tx.objectStore(STORE).put({ path, data });
|
||||
tx.oncomplete = () => resolve();
|
||||
tx.onerror = e => reject((e.target as IDBTransaction).error);
|
||||
});
|
||||
}
|
||||
|
||||
async function idbGet<T>(path: string): Promise<T | null> {
|
||||
const db = await openDB();
|
||||
return new Promise((resolve, reject) => {
|
||||
const req = db.transaction(STORE, 'readonly').objectStore(STORE).get(path);
|
||||
req.onsuccess = e => resolve((e.target as IDBRequest).result?.data ?? null);
|
||||
req.onerror = e => reject((e.target as IDBRequest).error);
|
||||
});
|
||||
}
|
||||
|
||||
// ── Public API ────────────────────────────────────────────────────────────────
|
||||
|
||||
/** Save a converted activity to IndexedDB and update the local summary index. */
|
||||
export async function saveActivityLocally(
|
||||
detail: Record<string, unknown>,
|
||||
geojson: Record<string, unknown> | null,
|
||||
): Promise<void> {
|
||||
const id = detail.id as string;
|
||||
|
||||
await idbPut(`/data/activities/${id}.json`, detail);
|
||||
if (geojson) {
|
||||
await idbPut(`/data/activities/${id}.geojson`, geojson);
|
||||
}
|
||||
|
||||
// Maintain a flat list of local summaries (read by the service worker)
|
||||
const existing = (await idbGet<ActivitySummary[]>('/data/local-index')) ?? [];
|
||||
const summary = toSummary(detail);
|
||||
const idx = existing.findIndex(a => a.id === id);
|
||||
if (idx >= 0) existing[idx] = summary; else existing.push(summary);
|
||||
await idbPut('/data/local-index', existing);
|
||||
}
|
||||
|
||||
/** Return all locally-stored activity summaries. */
|
||||
export async function listLocalActivities(): Promise<ActivitySummary[]> {
|
||||
return (await idbGet<ActivitySummary[]>('/data/local-index')) ?? [];
|
||||
}
|
||||
|
||||
/** Return true if at least one activity is stored locally. */
|
||||
export async function hasLocalActivities(): Promise<boolean> {
|
||||
const list = await listLocalActivities();
|
||||
return list.length > 0;
|
||||
}
|
||||
|
||||
// ── Helpers ───────────────────────────────────────────────────────────────────
|
||||
|
||||
type ActivitySummary = Record<string, unknown>;
|
||||
|
||||
const SUMMARY_KEYS = [
|
||||
'id', 'title', 'sport', 'sub_sport', 'started_at', 'distance_m',
|
||||
'duration_s', 'moving_time_s', 'elevation_gain_m', 'avg_speed_kmh',
|
||||
'avg_hr_bpm', 'avg_cadence_rpm', 'avg_power_w', 'privacy',
|
||||
'detail_url', 'track_url', 'preview_coords',
|
||||
] as const;
|
||||
|
||||
function toSummary(detail: Record<string, unknown>): ActivitySummary {
|
||||
return Object.fromEntries(
|
||||
SUMMARY_KEYS.filter(k => k in detail).map(k => [k, detail[k]])
|
||||
);
|
||||
}
|
||||
@@ -57,6 +57,9 @@ const baseUrl = import.meta.env.BASE_URL ?? '/';
|
||||
</div>
|
||||
|
||||
<div class="flex flex-col gap-2">
|
||||
<button id="btn-save-local" class="w-full py-2 px-4 rounded-lg text-sm font-medium text-white transition-colors" style="background:#3b82f6">
|
||||
📱 Save to this device
|
||||
</button>
|
||||
<button id="btn-download-json" class="w-full py-2 px-4 rounded-lg text-sm font-medium bg-zinc-700 hover:bg-zinc-600 text-white transition-colors">
|
||||
⬇ Download BAS JSON
|
||||
</button>
|
||||
@@ -64,8 +67,8 @@ const baseUrl = import.meta.env.BASE_URL ?? '/';
|
||||
⬇ Download GeoJSON track
|
||||
</button>
|
||||
{editUrl && (
|
||||
<button id="btn-save" class="w-full py-2 px-4 rounded-lg text-sm font-medium text-white transition-colors" style="background:#3b82f6">
|
||||
☁ Save to my bincio
|
||||
<button id="btn-save" class="w-full py-2 px-4 rounded-lg text-sm font-medium bg-zinc-800 hover:bg-zinc-700 text-white transition-colors border border-zinc-700">
|
||||
☁ Save to cloud instance
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
@@ -85,7 +88,16 @@ const baseUrl = import.meta.env.BASE_URL ?? '/';
|
||||
</div>
|
||||
</Base>
|
||||
|
||||
<script define:vars={{ editUrl, baseUrl }}>
|
||||
<div id="conv-config" data-edit-url={editUrl} data-base-url={baseUrl} style="display:none"></div>
|
||||
|
||||
<script>
|
||||
import { saveActivityLocally } from '../../lib/localstore';
|
||||
|
||||
// ── Config ──────────────────────────────────────────────────────────────────
|
||||
const _cfg = document.getElementById('conv-config') as HTMLElement;
|
||||
const editUrl = _cfg.dataset.editUrl ?? '';
|
||||
const baseUrl = _cfg.dataset.baseUrl ?? '/';
|
||||
|
||||
// ── DOM refs ────────────────────────────────────────────────────────────────
|
||||
const stepPick = document.getElementById('step-pick');
|
||||
const stepLoading = document.getElementById('step-loading');
|
||||
@@ -168,17 +180,17 @@ const baseUrl = import.meta.env.BASE_URL ?? '/';
|
||||
setProgress(20, 'Initialising Python…');
|
||||
pyodide = await window.loadPyodide({ indexURL: 'https://cdn.jsdelivr.net/pyodide/v0.26.4/full/' });
|
||||
|
||||
setProgress(40, 'Loading packages (lxml, pyyaml)…');
|
||||
await pyodide.loadPackage(['lxml', 'pyyaml']);
|
||||
setProgress(40, 'Loading packages (lxml, pyyaml, micropip)…');
|
||||
await pyodide.loadPackage(['lxml', 'pyyaml', 'micropip']);
|
||||
|
||||
setProgress(60, 'Installing fitdecode, gpxpy, rdp…');
|
||||
await pyodide.runPythonAsync(`
|
||||
import micropip
|
||||
await micropip.install(['fitdecode', 'gpxpy', 'rdp'])
|
||||
await micropip.install(['fitdecode', 'gpxpy'])
|
||||
`);
|
||||
|
||||
setProgress(80, 'Loading bincio extract pipeline…');
|
||||
const wheelUrl = new URL('/bincio.whl', window.location.origin).href;
|
||||
const wheelUrl = new URL('/bincio-0.1.0-py3-none-any.whl', window.location.origin).href;
|
||||
await pyodide.runPythonAsync(`
|
||||
import micropip
|
||||
await micropip.install('${wheelUrl}', deps=False)
|
||||
@@ -276,6 +288,27 @@ json.dumps({'id': act_id, 'detail': detail, 'geojson': geojson})
|
||||
showStep('error');
|
||||
}
|
||||
|
||||
// ── Save locally (IndexedDB → service worker serves it in the feed) ─────────
|
||||
document.getElementById('btn-save-local').addEventListener('click', async () => {
|
||||
if (!lastResult) return;
|
||||
const btn = document.getElementById('btn-save-local');
|
||||
btn.disabled = true;
|
||||
btn.textContent = 'Saving…';
|
||||
saveStatus.style.color = 'var(--text-4)';
|
||||
try {
|
||||
await saveActivityLocally(lastResult.detail, lastResult.geojson ?? null);
|
||||
btn.textContent = '✓ Saved to device';
|
||||
btn.style.background = '#16a34a';
|
||||
saveStatus.textContent = 'Activity saved. Visit the feed to see it.';
|
||||
saveStatus.style.color = '#4ade80';
|
||||
} catch (e) {
|
||||
btn.disabled = false;
|
||||
btn.textContent = '📱 Save to this device';
|
||||
saveStatus.textContent = 'Save failed: ' + e.message;
|
||||
saveStatus.style.color = '#f87171';
|
||||
}
|
||||
});
|
||||
|
||||
// ── Downloads ───────────────────────────────────────────────────────────────
|
||||
function downloadJson(data, filename) {
|
||||
const blob = new Blob([JSON.stringify(data, null, 2)], { type: 'application/json' });
|
||||
|
||||
Reference in New Issue
Block a user