Merge branch 'dev/edit'

This commit is contained in:
Davide Scaini
2026-03-29 15:57:02 +02:00
14 changed files with 1402 additions and 61 deletions
+131 -14
View File
@@ -1,9 +1,11 @@
<script lang="ts">
import { onMount } from 'svelte';
import { marked } from 'marked';
import type { ActivitySummary, ActivityDetail } from '../lib/types';
import { formatDistance, formatDuration, formatElevation, formatSpeed, formatDate, formatTime, sportIcon, sportLabel, sportColor } from '../lib/format';
import ActivityMap from './ActivityMap.svelte';
import ActivityCharts from './ActivityCharts.svelte';
import EditDrawer from './EditDrawer.svelte';
export let activity: ActivitySummary;
export let base: string = '/';
@@ -12,8 +14,14 @@
let detail: ActivityDetail | null = null;
let error = '';
// Linked hover index shared between map and charts
let hoveredIdx: number | null = null;
let editOpen = false;
let lightboxIndex: number | null = null;
// Local overrides applied immediately after a save (no re-fetch needed)
let localTitle = '';
let localDescription = '';
$: displayTitle = localTitle || activity.title;
onMount(async () => {
if (!activity.detail_url) return;
@@ -26,23 +34,112 @@
}
});
function onSaved(e: CustomEvent<{ title: string; description: string }>) {
editOpen = false;
localTitle = e.detail.title;
localDescription = e.detail.description;
}
$: trackUrl = activity.track_url ? `${base}data/${activity.track_url}` : null;
$: color = sportColor(activity.sport);
function lightboxPrev() { if (lightboxIndex !== null) lightboxIndex = (lightboxIndex - 1 + galleryImages.length) % galleryImages.length; }
function lightboxNext() { if (lightboxIndex !== null) lightboxIndex = (lightboxIndex + 1) % galleryImages.length; }
function onKeydown(e: KeyboardEvent) {
if (lightboxIndex === null) return;
if (e.key === 'ArrowLeft') { e.preventDefault(); lightboxPrev(); }
if (e.key === 'ArrowRight') { e.preventDefault(); lightboxNext(); }
if (e.key === 'Escape') { lightboxIndex = null; }
}
$: rawDescription = localDescription || detail?.description || '';
$: descriptionHtml = (() => {
if (!rawDescription) return '';
const renderer = new marked.Renderer();
// Local relative images are always shown in the gallery — suppress inline rendering
renderer.image = ({ href, title, text }) => {
const isLocal = href && !href.startsWith('http') && !href.startsWith('/') && !href.startsWith('data:');
if (isLocal) return '';
const titleAttr = title ? ` title="${title}"` : '';
return `<img src="${href ?? ''}" alt="${text}"${titleAttr} class="rounded-lg max-w-full my-2">`;
};
return marked(rawDescription, { renderer }) as string;
})();
$: imageBase = `${base}data/activities/images/${activity.id}/`;
$: galleryImages = (detail?.custom as any)?.images as string[] ?? [];
const stat = (label: string, value: string, key?: string) => ({ label, value, key });
$: hiddenStats = new Set<string>((detail?.custom as any)?.hide_stats ?? []);
$: stats = [
stat('Distance', formatDistance(activity.distance_m)),
stat('Moving time', formatDuration(activity.moving_time_s ?? activity.duration_s)),
stat('Elevation ↑', formatElevation(activity.elevation_gain_m), 'elevation'),
stat('Avg speed', formatSpeed(activity.avg_speed_kmh), 'speed'),
stat('Max speed', formatSpeed(activity.max_speed_kmh), 'speed'),
stat('Avg HR', activity.avg_hr_bpm ? `${activity.avg_hr_bpm} bpm` : '—', 'heart_rate'),
stat('Max HR', activity.max_hr_bpm ? `${activity.max_hr_bpm} bpm` : '—', 'heart_rate'),
stat('Elevation ↑', formatElevation(activity.elevation_gain_m), 'elevation'),
stat('Avg speed', formatSpeed(activity.avg_speed_kmh), 'speed'),
stat('Max speed', formatSpeed(activity.max_speed_kmh), 'speed'),
stat('Avg HR', activity.avg_hr_bpm ? `${activity.avg_hr_bpm} bpm` : '—', 'heart_rate'),
stat('Max HR', activity.max_hr_bpm ? `${activity.max_hr_bpm} bpm` : '—', 'heart_rate'),
stat('Cadence', activity.avg_cadence_rpm ? `${activity.avg_cadence_rpm} rpm` : '—', 'cadence'),
].filter(s => !s.key || !hiddenStats.has(s.key));
</script>
<svelte:window on:keydown={onKeydown} />
{#if editOpen && editUrl}
<EditDrawer activityId={activity.id} {editUrl} on:saved={onSaved} />
{/if}
<!-- Lightbox -->
{#if lightboxIndex !== null}
<!-- svelte-ignore a11y-no-static-element-interactions -->
<div
class="fixed inset-0 z-50 bg-black/95 flex items-center justify-center"
on:click={() => lightboxIndex = null}
on:keydown={onKeydown}
>
<!-- Prev -->
{#if galleryImages.length > 1}
<button
class="absolute left-4 top-1/2 -translate-y-1/2 text-white/60 hover:text-white text-3xl px-3 py-6 transition-colors z-10"
on:click|stopPropagation={lightboxPrev}
aria-label="Previous"
></button>
{/if}
<img
src={imageBase + galleryImages[lightboxIndex]}
alt={galleryImages[lightboxIndex]}
class="max-h-[90vh] max-w-[90vw] rounded-lg shadow-2xl object-contain"
on:click|stopPropagation
/>
<!-- Next -->
{#if galleryImages.length > 1}
<button
class="absolute right-4 top-1/2 -translate-y-1/2 text-white/60 hover:text-white text-3xl px-3 py-6 transition-colors z-10"
on:click|stopPropagation={lightboxNext}
aria-label="Next"
></button>
{/if}
<!-- Counter + filename -->
<div class="absolute bottom-6 left-1/2 -translate-x-1/2 text-white/50 text-xs text-center">
<p>{galleryImages[lightboxIndex]}</p>
{#if galleryImages.length > 1}
<p class="mt-0.5">{lightboxIndex + 1} / {galleryImages.length}</p>
{/if}
</div>
<!-- Close -->
<button
class="absolute top-4 right-5 text-white/50 hover:text-white text-2xl transition-colors"
on:click={() => lightboxIndex = null}
aria-label="Close"
>×</button>
</div>
{/if}
<!-- Header -->
<div class="flex items-start gap-4 mb-6">
<a href={`${base}`} class="text-zinc-500 hover:text-white transition-colors mt-1 shrink-0">
@@ -61,24 +158,44 @@
</span>
</div>
<div class="flex items-center gap-3">
<h1 class="text-2xl font-bold text-white">{activity.title}</h1>
<h1 class="text-2xl font-bold text-white">{displayTitle}</h1>
{#if editUrl}
<a
href={`${editUrl}/edit/${activity.id}`}
target="_blank"
rel="noopener"
<button
class="text-xs px-2 py-0.5 rounded border border-zinc-700 text-zinc-400 hover:border-zinc-500 hover:text-white transition-colors shrink-0"
on:click={() => editOpen = true}
>
Edit
</a>
</button>
{/if}
</div>
{#if detail?.description}
<p class="text-zinc-400 mt-1 text-sm whitespace-pre-line">{detail.description}</p>
{#if descriptionHtml}
<div class="text-zinc-400 mt-2 text-sm leading-relaxed [&_img]:rounded-lg [&_img]:my-2 [&_p]:my-1 [&_a]:text-blue-400">
{@html descriptionHtml}
</div>
{/if}
</div>
</div>
<!-- Photo gallery -->
{#if galleryImages.length}
<div class="mb-4 grid grid-cols-3 sm:grid-cols-4 md:grid-cols-5 gap-2">
{#each galleryImages as img, i}
<button
class="relative overflow-hidden rounded-lg bg-zinc-800 aspect-square hover:opacity-90 transition-opacity focus:outline-none focus:ring-2 focus:ring-blue-500"
on:click={() => lightboxIndex = i}
aria-label="Open photo {i + 1}"
>
<img
src={imageBase + img}
alt={img}
class="w-full h-full object-cover"
loading="lazy"
/>
</button>
{/each}
</div>
{/if}
<!-- Map + Stats split -->
<div class="grid grid-cols-1 lg:grid-cols-[1fr_280px] gap-4 mb-4">
<!-- Map -->
+291
View File
@@ -0,0 +1,291 @@
<script lang="ts">
import { createEventDispatcher } from 'svelte';
import type { Sport } from '../lib/types';
export let activityId: string;
export let editUrl: string;
const dispatch = createEventDispatcher<{ saved: { title: string; description: string } }>();
const SPORTS: Sport[] = ['cycling', 'running', 'hiking', 'walking', 'swimming', 'skiing', 'other'];
const STAT_PANELS = [
{ key: 'elevation', label: 'Elevation' },
{ key: 'speed', label: 'Speed' },
{ key: 'heart_rate', label: 'Heart rate' },
{ key: 'cadence', label: 'Cadence' },
{ key: 'power', label: 'Power' },
];
let loading = true;
let loadError = '';
let saving = false;
let saveStatus = '';
let saveOk = false;
// Form state
let title = '';
let sport: Sport = 'cycling';
let gear = '';
let description = '';
let highlight = false;
let isPrivate = false;
let hideStats: string[] = [];
let images: string[] = [];
// Image upload
let uploading = false;
let fileInput: HTMLInputElement;
const api = `${editUrl}/api/activity/${activityId}`;
async function load() {
loading = true;
loadError = '';
try {
const res = await fetch(api);
if (!res.ok) throw new Error(`Edit server returned ${res.status} — is bincio edit running?`);
const d = await res.json();
title = d.title ?? '';
sport = d.sport ?? 'cycling';
gear = d.gear ?? '';
description = d.description ?? '';
highlight = d.highlight ?? false;
isPrivate = d.private ?? false;
hideStats = d.hide_stats ?? [];
images = d.images ?? [];
} catch (e: any) {
loadError = e.message;
} finally {
loading = false;
}
}
async function save() {
saving = true;
saveStatus = '';
saveOk = false;
try {
const res = await fetch(api, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ title, sport, gear, description, highlight, private: isPrivate, hide_stats: hideStats }),
});
if (!res.ok) throw new Error(await res.text());
saveStatus = 'Saved';
saveOk = true;
dispatch('saved', { title, description });
} catch (e: any) {
saveStatus = e.message;
saveOk = false;
} finally {
saving = false;
}
}
async function uploadImages(files: FileList) {
uploading = true;
for (const file of Array.from(files)) {
const fd = new FormData();
fd.append('file', file);
const res = await fetch(`${api}/images`, { method: 'POST', body: fd });
if (res.ok) {
const d = await res.json();
if (!images.includes(d.filename)) images = [...images, d.filename];
// Insert markdown reference at cursor or end
const ref = `\n![${d.filename.replace(/\.[^.]+$/, '')}](${d.filename})`;
description = description.trimEnd() + ref;
}
}
uploading = false;
}
async function deleteImage(filename: string) {
await fetch(`${api}/images/${encodeURIComponent(filename)}`, { method: 'DELETE' });
images = images.filter(f => f !== filename);
// Remove the markdown reference too
description = description.replace(new RegExp(`!\\[[^\\]]*\\]\\(${filename}\\)`, 'g'), '').trim();
}
function toggleStat(key: string) {
hideStats = hideStats.includes(key)
? hideStats.filter(s => s !== key)
: [...hideStats, key];
}
load();
</script>
<!-- Backdrop -->
<div
class="fixed inset-0 bg-black/60 z-40 backdrop-blur-sm"
on:click={() => dispatch('saved', { title, description })}
role="presentation"
/>
<!-- Drawer -->
<aside class="fixed top-0 right-0 h-full w-full max-w-md bg-zinc-950 border-l border-zinc-800 z-50 flex flex-col shadow-2xl">
<!-- Header -->
<div class="flex items-center justify-between px-5 py-4 border-b border-zinc-800 shrink-0">
<h2 class="font-semibold text-white text-sm">Edit activity</h2>
<button
class="text-zinc-500 hover:text-white transition-colors text-xl leading-none"
on:click={() => dispatch('saved', { title, description })}
aria-label="Close"
>×</button>
</div>
<!-- Body -->
<div class="flex-1 overflow-y-auto px-5 py-4">
{#if loading}
<div class="space-y-3 animate-pulse">
{#each Array(4) as _}
<div class="h-9 rounded bg-zinc-800" />
{/each}
</div>
{:else if loadError}
<p class="text-red-400 text-sm">{loadError}</p>
{:else}
<!-- Title -->
<div class="mb-4">
<label class="block text-xs text-zinc-500 mb-1" for="ed-title">Title</label>
<input
id="ed-title"
type="text"
bind:value={title}
class="w-full px-3 py-2 bg-zinc-900 border border-zinc-700 rounded-lg text-sm text-white outline-none focus:border-blue-500 transition-colors"
/>
</div>
<!-- Sport + Gear -->
<div class="grid grid-cols-2 gap-3 mb-4">
<div>
<label class="block text-xs text-zinc-500 mb-1" for="ed-sport">Sport</label>
<select
id="ed-sport"
bind:value={sport}
class="w-full px-3 py-2 bg-zinc-900 border border-zinc-700 rounded-lg text-sm text-white outline-none focus:border-blue-500 transition-colors"
>
{#each SPORTS as s}
<option value={s}>{s.charAt(0).toUpperCase() + s.slice(1)}</option>
{/each}
</select>
</div>
<div>
<label class="block text-xs text-zinc-500 mb-1" for="ed-gear">Gear</label>
<input
id="ed-gear"
type="text"
bind:value={gear}
placeholder="e.g. Trek Domane"
class="w-full px-3 py-2 bg-zinc-900 border border-zinc-700 rounded-lg text-sm text-white placeholder-zinc-600 outline-none focus:border-blue-500 transition-colors"
/>
</div>
</div>
<!-- Description -->
<div class="mb-4">
<label class="block text-xs text-zinc-500 mb-1" for="ed-desc">Description <span class="text-zinc-600">(markdown)</span></label>
<textarea
id="ed-desc"
bind:value={description}
rows={6}
placeholder="Write about this activity…"
class="w-full px-3 py-2 bg-zinc-900 border border-zinc-700 rounded-lg text-sm text-white placeholder-zinc-600 outline-none focus:border-blue-500 transition-colors resize-y"
/>
</div>
<!-- Images -->
<div class="mb-4">
<p class="text-xs text-zinc-500 mb-2">Images</p>
<!-- svelte-ignore a11y-no-static-element-interactions -->
<div
class="border border-dashed border-zinc-700 rounded-lg px-4 py-3 text-center text-xs text-zinc-500 cursor-pointer hover:border-zinc-500 hover:text-zinc-300 transition-colors"
on:click={() => fileInput.click()}
on:dragover|preventDefault
on:drop|preventDefault={e => e.dataTransfer?.files && uploadImages(e.dataTransfer.files)}
>
{uploading ? 'Uploading…' : 'Drop images or click to upload'}
</div>
<input bind:this={fileInput} type="file" accept="image/*" multiple class="hidden"
on:change={e => e.currentTarget.files && uploadImages(e.currentTarget.files)} />
{#if images.length}
<div class="flex flex-wrap gap-2 mt-2">
{#each images as img}
<span class="flex items-center gap-1 text-xs bg-zinc-800 border border-zinc-700 rounded-full px-2 py-0.5">
{img}
<button class="text-zinc-500 hover:text-red-400 transition-colors" on:click={() => deleteImage(img)}>×</button>
</span>
{/each}
</div>
{/if}
</div>
<!-- Hide stats -->
<div class="mb-4">
<p class="text-xs text-zinc-500 mb-2">Hide stat panels</p>
<div class="flex flex-wrap gap-2">
{#each STAT_PANELS as panel}
<button
type="button"
class="text-xs px-3 py-1 rounded-full border transition-colors"
class:border-zinc-700={!hideStats.includes(panel.key)}
class:text-zinc-400={!hideStats.includes(panel.key)}
class:border-blue-500={hideStats.includes(panel.key)}
class:text-white={hideStats.includes(panel.key)}
style={hideStats.includes(panel.key) ? 'background:rgba(59,130,246,.15)' : ''}
on:click={() => toggleStat(panel.key)}
>
{panel.label}
</button>
{/each}
</div>
</div>
<!-- Flags -->
<div class="flex gap-3 mb-2">
<button
type="button"
class="flex items-center gap-2 text-xs px-3 py-1.5 rounded-lg border transition-colors"
class:border-zinc-700={!highlight}
class:text-zinc-400={!highlight}
class:border-yellow-500={highlight}
class:text-yellow-300={highlight}
style={highlight ? 'background:rgba(234,179,8,.1)' : ''}
on:click={() => highlight = !highlight}
>
★ Highlight
</button>
<button
type="button"
class="flex items-center gap-2 text-xs px-3 py-1.5 rounded-lg border transition-colors"
class:border-zinc-700={!isPrivate}
class:text-zinc-400={!isPrivate}
class:border-red-500={isPrivate}
class:text-red-300={isPrivate}
style={isPrivate ? 'background:rgba(239,68,68,.1)' : ''}
on:click={() => isPrivate = !isPrivate}
>
⊘ Private
</button>
</div>
{/if}
</div>
<!-- Footer -->
{#if !loading && !loadError}
<div class="px-5 py-4 border-t border-zinc-800 flex items-center gap-3 shrink-0">
<button
class="px-4 py-2 bg-blue-600 hover:bg-blue-500 disabled:opacity-40 text-white text-sm font-medium rounded-lg transition-colors"
disabled={saving}
on:click={save}
>
{saving ? 'Saving…' : 'Save'}
</button>
{#if saveStatus}
<span class="text-xs" class:text-green-400={saveOk} class:text-red-400={!saveOk}>
{saveStatus}
</span>
{/if}
</div>
{/if}
</aside>